alp-cli 0.1.6

The native `alp` CLI for ALP SDK embedded projects: board.yaml validate/generate, project scaffolding, toolchain bootstrap, and west build/flash with a stable JSON envelope.
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
// SPDX-License-Identifier: Apache-2.0
//! `alp support-bundle` — write a diagnostic bundle (inspect + trace + doctor).
//!
//! Mirrors TS `runSupportBundleCommand`: assemble an inspect report, generation
//! trace, and doctor report into one JSON file, then return an envelope with the
//! written path + decision count. Unsupported backend → exit 4; the exit code
//! otherwise follows the doctor summary (fail > 0 → exit 4).

use std::path::{Path, PathBuf};

use alp_core::{
    ALL_EMIT_MODES, DebugGenerationTraceDecision, DebugServerKind, DebugTargetKind,
    DebugTraceOutcome, DebugWorkspaceContext, DebuggerExtensionsState, DoctorCheck, DoctorReport,
    DoctorStatus, ProjectContext, build_doctor_report, collect_resolved_values,
    collect_runtime_capabilities_from_commands, create_debug_workspace_context, create_loader_plan,
    generation_target_support, is_server_supported_for_target, parse_server_kind,
    parse_target_kind,
};
use serde::Serialize;

use super::CommandRun;
use crate::cli::{GlobalArgs, SupportBundleArgs};
use crate::envelope::{Envelope, Issue, Project};
use crate::exit::ExitCode;
use crate::util::{command_on_path, generated_at_iso, normalize_path, resolve_cli_project_context};

/// Stdout envelope `data` payload for `support-bundle`: the written bundle path
/// plus the resolved target/server and trace decision count.
#[derive(Serialize)]
struct SupportBundleData {
    /// Payload schema version (always `"1"`).
    #[serde(rename = "schemaVersion")]
    schema_version: String,
    /// ISO-8601 timestamp the command ran.
    #[serde(rename = "generatedAt")]
    generated_at: String,
    /// Absolute path of the written bundle file (empty on failure).
    #[serde(rename = "outputPath")]
    output_path: String,
    /// Resolved debug target kind.
    #[serde(rename = "targetKind")]
    target_kind: DebugTargetKind,
    /// Resolved debug server kind.
    server: DebugServerKind,
    /// Number of generation-trace decisions captured.
    #[serde(rename = "decisionCount")]
    decision_count: usize,
}

// ── bundle file payload (not part of the stdout envelope) ───────────────────

/// Inspect section of the bundle file: the resolved debug workspace context and
/// its flattened resolved values.
#[derive(Serialize)]
struct InspectReport<'a> {
    /// Section schema version (always `"1"`).
    #[serde(rename = "schemaVersion")]
    schema_version: &'a str,
    /// ISO-8601 generation timestamp.
    #[serde(rename = "generatedAt")]
    generated_at: &'a str,
    /// Resolved debug workspace context.
    context: &'a DebugWorkspaceContext,
    /// Flattened resolved values derived from `context`.
    #[serde(rename = "resolvedValues")]
    resolved_values: Vec<alp_core::DebugResolvedValue>,
}

/// Trace section of the bundle file: the workflow id and the captured
/// generation-trace decisions.
#[derive(Serialize)]
struct TraceReport<'a> {
    /// Section schema version (always `"1"`).
    #[serde(rename = "schemaVersion")]
    schema_version: &'a str,
    /// ISO-8601 generation timestamp.
    #[serde(rename = "generatedAt")]
    generated_at: &'a str,
    /// Workflow identifier (`"cli.support-bundle"`).
    workflow: &'a str,
    /// Per-target generation-trace decisions.
    decisions: &'a [DebugGenerationTraceDecision],
}

/// Top-level JSON written to the bundle file: combines inspect, trace, and
/// doctor sections plus freeform notes.
#[derive(Serialize)]
struct BundlePayload<'a> {
    /// Bundle schema version (always `"1"`).
    #[serde(rename = "schemaVersion")]
    schema_version: &'a str,
    /// ISO-8601 generation timestamp.
    #[serde(rename = "generatedAt")]
    generated_at: &'a str,
    /// Inspect report section.
    inspect: InspectReport<'a>,
    /// Generation-trace section.
    trace: TraceReport<'a>,
    /// Doctor report section.
    doctor: &'a DoctorReport,
    /// Freeform metadata notes (target, server, workspace root).
    notes: Vec<String>,
}

/// Entry point for `alp support-bundle`: resolves project/target/server, builds
/// the inspect+trace+doctor payload, writes it to a bundle file, and returns the
/// envelope. Exit is `DoctorFailure` on unsupported backend or doctor fail count
/// > 0, else `Success`.
pub fn run(g: &GlobalArgs, args: &SupportBundleArgs) -> CommandRun {
    let generated_at = generated_at_iso();
    let project = resolve_cli_project_context(g);
    let context = create_debug_workspace_context(
        &project,
        generated_at.clone(),
        |path| Path::new(path).exists(),
        DebuggerExtensionsState {
            cortex_debug: true,
            cpp_tools: true,
            code_lldb: true,
        },
    );

    let target = match parse_target_kind(args.target_kind.as_deref()) {
        Ok(t) => t,
        Err(message) => return internal_failure(g, &generated_at, message),
    };
    let server = match parse_server_kind(args.server.as_deref()) {
        Ok(s) => s,
        Err(message) => return internal_failure(g, &generated_at, message),
    };

    if !is_server_supported_for_target(target, server) {
        return server_incompatible(g, &generated_at, target, server);
    }

    let runtime = collect_runtime_capabilities_from_commands(&project, command_on_path);

    let decisions =
        match create_bundle_trace_decisions(&project, g.target.as_deref(), args.path.as_deref()) {
            Ok(d) => d,
            Err(message) => return internal_failure(g, &generated_at, message),
        };
    let doctor = build_doctor_report(&context, target, server, &runtime);

    // Assemble + serialize the bundle file (side effect; not in the envelope).
    let notes = vec![
        format!("targetKind={}", target.as_str()),
        format!("server={}", server.as_str()),
        format!(
            "workspaceRoot={}",
            context.workspace_root.clone().unwrap_or_default()
        ),
    ];
    let payload = BundlePayload {
        schema_version: "1",
        generated_at: &generated_at,
        inspect: InspectReport {
            schema_version: "1",
            generated_at: &generated_at,
            context: &context,
            resolved_values: collect_resolved_values(&context),
        },
        trace: TraceReport {
            schema_version: "1",
            generated_at: &generated_at,
            workflow: "cli.support-bundle",
            decisions: &decisions,
        },
        doctor: &doctor,
        notes,
    };
    let content = serde_json::to_string_pretty(&payload).expect("bundle is serializable");

    let output_path = match write_bundle(
        args.destination.as_deref(),
        context.workspace_root.as_deref().unwrap_or("."),
        &generated_at,
        &content,
    ) {
        Ok(p) => p,
        Err(message) => return internal_failure(g, &generated_at, message),
    };

    let issues = doctor_checks_to_issues(&doctor.checks);
    let exit = if doctor.summary.fail > 0 {
        ExitCode::DoctorFailure
    } else {
        ExitCode::Success
    };

    let data = SupportBundleData {
        schema_version: "1".to_string(),
        generated_at: generated_at.clone(),
        output_path: output_path.clone(),
        target_kind: target,
        server,
        decision_count: decisions.len(),
    };
    let project_env = Project {
        root: context.workspace_root.clone(),
        board_yaml: context.board_yaml_path.clone(),
    };
    let text = if g.is_json() {
        Vec::new()
    } else {
        support_bundle_text(&output_path, decisions.len(), g)
    };
    let json = g
        .is_json()
        .then(|| Envelope::new("support-bundle", project_env, data, issues, exit.code()).to_json());

    CommandRun { exit, text, json }
}

/// Builds the generation-trace decisions: one `Planned` entry per emit target
/// (with the loader command/output it would run) when the project context is
/// fully resolved, otherwise a single `Failed` entry. Appends a path-focus entry
/// when `focus` is set.
fn create_bundle_trace_decisions(
    context: &ProjectContext,
    target: Option<&str>,
    focus: Option<&str>,
) -> Result<Vec<DebugGenerationTraceDecision>, String> {
    let mut decisions = Vec::new();

    match (
        context.workspace_root.as_deref(),
        context.sdk_root.as_deref(),
        context.board_yaml_path.as_deref(),
    ) {
        (Some(workspace_root), Some(sdk_root), Some(board_path)) => {
            for emit in resolve_targets(target)? {
                let support = generation_target_support(emit).expect("target validated");
                let plan = create_loader_plan(
                    workspace_root,
                    sdk_root,
                    board_path,
                    &context.python_binary,
                    support,
                );
                decisions.push(DebugGenerationTraceDecision {
                    key: format!("generation.target.{emit}"),
                    outcome: DebugTraceOutcome::Planned,
                    output_path: Some(plan.output_path),
                    detail: format!("Would run: {}", plan.command_line),
                });
            }
        }
        _ => decisions.push(DebugGenerationTraceDecision {
            key: "generation.targets".to_string(),
            outcome: DebugTraceOutcome::Failed,
            output_path: None,
            detail: "Generation targets were not traced because project context is unresolved."
                .to_string(),
        }),
    }

    if let Some(focus_path) = focus {
        decisions.push(DebugGenerationTraceDecision {
            key: format!("config.path.{focus_path}"),
            outcome: DebugTraceOutcome::Planned,
            output_path: None,
            detail: "Path-level trace was requested and captured as part of bundle metadata."
                .to_string(),
        });
    }

    Ok(decisions)
}

/// Resolves the emit targets to trace: all of `ALL_EMIT_MODES` when `raw` is
/// `None`, a single validated mode when given, or an error for an unknown mode.
fn resolve_targets(raw: Option<&str>) -> Result<Vec<&'static str>, String> {
    match raw {
        None => Ok(ALL_EMIT_MODES.to_vec()),
        Some(target) => match ALL_EMIT_MODES.iter().copied().find(|m| *m == target) {
            Some(m) => Ok(vec![m]),
            None => Err(format!(
                "Unsupported trace target '{target}'. Allowed values: {}.",
                ALL_EMIT_MODES.join(", ")
            )),
        },
    }
}

/// Writes `content` to a timestamped `debug-support-bundle-*.json` file under
/// `destination` (resolved against cwd) or `<workspace_root>/.alp-support`,
/// creating the directory. Returns the written path.
fn write_bundle(
    destination: Option<&str>,
    workspace_root: &str,
    generated_at: &str,
    content: &str,
) -> Result<String, String> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let base_dir = match destination {
        Some(dest) => normalize_path(&cwd.join(dest)),
        None => Path::new(workspace_root).join(".alp-support"),
    };
    let file_name = format!(
        "debug-support-bundle-{}.json",
        timestamp_for_file(generated_at)
    );
    let output_path = base_dir.join(file_name);

    std::fs::create_dir_all(&base_dir).map_err(|e| e.to_string())?;
    std::fs::write(&output_path, content).map_err(|e| e.to_string())?;
    Ok(output_path.to_string_lossy().to_string())
}

/// Makes an ISO timestamp filename-safe by replacing `:` and `.` with `-`.
fn timestamp_for_file(iso_timestamp: &str) -> String {
    iso_timestamp
        .chars()
        .map(|c| if c == ':' || c == '.' { '-' } else { c })
        .collect()
}

/// Maps non-`Pass` doctor checks to envelope `Issue`s, coding each as
/// `support-bundle.<name>` and severity `error` for `Fail`, `warning` otherwise.
fn doctor_checks_to_issues(checks: &[DoctorCheck]) -> Vec<Issue> {
    checks
        .iter()
        .filter(|c| c.status != DoctorStatus::Pass)
        .map(|c| Issue {
            code: format!("support-bundle.{}", c.name),
            severity: if c.status == DoctorStatus::Fail {
                "error".to_string()
            } else {
                "warning".to_string()
            },
            message: c.detail.clone(),
        })
        .collect()
}

/// Builds the human-readable (non-JSON) output lines: the exported path and
/// decision count, plus a `--format json` hint when `--verbose`.
fn support_bundle_text(output_path: &str, decision_count: usize, g: &GlobalArgs) -> Vec<String> {
    let mut lines = vec![
        format!("support-bundle: exported {output_path}"),
        format!("support-bundle: trace decisions={decision_count}"),
    ];
    if g.verbose {
        lines.push(
            "support-bundle: include --format json for machine-readable envelopes.".to_string(),
        );
    }
    lines
}

/// Builds the `DoctorFailure` result for an unsupported server/target pairing:
/// a `support-bundle.server-compatibility` issue and an empty-path data payload.
fn server_incompatible(
    g: &GlobalArgs,
    generated_at: &str,
    target: DebugTargetKind,
    server: DebugServerKind,
) -> CommandRun {
    let issues = vec![Issue {
        code: "support-bundle.server-compatibility".to_string(),
        severity: "error".to_string(),
        message: format!(
            "Server '{}' is not supported for target '{}'.",
            server.as_str(),
            target.as_str()
        ),
    }];
    let data = SupportBundleData {
        schema_version: "1".to_string(),
        generated_at: generated_at.to_string(),
        output_path: String::new(),
        target_kind: target,
        server,
        decision_count: 0,
    };
    let text = if g.is_json() {
        Vec::new()
    } else {
        vec![format!(
            "support-bundle: server '{}' is not supported for target '{}'.",
            server.as_str(),
            target.as_str()
        )]
    };
    let json = g.is_json().then(|| {
        Envelope::new(
            "support-bundle",
            null_project(),
            data,
            issues,
            ExitCode::DoctorFailure.code(),
        )
        .to_json()
    });
    CommandRun {
        exit: ExitCode::DoctorFailure,
        text,
        json,
    }
}

/// Builds the `InternalFailure` result for an unexpected error: a
/// `support-bundle.internal-failure` issue and a placeholder data payload.
fn internal_failure(g: &GlobalArgs, generated_at: &str, message: String) -> CommandRun {
    let issues = vec![Issue {
        code: "support-bundle.internal-failure".to_string(),
        severity: "error".to_string(),
        message: message.clone(),
    }];
    let data = SupportBundleData {
        schema_version: "1".to_string(),
        generated_at: generated_at.to_string(),
        output_path: String::new(),
        target_kind: DebugTargetKind::NativeHost,
        server: DebugServerKind::None,
        decision_count: 0,
    };
    let text = if g.is_json() {
        Vec::new()
    } else {
        vec!["support-bundle: internal failure".to_string(), message]
    };
    let json = g.is_json().then(|| {
        Envelope::new(
            "support-bundle",
            null_project(),
            data,
            issues,
            ExitCode::InternalFailure.code(),
        )
        .to_json()
    });
    CommandRun {
        exit: ExitCode::InternalFailure,
        text,
        json,
    }
}

/// Returns an empty envelope `Project` (no root or `board.yaml`) for failure paths.
fn null_project() -> Project {
    Project {
        root: None,
        board_yaml: None,
    }
}