trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
//! System-prompt assembler — composes the fixed-order parity prompt.
//!
//! Why: The cross-model harness must assemble a system prompt whose only
//! intentional per-model variation is the optional tool-use fallback guidance
//! (parity-spec §1, §2). Centralising assembly here guarantees the stable,
//! fixed section order the spec requires (§2) and the trusty-mpm-style
//! `\n\n---\n\n` separators (§2), so two runs of the same task differ only by
//! the model.
//! What: [`PromptAssembler`] and the free function [`assemble_system_prompt`],
//! which concatenate up to four sections — BASE preamble, agent prompt,
//! project/`CLAUDE.md` context, and fallback guidance — joining only the
//! non-empty ones with the section separator.
//! Test: `prompt::tests` covers stable order, idempotence, separator collapse,
//! empty-section skipping, and fallback-guidance ordering.

use crate::agents::AgentConfig;
use crate::prompt::preamble::{BASE_PREAMBLE, BATCH_WRITE_GUIDANCE, FILE_DISCOVERY_GUIDANCE};
use crate::tools::ToolRegistry;

/// Section separator between assembled prompt blocks (parity-spec §2).
///
/// Why: The spec fixes the separator as the same Markdown horizontal rule that
/// trusty-mpm uses, for visual and diff consistency across the two harnesses.
/// What: The literal `"\n\n---\n\n"`.
/// Test: `prompt::tests::omitted_sections_produce_no_double_separator` depends
/// on this exact value.
const SECTION_SEPARATOR: &str = "\n\n---\n\n";

/// DailyDriver-only discovery guidance (PR A, #2689) appended as a trailing
/// section, mirroring the `skills_catalog` pattern.
///
/// Why: the engineer gains a trusty-search-backed `search_code` tool in
/// DailyDriver mode; without steering, models default to shelling out or to the
/// literal `grep`/`glob` tools even for conceptual questions. This section
/// tells the model when to reach for semantic/call-graph discovery vs. exact
/// literal search, and to fall back silently when trusty-search is unavailable.
/// It is intentionally NOT in [`BASE_PREAMBLE`]: the parity spec forbids
/// MCP/tool catalogs there, so the preamble hash must not change. Parity mode
/// never appends it.
/// What: a static Markdown section joined with [`SECTION_SEPARATOR`] in the
/// `DailyDriver` arm of [`assemble_system_prompt_for_mode`], and only when the
/// run's registry carries every tool it names ([`DISCOVERY_GUIDANCE_TOOLS`]).
/// Test: `prompt::tests::daily_driver_appends_discovery_guidance`,
/// `prompt::tests::parity_omits_discovery_guidance`.
pub const DISCOVERY_GUIDANCE: &str = "## Code discovery\n\n\
Prefer the `search_code` tool for CONCEPTUAL discovery — \"where is X\", \"how \
does Y work\", \"what calls Z\", \"find the code that does <behaviour>\". It is \
backed by trusty-search (semantic + call-graph indexing) and finds code by \
meaning, not just literal text.\n\n\
Use the local `grep` and `glob` tools when you already know the exact text — a \
specific symbol name, a literal string, or a filename/path glob.\n\n\
If `search_code` reports that trusty-search is unavailable, silently fall back \
to `grep`/`glob` for the same query — do not retry `search_code`.";

/// Tool names [`FILE_DISCOVERY_GUIDANCE`] instructs the model to call (#4602).
///
/// Why: a prompt section that names a tool the run's registry does not hold is
/// an instruction the model cannot obey — the call it emits fails validation as
/// `ToolCallExtractError::UnknownTool`. Declaring the names beside the section
/// is what lets [`assemble_system_prompt_for_mode`] check them and lets the
/// regression test check every name the guidance actually mentions.
/// What: the exact backtick-quoted tool names appearing in the section text.
/// Test: `prompt::tests::guidance_never_names_an_unregistered_tool`,
/// `prompt::tests::every_gated_section_declares_the_tools_it_names`.
pub const FILE_DISCOVERY_TOOLS: &[&str] = &["glob", "grep", "list_dir"];

/// Tool names [`DISCOVERY_GUIDANCE`] instructs the model to call (#4602).
///
/// Why/What/Test: as [`FILE_DISCOVERY_TOOLS`], for the `search_code` section.
pub const DISCOVERY_GUIDANCE_TOOLS: &[&str] = &["search_code", "grep", "glob"];

/// Tool names [`BATCH_WRITE_GUIDANCE`] instructs the model to call (#4602).
///
/// Why/What/Test: as [`FILE_DISCOVERY_TOOLS`], for the batch-write section.
pub const BATCH_WRITE_TOOLS: &[&str] = &["write_file", "write_files"];

/// Every registry-gated section paired with the tool names it declares (#4602).
///
/// Why: the gate and its tests must range over the SAME set — a section added
/// to the assembler but missing here would silently escape both. Pairing the
/// text with its list in one table is what lets
/// `every_gated_section_declares_the_tools_it_names` check the hand-maintained
/// lists against the prose they describe.
/// What: `(section text, declared tool names, DailyDriver-only)` for all three
/// gated sections, in the order [`assemble_system_prompt_for_mode`] appends
/// them. Only [`DISCOVERY_GUIDANCE`] is DailyDriver-only: `search_code` is
/// itself registered only in that mode.
/// Test: `prompt::tests::every_gated_section_declares_the_tools_it_names`.
pub const GATED_SECTIONS: &[(&str, &[&str], bool)] = &[
    (FILE_DISCOVERY_GUIDANCE, FILE_DISCOVERY_TOOLS, false),
    (BATCH_WRITE_GUIDANCE, BATCH_WRITE_TOOLS, false),
    (DISCOVERY_GUIDANCE, DISCOVERY_GUIDANCE_TOOLS, true),
];

/// Whether `tools` carries every name a guidance section mentions (#4602).
///
/// Why: a discovery section is all-or-nothing — its advice ("use `search_code`
/// for concepts, `grep`/`glob` for literals") is only coherent when the whole
/// set is callable, and emitting a partial version would still name a tool the
/// model cannot call.
/// What: `false` when `tools` is `None` (the caller knows of no registry, so no
/// tool name is safe to emit), else every name in `names` must be registered.
/// Test: `prompt::tests::guidance_never_names_an_unregistered_tool`.
fn registry_carries_all(tools: Option<&ToolRegistry>, names: &[&str]) -> bool {
    tools.is_some_and(|reg| names.iter().all(|name| reg.contains(name)))
}

/// Append `section` to `out` behind the shared [`SECTION_SEPARATOR`].
fn push_section(out: &mut String, section: &str) {
    out.push_str(SECTION_SEPARATOR);
    out.push_str(section);
}

/// Assembles the parity system prompt from its constituent sections.
///
/// Why: A named type gives call sites (the agent loop, the parity report) a
/// single, discoverable entry point and room to grow — e.g. to also surface the
/// per-section hashes the parity report records (spec D5) — without changing the
/// free-function signature callers already use.
/// What: A zero-sized struct whose [`PromptAssembler::assemble`] method forwards
/// to [`assemble_system_prompt`]. Holds no state, honouring the crate's
/// no-global-state convention.
/// Test: `prompt::tests::assembler_struct_matches_free_function`.
#[derive(Debug, Clone, Copy, Default)]
pub struct PromptAssembler;

impl PromptAssembler {
    /// Assemble the system prompt for the given agent.
    ///
    /// Why: Provides the OO-style entry point that mirrors the free function so
    /// callers may hold an assembler instance if they prefer.
    /// What: Delegates verbatim to [`assemble_system_prompt`].
    /// Test: `prompt::tests::assembler_struct_matches_free_function`.
    pub fn assemble(
        &self,
        config: &AgentConfig,
        project_context: Option<&str>,
        fallback_guidance: Option<&str>,
    ) -> String {
        assemble_system_prompt(config, project_context, fallback_guidance)
    }
}

/// Assemble the parity system prompt in the spec's stable, fixed order.
///
/// Why: The model-comparison harness (parity-spec §1) requires that, for a
/// given agent and task, every byte of the assembled prompt except the
/// documented fallback exception is identical across models. A single
/// deterministic assembler with a fixed section order is how that guarantee is
/// realised.
/// What: Concatenates, in this order (spec §2): (1) [`BASE_PREAMBLE`],
/// (2) `config.system_prompt.content` if non-empty, (3) `project_context`
/// (verbatim `CLAUDE.md`, spec §2c/D1) if `Some` and non-empty, (4)
/// `fallback_guidance` (the §4 per-tier exception, supplied by #1023) if `Some`
/// and non-empty. Sections are joined by [`SECTION_SEPARATOR`]; empty sections
/// contribute neither text nor a separator, so the common native-tool case is
/// exactly sections 1→2→3 (spec D4) with no dangling rules.
/// Test: `prompt::tests::assembled_order_is_stable`,
/// `base_identical_across_calls`,
/// `omitted_sections_produce_no_double_separator`,
/// `empty_agent_prompt_skipped`, `fallback_guidance_is_last`.
pub fn assemble_system_prompt(
    config: &AgentConfig,
    project_context: Option<&str>,
    fallback_guidance: Option<&str>,
) -> String {
    // Collect the sections in fixed order, dropping any that are empty so the
    // separator never doubles up (spec §2c: "the separator collapses").
    let agent_prompt = config.system_prompt.content.trim();
    let project = project_context.map(str::trim).unwrap_or("");
    let fallback = fallback_guidance.map(str::trim).unwrap_or("");

    let mut sections: Vec<&str> = Vec::with_capacity(4);
    sections.push(BASE_PREAMBLE);
    if !agent_prompt.is_empty() {
        sections.push(agent_prompt);
    }
    if !project.is_empty() {
        sections.push(project);
    }
    if !fallback.is_empty() {
        sections.push(fallback);
    }

    sections.join(SECTION_SEPARATOR)
}

/// Mode-aware prompt assembly — the CONSUMPTION POINT #2059 wired up for
/// P1B's token-efficiency work; #2069 is the first arm to actually land in
/// it (progressive-disclosure skill loading).
///
/// Why: vision spec §5.9 resolves the parity/daily-driver split at the
/// prompt-assembly and tool-schema layers. This function is where the
/// prompt-assembly half of that branch lives — a single seam both call
/// sites (`task::executor`, `runner::in_process::InProcessAgentRunner::run_pipeline`)
/// go through, so a token-efficiency change lands in ONE arm without
/// touching either caller's call shape beyond the one new argument.
/// What: `HarnessMode::Parity` calls [`assemble_system_prompt`] verbatim and
/// ignores `skills_catalog` entirely — this is contractually permanent,
/// since parity-spec D2 requires byte-identical schemas/prompts for
/// benchmark fairness and must never progressively disclose (#2069's own
/// scope note: "Parity mode should NOT progressively disclose").
/// Both modes then append [`FILE_DISCOVERY_GUIDANCE`] and
/// [`BATCH_WRITE_GUIDANCE`], and `DailyDriver` appends two further trailing
/// sections via the same [`SECTION_SEPARATOR`] every other section uses:
/// (1) [`DISCOVERY_GUIDANCE`] (PR A, #2689), steering the model to the
/// `search_code` tool for conceptual discovery; then (2) `skills_catalog` (the
/// cheap, always-cached `skills::format_skill_catalog` output — NOT any skill's
/// full body) when non-empty. `Parity` appends neither of those two, keeping
/// its schema/prompt byte-identical for benchmark fairness.
///
/// #4602: every section in [`GATED_SECTIONS`] is emitted ONLY when `tools`
/// carries every tool that section names, so the top-level PM — whose registry
/// holds harness tools only — is never told to call
/// `glob`/`grep`/`list_dir`/`search_code`/`write_files`. `None` means the
/// caller knows of no registry and no tool-instructing section is emitted. This
/// gates on the registry, never on the model, so a parity run's prompt stays
/// byte-identical across models.
/// Test: `prompt::tests::daily_driver_appends_discovery_guidance`,
/// `prompt::tests::daily_driver_appends_skills_catalog`,
/// `prompt::tests::parity_ignores_skills_catalog`,
/// `prompt::tests::parity_omits_discovery_guidance`,
/// `prompt::tests::guidance_never_names_an_unregistered_tool`.
pub fn assemble_system_prompt_for_mode(
    mode: crate::mode::HarnessMode,
    config: &AgentConfig,
    project_context: Option<&str>,
    fallback_guidance: Option<&str>,
    skills_catalog: Option<&str>,
    tools: Option<&ToolRegistry>,
) -> String {
    let daily_driver = mode == crate::mode::HarnessMode::DailyDriver;
    let mut out = assemble_system_prompt(config, project_context, fallback_guidance);
    // #4602: every tool-instructing section is registry-gated. Most apply in
    // BOTH modes — a Parity engineer carries those tools and still needs the
    // blocks that tell it to use them.
    for (section, names, daily_driver_only) in GATED_SECTIONS {
        if (*daily_driver_only && !daily_driver) || !registry_carries_all(tools, names) {
            continue;
        }
        push_section(&mut out, section);
    }
    // The skills catalog instructs no tcode tool call, so it is appended
    // whenever DailyDriver supplies a non-empty one.
    if daily_driver && let Some(catalog) = skills_catalog.map(str::trim).filter(|s| !s.is_empty()) {
        push_section(&mut out, catalog);
    }
    out
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;