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
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
use std::collections::HashMap;
use std::path::Path;

/// Parsed frontmatter + body from a SKILL.md file.
#[derive(Debug, Clone)]
pub struct ParsedSkill {
    pub frontmatter: HashMap<String, String>,
    /// Sequence-valued keys, in document order. Also present in `frontmatter`, comma-joined, so a
    /// caller that only wants the text of a key does not need to know which shape it arrived in —
    /// which is why nothing outside the parser's own tests reads this yet.
    #[allow(dead_code)]
    pub lists: HashMap<String, Vec<String>>,
    pub body: String,
}

/// The two maps a frontmatter block parses into.
#[derive(Debug, Default)]
struct Frontmatter {
    values: HashMap<String, String>,
    lists: HashMap<String, Vec<String>>,
}

/// Parses a SKILL.md file into frontmatter and body.
///
/// Format:
/// ```text
/// ---
/// name: elliot-dev
/// description: Senior software engineer...
/// user-invocable: true
/// ---
///
/// # Elliot — Senior Software Engineer
/// ...markdown body...
/// ```
pub fn parse_skill_file(path: &Path) -> Result<ParsedSkill, String> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    parse_skill_content(&content)
}

/// Parses SKILL.md content from a string.
pub fn parse_skill_content(content: &str) -> Result<ParsedSkill, String> {
    let content = content.trim_start_matches('\u{FEFF}'); // strip BOM

    let (frontmatter_str, body) = match split_frontmatter(content) {
        Some((fm, body)) => (fm, body),
        None => return Err("No YAML frontmatter found (expected --- delimiters)".to_string()),
    };

    let Frontmatter { values, lists } = parse_yaml_frontmatter(frontmatter_str)?;
    let body = body.trim().to_string();

    if body.is_empty() {
        return Err("Skill body is empty after frontmatter".to_string());
    }

    Ok(ParsedSkill {
        frontmatter: values,
        lists,
        body,
    })
}

/// Splits content at the `---` frontmatter delimiters.
/// Returns (frontmatter_str, body_str) or None if delimiters are missing.
fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
    // Must start with ---
    let content = content.strip_prefix("---")?;

    // Find the closing --- (the next line that is exactly "---")
    // It must be on its own line (followed by newline or EOF)
    let close_pos = content.find("\n---\n").or_else(|| {
        if content.ends_with("\n---") {
            Some(content.len() - 4)
        } else {
            None
        }
    })?;

    let fm = content[..close_pos].trim();
    let after_close = close_pos + 4; // skip the "---" itself
    let body = if after_close < content.len() {
        content[after_close..].trim()
    } else {
        ""
    };

    Some((fm, body))
}

/// Minimal YAML parser for the shapes skill frontmatter actually uses: scalars, flow sequences
/// (`tools: [read, write]`) and block sequences (`tools:` followed by indented `- ` items).
///
/// Sequences are the reason this is not a plain key/value split: a block sequence item has no
/// colon, so treating one as a malformed line rejected the whole skill — a `SKILL.md` that any
/// YAML parser accepts would simply vanish from the registry. Nested mappings are still not
/// modelled; they are skipped and recorded rather than treated as fatal, for the same reason.
///
/// Note: values containing colons are supported (e.g., `description: foo: bar`).
fn parse_yaml_frontmatter(fm: &str) -> Result<Frontmatter, String> {
    let mut out = Frontmatter::default();
    // The most recent key whose value was empty, and so may be a block sequence's header.
    let mut open_key: Option<String> = None;

    for raw in fm.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some(item) = block_sequence_item(line) {
            match &open_key {
                Some(key) => {
                    let item = strip_quotes(item.trim())?;
                    out.lists.entry(key.clone()).or_default().push(item);
                }
                None => crate::diag::warn(format!(
                    "skill frontmatter: sequence item without a key, ignored: {}",
                    line
                )),
            }
            continue;
        }

        // An indented line that is not a sequence item belongs to a nested mapping.
        if raw.starts_with(' ') || raw.starts_with('\t') {
            crate::diag::warn(format!(
                "skill frontmatter: nested mapping not supported, ignored: {}",
                line
            ));
            open_key = None;
            continue;
        }

        let colon_pos = line
            .find(": ")
            .or_else(|| {
                // Handle colon at end of line (empty value)
                if line.ends_with(':') {
                    Some(line.len() - 1)
                } else {
                    None
                }
            })
            .ok_or_else(|| format!("Invalid frontmatter line (no colon): {}", line))?;

        let key = line[..colon_pos].trim().to_string();
        let value = if colon_pos + 2 < line.len() {
            line[colon_pos + 2..].trim().to_string()
        } else {
            String::new()
        };

        if value.is_empty() {
            // Either an empty scalar or the header of a block sequence; the next line decides.
            out.values.insert(key.clone(), String::new());
            open_key = Some(key);
            continue;
        }

        open_key = None;

        if let Some(items) = parse_flow_sequence(&value)? {
            out.values.insert(key.clone(), items.join(", "));
            out.lists.insert(key, items);
            continue;
        }

        out.values.insert(key, strip_quotes(&value)?);
    }

    // A key that opened a block sequence keeps the joined form too, matching flow sequences.
    for (key, items) in &out.lists {
        out.values.insert(key.clone(), items.join(", "));
    }

    Ok(out)
}

/// Returns the content of a block sequence item (`- value`), or None if the line is not one.
fn block_sequence_item(line: &str) -> Option<&str> {
    line.strip_prefix("- ")
        .or_else(|| if line == "-" { Some("") } else { None })
}

/// Parses a flow sequence (`[a, b]`), returning None if the value is not one.
///
/// Splitting is quote- and depth-aware: a comma inside `"a, b"` or a nested `[..]` is content, not
/// a separator. A value that opens a bracket without closing it on the same line is left to the
/// caller as a scalar — multi-line flow sequences are outside what this parser claims to handle.
fn parse_flow_sequence(value: &str) -> Result<Option<Vec<String>>, String> {
    if !value.starts_with('[') {
        return Ok(None);
    }
    if !value.ends_with(']') {
        crate::diag::warn(format!(
            "skill frontmatter: unterminated flow sequence kept as text: {}",
            value
        ));
        return Ok(None);
    }

    let inner = &value[1..value.len() - 1];
    let mut items: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut depth = 0usize;

    for c in inner.chars() {
        match c {
            '\'' | '"' if quote.is_none() => {
                quote = Some(c);
                current.push(c);
            }
            _ if Some(c) == quote => {
                quote = None;
                current.push(c);
            }
            '[' | '{' if quote.is_none() => {
                depth += 1;
                current.push(c);
            }
            ']' | '}' if quote.is_none() => {
                depth = depth.saturating_sub(1);
                current.push(c);
            }
            ',' if quote.is_none() && depth == 0 => {
                items.push(strip_quotes(current.trim())?);
                current.clear();
            }
            _ => current.push(c),
        }
    }

    if quote.is_some() {
        return Err(format!("Unterminated quote in flow sequence: {}", value));
    }

    // A trailing comma is legal YAML and yields no final item.
    if !current.trim().is_empty() {
        items.push(strip_quotes(current.trim())?);
    }

    Ok(Some(items))
}

/// Strips single or double quotes from a value.
/// Returns an error if quotes are mismatched (e.g., `"hello'`).
fn strip_quotes(s: &str) -> Result<String, String> {
    if s.starts_with('"') {
        if s.ends_with('"') {
            Ok(s[1..s.len() - 1].to_string())
        } else {
            Err(format!("Mismatched double quotes in: {}", s))
        }
    } else if s.starts_with('\'') {
        if s.ends_with('\'') {
            Ok(s[1..s.len() - 1].to_string())
        } else {
            Err(format!("Mismatched single quotes in: {}", s))
        }
    } else {
        Ok(s.to_string())
    }
}

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

    const SKILL_WITH_FRONTMATTER: &str = r#"---
name: elliot-dev
description: Senior software engineer for story execution.
user-invocable: true
argument-hint: "[story name]"
---

# Elliot — Senior Software Engineer

## Overview

You are Elliot, the Senior Software Engineer."#;

    const SKILL_MINIMAL: &str = r#"---
name: soroban
description: Soroban smart contract development
---

# Soroban Smart Contracts

Content here."#;

    const SKILL_NO_BODY: &str = r#"---
name: empty
description: has no body
---"#;

    const SKILL_NO_FRONTMATTER: &str = r#"# Just a markdown file

No frontmatter here."#;

    #[test]
    fn parses_frontmatter_and_body() {
        let parsed = parse_skill_content(SKILL_WITH_FRONTMATTER).unwrap();
        assert_eq!(parsed.frontmatter.get("name").unwrap(), "elliot-dev");
        assert_eq!(
            parsed.frontmatter.get("description").unwrap(),
            "Senior software engineer for story execution."
        );
        assert_eq!(parsed.frontmatter.get("user-invocable").unwrap(), "true");
        assert_eq!(
            parsed.frontmatter.get("argument-hint").unwrap(),
            "[story name]"
        );
        assert!(parsed.body.starts_with("# Elliot"));
    }

    #[test]
    fn parses_minimal_skill() {
        let parsed = parse_skill_content(SKILL_MINIMAL).unwrap();
        assert_eq!(parsed.frontmatter.get("name").unwrap(), "soroban");
        assert!(parsed.body.contains("Content here"));
    }

    #[test]
    fn rejects_empty_body() {
        let err = parse_skill_content(SKILL_NO_BODY).unwrap_err();
        assert!(err.contains("empty"), "got {}", err);
    }

    #[test]
    fn rejects_missing_frontmatter() {
        let err = parse_skill_content(SKILL_NO_FRONTMATTER).unwrap_err();
        assert!(err.contains("No YAML frontmatter"), "got {}", err);
    }

    #[test]
    fn handles_bom() {
        let with_bom = format!("\u{FEFF}{}", SKILL_MINIMAL);
        let parsed = parse_skill_content(&with_bom).unwrap();
        assert_eq!(parsed.frontmatter.get("name").unwrap(), "soroban");
    }

    fn values(fm: &str) -> HashMap<String, String> {
        parse_yaml_frontmatter(fm).unwrap().values
    }

    fn lists(fm: &str) -> HashMap<String, Vec<String>> {
        parse_yaml_frontmatter(fm).unwrap().lists
    }

    // Each case is a distinct scalar shape the line-splitter has to get right; table-driven since
    // none carries its own regression story the way the sequence tests below do.
    #[test]
    fn parses_scalar_value_shapes() {
        let cases = [
            ("name: 'my-skill'", "name", "my-skill"),
            ("description: \"a skill\"", "description", "a skill"),
            ("description: foo: bar: baz", "description", "foo: bar: baz"),
            ("description: test", "description", "test"),
        ];
        for (fm, key, expected) in cases {
            let map = values(fm);
            assert_eq!(map.get(key).unwrap(), expected, "input: {}", fm);
        }
    }

    #[test]
    fn rejects_mismatched_quotes() {
        let fm = "name: \"hello'";
        let err = parse_yaml_frontmatter(fm).unwrap_err();
        assert!(err.contains("Mismatched"), "{}", err);
    }

    #[test]
    fn handles_empty_value() {
        let fm = "name:\ndescription: test";
        let map = values(fm);
        assert_eq!(map.get("name").unwrap(), "");
        assert_eq!(map.get("description").unwrap(), "test");
    }

    #[test]
    fn skips_blank_lines_and_comments() {
        let fm = "\n# comment\nname: test\n\n";
        assert_eq!(values(fm).get("name").unwrap(), "test");
    }

    #[test]
    fn parses_a_flow_sequence() {
        let fm = "name: test\nallowed-tools: [read_file, write_file]";
        assert_eq!(
            lists(fm).get("allowed-tools").unwrap(),
            &vec!["read_file".to_string(), "write_file".to_string()]
        );
        // The joined form is there too, so a scalar-only caller still reads something sensible.
        assert_eq!(
            values(fm).get("allowed-tools").unwrap(),
            "read_file, write_file"
        );
    }

    // A comma inside a quoted element is content. Splitting on every comma would have turned one
    // element into two, silently.
    #[test]
    fn a_quoted_comma_does_not_split_a_flow_sequence() {
        let fm = r#"tags: ["a, b", 'c, d', e]"#;
        assert_eq!(
            lists(fm).get("tags").unwrap(),
            &vec!["a, b".to_string(), "c, d".to_string(), "e".to_string()]
        );
    }

    #[test]
    fn a_nested_flow_collection_stays_one_element() {
        let fm = "matrix: [[a, b], {k: v}]";
        assert_eq!(
            lists(fm).get("matrix").unwrap(),
            &vec!["[a, b]".to_string(), "{k: v}".to_string()]
        );
    }

    #[test]
    fn an_empty_flow_sequence_yields_no_items() {
        let fm = "tools: []";
        assert!(lists(fm).get("tools").unwrap().is_empty());
        assert_eq!(values(fm).get("tools").unwrap(), "");
    }

    #[test]
    fn a_trailing_comma_yields_no_extra_item() {
        let fm = "tools: [a, b,]";
        assert_eq!(lists(fm).get("tools").unwrap().len(), 2);
    }

    // The regression this parser existed to cause: a block sequence has no colon on its item
    // lines, so every one of them was reported as a malformed line and the skill never loaded.
    #[test]
    fn parses_a_block_sequence() {
        let fm = "name: test\nallowed-tools:\n  - read_file\n  - write_file\ndescription: after";
        let parsed = parse_yaml_frontmatter(fm).unwrap();

        assert_eq!(
            parsed.lists.get("allowed-tools").unwrap(),
            &vec!["read_file".to_string(), "write_file".to_string()]
        );
        assert_eq!(parsed.values.get("name").unwrap(), "test");
        assert_eq!(
            parsed.values.get("description").unwrap(),
            "after",
            "a key after the sequence must still parse"
        );
    }

    #[test]
    fn a_block_sequence_item_may_be_quoted() {
        let fm = "tags:\n  - \"a, b\"\n  - 'c'";
        assert_eq!(
            lists(fm).get("tags").unwrap(),
            &vec!["a, b".to_string(), "c".to_string()]
        );
    }

    #[test]
    fn a_skill_with_a_block_sequence_loads() {
        let content = "---\nname: seq\ndescription: has a sequence\nallowed-tools:\n  - read_file\n---\n\nBody.";
        let parsed = parse_skill_content(content).unwrap();

        assert_eq!(parsed.frontmatter.get("name").unwrap(), "seq");
        assert_eq!(
            parsed.lists.get("allowed-tools").unwrap(),
            &vec!["read_file".to_string()]
        );
    }

    // Anything this parser cannot model is skipped, not fatal — but it is recorded, so a key that
    // quietly went missing is explainable.
    #[test]
    fn a_nested_mapping_is_skipped_and_recorded() {
        let _guard = crate::diag::test_lock();
        crate::diag::drain();

        let fm = "name: test\nagent:\n  name: Tyler\ndescription: after";
        let parsed = parse_yaml_frontmatter(fm).unwrap();

        assert_eq!(parsed.values.get("name").unwrap(), "test");
        assert_eq!(parsed.values.get("description").unwrap(), "after");
        assert!(!parsed.lists.contains_key("agent"));

        let warnings = crate::diag::drain();
        assert!(
            warnings.iter().any(|w| w.contains("nested mapping")),
            "expected a recorded warning, got {:?}",
            warnings
        );
    }

    #[test]
    fn an_unterminated_quote_in_a_flow_sequence_is_an_error() {
        let err = parse_yaml_frontmatter("tags: [\"a, b]").unwrap_err();
        assert!(err.contains("Unterminated"), "got {}", err);
    }

    #[test]
    fn parses_file_from_disk() {
        let path = Path::new("/home/dionebastos/.claude/skills/elliot-dev/SKILL.md");
        if path.exists() {
            let parsed = parse_skill_file(path).unwrap();
            assert_eq!(parsed.frontmatter.get("name").unwrap(), "elliot-dev");
            assert!(!parsed.body.is_empty());
        }
    }
}