Skip to main content

trusty_code/prompt/
assembler.rs

1//! System-prompt assembler — composes the fixed-order parity prompt.
2//!
3//! Why: The cross-model harness must assemble a system prompt whose only
4//! intentional per-model variation is the optional tool-use fallback guidance
5//! (parity-spec §1, §2). Centralising assembly here guarantees the stable,
6//! fixed section order the spec requires (§2) and the trusty-mpm-style
7//! `\n\n---\n\n` separators (§2), so two runs of the same task differ only by
8//! the model.
9//! What: [`PromptAssembler`] and the free function [`assemble_system_prompt`],
10//! which concatenate up to four sections — BASE preamble, agent prompt,
11//! project/`CLAUDE.md` context, and fallback guidance — joining only the
12//! non-empty ones with the section separator.
13//! Test: `prompt::tests` covers stable order, idempotence, separator collapse,
14//! empty-section skipping, and fallback-guidance ordering.
15
16use crate::agents::AgentConfig;
17use crate::prompt::preamble::BASE_PREAMBLE;
18
19/// Section separator between assembled prompt blocks (parity-spec §2).
20///
21/// Why: The spec fixes the separator as the same Markdown horizontal rule that
22/// trusty-mpm uses, for visual and diff consistency across the two harnesses.
23/// What: The literal `"\n\n---\n\n"`.
24/// Test: `prompt::tests::omitted_sections_produce_no_double_separator` depends
25/// on this exact value.
26const SECTION_SEPARATOR: &str = "\n\n---\n\n";
27
28/// Assembles the parity system prompt from its constituent sections.
29///
30/// Why: A named type gives call sites (the agent loop, the parity report) a
31/// single, discoverable entry point and room to grow — e.g. to also surface the
32/// per-section hashes the parity report records (spec D5) — without changing the
33/// free-function signature callers already use.
34/// What: A zero-sized struct whose [`PromptAssembler::assemble`] method forwards
35/// to [`assemble_system_prompt`]. Holds no state, honouring the crate's
36/// no-global-state convention.
37/// Test: `prompt::tests::assembler_struct_matches_free_function`.
38#[derive(Debug, Clone, Copy, Default)]
39pub struct PromptAssembler;
40
41impl PromptAssembler {
42    /// Assemble the system prompt for the given agent.
43    ///
44    /// Why: Provides the OO-style entry point that mirrors the free function so
45    /// callers may hold an assembler instance if they prefer.
46    /// What: Delegates verbatim to [`assemble_system_prompt`].
47    /// Test: `prompt::tests::assembler_struct_matches_free_function`.
48    pub fn assemble(
49        &self,
50        config: &AgentConfig,
51        project_context: Option<&str>,
52        fallback_guidance: Option<&str>,
53    ) -> String {
54        assemble_system_prompt(config, project_context, fallback_guidance)
55    }
56}
57
58/// Assemble the parity system prompt in the spec's stable, fixed order.
59///
60/// Why: The model-comparison harness (parity-spec §1) requires that, for a
61/// given agent and task, every byte of the assembled prompt except the
62/// documented fallback exception is identical across models. A single
63/// deterministic assembler with a fixed section order is how that guarantee is
64/// realised.
65/// What: Concatenates, in this order (spec §2): (1) [`BASE_PREAMBLE`],
66/// (2) `config.system_prompt.content` if non-empty, (3) `project_context`
67/// (verbatim `CLAUDE.md`, spec §2c/D1) if `Some` and non-empty, (4)
68/// `fallback_guidance` (the §4 per-tier exception, supplied by #1023) if `Some`
69/// and non-empty. Sections are joined by [`SECTION_SEPARATOR`]; empty sections
70/// contribute neither text nor a separator, so the common native-tool case is
71/// exactly sections 1→2→3 (spec D4) with no dangling rules.
72/// Test: `prompt::tests::assembled_order_is_stable`,
73/// `base_identical_across_calls`,
74/// `omitted_sections_produce_no_double_separator`,
75/// `empty_agent_prompt_skipped`, `fallback_guidance_is_last`.
76pub fn assemble_system_prompt(
77    config: &AgentConfig,
78    project_context: Option<&str>,
79    fallback_guidance: Option<&str>,
80) -> String {
81    // Collect the sections in fixed order, dropping any that are empty so the
82    // separator never doubles up (spec §2c: "the separator collapses").
83    let agent_prompt = config.system_prompt.content.trim();
84    let project = project_context.map(str::trim).unwrap_or("");
85    let fallback = fallback_guidance.map(str::trim).unwrap_or("");
86
87    let mut sections: Vec<&str> = Vec::with_capacity(4);
88    sections.push(BASE_PREAMBLE);
89    if !agent_prompt.is_empty() {
90        sections.push(agent_prompt);
91    }
92    if !project.is_empty() {
93        sections.push(project);
94    }
95    if !fallback.is_empty() {
96        sections.push(fallback);
97    }
98
99    sections.join(SECTION_SEPARATOR)
100}
101
102/// Mode-aware prompt assembly — the CONSUMPTION POINT #2059 wired up for
103/// P1B's token-efficiency work; #2069 is the first arm to actually land in
104/// it (progressive-disclosure skill loading).
105///
106/// Why: vision spec §5.9 resolves the parity/daily-driver split at the
107/// prompt-assembly and tool-schema layers. This function is where the
108/// prompt-assembly half of that branch lives — a single seam both call
109/// sites (`task::executor`, `runner::in_process::InProcessAgentRunner::run_pipeline`)
110/// go through, so a token-efficiency change lands in ONE arm without
111/// touching either caller's call shape beyond the one new argument.
112/// What: `HarnessMode::Parity` calls [`assemble_system_prompt`] verbatim and
113/// ignores `skills_catalog` entirely — this is contractually permanent,
114/// since parity-spec D2 requires byte-identical schemas/prompts for
115/// benchmark fairness and must never progressively disclose (#2069's own
116/// scope note: "Parity mode should NOT progressively disclose").
117/// `HarnessMode::DailyDriver` appends `skills_catalog` (the cheap,
118/// always-cached `skills::format_skill_catalog` output — NOT any skill's
119/// full body) as a trailing section when non-empty, via the same
120/// [`SECTION_SEPARATOR`] every other section uses; when `skills_catalog` is
121/// `None` or empty, `DailyDriver` output is still byte-identical to
122/// `Parity`, preserving the pre-#2069 M1 contract for projects with no
123/// `.claude/skills/` catalog.
124/// Test: `prompt::tests::assemble_system_prompt_for_mode_identical_when_no_skills`,
125/// `prompt::tests::daily_driver_appends_skills_catalog`,
126/// `prompt::tests::parity_ignores_skills_catalog`.
127pub fn assemble_system_prompt_for_mode(
128    mode: crate::mode::HarnessMode,
129    config: &AgentConfig,
130    project_context: Option<&str>,
131    fallback_guidance: Option<&str>,
132    skills_catalog: Option<&str>,
133) -> String {
134    let base = assemble_system_prompt(config, project_context, fallback_guidance);
135    match mode {
136        crate::mode::HarnessMode::Parity => base,
137        crate::mode::HarnessMode::DailyDriver => {
138            match skills_catalog.map(str::trim).filter(|s| !s.is_empty()) {
139                Some(catalog) => format!("{base}{SECTION_SEPARATOR}{catalog}"),
140                None => base,
141            }
142        }
143    }
144}
145
146#[cfg(test)]
147#[path = "tests.rs"]
148mod tests;