agentnative 0.3.1

The agent-native CLI linter — check whether your CLI follows agent-readiness principles
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
//! Spec frontmatter parser used by `build.rs` to generate `REQUIREMENTS`.
//!
//! Mirrored by `agentnative:scripts/validate-principles.mjs` on the spec side
//! — the two parsers must agree on the schema. If a vendored file fails here,
//! the build fails loudly: every error names the offending file, requirement
//! id, and field so a human can fix it without grepping.

use std::collections::HashMap;
use std::fmt;

use serde::Deserialize;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
    Must,
    Should,
    May,
}

impl Level {
    fn sort_key(self) -> u8 {
        match self {
            Level::Must => 0,
            Level::Should => 1,
            Level::May => 2,
        }
    }

    fn rust_variant(self) -> &'static str {
        match self {
            Level::Must => "Level::Must",
            Level::Should => "Level::Should",
            Level::May => "Level::May",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Applicability {
    Universal,
    Conditional(String),
}

#[derive(Debug, Clone)]
pub struct ParsedRequirement {
    pub id: String,
    pub principle: u8,
    pub level: Level,
    pub summary: String,
    pub applicability: Applicability,
}

#[derive(Debug)]
pub enum ParseError {
    UnterminatedFrontmatter {
        file: String,
    },
    YamlError {
        file: String,
        message: String,
    },
    InvalidPrincipleId {
        file: String,
        value: String,
    },
    DuplicateId {
        id: String,
        file_a: String,
        file_b: String,
    },
    UnknownLevel {
        file: String,
        requirement_id: String,
        value: String,
    },
    UnknownApplicability {
        file: String,
        requirement_id: String,
        hint: String,
    },
    MissingField {
        file: String,
        requirement_id: Option<String>,
        field: String,
    },
    InvalidUniversal {
        file: String,
        requirement_id: String,
        value: String,
    },
    EmptyRequirements {
        file: String,
    },
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::UnterminatedFrontmatter { file } => write!(
                f,
                "{file}: frontmatter not terminated — expected closing `---` line"
            ),
            ParseError::YamlError { file, message } => {
                write!(f, "{file}: YAML parse error: {message}")
            }
            ParseError::InvalidPrincipleId { file, value } => write!(
                f,
                "{file}: file-level `id` must be `pN` (e.g., `p1`), got `{value}`"
            ),
            ParseError::DuplicateId { id, file_a, file_b } => write!(
                f,
                "duplicate requirement id `{id}` in `{file_a}` and `{file_b}` — ids must be unique across all principles"
            ),
            ParseError::UnknownLevel {
                file,
                requirement_id,
                value,
            } => write!(
                f,
                "{file}: requirement `{requirement_id}` has unknown level `{value}` — must be one of `must`, `should`, `may`"
            ),
            ParseError::UnknownApplicability {
                file,
                requirement_id,
                hint,
            } => write!(
                f,
                "{file}: requirement `{requirement_id}` has unsupported `applicability` shape — {hint}"
            ),
            ParseError::MissingField {
                file,
                requirement_id,
                field,
            } => match requirement_id {
                Some(id) => write!(
                    f,
                    "{file}: requirement `{id}` is missing required field `{field}`"
                ),
                None => write!(f, "{file}: missing required top-level field `{field}`"),
            },
            ParseError::InvalidUniversal {
                file,
                requirement_id,
                value,
            } => write!(
                f,
                "{file}: requirement `{requirement_id}` has bare-string `applicability: {value}` — only `universal` is accepted as a bare string; conditional forms must use `applicability: {{ if: \"<prose>\" }}`"
            ),
            ParseError::EmptyRequirements { file } => {
                write!(f, "{file}: `requirements` list is empty")
            }
        }
    }
}

impl std::error::Error for ParseError {}

#[derive(Debug, Deserialize)]
struct RawFrontmatter {
    id: String,
    requirements: Vec<RawRequirement>,
    // Fields we don't need at runtime: title, last-revised, status. Tolerated.
    #[serde(flatten)]
    _extra: serde_yaml::Mapping,
}

#[derive(Debug, Deserialize)]
struct RawRequirement {
    id: Option<String>,
    level: Option<serde_yaml::Value>,
    applicability: Option<serde_yaml::Value>,
    summary: Option<String>,
    #[serde(flatten)]
    _extra: serde_yaml::Mapping,
}

/// Parse a single principle markdown file.
///
/// Returns the requirements declared in `requirements:` in source order.
pub fn parse_principle_file(
    file_path: &str,
    content: &str,
) -> Result<Vec<ParsedRequirement>, ParseError> {
    let yaml_block = extract_frontmatter(file_path, content)?;
    let raw: RawFrontmatter =
        serde_yaml::from_str(yaml_block).map_err(|e| ParseError::YamlError {
            file: file_path.to_string(),
            message: e.to_string(),
        })?;

    let principle = parse_principle_id(file_path, &raw.id)?;

    if raw.requirements.is_empty() {
        return Err(ParseError::EmptyRequirements {
            file: file_path.to_string(),
        });
    }

    let mut out = Vec::with_capacity(raw.requirements.len());
    for raw_req in raw.requirements {
        let id = raw_req.id.ok_or_else(|| ParseError::MissingField {
            file: file_path.to_string(),
            requirement_id: None,
            field: "id".into(),
        })?;

        let level = parse_level(file_path, &id, raw_req.level.as_ref())?;
        let summary = raw_req.summary.ok_or_else(|| ParseError::MissingField {
            file: file_path.to_string(),
            requirement_id: Some(id.clone()),
            field: "summary".into(),
        })?;
        let applicability = parse_applicability(file_path, &id, raw_req.applicability.as_ref())?;

        out.push(ParsedRequirement {
            id,
            principle,
            level,
            summary,
            applicability,
        });
    }

    Ok(out)
}

/// Aggregate per-file parse results into a single, sorted, deduped slice.
///
/// Sort order: `(principle, level: must<should<may, source-order-within-level)`.
/// Source order is preserved by stable-sorting on the composite key while
/// keeping the per-file source order as the secondary tiebreaker.
pub fn aggregate(
    parsed: Vec<(String, Vec<ParsedRequirement>)>,
) -> Result<Vec<ParsedRequirement>, ParseError> {
    let mut seen: HashMap<String, String> = HashMap::new();
    let mut all: Vec<ParsedRequirement> = Vec::new();

    for (file, reqs) in parsed {
        for req in reqs {
            if let Some(existing_file) = seen.get(&req.id) {
                return Err(ParseError::DuplicateId {
                    id: req.id.clone(),
                    file_a: existing_file.clone(),
                    file_b: file.clone(),
                });
            }
            seen.insert(req.id.clone(), file.clone());
            all.push(req);
        }
    }

    // Stable sort preserves source order within identical (principle, level).
    all.sort_by_key(|r| (r.principle, r.level.sort_key()));
    Ok(all)
}

/// Emit Rust source for `$OUT_DIR/generated_requirements.rs`.
pub fn emit_rust(reqs: &[ParsedRequirement], spec_version: &str) -> String {
    let mut out = String::new();
    out.push_str(
        "// @generated by build.rs from src/principles/spec/principles/*.md.\n\
         // Do not edit by hand — rerun `cargo build` (or `scripts/sync-spec.sh` then `cargo build`)\n\
         // to regenerate.\n\n",
    );

    out.push_str(
        "/// Every MUST/SHOULD/MAY in the spec, generated from vendored frontmatter.\n\
         /// Sort order: principle ascending, then level (MUST → SHOULD → MAY),\n\
         /// preserving spec source order within a level.\n",
    );
    out.push_str("pub static REQUIREMENTS: &[Requirement] = &[\n");
    for r in reqs {
        out.push_str("    Requirement {\n");
        out.push_str(&format!("        id: \"{}\",\n", escape_rust_str(&r.id)));
        out.push_str(&format!("        principle: {},\n", r.principle));
        out.push_str(&format!("        level: {},\n", r.level.rust_variant()));
        out.push_str(&format!(
            "        summary: \"{}\",\n",
            escape_rust_str(&r.summary)
        ));
        match &r.applicability {
            Applicability::Universal => {
                out.push_str("        applicability: Applicability::Universal,\n");
            }
            Applicability::Conditional(cond) => {
                out.push_str(&format!(
                    "        applicability: Applicability::Conditional(\"{}\"),\n",
                    escape_rust_str(cond)
                ));
            }
        }
        out.push_str("    },\n");
    }
    out.push_str("];\n\n");

    out.push_str("/// Spec version vendored under `src/principles/spec/VERSION` at build time.\n");
    out.push_str("#[allow(dead_code)]\n");
    out.push_str(&format!(
        "pub const SPEC_VERSION: &str = \"{}\";\n",
        escape_rust_str(spec_version)
    ));

    out
}

fn extract_frontmatter<'a>(file_path: &str, content: &'a str) -> Result<&'a str, ParseError> {
    // First non-empty line must be `---`. Then find next `---` on its own line.
    let trimmed = content.trim_start_matches('\u{feff}'); // tolerate BOM
    let after_first = trimmed
        .strip_prefix("---\n")
        .or_else(|| trimmed.strip_prefix("---\r\n"))
        .ok_or_else(|| ParseError::UnterminatedFrontmatter {
            file: file_path.to_string(),
        })?;

    let end_idx =
        find_closing_fence(after_first).ok_or_else(|| ParseError::UnterminatedFrontmatter {
            file: file_path.to_string(),
        })?;

    Ok(&after_first[..end_idx])
}

fn find_closing_fence(s: &str) -> Option<usize> {
    // Look for a line that is exactly `---` (possibly followed by \r and \n or EOF).
    let mut idx = 0;
    for line in s.split_inclusive('\n') {
        let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
        if trimmed == "---" {
            return Some(idx);
        }
        idx += line.len();
    }
    None
}

fn parse_principle_id(file: &str, raw: &str) -> Result<u8, ParseError> {
    raw.strip_prefix('p')
        .and_then(|s| s.parse::<u8>().ok())
        .filter(|n| (1..=255).contains(n))
        .ok_or_else(|| ParseError::InvalidPrincipleId {
            file: file.to_string(),
            value: raw.to_string(),
        })
}

fn parse_level(
    file: &str,
    req_id: &str,
    value: Option<&serde_yaml::Value>,
) -> Result<Level, ParseError> {
    let value = value.ok_or_else(|| ParseError::MissingField {
        file: file.to_string(),
        requirement_id: Some(req_id.to_string()),
        field: "level".into(),
    })?;

    let s = value.as_str().ok_or_else(|| ParseError::UnknownLevel {
        file: file.to_string(),
        requirement_id: req_id.to_string(),
        value: format!("{value:?}"),
    })?;

    match s {
        "must" => Ok(Level::Must),
        "should" => Ok(Level::Should),
        "may" => Ok(Level::May),
        other => Err(ParseError::UnknownLevel {
            file: file.to_string(),
            requirement_id: req_id.to_string(),
            value: other.to_string(),
        }),
    }
}

fn parse_applicability(
    file: &str,
    req_id: &str,
    value: Option<&serde_yaml::Value>,
) -> Result<Applicability, ParseError> {
    let value = value.ok_or_else(|| ParseError::MissingField {
        file: file.to_string(),
        requirement_id: Some(req_id.to_string()),
        field: "applicability".into(),
    })?;

    if let Some(s) = value.as_str() {
        if s == "universal" {
            return Ok(Applicability::Universal);
        }
        return Err(ParseError::InvalidUniversal {
            file: file.to_string(),
            requirement_id: req_id.to_string(),
            value: s.to_string(),
        });
    }

    if let Some(map) = value.as_mapping() {
        let if_key = serde_yaml::Value::String("if".into());
        if map.len() == 1
            && let Some(if_val) = map.get(&if_key)
        {
            let cond = if_val
                .as_str()
                .ok_or_else(|| ParseError::UnknownApplicability {
                    file: file.to_string(),
                    requirement_id: req_id.to_string(),
                    hint: "`if:` value must be a non-empty string".into(),
                })?;
            if cond.is_empty() {
                return Err(ParseError::UnknownApplicability {
                    file: file.to_string(),
                    requirement_id: req_id.to_string(),
                    hint: "`if:` value must be a non-empty string".into(),
                });
            }
            return Ok(Applicability::Conditional(cond.to_string()));
        }
        return Err(ParseError::UnknownApplicability {
            file: file.to_string(),
            requirement_id: req_id.to_string(),
            hint: "expected `{ if: \"<prose>\" }`".into(),
        });
    }

    Err(ParseError::UnknownApplicability {
        file: file.to_string(),
        requirement_id: req_id.to_string(),
        hint: "must be `universal` or `{ if: \"<prose>\" }`".into(),
    })
}

fn escape_rust_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}