merry-coding 0.1.4

Coding prompts, project rules, tool catalog, permission policy, and subagent orchestration for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Provider-neutral coding composition for Merry.
//!
//! This crate is the single owner of coding composition: the parent runtime
//! builder, child-runtime inputs, workspace tools, project-rule and skill
//! projections, process admission lanes, tool order, and stable composition
//! identity. The facade and CLI consume these types rather than assembling a
//! second coding policy.

mod child_runtime;
mod policy_prompt;
mod profile_hash;
mod project_capabilities;
mod project_rules;
mod runtime;
mod search_tools;
mod subagent_roles;
mod workflow_commands;
mod workspace;
mod worktree;

#[cfg(test)]
mod tests;

pub use policy_prompt::{
    CODING_AGENT_POLICY_PROMPT, builtin_subagent_role_instructions, coding_subagent_policy_prompt,
};
pub use profile_hash::CodingAgentProfileHash;
pub use project_rules::{
    MAX_ROOT_PROJECT_RULES_BYTES, ProjectRulesLoadError, ROOT_PROJECT_RULES_FILE,
    load_root_project_rules,
};
pub use runtime::{
    CodingAutoFallback, CodingModelRoleConfig, CodingModelRoleConfigError, CodingPermissionMode,
    CodingPermissionPolicy, CodingPermissionPolicyError, CodingRuntime, CodingRuntimeBuildError,
    CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
};
pub use subagent_roles::{
    MAX_ROLE_PROMPT_FILE_BYTES, ResolvedSubagentRuntime, SubagentDefaultOverride,
    SubagentModelOverride, SubagentResolutionInput, SubagentRoleCatalog, SubagentRoleError,
    SubagentRoleOverlay, SubagentRoleSpec, SubagentWorkspaceAccess, load_workspace_prompt_file,
    resolve_subagent_runtime,
};
pub use workflow_commands::CodingWorkflowCommand;
pub use worktree::{
    WorktreeError, WorktreeGcReport, WorktreeIsolationManager, cleanup_orphaned_worktrees,
    cleanup_orphaned_worktrees_default, default_worktree_base_dir,
};

use merry_core::{CoreError, HostPathPolicy, ToolName};
use merry_llm::ModelRetryPolicy;
use merry_process::ProcessSession;
use merry_runtime::{
    AgentLoopConfig, DurableMemory, PermissionAdmissionError, ProcessCommandToolError,
    ProcessRunner, ProjectRules, PromptBlock, PromptError, PromptProfile, RegisteredTool,
    RuntimeBuilder, RuntimeError, RuntimeProfile, RuntimeProfileError, SkillCatalog, TaskAnchor,
    Tool, ToolBuildError,
};
pub use merry_tools::{
    BrowserLaunchSpec, BrowserLauncherFuture, BrowserProcessHandle, BrowserProcessLauncher,
    WorkspaceToolConfigError, WorkspaceToolLimits,
};
use serde_json::Error as JsonError;
use std::{path::PathBuf, sync::Arc};
use thiserror::Error;
use workspace::{WorkspaceCodingProfileBuildError, WorkspaceCodingProfileBuilder};

use profile_hash::coding_agent_profile_hash;

/// Stable identity of the provider-neutral coding profile contract.
pub const CODING_AGENT_PROFILE_ID: &str = "coding-agent-profile";

/// Stable provider-prefix layout owned by the runtime coding composition.
pub const CODING_AGENT_STABLE_PREFIX_LAYOUT: &str =
    "runtime-instructions|progress-commentary|skill-catalog|project-rules|tools";

/// Dynamic provider-context layout owned by the runtime coding composition.
pub const CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT: &str =
    "checkpoint|task-anchor|plan-control|compiled-context|transcript|tool-results|user-input";

/// Minimum model-turn budget for a coding-profile child agent.
pub const MIN_CODING_SUBAGENT_MODEL_TURNS: u32 = 1;

/// Default coding-profile ceiling for one child agent.
pub const DEFAULT_CODING_SUBAGENT_MAX_MODEL_TURNS: u32 = 80;

/// Maximum model-turn ceiling for the coding-profile main agent.
pub const DEFAULT_CODING_AGENT_MAX_MODEL_TURNS: usize = usize::MAX;

/// Final-report behavior for a coding-agent run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CodingFinalReportPolicy {
    /// Report changes, evidence, verification, blockers, and remaining risks.
    EvidenceBackedSummary,
}

impl CodingFinalReportPolicy {
    /// Returns the stable policy identifier.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::EvidenceBackedSummary => "evidence_backed_summary",
        }
    }
}

/// Coding-loop recovery and final-report policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CodingAgentRunPolicy {
    max_model_turns: usize,
    final_report: CodingFinalReportPolicy,
}

impl CodingAgentRunPolicy {
    /// Creates a validated coding run policy.
    pub fn new(
        max_model_turns: usize,
        final_report: CodingFinalReportPolicy,
    ) -> Result<Self, CodingAgentRunPolicyError> {
        if max_model_turns == 0 {
            return Err(CodingAgentRunPolicyError::MaxModelTurnsMustBeNonZero);
        }
        Ok(Self {
            max_model_turns,
            final_report,
        })
    }

    /// Returns the maximum number of model turns.
    #[must_use]
    pub const fn max_model_turns(self) -> usize {
        self.max_model_turns
    }

    /// Returns the final-report policy.
    #[must_use]
    pub const fn final_report(self) -> CodingFinalReportPolicy {
        self.final_report
    }

    /// Creates the runtime loop configuration owned by this policy.
    pub fn loop_config(self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
        AgentLoopConfig::new(self.max_model_turns)
    }
}

impl Default for CodingAgentRunPolicy {
    fn default() -> Self {
        Self {
            max_model_turns: DEFAULT_CODING_AGENT_MAX_MODEL_TURNS,
            final_report: CodingFinalReportPolicy::EvidenceBackedSummary,
        }
    }
}

/// Invalid coding-loop policy.
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
pub enum CodingAgentRunPolicyError {
    /// A coding loop without a turn budget cannot make progress.
    #[error("coding agent max_model_turns must be greater than zero")]
    MaxModelTurnsMustBeNonZero,
}

/// Returns the shared default coding-agent loop configuration.
pub fn coding_agent_loop_config() -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
    CodingAgentRunPolicy::default().loop_config()
}

/// Creates the shared coding-agent composition builder with one workspace root.
#[must_use]
pub fn coding_agent(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
    CodingAgentProfileBuilder::new(root)
}

/// One provider-neutral coding-agent composition applied to a runtime builder.
///
/// The profile owns the coding tool catalog and its runtime policy settings.
/// Provider adapters see only the resulting Merry-owned tool specifications;
/// provider wire types never enter this API. Task anchors, checkpoints,
/// transcript items, and tool results remain runtime-owned dynamic context.
#[derive(Clone)]
pub struct CodingAgentProfile {
    runtime_profile: RuntimeProfile,
    profile_hash: CodingAgentProfileHash,
    run_policy: CodingAgentRunPolicy,
}

impl CodingAgentProfile {
    /// Creates a shared coding-agent profile builder.
    #[must_use]
    pub fn builder(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
        CodingAgentProfileBuilder::new(root)
    }

    /// Applies this profile to a runtime builder.
    pub fn apply_to(&self, builder: RuntimeBuilder) -> Result<RuntimeBuilder, RuntimeError> {
        builder.with_profile(self.runtime_profile.clone())
    }

    /// Creates the shared coding loop configuration for this profile.
    pub fn loop_config(&self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
        self.run_policy.loop_config()
    }

    /// Returns the recovery and final-report policy carried by this profile.
    #[must_use]
    pub const fn run_policy(&self) -> CodingAgentRunPolicy {
        self.run_policy
    }

    /// Returns the complete runtime profile carried by this composition.
    #[must_use]
    pub fn runtime_profile(&self) -> RuntimeProfile {
        self.runtime_profile.clone()
    }

    /// Returns the provider-neutral registered tools in their advertised order.
    #[must_use]
    pub fn registered_tools(&self) -> &[RegisteredTool] {
        self.runtime_profile.registered_tools()
    }

    /// Returns the ordered provider-neutral tool names for diagnostics/tests.
    #[must_use]
    pub fn tool_names(&self) -> Vec<&ToolName> {
        self.registered_tools()
            .iter()
            .map(|tool| tool.spec().name())
            .collect()
    }

    /// Returns the deterministic identity of the profile's stable composition.
    #[must_use]
    pub fn profile_hash(&self) -> &CodingAgentProfileHash {
        &self.profile_hash
    }
}

/// Builder for the single shared coding-agent composition profile.
#[derive(Clone)]
pub struct CodingAgentProfileBuilder {
    workspace: WorkspaceCodingProfileBuilder,
    retry_policy: Option<ModelRetryPolicy>,
    run_policy: CodingAgentRunPolicy,
    allow_bridge_tools: bool,
    skill_catalog: Option<SkillCatalog>,
    project_rules: Option<ProjectRules>,
    task_anchor: Option<TaskAnchor>,
    prompt_profile_override: Option<PromptProfile>,
    tools: Vec<Tool>,
    registered_tools: Vec<RegisteredTool>,
}

impl CodingAgentProfileBuilder {
    /// Creates a coding-agent profile builder with one workspace root.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            workspace: WorkspaceCodingProfileBuilder::new(root),
            retry_policy: None,
            run_policy: CodingAgentRunPolicy::default(),
            allow_bridge_tools: false,
            skill_catalog: None,
            project_rules: None,
            task_anchor: None,
            prompt_profile_override: None,
            tools: Vec::new(),
            registered_tools: Vec::new(),
        }
    }

    /// Returns the configured workspace root path.
    #[must_use]
    pub fn workspace_root(&self) -> &std::path::Path {
        &self.workspace.root
    }

    /// Replaces the default main-agent prompt profile with a custom profile
    /// (used by child runtimes to install dedicated subagent instructions and
    /// role blocks without carrying parent-only policy text).
    #[must_use]
    pub fn prompt_profile(mut self, prompt_profile: PromptProfile) -> Self {
        self.prompt_profile_override = Some(prompt_profile);
        self
    }

    /// Replaces the workspace root.
    #[must_use]
    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
        self.workspace = self.workspace.root(root);
        self
    }

    /// Adds read-only resource roots that are not the writable workspace root.
    #[must_use]
    pub fn readonly_resource_roots<I, P>(mut self, roots: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.workspace = self.workspace.readonly_resource_roots(roots);
        self
    }

    /// Sets workspace tool limits.
    #[must_use]
    pub fn limits(mut self, limits: WorkspaceToolLimits) -> Self {
        self.workspace = self.workspace.limits(limits);
        self
    }

    /// Enables the constrained workspace patch tool.
    #[must_use]
    pub fn patch_tool(mut self) -> Self {
        self.workspace = self.workspace.patch_tool();
        self
    }

    /// Enables built-in web and browser verification tools (`web_fetch`, `browser_tab`, `browser_network`).
    #[must_use]
    pub fn web_tools(mut self) -> Self {
        self.workspace = self.workspace.web_tools();
        self
    }

    /// Sets workspace-relative paths that `read_file` may read.
    #[must_use]
    pub fn read_scope<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.workspace = self.workspace.read_scope(paths);
        self
    }

    /// Sets workspace-relative paths that `apply_patch` may write.
    #[must_use]
    pub fn patch_write_scope<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.workspace = self.workspace.patch_write_scope(paths);
        self
    }

    /// Denies all `apply_patch` writes.
    #[must_use]
    pub fn read_only_patch_scope(mut self) -> Self {
        self.workspace = self.workspace.read_only_patch_scope();
        self
    }

    /// Sets workspace-relative paths that `apply_patch` must never write.
    #[must_use]
    pub fn forbidden_paths<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.workspace = self.workspace.forbidden_paths(paths);
        self
    }

    /// Sets the shared host path policy governing denied private directories
    /// and Merry-owned read-only subtrees (such as session journals).
    #[must_use]
    pub fn host_path_policy(mut self, policy: HostPathPolicy) -> Self {
        self.workspace = self.workspace.host_path_policy(policy);
        self
    }

    /// Includes read-only process execution lanes.
    #[must_use]
    pub fn read_only_process_runner(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
        self.workspace = self.workspace.read_only_process_runner(runner);
        self
    }

    /// Includes read-only process execution lanes backed by a full
    /// [`ProcessSession`] so live filesystem/network policies and session
    /// permissions remain connected to the runtime.
    pub(crate) fn read_only_process_session(mut self, session: ProcessSession) -> Self {
        self.workspace = self.workspace.read_only_process_session(session);
        self
    }

    /// Includes one host-process session and its reviewed-action capability.
    #[must_use]
    pub fn accepted_process_session(mut self, session: ProcessSession) -> Self {
        self.workspace = self.workspace.accepted_process_session(session);
        self
    }

    /// Overrides the headless browser process launcher used by `browser_tab`
    /// when web tools are enabled (for custom host runners or disabling local
    /// browser launches).
    #[must_use]
    pub fn browser_process_launcher(mut self, launcher: Arc<dyn BrowserProcessLauncher>) -> Self {
        self.workspace = self.workspace.browser_process_launcher(launcher);
        self
    }

    /// Sets the provider-neutral retry/recovery policy for model turns.
    #[must_use]
    pub fn retry_policy(mut self, retry_policy: ModelRetryPolicy) -> Self {
        self.retry_policy = Some(retry_policy);
        self
    }

    /// Sets coding-loop recovery and final-report policy.
    #[must_use]
    pub fn run_policy(mut self, run_policy: CodingAgentRunPolicy) -> Self {
        self.run_policy = run_policy;
        self
    }

    /// Allows explicitly registered bridge tools in this coding profile.
    #[doc(hidden)]
    #[must_use]
    pub fn allow_bridge_tools(mut self) -> Self {
        self.allow_bridge_tools = true;
        self
    }

    /// Adds the stable project rules projection.
    #[must_use]
    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
        self.project_rules = Some(project_rules);
        self
    }

    /// Adds stable skill metadata without embedding skill bodies.
    #[must_use]
    pub fn skill_catalog(mut self, skill_catalog: SkillCatalog) -> Self {
        self.skill_catalog = Some(skill_catalog);
        self
    }

    /// Adds the dynamic task anchor projection.
    #[must_use]
    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
        self.task_anchor = Some(task_anchor);
        self
    }

    /// Adds a typed application tool after the canonical Merry-managed tools.
    #[must_use]
    pub fn tool(mut self, tool: Tool) -> Self {
        self.tools.push(tool);
        self
    }

    /// Adds a runtime-owned tool after the canonical workspace tool catalog.
    #[doc(hidden)]
    #[must_use]
    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
        self.registered_tools.push(tool);
        self
    }

    /// Adds runtime-owned tools in the supplied stable order.
    #[doc(hidden)]
    #[must_use]
    pub fn register_tools<I>(mut self, tools: I) -> Self
    where
        I: IntoIterator<Item = RegisteredTool>,
    {
        self.registered_tools.extend(tools);
        self
    }

    /// Attaches the durable memory store shared by parent and child runtimes.
    ///
    /// The store supplies the stable memory instructions and the workspace
    /// tool policy. The frozen index is attached separately on the runtime.
    #[must_use]
    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
        self.workspace = self.workspace.durable_memory(memory);
        self
    }

    /// Returns the attached memory store, when this profile has one.
    #[must_use]
    pub fn durable_memory_handle(&self) -> Option<Arc<DurableMemory>> {
        self.workspace.durable_memory.clone()
    }

    /// Builds the shared coding-agent profile.
    pub fn build(self) -> Result<CodingAgentProfile, CodingAgentProfileBuildError> {
        let Self {
            workspace,
            retry_policy,
            run_policy,
            allow_bridge_tools,
            skill_catalog,
            project_rules,
            task_anchor,
            prompt_profile_override,
            tools,
            registered_tools,
        } = self;
        let workspace_hash_material = workspace.hash_material();
        let memory_instructions = workspace
            .durable_memory
            .as_deref()
            .map(DurableMemory::instructions);
        let mut prompt_profile = match prompt_profile_override {
            Some(profile) => profile,
            None => PromptProfile::default().with_stable_block(PromptBlock::new(
                "merry_coding_policy",
                CODING_AGENT_POLICY_PROMPT,
            )?)?,
        };
        if let Some(instructions) = memory_instructions {
            prompt_profile = prompt_profile
                .with_stable_block(PromptBlock::new("merry_memory", instructions)?)?;
        }
        let mut builder = RuntimeProfile::builder().prompt_profile(prompt_profile);
        builder = workspace
            .apply_to_runtime_profile(builder)
            .map_err(|error| match error {
                WorkspaceCodingProfileBuildError::WorkspaceTools(source) => {
                    CodingAgentProfileBuildError::WorkspaceTools(source)
                }
                WorkspaceCodingProfileBuildError::ProcessTool(source) => {
                    CodingAgentProfileBuildError::ProcessTool(source)
                }
                WorkspaceCodingProfileBuildError::PermissionTool(source) => {
                    CodingAgentProfileBuildError::PermissionTool(source)
                }
                WorkspaceCodingProfileBuildError::Core(source) => {
                    CodingAgentProfileBuildError::Core(source)
                }
                WorkspaceCodingProfileBuildError::WebToolBuild(source) => {
                    CodingAgentProfileBuildError::WebToolBuild(source)
                }
            })?;
        if allow_bridge_tools {
            builder = builder.allow_bridge_tools();
        }
        if let Some(retry_policy) = retry_policy {
            builder = builder.model_retry_policy(retry_policy);
        }
        if let Some(skill_catalog) = skill_catalog {
            builder = builder.skill_catalog(skill_catalog);
        }
        if let Some(project_rules) = project_rules {
            builder = builder.project_rules(project_rules);
        }
        if let Some(task_anchor) = task_anchor {
            builder = builder.task_anchor(task_anchor);
        }
        for tool in tools {
            builder = builder.register_tool(tool.into_registered_tool());
        }
        for tool in registered_tools {
            builder = builder.register_tool(tool);
        }
        let runtime_profile = builder.build()?;
        let profile_hash =
            coding_agent_profile_hash(&runtime_profile, run_policy, &workspace_hash_material)?;
        Ok(CodingAgentProfile {
            runtime_profile,
            profile_hash,
            run_policy,
        })
    }
}

/// Errors raised while building the shared coding-agent profile.
#[derive(Debug, Error)]
pub enum CodingAgentProfileBuildError {
    /// Workspace tool configuration was invalid.
    #[error(transparent)]
    WorkspaceTools(#[from] WorkspaceToolConfigError),
    /// The process command tool could not be constructed.
    #[error(transparent)]
    ProcessTool(#[from] ProcessCommandToolError),
    /// The permission request tool could not be constructed.
    #[error(transparent)]
    PermissionTool(#[from] PermissionAdmissionError),
    /// A provider-neutral protocol value failed validation.
    #[error(transparent)]
    Core(#[from] CoreError),
    /// The final runtime profile was invalid.
    #[error(transparent)]
    RuntimeProfile(#[from] RuntimeProfileError),
    /// Profile hash material could not be serialized.
    #[error("coding agent profile hash material could not be serialized: {0}")]
    HashSerialization(#[from] JsonError),
    /// Stable prompt composition was invalid.
    #[error(transparent)]
    Prompt(#[from] PromptError),
    /// A web or browser tool schema failed validation.
    #[error(transparent)]
    WebToolBuild(#[from] ToolBuildError),
}

/// Coding-profile name for runtime-owned process execution.
pub const CODING_LOOP_PROCESS_TOOL: &str = "run_process";