alp-core 0.1.6

Pure domain logic for the ALP SDK tooling: board.yaml model/validate, build-plan + system-manifest contracts, presets, and debug/doctor reports. Shared by the `alp` CLI.
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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// SPDX-License-Identifier: Apache-2.0
//! Local (offline) board.yaml validation.
//!
//! Mirrors the TypeScript `validateBoardYamlLocally` in
//! `@alp-sdk/core/validation/service.ts`. This is the offline parity
//! target shared by the conformance fixtures; full SDK-spawn validation
//! arrives in a later phase.

use crate::model::BoardModel;

/// Validation outcome — stable string identifiers shared with the CLI
/// envelope and the TS implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// Validation passed with no issues.
    Clean,
    /// SoM/preset could not be resolved (validator exit 2); treated as a warning.
    MissingPreset,
    /// Schema/structural violation (validator exit 1).
    SchemaViolation,
    /// Hardware-revision incompatibility (validator exit 3).
    HardwareRevision,
    /// Validation could not be completed (validator crashed / unknown exit status).
    Failed,
}

impl Outcome {
    /// Stable string identifier for this outcome, as emitted in the CLI envelope.
    pub fn as_str(self) -> &'static str {
        match self {
            Outcome::Clean => "clean",
            Outcome::MissingPreset => "missing-preset",
            Outcome::SchemaViolation => "schema-violation",
            Outcome::HardwareRevision => "hardware-revision",
            Outcome::Failed => "failed",
        }
    }
}

/// Per-issue severity level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
    Suggestion,
}

impl Severity {
    /// Stable lowercase string identifier for this severity.
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Suggestion => "suggestion",
        }
    }
}

/// A single validation finding: human-readable `message` plus its `severity`.
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    pub message: String,
    pub severity: Severity,
}

/// Aggregate validation result: overall `outcome` plus the list of `issues`.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub outcome: Outcome,
    pub issues: Vec<ValidationIssue>,
}

/// Error returned when board.yaml text cannot be parsed into a `BoardModel`.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    /// The input was not syntactically valid YAML.
    #[error("board.yaml is not valid YAML: {0}")]
    Yaml(#[from] serde_yaml::Error),
}

/// Parse board.yaml text into a [`BoardModel`].
///
/// Matches TS `parseBoardModel`: a YAML scalar/null parses to the default
/// model rather than an error; only true syntax errors fail.
pub fn parse_board_model(text: &str) -> Result<BoardModel, ParseError> {
    match serde_yaml::from_str::<Option<BoardModel>>(text) {
        Ok(Some(model)) => Ok(model),
        Ok(None) => Ok(BoardModel::default()),
        Err(e) => Err(ParseError::Yaml(e)),
    }
}

/// Local structural validation. Mirrors `validateBoardYamlLocally`:
/// for schema_version >= 2, top-level `os:` is rejected and a non-empty
/// `cores:` block is required.
pub fn validate_board_yaml_local(text: &str) -> Result<ValidationResult, ParseError> {
    let model = parse_board_model(text)?;
    let mut issues = Vec::new();

    if model.effective_schema_version() >= 2 {
        if model.os.is_some() {
            issues.push(ValidationIssue {
                message:
                    "board.yaml v2: top-level 'os:' is not valid; move it into a 'cores:' block"
                        .to_string(),
                severity: Severity::Error,
            });
        }
        let has_cores = model.cores.as_ref().is_some_and(|c| !c.is_empty());
        if !has_cores {
            issues.push(ValidationIssue {
                message:
                    "board.yaml v2: 'cores:' block is required and must have at least one entry"
                        .to_string(),
                severity: Severity::Error,
            });
        }
    }

    let outcome = if issues.is_empty() {
        Outcome::Clean
    } else {
        Outcome::SchemaViolation
    };

    Ok(ValidationResult { outcome, issues })
}

// ───────────────────────── full (spawn) validation ─────────────────────────
//
// The real `alp validate` shells out to `<sdk>/scripts/validate_board_yaml.py`.
// The analysis below mirrors TS `analyzeValidationResult` + `parseValidationIssues`:
// classify by the process exit status, then turn stderr into structured issues.

/// Result of spawning the Python validator (mirrors TS `ValidatorExecutionResult`).
pub struct ValidatorExecution {
    /// Process exit status; `None` if the process was killed / never started.
    pub status: Option<i32>,
    /// Captured standard output of the validator process.
    pub stdout: String,
    /// Captured standard error; the source of structured issues.
    pub stderr: String,
}

/// Map the validator's exit status to an [`Outcome`] (TS `classifyValidationOutcome`).
pub fn classify_validation_outcome(status: Option<i32>) -> Outcome {
    match status {
        Some(0) => Outcome::Clean,
        Some(2) => Outcome::MissingPreset,
        Some(3) => Outcome::HardwareRevision,
        Some(1) => Outcome::SchemaViolation,
        _ => Outcome::Failed,
    }
}

fn severity_for_outcome(outcome: Outcome) -> Severity {
    if outcome == Outcome::MissingPreset {
        Severity::Warning
    } else {
        Severity::Error
    }
}

/// Classify + parse a validator execution into a [`ValidationResult`]
/// (TS `analyzeValidationResult`).
pub fn analyze_validation_result(execution: &ValidatorExecution) -> ValidationResult {
    let outcome = classify_validation_outcome(execution.status);
    let issues = parse_validation_issues(&execution.stderr, severity_for_outcome(outcome));
    ValidationResult { outcome, issues }
}

/// Parse validator stderr into structured issues — a faithful port of TS
/// `parseValidationIssues`. Handles rich `error[ALP-B*]` blocks (with `-->`
/// location arrows + indented source/hint continuation), legacy `FAIL`/`WARN`
/// lines with indented continuations, and standalone `hint:` suggestions.
///
/// The CLI only consumes `message` + `severity` (it rewrites the issue code to
/// `validate.<outcome>`), so block code/line/col are parsed for correct line
/// skipping but not retained.
fn parse_validation_issues(stderr: &str, severity: Severity) -> Vec<ValidationIssue> {
    let lines: Vec<&str> = stderr
        .split('\n')
        .map(|l| l.strip_suffix('\r').unwrap_or(l))
        .collect();

    let mut issues = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];

        if line.trim().is_empty() || is_summary_line(line) {
            i += 1;
            continue;
        }

        // Rich ALP-B* block.
        if let Some((sev, message)) = parse_rich_header(line) {
            let issue_severity = match sev {
                "error" => Severity::Error,
                "warning" => Severity::Warning,
                _ => Severity::Suggestion,
            };
            let issue = ValidationIssue {
                message: message.trim().to_string(),
                severity: issue_severity,
            };
            if i + 1 < lines.len() && is_arrow_line(lines[i + 1]) {
                i += 2;
                while i < lines.len() && is_block_continuation(lines[i]) {
                    i += 1;
                }
                issues.push(issue);
                continue;
            }
            issues.push(issue);
            i += 1;
            continue;
        }

        // Legacy FAIL / WARN lines.
        if let Some((level, rest)) = parse_fail_warn(line) {
            let issue_severity = if level == "WARN" {
                Severity::Warning
            } else {
                severity
            };
            let mut parts = vec![rest.trim().to_string()];
            while i + 1 < lines.len() && is_fail_continuation(lines[i + 1]) {
                i += 1;
                parts.push(lines[i].trim().to_string());
            }
            issues.push(ValidationIssue {
                message: parts.join("  "),
                severity: issue_severity,
            });
            i += 1;
            continue;
        }

        // Standalone hint / suggestion lines.
        if is_hint_line(line) {
            issues.push(ValidationIssue {
                message: line.trim().to_string(),
                severity: Severity::Suggestion,
            });
            i += 1;
            continue;
        }

        i += 1;
    }

    issues
}

/// `^\S.*\.yaml:\s+(missing-preset|hardware|capability)` — non-actionable
/// summary lines emitted by `validate_board_yaml.py main()`.
fn is_summary_line(line: &str) -> bool {
    let Some(first) = line.chars().next() else {
        return false;
    };
    if first.is_whitespace() {
        return false;
    }
    let after_first = &line[first.len_utf8()..];
    let Some(rel) = after_first.find(".yaml:") else {
        return false;
    };
    let rest = &after_first[rel + ".yaml:".len()..];
    let trimmed = rest.trim_start();
    if trimmed.len() == rest.len() {
        return false; // needs at least one whitespace (\s+)
    }
    trimmed.starts_with("missing-preset")
        || trimmed.starts_with("hardware")
        || trimmed.starts_with("capability")
}

/// `^(error|warning|note)\[(ALP-[A-Z]\d+)\]:\s*(.+)` — returns (severity, message).
fn parse_rich_header(line: &str) -> Option<(&str, &str)> {
    for kw in ["error", "warning", "note"] {
        if let Some(rest) = line.strip_prefix(kw) {
            if let Some(rest) = rest.strip_prefix('[') {
                if let Some(close) = rest.find("]:") {
                    if is_alp_code(&rest[..close]) {
                        let message = rest[close + 2..].trim_start();
                        if !message.is_empty() {
                            return Some((kw, message));
                        }
                    }
                }
            }
        }
    }
    None
}

/// `ALP-[A-Z]\d+`
fn is_alp_code(code: &str) -> bool {
    let Some(rest) = code.strip_prefix("ALP-") else {
        return false;
    };
    let mut chars = rest.chars();
    match chars.next() {
        Some(c) if c.is_ascii_uppercase() => {}
        _ => return false,
    }
    let digits = chars.as_str();
    !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit())
}

/// `^\s+-->\s+\S+:(\d+):(\d+)` — the location arrow inside a rich block.
fn is_arrow_line(line: &str) -> bool {
    if !line.starts_with(char::is_whitespace) {
        return false;
    }
    let Some(after) = line.trim_start().strip_prefix("-->") else {
        return false;
    };
    if !after.starts_with(char::is_whitespace) {
        return false;
    }
    // `split_whitespace` already skips the leading `\s+` after `-->`.
    let Some(token) = after.split_whitespace().next() else {
        return false;
    };
    let parts: Vec<&str> = token.rsplitn(3, ':').collect();
    if parts.len() < 3 {
        return false;
    }
    let is_num = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
    !parts[2].is_empty() && is_num(parts[0]) && is_num(parts[1])
}

/// `^\s+[|0-9^= ]` — indented source/underline/hint continuation of a rich block.
fn is_block_continuation(line: &str) -> bool {
    let mut chars = line.chars();
    match chars.next() {
        Some(c) if c.is_whitespace() => {}
        _ => return false,
    }
    match chars.next() {
        Some(c) if c.is_whitespace() => true, // ≥2 leading whitespace (space ∈ set)
        Some(c) if c == '|' || c == '^' || c == '=' || c.is_ascii_digit() => true,
        _ => false,
    }
}

/// `^(FAIL|WARN)\s+(.+)` — returns (level, message-without-leading-ws).
fn parse_fail_warn(line: &str) -> Option<(&str, &str)> {
    for level in ["FAIL", "WARN"] {
        if let Some(rest) = line.strip_prefix(level) {
            if rest.starts_with(char::is_whitespace) {
                let message = rest.trim_start();
                if !message.is_empty() {
                    return Some((level, message));
                }
            }
        }
    }
    None
}

/// `^\s{2,}\S` — indented continuation of a legacy FAIL/WARN line.
fn is_fail_continuation(line: &str) -> bool {
    let leading_ws = line.chars().take_while(|c| c.is_whitespace()).count();
    leading_ws >= 2 && !line.trim_start().is_empty()
}

/// `^\s*(hint|suggestion|suggest):` (case-insensitive)
fn is_hint_line(line: &str) -> bool {
    let lowered = line.trim_start().to_ascii_lowercase();
    lowered.starts_with("hint:")
        || lowered.starts_with("suggestion:")
        || lowered.starts_with("suggest:")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Carrier, Inference, Iot, Som, normalize_board_model};
    use std::collections::BTreeMap;

    #[test]
    fn v1_board_passes_without_errors() {
        let text = "som:\n  sku: E1M-AEN701\npreset: e1m-evk\n";
        let r = validate_board_yaml_local(text).unwrap();
        assert_eq!(r.outcome, Outcome::Clean);
        assert!(r.issues.is_empty());
    }

    #[test]
    fn v2_clean_board_passes() {
        let text =
            "schema_version: 2\nsom:\n  sku: E1M-AEN701\ncores:\n  m55_hp:\n    app: ./src\n";
        let r = validate_board_yaml_local(text).unwrap();
        assert_eq!(r.outcome, Outcome::Clean);
    }

    #[test]
    fn v2_top_level_os_is_rejected() {
        let text = "schema_version: 2\nos: zephyr\ncores:\n  m55_hp:\n    app: ./src\n";
        let r = validate_board_yaml_local(text).unwrap();
        assert_eq!(r.outcome, Outcome::SchemaViolation);
        assert_eq!(r.issues.len(), 1);
    }

    #[test]
    fn v2_without_cores_is_rejected() {
        let text = "schema_version: 2\nsom:\n  sku: E1M-AEN701\n";
        let r = validate_board_yaml_local(text).unwrap();
        assert_eq!(r.outcome, Outcome::SchemaViolation);
        assert_eq!(r.issues.len(), 1);
    }

    #[test]
    fn parse_rich_board_fields() {
        let text = r#"
schema_version: 2
som:
  sku: E1M-AEN701
cores:
  m55_hp:
    os: zephyr
    app: ./src
    image: app.bin
    peripherals: [i2c, spi]
    libraries: [mbedtls]
    inference:
      backend: ethos_u
      default_arena_kib: 256
    iot:
      wifi: true
ipc:
  - name: telemetry
    endpoints: [m55_hp, a32_cluster]
    size_kib: 64
"#;
        let model = parse_board_model(text).unwrap();
        let core = model.cores.unwrap().remove("m55_hp").unwrap();
        assert_eq!(core.os.as_deref(), Some("zephyr"));
        assert_eq!(core.peripherals.unwrap(), vec!["i2c", "spi"]);
        assert_eq!(core.inference.unwrap().default_arena_kib, Some(256));
        assert_eq!(model.ipc.unwrap()[0].size_kib, 64);
    }

    #[test]
    fn normalize_v1_removes_empty_optional_blocks() {
        let model = BoardModel {
            schema_version: Some(1),
            som: Some(Som {
                sku: Some("E1M-AEN701".to_string()),
            }),
            carrier: Some(Carrier {
                name: Some("E1M-EVK".to_string()),
                populated: Some(BTreeMap::new()),
            }),
            inference: Some(Inference::default()),
            libraries: Some(Vec::new()),
            iot: Some(Iot::default()),
            ..BoardModel::default()
        };

        let normalized = normalize_board_model(model);
        assert!(normalized.libraries.is_none());
        assert!(normalized.iot.is_none());
        assert!(normalized.inference.is_none());
        assert!(normalized.carrier.unwrap().populated.is_none());
    }

    #[test]
    fn normalize_v2_removes_top_level_os() {
        let model = BoardModel {
            schema_version: Some(2),
            os: Some("zephyr".to_string()),
            ..BoardModel::default()
        };

        assert!(normalize_board_model(model).os.is_none());
    }

    #[test]
    fn classify_maps_exit_status_to_outcome() {
        assert_eq!(classify_validation_outcome(Some(0)), Outcome::Clean);
        assert_eq!(
            classify_validation_outcome(Some(1)),
            Outcome::SchemaViolation
        );
        assert_eq!(classify_validation_outcome(Some(2)), Outcome::MissingPreset);
        assert_eq!(
            classify_validation_outcome(Some(3)),
            Outcome::HardwareRevision
        );
        assert_eq!(classify_validation_outcome(Some(9)), Outcome::Failed);
        assert_eq!(classify_validation_outcome(None), Outcome::Failed);
    }

    #[test]
    fn analyze_parses_rich_alp_block() {
        let stderr = "error[ALP-B005]: SoM SKU 'E1M-NX9999' does not resolve\n  --> board.yaml:3:8\n   |\n 3 | som: {sku: E1M-NX9999}\n   |          ^^^^^^^^^^^^\n   = hint: did you mean E1M-NX9?\n   = see: docs/diagnostics/ALP-B005.md\n";
        let execution = ValidatorExecution {
            status: Some(1),
            stdout: String::new(),
            stderr: stderr.to_string(),
        };
        let result = analyze_validation_result(&execution);
        assert_eq!(result.outcome, Outcome::SchemaViolation);
        assert_eq!(result.issues.len(), 1, "block continuation must be skipped");
        assert_eq!(result.issues[0].severity, Severity::Error);
        assert_eq!(
            result.issues[0].message,
            "SoM SKU 'E1M-NX9999' does not resolve"
        );
    }

    #[test]
    fn analyze_parses_legacy_fail_warn_with_continuation() {
        let stderr = "FAIL som preset: no preset for E1M-NX9999\n     expected shared definition at metadata/boards/...\nWARN hw_compat: minor version mismatch\n";
        let execution = ValidatorExecution {
            status: Some(2),
            stdout: String::new(),
            stderr: stderr.to_string(),
        };
        let result = analyze_validation_result(&execution);
        assert_eq!(result.outcome, Outcome::MissingPreset);
        assert_eq!(result.issues.len(), 2);
        // FAIL line folds in its indented continuation; severity follows outcome.
        assert_eq!(
            result.issues[0].message,
            "som preset: no preset for E1M-NX9999  expected shared definition at metadata/boards/..."
        );
        assert_eq!(result.issues[0].severity, Severity::Warning); // missing-preset outcome
        // WARN line is always a warning regardless of outcome.
        assert_eq!(result.issues[1].severity, Severity::Warning);
        assert_eq!(
            result.issues[1].message,
            "hw_compat: minor version mismatch"
        );
    }

    #[test]
    fn analyze_skips_summary_lines_and_keeps_hints() {
        let stderr = "board.yaml: missing-preset\nhint: run `alp presets` to list valid SKUs\n";
        let execution = ValidatorExecution {
            status: Some(2),
            stdout: String::new(),
            stderr: stderr.to_string(),
        };
        let result = analyze_validation_result(&execution);
        assert_eq!(result.issues.len(), 1);
        assert_eq!(result.issues[0].severity, Severity::Suggestion);
        assert!(result.issues[0].message.starts_with("hint:"));
    }

    #[test]
    fn clean_execution_has_no_issues() {
        let execution = ValidatorExecution {
            status: Some(0),
            stdout: String::new(),
            stderr: String::new(),
        };
        let result = analyze_validation_result(&execution);
        assert_eq!(result.outcome, Outcome::Clean);
        assert!(result.issues.is_empty());
    }

    #[test]
    fn rich_header_rejects_non_alp_code() {
        assert!(parse_rich_header("error[B005]: nope").is_none());
        assert!(parse_rich_header("error[ALP-B005]: ok").is_some());
        assert!(parse_rich_header("note[ALP-Z9]: hi").is_some());
    }
}