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/// DailyDriver-only discovery guidance (PR A, #2689) appended as a trailing
29/// section, mirroring the `skills_catalog` pattern.
30///
31/// Why: the engineer gains a trusty-search-backed `search_code` tool in
32/// DailyDriver mode; without steering, models default to shelling out or to the
33/// literal `grep`/`glob` tools even for conceptual questions. This section
34/// tells the model when to reach for semantic/call-graph discovery vs. exact
35/// literal search, and to fall back silently when trusty-search is unavailable.
36/// It is intentionally NOT in [`BASE_PREAMBLE`]: the parity spec forbids
37/// MCP/tool catalogs there, so the preamble hash must not change. Parity mode
38/// never appends it.
39/// What: a static Markdown section joined with [`SECTION_SEPARATOR`] in the
40/// `DailyDriver` arm of [`assemble_system_prompt_for_mode`].
41/// Test: `prompt::tests::daily_driver_appends_discovery_guidance`,
42/// `prompt::tests::parity_omits_discovery_guidance`.
43pub const DISCOVERY_GUIDANCE: &str = "## Code discovery\n\n\
44Prefer the `search_code` tool for CONCEPTUAL discovery — \"where is X\", \"how \
45does Y work\", \"what calls Z\", \"find the code that does <behaviour>\". It is \
46backed by trusty-search (semantic + call-graph indexing) and finds code by \
47meaning, not just literal text.\n\n\
48Use the local `grep` and `glob` tools when you already know the exact text — a \
49specific symbol name, a literal string, or a filename/path glob.\n\n\
50If `search_code` reports that trusty-search is unavailable, silently fall back \
51to `grep`/`glob` for the same query — do not retry `search_code`.";
52
53/// Assembles the parity system prompt from its constituent sections.
54///
55/// Why: A named type gives call sites (the agent loop, the parity report) a
56/// single, discoverable entry point and room to grow — e.g. to also surface the
57/// per-section hashes the parity report records (spec D5) — without changing the
58/// free-function signature callers already use.
59/// What: A zero-sized struct whose [`PromptAssembler::assemble`] method forwards
60/// to [`assemble_system_prompt`]. Holds no state, honouring the crate's
61/// no-global-state convention.
62/// Test: `prompt::tests::assembler_struct_matches_free_function`.
63#[derive(Debug, Clone, Copy, Default)]
64pub struct PromptAssembler;
65
66impl PromptAssembler {
67    /// Assemble the system prompt for the given agent.
68    ///
69    /// Why: Provides the OO-style entry point that mirrors the free function so
70    /// callers may hold an assembler instance if they prefer.
71    /// What: Delegates verbatim to [`assemble_system_prompt`].
72    /// Test: `prompt::tests::assembler_struct_matches_free_function`.
73    pub fn assemble(
74        &self,
75        config: &AgentConfig,
76        project_context: Option<&str>,
77        fallback_guidance: Option<&str>,
78    ) -> String {
79        assemble_system_prompt(config, project_context, fallback_guidance)
80    }
81}
82
83/// Assemble the parity system prompt in the spec's stable, fixed order.
84///
85/// Why: The model-comparison harness (parity-spec §1) requires that, for a
86/// given agent and task, every byte of the assembled prompt except the
87/// documented fallback exception is identical across models. A single
88/// deterministic assembler with a fixed section order is how that guarantee is
89/// realised.
90/// What: Concatenates, in this order (spec §2): (1) [`BASE_PREAMBLE`],
91/// (2) `config.system_prompt.content` if non-empty, (3) `project_context`
92/// (verbatim `CLAUDE.md`, spec §2c/D1) if `Some` and non-empty, (4)
93/// `fallback_guidance` (the §4 per-tier exception, supplied by #1023) if `Some`
94/// and non-empty. Sections are joined by [`SECTION_SEPARATOR`]; empty sections
95/// contribute neither text nor a separator, so the common native-tool case is
96/// exactly sections 1→2→3 (spec D4) with no dangling rules.
97/// Test: `prompt::tests::assembled_order_is_stable`,
98/// `base_identical_across_calls`,
99/// `omitted_sections_produce_no_double_separator`,
100/// `empty_agent_prompt_skipped`, `fallback_guidance_is_last`.
101pub fn assemble_system_prompt(
102    config: &AgentConfig,
103    project_context: Option<&str>,
104    fallback_guidance: Option<&str>,
105) -> String {
106    // Collect the sections in fixed order, dropping any that are empty so the
107    // separator never doubles up (spec §2c: "the separator collapses").
108    let agent_prompt = config.system_prompt.content.trim();
109    let project = project_context.map(str::trim).unwrap_or("");
110    let fallback = fallback_guidance.map(str::trim).unwrap_or("");
111
112    let mut sections: Vec<&str> = Vec::with_capacity(4);
113    sections.push(BASE_PREAMBLE);
114    if !agent_prompt.is_empty() {
115        sections.push(agent_prompt);
116    }
117    if !project.is_empty() {
118        sections.push(project);
119    }
120    if !fallback.is_empty() {
121        sections.push(fallback);
122    }
123
124    sections.join(SECTION_SEPARATOR)
125}
126
127/// Mode-aware prompt assembly — the CONSUMPTION POINT #2059 wired up for
128/// P1B's token-efficiency work; #2069 is the first arm to actually land in
129/// it (progressive-disclosure skill loading).
130///
131/// Why: vision spec §5.9 resolves the parity/daily-driver split at the
132/// prompt-assembly and tool-schema layers. This function is where the
133/// prompt-assembly half of that branch lives — a single seam both call
134/// sites (`task::executor`, `runner::in_process::InProcessAgentRunner::run_pipeline`)
135/// go through, so a token-efficiency change lands in ONE arm without
136/// touching either caller's call shape beyond the one new argument.
137/// What: `HarnessMode::Parity` calls [`assemble_system_prompt`] verbatim and
138/// ignores `skills_catalog` entirely — this is contractually permanent,
139/// since parity-spec D2 requires byte-identical schemas/prompts for
140/// benchmark fairness and must never progressively disclose (#2069's own
141/// scope note: "Parity mode should NOT progressively disclose").
142/// `HarnessMode::DailyDriver` appends two trailing sections via the same
143/// [`SECTION_SEPARATOR`] every other section uses: (1) [`DISCOVERY_GUIDANCE`]
144/// (PR A, #2689) — always present, steering the model to the `search_code`
145/// tool for conceptual discovery; then (2) `skills_catalog` (the cheap,
146/// always-cached `skills::format_skill_catalog` output — NOT any skill's full
147/// body) when non-empty. `Parity` appends neither, keeping its schema/prompt
148/// byte-identical for benchmark fairness.
149/// Test: `prompt::tests::daily_driver_appends_discovery_guidance`,
150/// `prompt::tests::daily_driver_appends_skills_catalog`,
151/// `prompt::tests::parity_ignores_skills_catalog`,
152/// `prompt::tests::parity_omits_discovery_guidance`.
153pub fn assemble_system_prompt_for_mode(
154    mode: crate::mode::HarnessMode,
155    config: &AgentConfig,
156    project_context: Option<&str>,
157    fallback_guidance: Option<&str>,
158    skills_catalog: Option<&str>,
159) -> String {
160    let base = assemble_system_prompt(config, project_context, fallback_guidance);
161    match mode {
162        crate::mode::HarnessMode::Parity => base,
163        crate::mode::HarnessMode::DailyDriver => {
164            // Discovery guidance (PR A) is always present in DailyDriver; the
165            // skills catalog is appended after it only when non-empty.
166            let mut out = format!("{base}{SECTION_SEPARATOR}{DISCOVERY_GUIDANCE}");
167            if let Some(catalog) = skills_catalog.map(str::trim).filter(|s| !s.is_empty()) {
168                out.push_str(SECTION_SEPARATOR);
169                out.push_str(catalog);
170            }
171            out
172        }
173    }
174}
175
176#[cfg(test)]
177#[path = "tests.rs"]
178mod tests;