Skip to main content

merry_coding/
lib.rs

1//! Provider-neutral coding composition for Merry.
2//!
3//! This crate is the single owner of coding composition: the parent runtime
4//! builder, child-runtime inputs, workspace tools, project-rule and skill
5//! projections, process admission lanes, tool order, and stable composition
6//! identity. The facade and CLI consume these types rather than assembling a
7//! second coding policy.
8
9mod child_runtime;
10mod policy_prompt;
11mod profile_hash;
12mod project_capabilities;
13mod project_rules;
14mod runtime;
15mod search_tools;
16mod subagent_roles;
17mod workflow_commands;
18mod workspace;
19mod worktree;
20
21#[cfg(test)]
22mod tests;
23
24pub use policy_prompt::{
25    CODING_AGENT_POLICY_PROMPT, builtin_subagent_role_instructions, coding_subagent_policy_prompt,
26};
27pub use profile_hash::CodingAgentProfileHash;
28pub use project_rules::{
29    MAX_ROOT_PROJECT_RULES_BYTES, ProjectRulesLoadError, ROOT_PROJECT_RULES_FILE,
30    load_root_project_rules,
31};
32pub use runtime::{
33    CodingAutoFallback, CodingModelRoleConfig, CodingModelRoleConfigError, CodingPermissionMode,
34    CodingPermissionPolicy, CodingPermissionPolicyError, CodingRuntime, CodingRuntimeBuildError,
35    CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
36};
37pub use subagent_roles::{
38    MAX_ROLE_PROMPT_FILE_BYTES, ResolvedSubagentRuntime, SubagentDefaultOverride,
39    SubagentModelOverride, SubagentResolutionInput, SubagentRoleCatalog, SubagentRoleError,
40    SubagentRoleOverlay, SubagentRoleSpec, SubagentWorkspaceAccess, load_workspace_prompt_file,
41    resolve_subagent_runtime,
42};
43pub use workflow_commands::CodingWorkflowCommand;
44pub use worktree::{
45    WorktreeError, WorktreeGcReport, WorktreeIsolationManager, cleanup_orphaned_worktrees,
46    cleanup_orphaned_worktrees_default, default_worktree_base_dir,
47};
48
49use merry_core::{CoreError, ToolName};
50use merry_llm::ModelRetryPolicy;
51use merry_process::ProcessSession;
52use merry_runtime::{
53    AgentLoopConfig, DurableMemory, PermissionAdmissionError, ProcessCommandToolError,
54    ProcessRunner, ProjectRules, PromptBlock, PromptError, PromptProfile, RegisteredTool,
55    RuntimeBuilder, RuntimeError, RuntimeProfile, RuntimeProfileError, SkillCatalog, TaskAnchor,
56    Tool, ToolBuildError,
57};
58pub use merry_tools::{WorkspaceToolConfigError, WorkspaceToolLimits};
59use serde_json::Error as JsonError;
60use std::{path::PathBuf, sync::Arc};
61use thiserror::Error;
62use workspace::{WorkspaceCodingProfileBuildError, WorkspaceCodingProfileBuilder};
63
64use profile_hash::coding_agent_profile_hash;
65
66/// Stable identity of the provider-neutral coding profile contract.
67pub const CODING_AGENT_PROFILE_ID: &str = "coding-agent-profile";
68
69/// Stable provider-prefix layout owned by the runtime coding composition.
70pub const CODING_AGENT_STABLE_PREFIX_LAYOUT: &str =
71    "runtime-instructions|progress-commentary|skill-catalog|project-rules|tools";
72
73/// Dynamic provider-context layout owned by the runtime coding composition.
74pub const CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT: &str =
75    "checkpoint|task-anchor|plan-control|compiled-context|transcript|tool-results|user-input";
76
77/// Minimum model-turn budget for a coding-profile child agent.
78pub const MIN_CODING_SUBAGENT_MODEL_TURNS: u32 = 1;
79
80/// Default coding-profile ceiling for one child agent.
81pub const DEFAULT_CODING_SUBAGENT_MAX_MODEL_TURNS: u32 = 80;
82
83/// Maximum model-turn ceiling for the coding-profile main agent.
84pub const DEFAULT_CODING_AGENT_MAX_MODEL_TURNS: usize = usize::MAX;
85
86/// Final-report behavior for a coding-agent run.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub enum CodingFinalReportPolicy {
89    /// Report changes, evidence, verification, blockers, and remaining risks.
90    EvidenceBackedSummary,
91}
92
93impl CodingFinalReportPolicy {
94    /// Returns the stable policy identifier.
95    #[must_use]
96    pub const fn as_str(self) -> &'static str {
97        match self {
98            Self::EvidenceBackedSummary => "evidence_backed_summary",
99        }
100    }
101}
102
103/// Coding-loop recovery and final-report policy.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub struct CodingAgentRunPolicy {
106    max_model_turns: usize,
107    final_report: CodingFinalReportPolicy,
108}
109
110impl CodingAgentRunPolicy {
111    /// Creates a validated coding run policy.
112    pub fn new(
113        max_model_turns: usize,
114        final_report: CodingFinalReportPolicy,
115    ) -> Result<Self, CodingAgentRunPolicyError> {
116        if max_model_turns == 0 {
117            return Err(CodingAgentRunPolicyError::MaxModelTurnsMustBeNonZero);
118        }
119        Ok(Self {
120            max_model_turns,
121            final_report,
122        })
123    }
124
125    /// Returns the maximum number of model turns.
126    #[must_use]
127    pub const fn max_model_turns(self) -> usize {
128        self.max_model_turns
129    }
130
131    /// Returns the final-report policy.
132    #[must_use]
133    pub const fn final_report(self) -> CodingFinalReportPolicy {
134        self.final_report
135    }
136
137    /// Creates the runtime loop configuration owned by this policy.
138    pub fn loop_config(self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
139        AgentLoopConfig::new(self.max_model_turns)
140    }
141}
142
143impl Default for CodingAgentRunPolicy {
144    fn default() -> Self {
145        Self {
146            max_model_turns: DEFAULT_CODING_AGENT_MAX_MODEL_TURNS,
147            final_report: CodingFinalReportPolicy::EvidenceBackedSummary,
148        }
149    }
150}
151
152/// Invalid coding-loop policy.
153#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
154pub enum CodingAgentRunPolicyError {
155    /// A coding loop without a turn budget cannot make progress.
156    #[error("coding agent max_model_turns must be greater than zero")]
157    MaxModelTurnsMustBeNonZero,
158}
159
160/// Returns the shared default coding-agent loop configuration.
161pub fn coding_agent_loop_config() -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
162    CodingAgentRunPolicy::default().loop_config()
163}
164
165/// Creates the shared coding-agent composition builder with one workspace root.
166#[must_use]
167pub fn coding_agent(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
168    CodingAgentProfileBuilder::new(root)
169}
170
171/// One provider-neutral coding-agent composition applied to a runtime builder.
172///
173/// The profile owns the coding tool catalog and its runtime policy settings.
174/// Provider adapters see only the resulting Merry-owned tool specifications;
175/// provider wire types never enter this API. Task anchors, checkpoints,
176/// transcript items, and tool results remain runtime-owned dynamic context.
177#[derive(Clone)]
178pub struct CodingAgentProfile {
179    runtime_profile: RuntimeProfile,
180    profile_hash: CodingAgentProfileHash,
181    run_policy: CodingAgentRunPolicy,
182}
183
184impl CodingAgentProfile {
185    /// Creates a shared coding-agent profile builder.
186    #[must_use]
187    pub fn builder(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
188        CodingAgentProfileBuilder::new(root)
189    }
190
191    /// Applies this profile to a runtime builder.
192    pub fn apply_to(&self, builder: RuntimeBuilder) -> Result<RuntimeBuilder, RuntimeError> {
193        builder.with_profile(self.runtime_profile.clone())
194    }
195
196    /// Creates the shared coding loop configuration for this profile.
197    pub fn loop_config(&self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
198        self.run_policy.loop_config()
199    }
200
201    /// Returns the recovery and final-report policy carried by this profile.
202    #[must_use]
203    pub const fn run_policy(&self) -> CodingAgentRunPolicy {
204        self.run_policy
205    }
206
207    /// Returns the complete runtime profile carried by this composition.
208    #[must_use]
209    pub fn runtime_profile(&self) -> RuntimeProfile {
210        self.runtime_profile.clone()
211    }
212
213    /// Returns the provider-neutral registered tools in their advertised order.
214    #[must_use]
215    pub fn registered_tools(&self) -> &[RegisteredTool] {
216        self.runtime_profile.registered_tools()
217    }
218
219    /// Returns the ordered provider-neutral tool names for diagnostics/tests.
220    #[must_use]
221    pub fn tool_names(&self) -> Vec<&ToolName> {
222        self.registered_tools()
223            .iter()
224            .map(|tool| tool.spec().name())
225            .collect()
226    }
227
228    /// Returns the deterministic identity of the profile's stable composition.
229    #[must_use]
230    pub fn profile_hash(&self) -> &CodingAgentProfileHash {
231        &self.profile_hash
232    }
233}
234
235/// Builder for the single shared coding-agent composition profile.
236#[derive(Clone)]
237pub struct CodingAgentProfileBuilder {
238    workspace: WorkspaceCodingProfileBuilder,
239    retry_policy: Option<ModelRetryPolicy>,
240    run_policy: CodingAgentRunPolicy,
241    allow_bridge_tools: bool,
242    skill_catalog: Option<SkillCatalog>,
243    project_rules: Option<ProjectRules>,
244    task_anchor: Option<TaskAnchor>,
245    prompt_profile_override: Option<PromptProfile>,
246    tools: Vec<Tool>,
247    registered_tools: Vec<RegisteredTool>,
248}
249
250impl CodingAgentProfileBuilder {
251    /// Creates a coding-agent profile builder with one workspace root.
252    #[must_use]
253    pub fn new(root: impl Into<PathBuf>) -> Self {
254        Self {
255            workspace: WorkspaceCodingProfileBuilder::new(root),
256            retry_policy: None,
257            run_policy: CodingAgentRunPolicy::default(),
258            allow_bridge_tools: false,
259            skill_catalog: None,
260            project_rules: None,
261            task_anchor: None,
262            prompt_profile_override: None,
263            tools: Vec::new(),
264            registered_tools: Vec::new(),
265        }
266    }
267
268    /// Returns the configured workspace root path.
269    #[must_use]
270    pub fn workspace_root(&self) -> &std::path::Path {
271        &self.workspace.root
272    }
273
274    /// Replaces the default main-agent prompt profile with a custom profile
275    /// (used by child runtimes to install dedicated subagent instructions and
276    /// role blocks without carrying parent-only policy text).
277    #[must_use]
278    pub fn prompt_profile(mut self, prompt_profile: PromptProfile) -> Self {
279        self.prompt_profile_override = Some(prompt_profile);
280        self
281    }
282
283    /// Replaces the workspace root.
284    #[must_use]
285    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
286        self.workspace = self.workspace.root(root);
287        self
288    }
289
290    /// Adds read-only resource roots that are not the writable workspace root.
291    #[must_use]
292    pub fn readonly_resource_roots<I, P>(mut self, roots: I) -> Self
293    where
294        I: IntoIterator<Item = P>,
295        P: Into<PathBuf>,
296    {
297        self.workspace = self.workspace.readonly_resource_roots(roots);
298        self
299    }
300
301    /// Sets workspace tool limits.
302    #[must_use]
303    pub fn limits(mut self, limits: WorkspaceToolLimits) -> Self {
304        self.workspace = self.workspace.limits(limits);
305        self
306    }
307
308    /// Enables the constrained workspace patch tool.
309    #[must_use]
310    pub fn patch_tool(mut self) -> Self {
311        self.workspace = self.workspace.patch_tool();
312        self
313    }
314
315    /// Enables built-in web and browser verification tools (`web_fetch`, `browser_tab`, `browser_network`).
316    #[must_use]
317    pub fn web_tools(mut self) -> Self {
318        self.workspace = self.workspace.web_tools();
319        self
320    }
321
322    /// Sets workspace-relative paths that `read_file` may read.
323    #[must_use]
324    pub fn read_scope<I, P>(mut self, paths: I) -> Self
325    where
326        I: IntoIterator<Item = P>,
327        P: Into<PathBuf>,
328    {
329        self.workspace = self.workspace.read_scope(paths);
330        self
331    }
332
333    /// Sets workspace-relative paths that `apply_patch` may write.
334    #[must_use]
335    pub fn patch_write_scope<I, P>(mut self, paths: I) -> Self
336    where
337        I: IntoIterator<Item = P>,
338        P: Into<PathBuf>,
339    {
340        self.workspace = self.workspace.patch_write_scope(paths);
341        self
342    }
343
344    /// Denies all `apply_patch` writes.
345    #[must_use]
346    pub fn read_only_patch_scope(mut self) -> Self {
347        self.workspace = self.workspace.read_only_patch_scope();
348        self
349    }
350
351    /// Sets workspace-relative paths that `apply_patch` must never write.
352    #[must_use]
353    pub fn forbidden_paths<I, P>(mut self, paths: I) -> Self
354    where
355        I: IntoIterator<Item = P>,
356        P: Into<PathBuf>,
357    {
358        self.workspace = self.workspace.forbidden_paths(paths);
359        self
360    }
361
362    /// Sets absolute host paths that `read_file` and `apply_patch` must never
363    /// read or modify (such as Merry's private state and credential store).
364    #[must_use]
365    pub fn denied_absolute_paths<I, P>(mut self, paths: I) -> Self
366    where
367        I: IntoIterator<Item = P>,
368        P: Into<PathBuf>,
369    {
370        self.workspace = self.workspace.denied_absolute_paths(paths);
371        self
372    }
373
374    /// Includes read-only process execution lanes.
375    #[must_use]
376    pub fn read_only_process_runner(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
377        self.workspace = self.workspace.read_only_process_runner(runner);
378        self
379    }
380
381    /// Includes one host-process session and its reviewed-action capability.
382    #[must_use]
383    pub fn accepted_process_session(mut self, session: ProcessSession) -> Self {
384        self.workspace = self.workspace.accepted_process_session(session);
385        self
386    }
387
388    /// Sets the provider-neutral retry/recovery policy for model turns.
389    #[must_use]
390    pub fn retry_policy(mut self, retry_policy: ModelRetryPolicy) -> Self {
391        self.retry_policy = Some(retry_policy);
392        self
393    }
394
395    /// Sets coding-loop recovery and final-report policy.
396    #[must_use]
397    pub fn run_policy(mut self, run_policy: CodingAgentRunPolicy) -> Self {
398        self.run_policy = run_policy;
399        self
400    }
401
402    /// Allows explicitly registered bridge tools in this coding profile.
403    #[doc(hidden)]
404    #[must_use]
405    pub fn allow_bridge_tools(mut self) -> Self {
406        self.allow_bridge_tools = true;
407        self
408    }
409
410    /// Adds the stable project rules projection.
411    #[must_use]
412    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
413        self.project_rules = Some(project_rules);
414        self
415    }
416
417    /// Adds stable skill metadata without embedding skill bodies.
418    #[must_use]
419    pub fn skill_catalog(mut self, skill_catalog: SkillCatalog) -> Self {
420        self.skill_catalog = Some(skill_catalog);
421        self
422    }
423
424    /// Adds the dynamic task anchor projection.
425    #[must_use]
426    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
427        self.task_anchor = Some(task_anchor);
428        self
429    }
430
431    /// Adds a typed application tool after the canonical Merry-managed tools.
432    #[must_use]
433    pub fn tool(mut self, tool: Tool) -> Self {
434        self.tools.push(tool);
435        self
436    }
437
438    /// Adds a runtime-owned tool after the canonical workspace tool catalog.
439    #[doc(hidden)]
440    #[must_use]
441    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
442        self.registered_tools.push(tool);
443        self
444    }
445
446    /// Adds runtime-owned tools in the supplied stable order.
447    #[doc(hidden)]
448    #[must_use]
449    pub fn register_tools<I>(mut self, tools: I) -> Self
450    where
451        I: IntoIterator<Item = RegisteredTool>,
452    {
453        self.registered_tools.extend(tools);
454        self
455    }
456
457    /// Attaches the durable memory store shared by parent and child runtimes.
458    ///
459    /// The store supplies the stable memory instructions and the workspace
460    /// tool policy. The frozen index is attached separately on the runtime.
461    #[must_use]
462    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
463        self.workspace = self.workspace.durable_memory(memory);
464        self
465    }
466
467    /// Returns the attached memory store, when this profile has one.
468    #[must_use]
469    pub fn durable_memory_handle(&self) -> Option<Arc<DurableMemory>> {
470        self.workspace.durable_memory.clone()
471    }
472
473    /// Builds the shared coding-agent profile.
474    pub fn build(self) -> Result<CodingAgentProfile, CodingAgentProfileBuildError> {
475        let Self {
476            workspace,
477            retry_policy,
478            run_policy,
479            allow_bridge_tools,
480            skill_catalog,
481            project_rules,
482            task_anchor,
483            prompt_profile_override,
484            tools,
485            registered_tools,
486        } = self;
487        let workspace_hash_material = workspace.hash_material();
488        let memory_instructions = workspace
489            .durable_memory
490            .as_deref()
491            .map(DurableMemory::instructions);
492        let mut prompt_profile = match prompt_profile_override {
493            Some(profile) => profile,
494            None => PromptProfile::default().with_stable_block(PromptBlock::new(
495                "merry_coding_policy",
496                CODING_AGENT_POLICY_PROMPT,
497            )?)?,
498        };
499        if let Some(instructions) = memory_instructions {
500            prompt_profile = prompt_profile
501                .with_stable_block(PromptBlock::new("merry_memory", instructions)?)?;
502        }
503        let mut builder = RuntimeProfile::builder().prompt_profile(prompt_profile);
504        builder = workspace
505            .apply_to_runtime_profile(builder)
506            .map_err(|error| match error {
507                WorkspaceCodingProfileBuildError::WorkspaceTools(source) => {
508                    CodingAgentProfileBuildError::WorkspaceTools(source)
509                }
510                WorkspaceCodingProfileBuildError::ProcessTool(source) => {
511                    CodingAgentProfileBuildError::ProcessTool(source)
512                }
513                WorkspaceCodingProfileBuildError::PermissionTool(source) => {
514                    CodingAgentProfileBuildError::PermissionTool(source)
515                }
516                WorkspaceCodingProfileBuildError::Core(source) => {
517                    CodingAgentProfileBuildError::Core(source)
518                }
519                WorkspaceCodingProfileBuildError::WebToolBuild(source) => {
520                    CodingAgentProfileBuildError::WebToolBuild(source)
521                }
522            })?;
523        if allow_bridge_tools {
524            builder = builder.allow_bridge_tools();
525        }
526        if let Some(retry_policy) = retry_policy {
527            builder = builder.model_retry_policy(retry_policy);
528        }
529        if let Some(skill_catalog) = skill_catalog {
530            builder = builder.skill_catalog(skill_catalog);
531        }
532        if let Some(project_rules) = project_rules {
533            builder = builder.project_rules(project_rules);
534        }
535        if let Some(task_anchor) = task_anchor {
536            builder = builder.task_anchor(task_anchor);
537        }
538        for tool in tools {
539            builder = builder.register_tool(tool.into_registered_tool());
540        }
541        for tool in registered_tools {
542            builder = builder.register_tool(tool);
543        }
544        let runtime_profile = builder.build()?;
545        let profile_hash =
546            coding_agent_profile_hash(&runtime_profile, run_policy, &workspace_hash_material)?;
547        Ok(CodingAgentProfile {
548            runtime_profile,
549            profile_hash,
550            run_policy,
551        })
552    }
553}
554
555/// Errors raised while building the shared coding-agent profile.
556#[derive(Debug, Error)]
557pub enum CodingAgentProfileBuildError {
558    /// Workspace tool configuration was invalid.
559    #[error(transparent)]
560    WorkspaceTools(#[from] WorkspaceToolConfigError),
561    /// The process command tool could not be constructed.
562    #[error(transparent)]
563    ProcessTool(#[from] ProcessCommandToolError),
564    /// The permission request tool could not be constructed.
565    #[error(transparent)]
566    PermissionTool(#[from] PermissionAdmissionError),
567    /// A provider-neutral protocol value failed validation.
568    #[error(transparent)]
569    Core(#[from] CoreError),
570    /// The final runtime profile was invalid.
571    #[error(transparent)]
572    RuntimeProfile(#[from] RuntimeProfileError),
573    /// Profile hash material could not be serialized.
574    #[error("coding agent profile hash material could not be serialized: {0}")]
575    HashSerialization(#[from] JsonError),
576    /// Stable prompt composition was invalid.
577    #[error(transparent)]
578    Prompt(#[from] PromptError),
579    /// A web or browser tool schema failed validation.
580    #[error(transparent)]
581    WebToolBuild(#[from] ToolBuildError),
582}
583
584/// Coding-profile name for runtime-owned process execution.
585pub const CODING_LOOP_PROCESS_TOOL: &str = "run_process";