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