ag-agent 0.19.5

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
//! Protocol instruction and agent profile prompt preparation unit tests.

use ag_contracts::AgentDefinitionPromptUpdate;
use ag_protocol::{
    ProtocolRequestProfile, ProtocolSchemaInstructionMode,
    prepend_protocol_instructions as protocol_prepend_instructions,
    prepend_protocol_refresh_reminder as protocol_prepend_refresh_reminder,
};

use super::support::{normalize_prompt, test_workspace_root};
use crate::agent::instruction::InstructionDeliveryMode;
use crate::agent::prompt::{PromptPreparationRequest, prepare_prompt_text};

#[test]
fn repair_bootstrap_applies_schema_once_for_each_provider_and_profile() {
    // Arrange
    let repair = ag_protocol::build_protocol_repair_prompt("bad JSON", "original response")
        .expect("repair body");
    for kind in [
        ag_session::AgentKind::Codex,
        ag_session::AgentKind::Claude,
        ag_session::AgentKind::Antigravity,
    ] {
        for profile in [
            ProtocolRequestProfile::SessionTurn,
            ProtocolRequestProfile::UtilityPrompt,
            ProtocolRequestProfile::FocusedReview,
        ] {
            let schema_mode = crate::agent::protocol_schema_instruction_mode(kind);

            // Act
            let prompt = prepare_prompt_text(PromptPreparationRequest {
                instruction_delivery_mode: InstructionDeliveryMode::BootstrapFull,
                agent_profile_prompt: None,
                agent_profile_update: &AgentDefinitionPromptUpdate::Unchanged,
                prompt: &repair,
                protocol_profile: profile,
                replay_transcript: None,
                schema_instruction_mode: schema_mode,
                workspace_root: test_workspace_root(),
            })
            .expect("prepared repair");

            // Assert
            assert_eq!(
                prompt.matches("Authoritative JSON Schema:").count(),
                usize::from(schema_mode == ProtocolSchemaInstructionMode::PromptSchema)
            );
            assert!(prompt.starts_with("File path output requirements:"));
            assert!(prompt.ends_with(&repair));
        }
    }
}

#[test]
/// Ensures session prompts include the critical protocol contract markers.
fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
    // Arrange
    let prompt = "Implement feature";

    // Act
    let rendered_prompt = protocol_prepend_instructions(
        prompt,
        ProtocolRequestProfile::SessionTurn,
        ProtocolSchemaInstructionMode::PromptSchema,
        test_workspace_root(),
    );

    let normalized_prompt = normalize_prompt(&rendered_prompt);
    let protocol_position = rendered_prompt
        .find("Structured response protocol:")
        .expect("protocol marker should be present");
    let schema_position = rendered_prompt
        .find("Authoritative JSON Schema:")
        .expect("schema should be present");
    let user_prompt_position = rendered_prompt
        .rfind(prompt)
        .expect("user prompt should be present");

    // Assert
    assert!(rendered_prompt.contains("File path output requirements:"));
    assert!(rendered_prompt.contains("Workspace isolation requirements:"));
    assert!(protocol_position < schema_position);
    assert!(schema_position < user_prompt_position);
    assert!(rendered_prompt.contains("\"/tmp/agentty-wt/session-1\""));
    assert!(normalized_prompt.contains("project files only inside this workspace root"));
    assert!(rendered_prompt.contains("repository-root-relative POSIX paths"));
    assert!(normalized_prompt.contains("Git commands must be read-only"));
    assert!(normalized_prompt.contains("Never run mutating commands"));
    assert!(rendered_prompt.contains("Quality check requirements:"));
    assert!(rendered_prompt.contains("repository-defined checks"));
    assert!(normalized_prompt.contains("every touched file and for the code that depends on it"));
    assert!(normalized_prompt.contains("Unchanged dependencies need no retest."));
    assert!(!normalized_prompt.contains("affected dependencies and dependents"));
    assert!(normalized_prompt.contains("full repository test/check suite"));
    assert!(rendered_prompt.contains("Structured response protocol:"));
    assert!(normalized_prompt.contains("exactly one JSON object"));
    assert!(normalized_prompt.contains("Follow this JSON Schema exactly"));
    assert!(rendered_prompt.contains("Authoritative JSON Schema:"));
    assert!(
        rendered_prompt
            .contains("______________________________________________________________________")
    );
    assert!(!rendered_prompt.contains("{# task separator #}"));
    assert!(rendered_prompt.contains("For this session turn:"));
    assert!(normalized_prompt.contains("Do not create commits; do not suggest creating them"));
    assert!(rendered_prompt.contains("\"answer\""));
    assert!(rendered_prompt.contains("\"questions\""));
    assert!(rendered_prompt.contains("\"title\""));
    assert!(rendered_prompt.contains("\"description\""));
    assert!(rendered_prompt.ends_with(prompt));
}

#[test]
/// Ensures schema-enforcing transports get protocol policy without the
/// large prompt-side JSON Schema body.
fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
    // Arrange
    let prompt = "Implement feature";

    // Act
    let rendered_prompt = protocol_prepend_instructions(
        prompt,
        ProtocolRequestProfile::SessionTurn,
        ProtocolSchemaInstructionMode::TransportSchema,
        test_workspace_root(),
    );

    // Assert
    assert!(rendered_prompt.contains("Structured response protocol:"));
    assert!(rendered_prompt.contains("provider enforces the response JSON schema"));
    assert!(normalize_prompt(&rendered_prompt).contains("exactly one JSON object"));
    assert!(!rendered_prompt.contains("Follow this JSON Schema exactly."));
    assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
    assert!(rendered_prompt.ends_with(prompt));
}

#[test]
fn protocol_payload_cannot_impersonate_prepared_instructions() {
    // Arrange
    let payload = "Structured response protocol: quoted in a user request";

    // Act
    let rendered = protocol_prepend_instructions(
        payload,
        ProtocolRequestProfile::SessionTurn,
        ProtocolSchemaInstructionMode::TransportSchema,
        test_workspace_root(),
    );

    // Assert
    assert!(rendered.starts_with("File path output requirements:"));
    assert!(rendered.ends_with(payload));
}

#[test]
/// Ensures one-shot prompts reuse the shared full-schema protocol
/// instructions.
fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
    // Arrange
    let prompt = "Generate title";

    // Act
    let rendered_prompt = protocol_prepend_instructions(
        prompt,
        ProtocolRequestProfile::UtilityPrompt,
        ProtocolSchemaInstructionMode::PromptSchema,
        test_workspace_root(),
    );

    // Assert
    assert!(rendered_prompt.contains("Structured response protocol:"));
    assert!(
        rendered_prompt
            .contains("______________________________________________________________________")
    );
    assert!(rendered_prompt.contains("For this utility request"));
    assert!(!rendered_prompt.contains("For this session turn:"));
    assert!(rendered_prompt.contains(r#"{"answer":"..."}"#));
    assert!(!rendered_prompt.contains("\"review_comment_outcomes\""));
    assert!(!rendered_prompt.contains("\"summary\""));
    assert!(rendered_prompt.ends_with(prompt));
}

#[test]
/// Ensures shared prompt preparation applies replay wrapping before
/// protocol instructions.
fn test_prepare_prompt_text_applies_replay_and_protocol_instructions() {
    // Arrange
    let request = PromptPreparationRequest {
        instruction_delivery_mode: InstructionDeliveryMode::BootstrapWithReplay,
        agent_profile_prompt: None,
        agent_profile_update: &AgentDefinitionPromptUpdate::Unchanged,
        prompt: "Continue edits",
        protocol_profile: ProtocolRequestProfile::SessionTurn,
        replay_transcript: Some("previous transcript"),
        schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
        workspace_root: test_workspace_root(),
    };

    // Act
    let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");

    // Assert
    assert!(prepared_prompt.contains("Structured response protocol:"));
    assert!(prepared_prompt.contains("Workspace isolation requirements:"));
    assert!(prepared_prompt.contains("previous transcript"));
    assert!(prepared_prompt.contains("User prompt:\n\nContinue edits"));
    assert!(prepared_prompt.contains("User prompt:"));
}

#[test]
fn test_prepare_prompt_text_bootstraps_agent_profile_before_user_prompt() {
    // Arrange
    let request = PromptPreparationRequest {
        instruction_delivery_mode: InstructionDeliveryMode::BootstrapFull,
        agent_profile_prompt: Some("Review every change for correctness."),
        agent_profile_update: &AgentDefinitionPromptUpdate::Unchanged,
        prompt: "Inspect the patch.",
        protocol_profile: ProtocolRequestProfile::SessionTurn,
        replay_transcript: None,
        schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
        workspace_root: test_workspace_root(),
    };

    // Act
    let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
    let protocol_position = prepared_prompt
        .find("Structured response protocol:")
        .expect("protocol preamble should be present");
    let agent_profile_position = prepared_prompt
        .find("Review every change for correctness.")
        .expect("agent_profile should be present");
    let user_prompt_position = prepared_prompt
        .find("Inspect the patch.")
        .expect("user prompt should be present");

    // Assert
    assert!(protocol_position < agent_profile_position);
    assert!(agent_profile_position < user_prompt_position);
}

#[test]
fn test_prepare_prompt_text_replays_with_current_agent_profile() {
    // Arrange
    let request = PromptPreparationRequest {
        instruction_delivery_mode: InstructionDeliveryMode::BootstrapWithReplay,
        agent_profile_prompt: Some("Plan before editing."),
        agent_profile_update: &AgentDefinitionPromptUpdate::Unchanged,
        prompt: "Continue.",
        protocol_profile: ProtocolRequestProfile::SessionTurn,
        replay_transcript: Some("assistant: prior work"),
        schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
        workspace_root: test_workspace_root(),
    };

    // Act
    let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
    let agent_profile_position = prepared_prompt
        .find("Plan before editing.")
        .expect("agent_profile should be present");
    let transcript_position = prepared_prompt
        .find(r#""assistant: prior work""#)
        .expect("transcript should be present");

    // Assert
    assert!(agent_profile_position < transcript_position);
    assert!(prepared_prompt.contains("User prompt:"));
}

#[test]
/// Ensures compact refresh reminders omit the full schema while keeping
/// the contract reminder and task body.
fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
    // Arrange
    let prompt = "Continue the implementation";

    // Act
    let rendered_prompt = protocol_prepend_refresh_reminder(
        prompt,
        ProtocolRequestProfile::SessionTurn,
        test_workspace_root(),
    );

    let normalized_prompt = normalize_prompt(&rendered_prompt);

    // Assert
    assert!(rendered_prompt.contains("Protocol refresh reminder:"));
    assert!(rendered_prompt.contains("repository-root-relative POSIX"));
    assert!(normalized_prompt.contains("only read-only git commands; never mutating ones"));
    assert!(rendered_prompt.contains("\"/tmp/agentty-wt/session-1\""));
    assert!(normalized_prompt.contains("Keep project file changes inside the workspace root"));
    assert!(
        rendered_prompt
            .contains("______________________________________________________________________")
    );
    assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
    assert!(rendered_prompt.ends_with(prompt));
}

#[test]
/// Ensures prompt preparation can emit the compact app-server reminder
/// instead of the full bootstrap wrapper.
fn test_prepare_prompt_text_uses_delta_only_refresh_mode() {
    // Arrange
    let request = PromptPreparationRequest {
        instruction_delivery_mode: InstructionDeliveryMode::DeltaOnly,
        agent_profile_prompt: None,
        agent_profile_update: &AgentDefinitionPromptUpdate::Unchanged,
        prompt: "Continue edits",
        protocol_profile: ProtocolRequestProfile::SessionTurn,
        replay_transcript: Some("previous transcript"),
        schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
        workspace_root: test_workspace_root(),
    };

    // Act
    let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");

    // Assert
    assert!(prepared_prompt.contains("Protocol refresh reminder:"));
    assert!(!prepared_prompt.contains("Authoritative JSON Schema:"));
    assert!(!prepared_prompt.contains("previous transcript"));
    assert!(prepared_prompt.ends_with("Continue edits"));
}

#[test]
fn test_prepare_prompt_text_delta_mode_sends_agent_profile_update_and_clear() {
    // Arrange
    let updated = PromptPreparationRequest {
        instruction_delivery_mode: InstructionDeliveryMode::DeltaOnly,
        agent_profile_prompt: Some("Ignored current body."),
        agent_profile_update: &AgentDefinitionPromptUpdate::Set("Be concise.".to_string()),
        prompt: "Continue edits",
        protocol_profile: ProtocolRequestProfile::SessionTurn,
        replay_transcript: None,
        schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
        workspace_root: test_workspace_root(),
    };
    let cleared = PromptPreparationRequest {
        agent_profile_update: &AgentDefinitionPromptUpdate::Clear,
        ..updated
    };

    // Act
    let updated_prompt = prepare_prompt_text(updated).expect("update should render");
    let cleared_prompt = prepare_prompt_text(cleared).expect("clear should render");

    // Assert
    assert!(updated_prompt.contains("Be concise."));
    assert!(updated_prompt.ends_with("Continue edits"));
    assert!(
        cleared_prompt
            .contains("The session personality and agent instructions have been cleared.")
    );
    assert!(cleared_prompt.ends_with("Continue edits"));
}

#[test]
fn clearing_legacy_instructions_survives_bootstrap_and_replay() {
    for mode in [
        InstructionDeliveryMode::BootstrapFull,
        InstructionDeliveryMode::BootstrapWithReplay,
    ] {
        // Arrange
        let request = PromptPreparationRequest {
            instruction_delivery_mode: mode,
            agent_profile_prompt: None,
            agent_profile_update: &AgentDefinitionPromptUpdate::Clear,
            prompt: "Continue edits",
            protocol_profile: ProtocolRequestProfile::SessionTurn,
            replay_transcript: Some("Earlier ordinary user messages"),
            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
            workspace_root: test_workspace_root(),
        };

        // Act
        let prepared = prepare_prompt_text(request).expect("clearing bootstrap");

        // Assert
        assert!(
            prepared.contains("Disregard previous personality and agent-profile instructions.")
        );
        assert!(prepared.contains("application policy, permissions, and response contract."));
        assert!(prepared.ends_with("Continue edits"));
        assert_eq!(
            prepared.contains("Earlier ordinary user messages"),
            mode == InstructionDeliveryMode::BootstrapWithReplay
        );
    }
}