supercode-harness 0.4.20

The optional native Supercode agent and tool harness
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
//! Claude Code project compatibility helpers.
//!
//! Claude stores named subagent definitions as Markdown files under
//! `<project>/.claude/agents/`. The body is the child's system prompt and a
//! small YAML-like frontmatter block carries its name, tool allowlist, and
//! model pin. These helpers import that durable project state without
//! starting a child or otherwise executing it.

use std::path::{Path, PathBuf};

use crate::subagents::NamedAgentDefinition;
use crate::{Config, Error, Result};

/// Claude-specific project state installed into a resumed agent config.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeCompatibilitySnapshot {
    /// Exact global `~/.claude/CLAUDE.md` bytes, when present.
    pub global_instructions: Option<String>,
    /// Global instruction path that was checked.
    pub global_instructions_path: PathBuf,
    /// Imported project agent definitions and their exact source bytes.
    pub project_agents: Vec<ClaudeProjectAgent>,
}

/// One imported Claude project-agent file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeProjectAgent {
    /// Parsed definition usable by Supercode's named-subagent runtime.
    pub definition: NamedAgentDefinition,
    /// Optional human-facing description from the Claude frontmatter.
    pub description: Option<String>,
    /// Exact source path from which the definition was read.
    pub path: PathBuf,
    /// Exact Markdown source, retained for snapshot/export fidelity.
    pub raw_source: String,
    /// Original model value before alias resolution (for fidelity reporting).
    pub original_model: Option<String>,
    /// Original Claude tool names before compatibility mapping.
    pub original_tools: Option<Vec<String>>,
}

/// Discover and parse every `<cwd>/.claude/agents/*.md` definition.
///
/// Results are sorted by path. A malformed definition fails the whole import
/// instead of silently omitting a capability that the resumed session may
/// rely on. A missing agents directory is the ordinary empty result.
pub fn load_project_agents(cwd: &Path) -> Result<Vec<ClaudeProjectAgent>> {
    let dir = cwd.join(".claude/agents");
    let entries = match std::fs::read_dir(&dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(error.into()),
    };
    let mut paths: Vec<PathBuf> = entries
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("md"))
        .collect();
    paths.sort();
    paths
        .into_iter()
        .map(|path| {
            let source = std::fs::read_to_string(&path)?;
            parse_project_agent(&path, &source)
        })
        .collect()
}

/// Install Claude Code's non-executing compatibility state into `config`.
///
/// This imports Claude's global instructions and project named agents, then
/// enables the inert `Agent` compatibility surface. It does not spawn a child,
/// start a scheduler, or change sandbox/approval posture. The caller supplies
/// Claude's home (normally `$HOME/.claude`) explicitly so embedding/tests do
/// not depend on process-global environment mutation.
pub fn apply_resume_compatibility(
    config: &mut Config,
    claude_home: &Path,
) -> Result<ClaudeCompatibilitySnapshot> {
    // Restore Claude's scheduler-shaped tool surface over an inert manifest.
    // This only enables schemas/paused state mutation; Agent owns no timer
    // and the runtime manifest has no active execution posture.
    config.claude_runtime_tools_enabled = true;
    enable_claude_subagent_compatibility(config);
    let global_instructions_path = claude_home.join("CLAUDE.md");
    let global_instructions = match std::fs::read_to_string(&global_instructions_path) {
        Ok(source) => {
            if !source.trim().is_empty() {
                config
                    .system_prompt
                    .push_str("\n\n# Claude global CLAUDE.md\n");
                config.system_prompt.push_str(source.trim());
            }
            Some(source)
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(error.into()),
    };

    let project_agents = load_project_agents(&config.cwd)?;
    for imported in &project_agents {
        config.subagents_definitions.insert(
            imported.definition.name.clone(),
            imported.definition.clone(),
        );
    }

    Ok(ClaudeCompatibilitySnapshot {
        global_instructions,
        global_instructions_path,
        project_agents,
    })
}

pub(crate) fn enable_claude_subagent_compatibility(config: &mut Config) {
    config.subagents_enabled = true;
    config.subagents_background = true;
    config.subagents_background_prompts = Some(crate::subagents::BackgroundPromptsPolicy::Parent);
    config.subagents_claude_agent_alias = true;
}

/// Parse one Claude project-agent Markdown definition.
pub fn parse_project_agent(path: &Path, source: &str) -> Result<ClaudeProjectAgent> {
    let normalized = source.replace("\r\n", "\n");
    let mut lines = normalized.lines();
    if lines.next() != Some("---") {
        return Err(agent_error(
            path,
            "missing opening `---` frontmatter delimiter",
        ));
    }

    let mut name = None;
    let mut description = None;
    let mut model = None;
    let mut tools = None;
    let mut approval = None;
    let mut sandbox = None;
    let mut auto_approved_tools = None;
    let mut deny: Vec<String> = Vec::new();
    let mut body_start = None;
    let mut offset = 4usize; // opening `---\n`
    for line in lines {
        if line == "---" {
            body_start = Some(offset + line.len() + 1);
            break;
        }
        let Some((key, value)) = line.split_once(':') else {
            return Err(agent_error(
                path,
                format!("invalid frontmatter line `{line}`"),
            ));
        };
        let value = unquote(value.trim());
        match key.trim() {
            "name" => name = nonempty(value),
            "description" => description = nonempty(value),
            "model" => model = nonempty(value),
            "tools" => tools = Some(parse_tool_list(value)),
            // BP-7 (catalog §4a "Named agent definitions as data":
            // "prompt+model+tools+PERMISSIONS in a file/config"). CC's own
            // frontmatter has no permission keys; these are supercode's
            // extension, and they can only TIGHTEN — see
            // `crate::subagents::AgentPermissions`. A frontmatter file is
            // repo-trust-tier data, so anything looser than the parent's
            // posture is ignored rather than honored.
            "approval" => {
                approval = nonempty(value).and_then(|v| crate::configfile::parse_approval_str(&v))
            }
            "sandbox" => {
                sandbox = nonempty(value).and_then(|v| crate::configfile::parse_sandbox_str(&v))
            }
            "auto_approved_tools" => {
                auto_approved_tools = Some(
                    parse_tool_list(value)
                        .iter()
                        .map(|tool| map_claude_tool(tool))
                        .collect(),
                )
            }
            "deny" => deny = parse_tool_list(value),
            _ => {}
        }
        offset += line.len() + 1;
    }
    let Some(body_start) = body_start else {
        return Err(agent_error(
            path,
            "missing closing `---` frontmatter delimiter",
        ));
    };
    let body = normalized[body_start..].trim().to_string();
    if body.is_empty() {
        return Err(agent_error(path, "agent system-prompt body is empty"));
    }
    let name = name
        .or_else(|| {
            path.file_stem()
                .and_then(|stem| stem.to_str())
                .map(str::to_string)
        })
        .filter(|name| !name.trim().is_empty())
        .ok_or_else(|| agent_error(path, "agent name is empty"))?;
    let mapped_tools = tools
        .as_ref()
        .map(|tools| tools.iter().map(|tool| map_claude_tool(tool)).collect());
    let mapped_model = model
        .as_deref()
        .map(|model| crate::model_catalog::resolve_alias(model));

    let permissions = (approval.is_some()
        || sandbox.is_some()
        || auto_approved_tools.is_some()
        || !deny.is_empty())
    .then(|| crate::subagents::AgentPermissions {
        approval,
        sandbox,
        auto_approved_tools,
        deny,
    });

    Ok(ClaudeProjectAgent {
        definition: NamedAgentDefinition {
            name,
            system_prompt: body,
            tools: mapped_tools,
            model: mapped_model,
            permissions,
        },
        description,
        path: path.to_path_buf(),
        raw_source: source.to_string(),
        original_model: model,
        original_tools: tools,
    })
}

fn parse_tool_list(value: &str) -> Vec<String> {
    let value = value
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
        .unwrap_or(value);
    value
        .split(',')
        .map(|tool| unquote(tool.trim()))
        .filter(|tool| !tool.is_empty())
        .map(str::to_string)
        .collect()
}

fn map_claude_tool(tool: &str) -> String {
    match tool {
        "Bash" => "bash",
        "Read" => "read_file",
        "Write" => "write_file",
        "Edit" => "edit_file",
        "Glob" => "glob",
        "Grep" => "search",
        "Agent" | "Task" => "spawn_subagent",
        other => other,
    }
    .to_string()
}

fn nonempty(value: &str) -> Option<String> {
    (!value.is_empty()).then(|| value.to_string())
}

fn unquote(value: &str) -> &str {
    value
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
        .or_else(|| {
            value
                .strip_prefix('\'')
                .and_then(|value| value.strip_suffix('\''))
        })
        .unwrap_or(value)
}

fn agent_error(path: &Path, message: impl std::fmt::Display) -> Error {
    Error::Other(format!(
        "invalid Claude project agent `{}`: {message}",
        path.display()
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_realistic_agent_and_maps_tools_and_model_without_losing_source() {
        let source = "---\nname: pilot-tick\ndescription: Sweep the fleet\ntools: Bash, Read, Write, Edit\nmodel: sonnet\n---\nYou are the pilot.\n\nFollow the drill exactly.\n";
        let parsed = parse_project_agent(Path::new(".claude/agents/pilot-tick.md"), source)
            .expect("definition parses");
        assert_eq!(parsed.definition.name, "pilot-tick");
        assert_eq!(parsed.description.as_deref(), Some("Sweep the fleet"));
        assert_eq!(parsed.original_model.as_deref(), Some("sonnet"));
        assert_eq!(
            parsed.definition.model.as_deref(),
            Some("anthropic/claude-sonnet-4-6")
        );
        assert_eq!(
            parsed.definition.tools.as_deref(),
            Some(
                ["bash", "read_file", "write_file", "edit_file"]
                    .map(str::to_string)
                    .as_slice()
            )
        );
        assert_eq!(
            parsed.definition.system_prompt,
            "You are the pilot.\n\nFollow the drill exactly."
        );
        assert_eq!(parsed.raw_source, source);
    }

    #[test]
    fn filename_supplies_name_and_bracketed_tools_are_supported() {
        let parsed = parse_project_agent(
            Path::new("reviewer.md"),
            "---\ntools: [Read, Grep, Agent]\n---\nReview carefully.\n",
        )
        .unwrap();
        assert_eq!(parsed.definition.name, "reviewer");
        assert_eq!(
            parsed.definition.tools.unwrap(),
            ["read_file", "search", "spawn_subagent"].map(str::to_string)
        );
    }

    #[test]
    fn malformed_definition_fails_loudly() {
        let error = parse_project_agent(Path::new("broken.md"), "No frontmatter")
            .expect_err("must reject malformed agent");
        assert!(error.to_string().contains("missing opening"));
    }

    #[test]
    fn compatibility_install_adds_global_and_named_agent_without_executing_it() {
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "supercode-claude-compat-{}-{nonce}",
            std::process::id()
        ));
        let project = root.join("project");
        let claude_home = root.join(".claude");
        std::fs::create_dir_all(project.join(".claude/agents")).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();
        std::fs::write(claude_home.join("CLAUDE.md"), "GLOBAL CLAUDE RULE").unwrap();
        std::fs::write(
            project.join(".claude/agents/pilot-tick.md"),
            "---\nname: pilot-tick\ntools: Bash, Read\nmodel: sonnet\n---\nPilot exactly.\n",
        )
        .unwrap();

        let mut config = Config::builder().cwd(&project).build();
        let snapshot = apply_resume_compatibility(&mut config, &claude_home).unwrap();
        assert!(config.system_prompt.contains("GLOBAL CLAUDE RULE"));
        assert!(config.subagents_enabled);
        assert!(config.subagents_background);
        assert!(config.subagents_claude_agent_alias);
        assert!(config.claude_runtime_tools_enabled);
        assert_eq!(snapshot.project_agents.len(), 1);
        assert_eq!(
            config
                .subagents_definitions
                .get("pilot-tick")
                .and_then(|definition| definition.model.as_deref()),
            Some("anthropic/claude-sonnet-4-6")
        );
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn compatibility_always_installs_claudes_builtin_general_purpose_agent() {
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "supercode-claude-built-in-{}-{nonce}",
            std::process::id()
        ));
        let project = root.join("project");
        let claude_home = root.join(".claude");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        let mut config = Config::builder().cwd(&project).build();
        let snapshot = apply_resume_compatibility(&mut config, &claude_home).unwrap();
        assert!(snapshot.project_agents.is_empty());
        assert!(config.subagents_enabled);
        assert!(config.subagents_background);
        assert_eq!(
            config.subagents_background_prompts,
            Some(crate::subagents::BackgroundPromptsPolicy::Parent)
        );
        assert!(config.subagents_claude_agent_alias);
        std::fs::remove_dir_all(root).ok();
    }
}