aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
//! Bash list surface adapter (R17, R20, R22).
//!
//! List surface metadata and envelope builder for `bash.output`.
//! Unit: `lines`. Reason: `cap` (`ReasonKind::Selecting`). Narrow: `[]`.
//! No narrow clause in rendered text.
//! `shown` = output line count, `total` = `Exact(input line count)`, both
//! measured on the text the agent receives.
//! `dropped_by_class` counts blocks and is NEVER a line-count source.

use crate::list_envelope::{derive_wire_key, ListEnvelope, Reason, Total, Unit};
use crate::list_surfaces::ReasonKind;

/// Registered list ID for bash text output.
pub const LIST_ID: &str = "bash.output";

/// Wire serialization key at reply root beside `output` (R14, R21).
pub const WIRE_KEY: &str = "bash_output_list_envelope";

/// Registered unit for bash output.
pub const UNIT: Unit = Unit::Lines;

/// Registered reason for bash truncation.
pub const REASON: Reason = Reason::Cap;

/// Reason kind for bash cap.
pub const REASON_KIND: ReasonKind = ReasonKind::Selecting;

/// Narrowing parameters: bash accepts no narrowing parameter.
pub const NARROW: &[&str] = &[];

/// Count output lines, excluding recovery metadata, the omitted-lines marker a
/// compressor puts where it cut, the line naming a finished task, and the
/// `shown N of M lines (cap)` trailer added when the output was cut.
#[inline]
pub fn count_output_lines(output: &str) -> usize {
    output
        .lines()
        .filter(|line| {
            let recovery_marker = line.starts_with('[')
                && line.ends_with(']')
                && (line.contains("; full output:")
                    || line.contains("; full output unavailable")
                    || line.contains("; retained output:")
                    || line.contains("; see remaining: tail -n +")
                    || line.contains("; use bash_status("));
            let trailer = line.strip_prefix("shown ").is_some_and(|rest| {
                rest.strip_suffix(" lines (cap)").is_some_and(|counts| {
                    counts.split_once(" of ").is_some_and(|(shown, total)| {
                        shown.parse::<usize>().is_ok() && total.parse::<usize>().is_ok()
                    })
                })
            });
            !recovery_marker
                && !trailer
                && !is_foreground_task_line(line)
                && !crate::compress::line_cut::is_omitted_lines_marker(line)
        })
        .count()
}

/// Derive the wire key for serializing the bash envelope.
#[inline]
pub fn wire_key() -> String {
    derive_wire_key(LIST_ID, true)
}

/// Construct a truncation envelope for bash output if lines were dropped.
///
/// Returns `Some(ListEnvelope)` when `shown < total_input_lines`.
/// When output was not compressed or no lines were dropped (`shown >= total_input_lines`),
/// returns `None` (reason is `None`, nothing rendered, no envelope field serialized).
pub fn build_bash_output_envelope(shown: usize, total_input_lines: usize) -> Option<ListEnvelope> {
    if shown >= total_input_lines {
        None
    } else {
        Some(ListEnvelope::new(
            shown,
            Total::Exact(total_input_lines),
            UNIT,
            vec![REASON],
            NARROW,
        ))
    }
}

/// Construct a truncation envelope measured directly on the agent-facing output text
/// and the compressor-reported input line count.
///
/// `shown` is the output line count of `agent_received_output`.
/// `total` is `Exact(input_line_count)`.
/// Neither count is ever sourced from `dropped_by_class`.
pub fn build_envelope_from_output(
    agent_received_output: &str,
    input_line_count: usize,
) -> Option<ListEnvelope> {
    let shown = count_output_lines(agent_received_output);
    build_bash_output_envelope(shown, input_line_count)
}

/// Append the text-surface trailer and return its envelope when compression dropped lines.
///
/// Recovery markers and the trailer describe output; they are not output lines.
/// Uncompressed text remains byte-identical.
pub fn append_envelope_trailer(
    agent_received_output: &mut String,
    input_line_count: usize,
) -> Option<ListEnvelope> {
    let envelope = build_envelope_from_output(agent_received_output, input_line_count)?;
    debug_assert!(envelope.shown < input_line_count);
    let trailer = envelope_trailer(&envelope);
    if !agent_received_output.is_empty() && !agent_received_output.ends_with('\n') {
        agent_received_output.push('\n');
    }
    agent_received_output.push_str(&trailer);
    Some(envelope)
}

/// Render a bash envelope through the authorized NDJSON trailer seam.
///
/// An empty base isolates the trailer, while array mode asks the shared seam to
/// render it before bash integrates that text into its output payload.
pub fn envelope_trailer(envelope: &ListEnvelope) -> String {
    let mut data = serde_json::Map::new();
    data.insert(
        derive_wire_key(LIST_ID, false),
        serde_json::to_value(envelope).expect("ListEnvelope serialization"),
    );
    crate::ndjson_text::build_ndjson_text(
        "",
        &serde_json::Value::Object(data),
        Some(LIST_ID),
        false,
    )
}

/// Attach the bash output list envelope to a JSON response object beside `output`.
pub fn attach_bash_output_envelope(
    data: &mut serde_json::Map<String, serde_json::Value>,
    envelope: &Option<ListEnvelope>,
) {
    if let Some(env) = envelope {
        data.insert(
            WIRE_KEY.to_string(),
            serde_json::to_value(env).expect("ListEnvelope serialization"),
        );
    }
}

/// Produce a bash reply data map containing `output` and optionally `bash_output_list_envelope`.
pub fn produce_bash_reply_data(
    output: String,
    envelope: Option<ListEnvelope>,
) -> serde_json::Map<String, serde_json::Value> {
    let mut map = serde_json::Map::new();
    map.insert("output".to_string(), serde_json::Value::String(output));
    attach_bash_output_envelope(&mut map, &envelope);
    map
}

/// Envelope for the optional watcher file list and its per-file diff lines.
/// Callers supply measured retained and observed counts after applying caps.
pub fn build_changed_files_envelope(
    shown: usize,
    total: usize,
    lines: bool,
    incomplete: bool,
) -> ListEnvelope {
    build_changed_files_envelope_with_time_limit(shown, total, lines, incomplete, false)
}

/// A reply deadline can stop path enumeration before the full total is known.
pub fn build_changed_files_envelope_with_time_limit(
    shown: usize,
    total: usize,
    lines: bool,
    incomplete: bool,
    time_limit: bool,
) -> ListEnvelope {
    let mut causes = Vec::new();
    if shown < total {
        causes.push(Reason::Cap);
    }
    if time_limit {
        causes.push(Reason::TimeLimit);
    }
    ListEnvelope::new(
        shown,
        if incomplete || time_limit {
            Total::AtLeast(total)
        } else {
            Total::Exact(total)
        },
        if lines { Unit::Lines } else { Unit::Files },
        causes,
        &[],
    )
}

/// True for a foreground task annotation: `[task <id>]` or
/// `[task <id> (job <job>)]`. It is AFT's annotation, not command output, so
/// it does not affect output line counts or the hash used to detect repeated output.
pub fn is_foreground_task_line(line: &str) -> bool {
    let Some(inner) = line
        .strip_prefix("[task ")
        .and_then(|rest| rest.strip_suffix(']'))
    else {
        return false;
    };
    let (id, rest) = inner.split_once(' ').unwrap_or((inner, ""));
    !id.is_empty()
        && (rest.is_empty()
            || rest
                .strip_prefix("(job ")
                .and_then(|job| job.strip_suffix(')'))
                .is_some_and(|job| !job.is_empty() && !job.contains(' ')))
}