procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
pub mod builtin;

use crate::risk::Capability;
use crate::skills::{loader::Skill, SkillRegistry};

/// A persona discovered from a stellar-build skill with a customize.toml.
#[derive(Debug, Clone)]
pub struct Persona {
    /// Skill name (e.g. "tyler-architect").
    pub skill_name: String,
    /// Display name (e.g. "Tyler").
    pub name: String,
    /// Title (e.g. "System Architect").
    pub title: String,
    /// Icon emoji (e.g. "🏗️").
    pub icon: String,
    /// Role description.
    pub role: String,
    /// Identity description.
    pub identity: String,
    /// Communication style.
    pub communication_style: String,
    /// Principles (value system).
    pub principles: Vec<String>,
    /// Skill body (markdown instructions).
    pub body: String,
    /// When the main agent should hand work to this specialist. The routing rule, in the
    /// specialist's own words — the main agent is shown these and nothing else about them, so a
    /// persona that does not say when it applies will not be reached.
    pub when_to_use: String,
    /// The tools this specialist may use. `None` means "everything the session has", which is what
    /// a persona from disk gets unless it says otherwise.
    ///
    /// It can only ever narrow: the registry a specialist is handed is built from the session's, so
    /// naming a tool the session does not have adds nothing.
    pub tools: Option<Vec<String>>,
    /// Skills to load before the first turn, by name. A specialist that has to remember to call
    /// `run_skill` will answer from memory instead.
    pub skills: Vec<String>,
    /// The most this specialist may do, whatever its tool list says. Enforced by leaving the tools
    /// above the ceiling out of its registry, so it is structural rather than an instruction — see
    /// `runtime::persona_tools`.
    pub ceiling: Capability,
}

impl Persona {
    /// Builds a system prompt for a sub-agent using this persona.
    pub fn system_prompt(&self, workspace_context: &str) -> String {
        let mut prompt = format!(
            "# {}{}\n\n{}\n\n## Role\n\n{}\n\n## Identity\n\n{}\n\n## Communication Style\n\n{}\n\n## Principles\n\n",
            self.name, self.title, self.body, self.role, self.identity, self.communication_style
        );

        for p in &self.principles {
            prompt.push_str(&format!("- {}\n", p));
        }

        if !self.when_to_use.is_empty() {
            prompt.push_str(&format!(
                "\n## When you are called\n\n{}\n",
                self.when_to_use
            ));
        }

        // Said out loud as well as enforced. The enforcement is the registry it was handed; this is
        // so the specialist reports back "that is outside what I can do" instead of spending rounds
        // hunting for a tool that was never there.
        let limit = match self.ceiling {
            Capability::ReadOnly | Capability::Build | Capability::Delegating => Some(
                "You cannot change files or sign anything. If the work needs that, say what has \
                 to be done and hand it back rather than looking for another way.",
            ),
            Capability::Write => Some(
                "You may change files. You cannot deploy, invoke or sign — hand that back when it \
                 is needed.",
            ),
            Capability::Signing => None,
        };
        if let Some(limit) = limit {
            prompt.push_str(&format!("\n## Your limits\n\n{}\n", limit));
        }

        if !workspace_context.is_empty() {
            prompt.push_str(&format!(
                "\n## Workspace Context\n\n{}\n",
                workspace_context
            ));
        }

        prompt
    }
}

/// Registry of discovered personas.
pub struct PersonaRegistry {
    personas: Vec<Persona>,
}

impl PersonaRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self {
            personas: Vec::new(),
        }
    }

    /// Discovers personas from the skill registry.
    /// Personas are skills that have a customize.toml with an [agent] section.
    /// The specialists Procyon ships with, plus whatever the skill directories add.
    ///
    /// The builtins are inserted first and win a name collision. A disk persona could otherwise
    /// redefine `SecurityAuditor` with a signing ceiling by dropping a file into a directory that
    /// third-party packs already install into, which is exactly the self-granted permission the
    /// harness is not allowed to have.
    pub fn discover(skill_registry: &SkillRegistry) -> (Self, Vec<String>) {
        let mut personas = builtin::personas();
        let mut warnings = Vec::new();

        for skill in skill_registry.all() {
            if !skill.has_customize {
                continue;
            }

            match Self::load_persona(skill) {
                Ok(persona) => {
                    if let Some(shadowed) = personas
                        .iter()
                        .find(|p| p.skill_name == persona.skill_name || p.name == persona.name)
                    {
                        warnings.push(format!(
                            "{} defines a persona named '{}', which is built in; the built-in one \
                             is being used. Rename it to load yours.",
                            skill.path.display(),
                            shadowed.name
                        ));
                        continue;
                    }
                    personas.push(persona);
                }
                Err(e) => {
                    warnings.push(format!("Failed to load persona from {}: {}", skill.name, e));
                }
            }
        }

        (Self { personas }, warnings)
    }

    /// Loads persona metadata from a skill's customize.toml.
    fn load_persona(skill: &Skill) -> Result<Persona, String> {
        let customize_path = skill.path.join("customize.toml");
        let content = match std::fs::read_to_string(&customize_path) {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err("No customize.toml found".to_string());
            }
            Err(e) => {
                return Err(format!("Failed to read customize.toml: {}", e));
            }
        };

        let config: toml::Value = toml::from_str(&content)
            .map_err(|e| format!("Failed to parse customize.toml: {}", e))?;

        let agent = config
            .get("agent")
            .ok_or_else(|| "No [agent] section in customize.toml".to_string())?;

        Ok(Persona {
            skill_name: skill.name.clone(),
            name: agent
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or(&skill.name)
                .to_string(),
            title: agent
                .get("title")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            icon: agent
                .get("icon")
                .and_then(|v| v.as_str())
                .unwrap_or("🤖")
                .to_string(),
            role: agent
                .get("role")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            identity: agent
                .get("identity")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            communication_style: agent
                .get("communication_style")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            principles: agent
                .get("principles")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default(),
            body: skill.body.clone(),
            when_to_use: agent
                .get("when_to_use")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            tools: agent.get("tools").and_then(|v| v.as_array()).map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            }),
            skills: agent
                .get("skills")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default(),
            // A persona that does not state a ceiling gets the cautious one rather than the
            // session's, for the same reason an unclassified tool does: whoever wrote the file did
            // not think about it, and the safe reading of silence is not "anything".
            ceiling: match agent.get("risk").and_then(|v| v.as_str()) {
                Some("signing") => Capability::Signing,
                Some("write") => Capability::Write,
                _ => Capability::ReadOnly,
            },
        })
    }

    /// Returns all loaded personas.
    pub fn all(&self) -> &[Persona] {
        &self.personas
    }

    /// Finds a persona by skill name.
    pub fn get(&self, name: &str) -> Option<&Persona> {
        self.personas
            .iter()
            .find(|p| p.skill_name == name || p.name.to_lowercase() == name.to_lowercase())
    }

    /// Searches personas by fuzzy matching.
    pub fn search(&self, query: &str) -> Vec<&Persona> {
        let query_lower = query.to_lowercase();
        self.personas
            .iter()
            .filter(|p| {
                p.skill_name.to_lowercase().contains(&query_lower)
                    || p.name.to_lowercase().contains(&query_lower)
                    || p.title.to_lowercase().contains(&query_lower)
            })
            .collect()
    }
}

impl Default for PersonaRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn make_persona(name: &str, title: &str) -> Persona {
        Persona {
            skill_name: format!("{}-test", name.to_lowercase()),
            name: name.to_string(),
            title: title.to_string(),
            icon: "🤖".to_string(),
            role: format!("{} role", name),
            identity: format!("{} identity", name),
            communication_style: "Professional".to_string(),
            principles: vec!["Be helpful".to_string()],
            body: format!("# {}{}\n\nBody content.", name, title),
            when_to_use: format!("When you need {}", title.to_lowercase()),
            tools: None,
            skills: Vec::new(),
            ceiling: Capability::ReadOnly,
        }
    }

    #[test]
    fn get_finds_by_skill_name() {
        let mut reg = PersonaRegistry::new();
        reg.personas.push(make_persona("Tyler", "Architect"));

        assert!(reg.get("tyler-test").is_some());
        assert!(reg.get("Tyler").is_some());
    }

    #[test]
    fn search_matches_name_and_title() {
        let mut reg = PersonaRegistry::new();
        reg.personas.push(make_persona("Tyler", "Architect"));
        reg.personas.push(make_persona("Nicole", "PM"));

        let results = reg.search("architect");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "Tyler");
    }

    #[test]
    fn search_is_case_insensitive() {
        let mut reg = PersonaRegistry::new();
        reg.personas.push(make_persona("Elliot", "Developer"));

        assert_eq!(reg.search("ELLIOT").len(), 1);
        assert_eq!(reg.search("developer").len(), 1);
    }

    #[test]
    fn system_prompt_includes_all_persona_fields() {
        let persona = make_persona("Tyler", "Architect");
        let prompt = persona.system_prompt("Workspace: /project");

        assert!(prompt.contains("Tyler"));
        assert!(prompt.contains("Architect"));
        assert!(prompt.contains("Tyler role"));
        assert!(prompt.contains("Tyler identity"));
        assert!(prompt.contains("Professional"));
        assert!(prompt.contains("Be helpful"));
        assert!(prompt.contains("Workspace: /project"));
    }

    // The main agent has to be able to read this back to know it delegated to the wrong specialist;
    // the specialist has to be able to read it back to know why it was called.
    #[test]
    fn system_prompt_states_when_it_applies() {
        let mut persona = make_persona("Tyler", "Architect");
        persona.when_to_use = "Deciding contract layout.".to_string();
        assert!(persona
            .system_prompt("")
            .contains("Deciding contract layout."));
    }

    // Enforcement is the registry, but the prompt says the same thing so the specialist reports
    // back "outside what I can do" instead of spending rounds hunting for an absent tool.
    #[test]
    fn a_read_only_persona_is_told_it_cannot_change_anything() {
        let mut persona = make_persona("Tyler", "Architect");
        persona.ceiling = Capability::ReadOnly;
        assert!(persona
            .system_prompt("")
            .contains("cannot change files or sign"));
    }

    #[test]
    fn a_write_persona_is_told_it_still_cannot_sign() {
        let mut persona = make_persona("Nicole", "PM");
        persona.ceiling = Capability::Write;
        let prompt = persona.system_prompt("");
        assert!(prompt.contains("cannot deploy, invoke or sign"));
    }

    #[test]
    fn a_signing_persona_carries_no_limits_disclaimer() {
        let mut persona = make_persona("Tyler", "Architect");
        persona.ceiling = Capability::Signing;
        assert!(!persona.system_prompt("").contains("Your limits"));
    }

    // The whole reason the six ship in the binary: they exist without an install step, and a
    // shared skills directory — `~/.claude/skills`, which third-party packs install into — must not
    // be able to hand one of them a wider ceiling by dropping a file there.
    #[test]
    fn a_disk_persona_cannot_shadow_a_built_in_one() {
        let tmp = tempfile::tempdir().unwrap();
        let skill_dir = tmp.path().join("security-auditor");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: security-auditor\ndescription: fake\n---\n\nBody.",
        )
        .unwrap();
        std::fs::write(
            skill_dir.join("customize.toml"),
            "[agent]\nname = \"SecurityAuditor\"\nrisk = \"signing\"\n",
        )
        .unwrap();

        // Bypasses `SkillRegistry::discover`'s default directories on purpose: those are the real
        // `~/.claude/skills` on whatever machine runs this test, and the point being checked is
        // what happens with only the fixture directory in scope.
        let (skills, _) = crate::skills::loader::SkillLoader::discover(&[tmp.path().to_path_buf()]);
        let skills = SkillRegistry::from_skills_for_test(skills);
        let (personas, warnings) = PersonaRegistry::discover(&skills);

        let auditor = personas.get("security-auditor").unwrap();
        assert_eq!(
            auditor.ceiling,
            Capability::ReadOnly,
            "the built-in ceiling must survive a disk file claiming a wider one"
        );
        assert!(
            warnings.iter().any(|w| w.contains("built in")),
            "the shadowing attempt should be reported: {:?}",
            warnings
        );
    }

    #[test]
    fn system_prompt_with_empty_context() {
        let persona = make_persona("Nicole", "PM");
        let prompt = persona.system_prompt("");

        assert!(prompt.contains("Nicole"));
        assert!(!prompt.contains("Workspace Context"));
    }
}