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, HostPathPolicy, 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 the shared host path policy governing denied private directories
363    /// and Merry-owned read-only subtrees (such as session journals).
364    #[must_use]
365    pub fn host_path_policy(mut self, policy: HostPathPolicy) -> Self {
366        self.workspace = self.workspace.host_path_policy(policy);
367        self
368    }
369
370    /// Includes read-only process execution lanes.
371    #[must_use]
372    pub fn read_only_process_runner(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
373        self.workspace = self.workspace.read_only_process_runner(runner);
374        self
375    }
376
377    /// Includes one host-process session and its reviewed-action capability.
378    #[must_use]
379    pub fn accepted_process_session(mut self, session: ProcessSession) -> Self {
380        self.workspace = self.workspace.accepted_process_session(session);
381        self
382    }
383
384    /// Sets the provider-neutral retry/recovery policy for model turns.
385    #[must_use]
386    pub fn retry_policy(mut self, retry_policy: ModelRetryPolicy) -> Self {
387        self.retry_policy = Some(retry_policy);
388        self
389    }
390
391    /// Sets coding-loop recovery and final-report policy.
392    #[must_use]
393    pub fn run_policy(mut self, run_policy: CodingAgentRunPolicy) -> Self {
394        self.run_policy = run_policy;
395        self
396    }
397
398    /// Allows explicitly registered bridge tools in this coding profile.
399    #[doc(hidden)]
400    #[must_use]
401    pub fn allow_bridge_tools(mut self) -> Self {
402        self.allow_bridge_tools = true;
403        self
404    }
405
406    /// Adds the stable project rules projection.
407    #[must_use]
408    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
409        self.project_rules = Some(project_rules);
410        self
411    }
412
413    /// Adds stable skill metadata without embedding skill bodies.
414    #[must_use]
415    pub fn skill_catalog(mut self, skill_catalog: SkillCatalog) -> Self {
416        self.skill_catalog = Some(skill_catalog);
417        self
418    }
419
420    /// Adds the dynamic task anchor projection.
421    #[must_use]
422    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
423        self.task_anchor = Some(task_anchor);
424        self
425    }
426
427    /// Adds a typed application tool after the canonical Merry-managed tools.
428    #[must_use]
429    pub fn tool(mut self, tool: Tool) -> Self {
430        self.tools.push(tool);
431        self
432    }
433
434    /// Adds a runtime-owned tool after the canonical workspace tool catalog.
435    #[doc(hidden)]
436    #[must_use]
437    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
438        self.registered_tools.push(tool);
439        self
440    }
441
442    /// Adds runtime-owned tools in the supplied stable order.
443    #[doc(hidden)]
444    #[must_use]
445    pub fn register_tools<I>(mut self, tools: I) -> Self
446    where
447        I: IntoIterator<Item = RegisteredTool>,
448    {
449        self.registered_tools.extend(tools);
450        self
451    }
452
453    /// Attaches the durable memory store shared by parent and child runtimes.
454    ///
455    /// The store supplies the stable memory instructions and the workspace
456    /// tool policy. The frozen index is attached separately on the runtime.
457    #[must_use]
458    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
459        self.workspace = self.workspace.durable_memory(memory);
460        self
461    }
462
463    /// Returns the attached memory store, when this profile has one.
464    #[must_use]
465    pub fn durable_memory_handle(&self) -> Option<Arc<DurableMemory>> {
466        self.workspace.durable_memory.clone()
467    }
468
469    /// Builds the shared coding-agent profile.
470    pub fn build(self) -> Result<CodingAgentProfile, CodingAgentProfileBuildError> {
471        let Self {
472            workspace,
473            retry_policy,
474            run_policy,
475            allow_bridge_tools,
476            skill_catalog,
477            project_rules,
478            task_anchor,
479            prompt_profile_override,
480            tools,
481            registered_tools,
482        } = self;
483        let workspace_hash_material = workspace.hash_material();
484        let memory_instructions = workspace
485            .durable_memory
486            .as_deref()
487            .map(DurableMemory::instructions);
488        let mut prompt_profile = match prompt_profile_override {
489            Some(profile) => profile,
490            None => PromptProfile::default().with_stable_block(PromptBlock::new(
491                "merry_coding_policy",
492                CODING_AGENT_POLICY_PROMPT,
493            )?)?,
494        };
495        if let Some(instructions) = memory_instructions {
496            prompt_profile = prompt_profile
497                .with_stable_block(PromptBlock::new("merry_memory", instructions)?)?;
498        }
499        let mut builder = RuntimeProfile::builder().prompt_profile(prompt_profile);
500        builder = workspace
501            .apply_to_runtime_profile(builder)
502            .map_err(|error| match error {
503                WorkspaceCodingProfileBuildError::WorkspaceTools(source) => {
504                    CodingAgentProfileBuildError::WorkspaceTools(source)
505                }
506                WorkspaceCodingProfileBuildError::ProcessTool(source) => {
507                    CodingAgentProfileBuildError::ProcessTool(source)
508                }
509                WorkspaceCodingProfileBuildError::PermissionTool(source) => {
510                    CodingAgentProfileBuildError::PermissionTool(source)
511                }
512                WorkspaceCodingProfileBuildError::Core(source) => {
513                    CodingAgentProfileBuildError::Core(source)
514                }
515                WorkspaceCodingProfileBuildError::WebToolBuild(source) => {
516                    CodingAgentProfileBuildError::WebToolBuild(source)
517                }
518            })?;
519        if allow_bridge_tools {
520            builder = builder.allow_bridge_tools();
521        }
522        if let Some(retry_policy) = retry_policy {
523            builder = builder.model_retry_policy(retry_policy);
524        }
525        if let Some(skill_catalog) = skill_catalog {
526            builder = builder.skill_catalog(skill_catalog);
527        }
528        if let Some(project_rules) = project_rules {
529            builder = builder.project_rules(project_rules);
530        }
531        if let Some(task_anchor) = task_anchor {
532            builder = builder.task_anchor(task_anchor);
533        }
534        for tool in tools {
535            builder = builder.register_tool(tool.into_registered_tool());
536        }
537        for tool in registered_tools {
538            builder = builder.register_tool(tool);
539        }
540        let runtime_profile = builder.build()?;
541        let profile_hash =
542            coding_agent_profile_hash(&runtime_profile, run_policy, &workspace_hash_material)?;
543        Ok(CodingAgentProfile {
544            runtime_profile,
545            profile_hash,
546            run_policy,
547        })
548    }
549}
550
551/// Errors raised while building the shared coding-agent profile.
552#[derive(Debug, Error)]
553pub enum CodingAgentProfileBuildError {
554    /// Workspace tool configuration was invalid.
555    #[error(transparent)]
556    WorkspaceTools(#[from] WorkspaceToolConfigError),
557    /// The process command tool could not be constructed.
558    #[error(transparent)]
559    ProcessTool(#[from] ProcessCommandToolError),
560    /// The permission request tool could not be constructed.
561    #[error(transparent)]
562    PermissionTool(#[from] PermissionAdmissionError),
563    /// A provider-neutral protocol value failed validation.
564    #[error(transparent)]
565    Core(#[from] CoreError),
566    /// The final runtime profile was invalid.
567    #[error(transparent)]
568    RuntimeProfile(#[from] RuntimeProfileError),
569    /// Profile hash material could not be serialized.
570    #[error("coding agent profile hash material could not be serialized: {0}")]
571    HashSerialization(#[from] JsonError),
572    /// Stable prompt composition was invalid.
573    #[error(transparent)]
574    Prompt(#[from] PromptError),
575    /// A web or browser tool schema failed validation.
576    #[error(transparent)]
577    WebToolBuild(#[from] ToolBuildError),
578}
579
580/// Coding-profile name for runtime-owned process execution.
581pub const CODING_LOOP_PROCESS_TOOL: &str = "run_process";