shepherd-compiler 6.7.1

Pure, deterministic Shepherd content compiler and prompt-budget engine.
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
//! Per-harness emission.
//!
//! `emit_claude`, `emit_codex`, and `emit_pi` are the same shape keyed on
//! `Harness`, plus the helpers that build one emitted file.

// Tightly coupled to its siblings by construction: this is one compiler
// split by concern, not four independent modules.
use super::*;

pub(super) fn emit_claude(
    roles: &[&RoleInput],
    emitted_roles: &[EmittedRole],
    skills: &[&SkillInput],
) -> Result<Vec<EmittedFile>, CompileError> {
    let mut files = Vec::new();
    for (role, emitted_role) in roles.iter().zip(emitted_roles) {
        let startup_skill = required_startup_skill(emitted_role)?;
        let mut fields = vec![
            ("name", role.role.clone()),
            ("description", quote(&role.description)),
            (
                "model",
                emitted_role
                    .model
                    .clone()
                    .expect("validated Claude role has a model"),
            ),
            ("tools", inline_array(&emitted_role.tools)),
            ("skills", inline_array(&[startup_skill.into()])),
        ];
        fields.extend([
            ("dispatchable", role.dispatchable.to_string()),
            ("write_eligible", role.write_eligible.to_string()),
            ("write_scope", quote(&role.write_scope)),
        ]);
        let content = frontmatter_file(&fields, &role.body)?;
        files.push(emitted(
            format!("agents/{}.md", role.role),
            EmittedKind::Role,
            content,
            &role.source_path,
            &role.source_content,
            BudgetClass::Role,
        )?);
    }
    emit_skills(&mut files, TargetHarness::Claude, skills)?;
    Ok(files)
}

pub(super) fn emit_codex(
    roles: &[&RoleInput],
    emitted_roles: &[EmittedRole],
    skills: &[&SkillInput],
    profile: &HarnessProfile,
) -> Result<Vec<EmittedFile>, CompileError> {
    let mut content = String::from(
        "# Generated by the canonical Rust shepherd compiler. Source: content/roles/*.md.\n\
# Do not hand-edit; regenerate via `shepherd compile --target codex --out <directory>`.\n\n",
    );
    writeln!(
        content,
        "max_concurrent_children = {}\n\n[agent_types]",
        profile.max_concurrent_children
    )
    .expect("writing to String cannot fail");
    for role in roles {
        // Keyed on `dispatchable`, which is what the field MEANS, not on the
        // model hint, which merely correlated with it for one role. The proxy
        // was wrong in both directions: `planter` is `dispatchable: false` and
        // was listed here anyway because its hint is `reasoning-high`, so Codex
        // advertised the operator-escalation role as a spawnable agent type;
        // and any lead that adopts `inherit-caller` would have silently
        // vanished from this table.
        if !role.dispatchable {
            continue;
        }
        writeln!(
            content,
            "{} = \"{}\"",
            role.role,
            if role.write_eligible {
                "worker"
            } else {
                "explorer"
            }
        )
        .expect("writing to String cannot fail");
    }
    content.push_str("\n[models]\n");
    let mut profiles = alloc::collections::BTreeMap::new();
    for role in emitted_roles {
        let Some(profile_name) = role.profile.as_deref() else {
            continue;
        };
        let effort = role
            .reasoning_effort
            .as_deref()
            .expect("validated Codex profile has reasoning effort");
        writeln!(content, "{} = \"{profile_name}\"", role.role)
            .expect("writing to String cannot fail");
        if let Some(previous) = profiles.insert(profile_name, effort)
            && previous != effort
        {
            return Err(CompileError::Invalid(format!(
                "Codex profile `{profile_name}` has conflicting reasoning effort"
            )));
        }
    }
    content.push('\n');
    for (profile_name, effort) in profiles {
        writeln!(content, "[profiles.\"{profile_name}\"]").expect("writing to String cannot fail");
        writeln!(content, "reasoning_effort = \"{effort}\"\n")
            .expect("writing to String cannot fail");
    }
    if content.ends_with("\n\n") {
        content.pop();
    }
    let source = roles
        .iter()
        .map(|role| role.source_content.as_str())
        .collect::<String>();
    let mut files = vec![emitted(
        "shepherd.codex.toml".into(),
        EmittedKind::Config,
        content,
        "content/roles/*.md",
        &source,
        BudgetClass::Command,
    )?];
    for (role, emitted_role) in roles.iter().zip(emitted_roles) {
        let startup_skill = required_startup_skill(emitted_role)?;
        if !role.dispatchable {
            continue;
        }
        let mut agent = String::new();
        writeln!(agent, "name = {}", quote(&role.role)).expect("writing to String cannot fail");
        writeln!(agent, "description = {}", quote(&role.description))
            .expect("writing to String cannot fail");
        if let Some(model) = &emitted_role.model {
            writeln!(agent, "model = {}", quote(model)).expect("writing to String cannot fail");
        }
        if let Some(effort) = &emitted_role.reasoning_effort {
            writeln!(agent, "model_reasoning_effort = {}", quote(effort))
                .expect("writing to String cannot fail");
        }
        writeln!(
            agent,
            "sandbox_mode = {}",
            quote(if role.write_eligible {
                "workspace-write"
            } else {
                "read-only"
            })
        )
        .expect("writing to String cannot fail");
        let instructions = format!(
            "First invoke the installed `${startup_skill}` skill. Do not continue until it loads successfully.\n\n{}",
            role.body.trim()
        );
        writeln!(agent, "developer_instructions = {}", quote(&instructions))
            .expect("writing to String cannot fail");
        files.push(emitted(
            format!(".codex/agents/{}.toml", role.role),
            EmittedKind::Role,
            agent,
            &role.source_path,
            &role.source_content,
            BudgetClass::Role,
        )?);
    }
    emit_skills(&mut files, TargetHarness::Codex, skills)?;
    Ok(files)
}

pub(super) fn emit_pi(
    roles: &[&RoleInput],
    emitted_roles: &[EmittedRole],
    skills: &[&SkillInput],
) -> Result<Vec<EmittedFile>, CompileError> {
    let mut files = Vec::new();
    for (role, emitted_role) in roles.iter().zip(emitted_roles) {
        let startup_skill = required_startup_skill(emitted_role)?;
        let mut fields = vec![
            ("name", role.role.clone()),
            ("description", quote(&role.description)),
            ("capabilities", inline_array(&role.capabilities)),
            ("skills", startup_skill.into()),
        ];
        fields.extend([
            ("dispatchable", role.dispatchable.to_string()),
            ("write_eligible", role.write_eligible.to_string()),
            ("write_scope", quote(&role.write_scope)),
        ]);
        let content = frontmatter_file(&fields, &role.body)?;
        files.push(emitted(
            format!("prompts/{}.md", role.role),
            EmittedKind::Role,
            content.clone(),
            &role.source_path,
            &role.source_content,
            BudgetClass::Role,
        )?);
        if role.dispatchable {
            let mut tools = emitted_role.tools.clone();
            if !tools.iter().any(|tool| tool == "subagent") {
                tools.push("subagent".into());
            }
            let model = emitted_role
                .model
                .as_deref()
                .unwrap_or("model-required/model-required");
            let mut agent = String::from("---\n");
            writeln!(agent, "name: {}", quote(&format!("shepherd:{}", role.role)))
                .expect("writing to String cannot fail");
            writeln!(agent, "description: {}", quote(&role.description))
                .expect("writing to String cannot fail");
            writeln!(agent, "tools: {}", tools.join(", ")).expect("writing to String cannot fail");
            writeln!(agent, "skills: {startup_skill}").expect("writing to String cannot fail");
            writeln!(agent, "model: {model}").expect("writing to String cannot fail");
            agent.push_str("systemPromptMode: replace\n");
            agent.push_str("inheritProjectContext: true\n");
            agent.push_str("inheritSkills: false\n");
            agent.push_str("subagentOnlyExtensions: ../src/extension.mjs\n");
            writeln!(
                agent,
                "acceptanceRole: {}",
                if role.write_eligible {
                    "writer"
                } else {
                    "read-only"
                }
            )
            .expect("writing to String cannot fail");
            agent.push_str("maxSubagentDepth: 2\n");
            if !role.write_eligible {
                agent.push_str("completionGuard: false\n");
            }
            agent.push_str("---\n\n");
            agent.push_str(&content);
            files.push(emitted_file(
                format!("agents/{}.md", role.role),
                EmittedKind::Role,
                agent,
                &role.source_path,
                role.source_content.as_bytes(),
                REGULAR_MODE,
                Some(BudgetClass::Command),
            )?);
        }
    }
    emit_skills(&mut files, TargetHarness::Pi, skills)?;
    Ok(files)
}

pub(super) fn emit_skills(
    files: &mut Vec<EmittedFile>,
    target: TargetHarness,
    skills: &[&SkillInput],
) -> Result<(), CompileError> {
    let root = if target == TargetHarness::Codex {
        ".agents/skills"
    } else {
        "skills"
    };
    for skill in skills {
        if skill.portability == Portability::ClaudeOnly && target != TargetHarness::Claude {
            continue;
        }
        let content = frontmatter_file(
            &[
                ("name", skill.name.clone()),
                ("description", quote(&skill.description)),
            ],
            &skill.body,
        )?;
        let frontmatter_end = content.find("\n---\n").ok_or_else(|| {
            CompileError::Invalid(format!(
                "{}: emitted frontmatter is malformed",
                skill.source_path
            ))
        })? + 5;
        if frontmatter_end > 1_024 {
            return Err(CompileError::Invalid(format!(
                "{}: frontmatter exceeds 1024 bytes",
                skill.source_path
            )));
        }
        files.push(emitted(
            format!("{root}/{}/SKILL.md", skill.name),
            EmittedKind::Skill,
            content,
            &skill.source_path,
            &skill.source_content,
            BudgetClass::Skill,
        )?);
        for resource in &skill.resources {
            let content = String::from_utf8(resource.content.clone()).map_err(|_| {
                CompileError::Invalid(format!(
                    "{}: skill resource must be UTF-8",
                    resource.source_path
                ))
            })?;
            files.push(emitted_resource(
                format!("{root}/{}/{}", skill.name, resource.relative_path),
                content,
                &resource.source_path,
                &resource.content,
                if resource.executable {
                    EXECUTABLE_MODE
                } else {
                    REGULAR_MODE
                },
                (resource.relative_path.starts_with("references/") && !resource.content.is_empty())
                    .then_some(BudgetClass::Reference),
            )?);
        }
    }
    Ok(())
}

pub(super) fn frontmatter_file(
    fields: &[(&str, String)],
    body: &str,
) -> Result<String, CompileError> {
    let body = body.trim();
    if body.lines().any(|line| line.trim() == "---") {
        return Err(CompileError::Invalid(
            "body contains a bare `---` frontmatter fence".into(),
        ));
    }
    let mut output = String::from("---\n");
    for (key, value) in fields {
        writeln!(output, "{key}: {value}").expect("writing to String cannot fail");
    }
    output.push_str("---\n\n");
    output.push_str(body);
    output.push('\n');
    Ok(output)
}

pub(super) fn quote(value: &str) -> String {
    let mut output = String::from("\"");
    for character in value.chars() {
        match character {
            '\\' => output.push_str("\\\\"),
            '"' => output.push_str("\\\""),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            '\0' => output.push_str("\\0"),
            character if character.is_control() => {
                write!(output, "\\u{:04x}", character as u32)
                    .expect("writing to String cannot fail");
            }
            _ => output.push(character),
        }
    }
    output.push('"');
    output
}

pub(super) fn inline_array(values: &[String]) -> String {
    format!("[{}]", values.join(", "))
}

pub(super) fn emitted(
    path: String,
    kind: EmittedKind,
    content: String,
    source_path: &str,
    source_content: &str,
    budget_class: BudgetClass,
) -> Result<EmittedFile, CompileError> {
    emitted_file(
        path,
        kind,
        content,
        source_path,
        source_content.as_bytes(),
        REGULAR_MODE,
        Some(budget_class),
    )
}

pub(super) fn emitted_resource(
    path: String,
    content: String,
    source_path: &str,
    source_content: &[u8],
    mode: u32,
    budget_class: Option<BudgetClass>,
) -> Result<EmittedFile, CompileError> {
    emitted_file(
        path,
        EmittedKind::Skill,
        content,
        source_path,
        source_content,
        mode,
        budget_class,
    )
}

pub(super) fn emitted_file(
    path: String,
    kind: EmittedKind,
    content: String,
    source_path: &str,
    source_content: &[u8],
    mode: u32,
    budget_class: Option<BudgetClass>,
) -> Result<EmittedFile, CompileError> {
    let measurement = if let Some(budget_class) = budget_class {
        validate_budget(&path, budget_class, &content)?
    } else {
        measure_text(&content)
    };
    Ok(EmittedFile {
        path,
        kind,
        source_sha256: sha256(source_content),
        content_sha256: sha256(content.as_bytes()),
        content,
        mode,
        source_path: source_path.into(),
        measurement,
    })
}