Skip to main content

merry_coding/
profile_hash.rs

1//! Stable identity of a coding-agent composition profile.
2//!
3//! The hash answers one question: would two runs send the same provider-visible
4//! prefix and the same tool contract? Everything that shapes that prefix is
5//! folded into one byte string in a fixed field order, so a change to prompt
6//! text, layouts, retry policy, workspace roots, context summaries, project
7//! rules, skills, or any registered tool specification produces a different
8//! identity. Dynamic context is deliberately excluded, because a task anchor or
9//! checkpoint must not look like a different profile.
10//!
11//! Field names and their order are part of the contract: they make two
12//! different values distinguishable (`ab` + `c` hashes differently from `a` +
13//! `bc`), and reordering or renaming a field is a compatibility change.
14
15use std::fmt;
16
17use merry_runtime::{RuntimeProfile, ToolActionKind, ToolConcurrency, ToolRunner};
18use serde_json::Error as JsonError;
19
20use crate::{
21    CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT, CODING_AGENT_PROFILE_ID,
22    CODING_AGENT_STABLE_PREFIX_LAYOUT, CodingAgentRunPolicy,
23};
24
25/// Stable identity of a shared coding-agent composition profile.
26#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct CodingAgentProfileHash(String);
28
29impl CodingAgentProfileHash {
30    /// Borrows the stable profile hash label.
31    #[must_use]
32    pub fn as_str(&self) -> &str {
33        &self.0
34    }
35}
36
37impl fmt::Display for CodingAgentProfileHash {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        formatter.write_str(&self.0)
40    }
41}
42
43/// Hashes every provider-visible part of one coding-agent composition.
44///
45/// `workspace_hash_material` is produced by the workspace profile builder,
46/// which owns the workspace fields and their own field names. Failures come
47/// from serializing a tool specification, which is the only value here that
48/// cannot be folded in as bytes directly.
49pub(crate) fn coding_agent_profile_hash(
50    profile: &RuntimeProfile,
51    run_policy: CodingAgentRunPolicy,
52    workspace_hash_material: &[u8],
53) -> Result<CodingAgentProfileHash, JsonError> {
54    let mut material = Vec::new();
55    append_hash_field(&mut material, "profile-id", CODING_AGENT_PROFILE_ID);
56    material.extend_from_slice(workspace_hash_material);
57    append_hash_field(
58        &mut material,
59        "stable-layout",
60        CODING_AGENT_STABLE_PREFIX_LAYOUT,
61    );
62    append_hash_field(
63        &mut material,
64        "dynamic-layout",
65        CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT,
66    );
67    append_hash_field(
68        &mut material,
69        "prompt-base",
70        profile.prompt_profile().base_instructions(),
71    );
72    append_hash_field(
73        &mut material,
74        "prompt-progress",
75        profile.prompt_profile().progress_commentary_instructions(),
76    );
77    for block in profile.prompt_profile().stable_blocks() {
78        append_hash_field(&mut material, "prompt-block-tag", block.tag());
79        append_hash_field(&mut material, "prompt-block-text", block.text());
80    }
81    append_hash_field(
82        &mut material,
83        "run-max-model-turns",
84        &run_policy.max_model_turns().to_string(),
85    );
86    append_hash_field(
87        &mut material,
88        "run-final-report",
89        run_policy.final_report().as_str(),
90    );
91    append_model_retry_policy(&mut material, profile.model_retry_policy().as_ref());
92    append_hash_field(
93        &mut material,
94        "progress-commentary",
95        on_or_off(profile.progress_commentary()),
96    );
97    append_hash_field(
98        &mut material,
99        "bridge-tools",
100        on_or_off(profile.allow_bridge_tools()),
101    );
102    append_hash_field(
103        &mut material,
104        "workspace-patches",
105        on_or_off(profile.allow_low_risk_apply_patches()),
106    );
107    append_hash_field(
108        &mut material,
109        "low-risk-process",
110        on_or_off(profile.low_risk_process_runner().is_some()),
111    );
112    append_hash_field(
113        &mut material,
114        "read-only-process",
115        on_or_off(profile.read_only_shell_process_runner().is_some()),
116    );
117    append_hash_field(
118        &mut material,
119        "accepted-process",
120        on_or_off(profile.accepted_local_workspace_process_runner().is_some()),
121    );
122    append_hash_field(
123        &mut material,
124        "permissioned-process",
125        on_or_off(profile.permissioned_process_runner_factory().is_some()),
126    );
127
128    for (id, text) in profile.initial_context_summaries() {
129        append_hash_field(&mut material, "initial-context-id", id);
130        append_hash_field(&mut material, "initial-context-text", text);
131    }
132    if let Some(project_rules) = profile.project_rules() {
133        append_hash_field(
134            &mut material,
135            "project-rules-source",
136            project_rules.source_path(),
137        );
138        append_hash_field(
139            &mut material,
140            "project-rules-hash",
141            project_rules.content_hash(),
142        );
143        append_hash_field(
144            &mut material,
145            "project-rules-stable-text",
146            &project_rules.to_stable_prefix_message_text(),
147        );
148    }
149    if let Some(skill_catalog) = profile.skill_catalog()
150        && let Some(text) = skill_catalog.to_stable_prefix_message_text()
151    {
152        append_hash_field(&mut material, "skill-catalog", &text);
153    }
154
155    // Task anchors and checkpoints are intentionally excluded: they are dynamic
156    // runtime context and must not invalidate the stable profile identity.
157    for tool in profile.registered_tools() {
158        let spec = serde_json::to_string(tool.spec())?;
159        append_hash_field(&mut material, "tool-spec", &spec);
160        append_hash_field(
161            &mut material,
162            "tool-action-kind",
163            tool_action_kind_label(tool.action_kind()),
164        );
165        append_hash_field(
166            &mut material,
167            "tool-runner",
168            tool_runner_label(tool.runner()),
169        );
170        append_hash_field(
171            &mut material,
172            "tool-concurrency",
173            tool_concurrency_label(tool.concurrency()),
174        );
175        append_hash_field(
176            &mut material,
177            "tool-proposals",
178            on_or_off(tool.proposals_enabled()),
179        );
180    }
181
182    Ok(CodingAgentProfileHash(format!(
183        "fnv1a64:{:016x}",
184        fnv1a64(&material)
185    )))
186}
187
188/// Folds the retry policy in, or records that the runtime default applies.
189fn append_model_retry_policy(
190    material: &mut Vec<u8>,
191    retry_policy: Option<&merry_llm::ModelRetryPolicy>,
192) {
193    let Some(retry_policy) = retry_policy else {
194        append_hash_field(material, "retry-policy", "runtime-default");
195        return;
196    };
197    append_hash_field(material, "retry-enabled", on_or_off(retry_policy.enabled()));
198    append_hash_field(
199        material,
200        "retry-max-attempts",
201        &retry_policy.max_attempts().to_string(),
202    );
203    append_hash_field(
204        material,
205        "retry-initial-delay-nanos",
206        &retry_policy.initial_delay().as_nanos().to_string(),
207    );
208    append_hash_field(
209        material,
210        "retry-max-delay-nanos",
211        &retry_policy.max_delay().as_nanos().to_string(),
212    );
213    append_hash_field(
214        material,
215        "retry-max-elapsed-nanos",
216        &retry_policy.max_elapsed().as_nanos().to_string(),
217    );
218    append_hash_field(material, "retry-jitter", on_or_off(retry_policy.jitter()));
219}
220
221/// Appends one length-prefixed, name-tagged field.
222///
223/// The name keeps two adjacent fields from colliding, and the length keeps a
224/// value from absorbing the next field's name.
225fn append_hash_field(material: &mut Vec<u8>, name: &str, value: &str) {
226    material.extend_from_slice(name.as_bytes());
227    material.push(0);
228    material.extend_from_slice(&(value.len() as u64).to_be_bytes());
229    material.extend_from_slice(value.as_bytes());
230}
231
232fn fnv1a64(bytes: &[u8]) -> u64 {
233    let mut hash = 0xcbf29ce484222325_u64;
234    for byte in bytes {
235        hash = (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3);
236    }
237    hash
238}
239
240fn on_or_off(enabled: bool) -> &'static str {
241    if enabled { "on" } else { "off" }
242}
243
244fn tool_action_kind_label(kind: ToolActionKind) -> &'static str {
245    match kind {
246        ToolActionKind::ReadOnly => "read_only",
247        ToolActionKind::RuntimeControl => "runtime_control",
248        ToolActionKind::WorkspaceWrite => "workspace_write",
249        ToolActionKind::CommandExec => "command_exec",
250        ToolActionKind::Network => "network",
251        ToolActionKind::TrustedExternal => "trusted_external",
252    }
253}
254
255fn tool_runner_label(runner: ToolRunner) -> &'static str {
256    match runner {
257        ToolRunner::Runtime => "runtime",
258        ToolRunner::Bridge => "bridge",
259    }
260}
261
262fn tool_concurrency_label(concurrency: ToolConcurrency) -> &'static str {
263    match concurrency {
264        ToolConcurrency::ParallelSafe => "parallel_safe",
265        ToolConcurrency::Exclusive => "exclusive",
266    }
267}