sim-lib-compute-cli 0.2.0

Loadable compute command surface for SIM.
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
//! Argument parsing for the loadable compute command.

use crate::ComputeCliError;

const MAX_SELECTOR_BYTES: usize = 64;
const MAX_DEVICES: usize = 64;
const MAX_PROFILE_BYTES: usize = 64 * 1024;

/// Output encoding requested by the command.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputMode {
    /// Stable human-readable text.
    Text,
    /// Stable machine-readable JSON.
    Json,
}

/// Profile store action.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProfileAction {
    /// List stored profile keys.
    List,
    /// Read and check one stored profile.
    Read,
    /// Save a bounded synthetic profile.
    Save,
}

/// Parsed compute CLI command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ComputeCommand {
    /// Render command help.
    Help,
    /// List installed compute providers.
    Devices(Selection),
    /// Render bounded probe evidence for selected providers.
    Probe(Selection),
    /// Read, write, or list injected profile storage.
    Profile(ProfileRequest),
    /// Explain profile routing for one selected device identity.
    Explain(ProfileRequest),
    /// Render a checked recipe descriptor.
    Recipe(RecipeRequest),
    /// Capture, verify, or import a physical acceptance artifact.
    Acceptance(AcceptanceRequest),
}

/// Provider selection and common output options.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Selection {
    /// Optional provider selector.
    pub selector: Option<String>,
    /// Output encoding.
    pub output: OutputMode,
    /// Maximum provider rows to inspect.
    pub max_devices: usize,
}

/// Profile command options.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProfileRequest {
    /// Requested action.
    pub action: ProfileAction,
    /// Optional profile key.
    pub key: Option<String>,
    /// Expected adapter identity.
    pub adapter: String,
    /// Expected driver identity.
    pub driver: String,
    /// Expected backend identity.
    pub backend: String,
    /// Logical tick for stale checks.
    pub now_tick: u64,
    /// Output encoding.
    pub output: OutputMode,
    /// Maximum accepted profile bytes.
    pub max_profile_bytes: usize,
}

/// Recipe render options.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecipeRequest {
    /// Recipe id.
    pub id: String,
    /// Output encoding.
    pub output: OutputMode,
}

/// Acceptance artifact action.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AcceptanceAction {
    /// Capture one exact physical artifact.
    Capture,
    /// Verify an existing artifact.
    Verify,
    /// Import an existing artifact after verification.
    Import,
}

/// Acceptance command options.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AcceptanceRequest {
    /// Requested action.
    pub action: AcceptanceAction,
    /// Case manifest path for capture.
    pub manifest: Option<String>,
    /// Exact sim-compute source commit expected by the artifact.
    pub source: String,
    /// Exact registered target capability captured by the artifact.
    pub target: Option<String>,
    /// Output artifact path for capture.
    pub output: Option<String>,
    /// Input artifact path for verify/import.
    pub input: Option<String>,
}

/// Parses a `sim compute` payload argument list.
pub fn parse_compute_args(args: &[String]) -> Result<ComputeCommand, ComputeCliError> {
    let args = strip_verb(args);
    if args.is_empty() || args.iter().any(|arg| arg == "--help" || arg == "-h") {
        return Ok(ComputeCommand::Help);
    }
    match args[0].as_str() {
        "devices" => Ok(ComputeCommand::Devices(parse_selection(
            "devices",
            &args[1..],
        )?)),
        "probe" => Ok(ComputeCommand::Probe(parse_selection("probe", &args[1..])?)),
        "profile" => Ok(ComputeCommand::Profile(parse_profile(&args[1..])?)),
        "explain" => {
            let mut request = parse_profile(&args[1..])?;
            if request.action == ProfileAction::List {
                request.action = ProfileAction::Read;
            }
            Ok(ComputeCommand::Explain(request))
        }
        "recipe" => Ok(ComputeCommand::Recipe(parse_recipe(&args[1..])?)),
        "acceptance" => Ok(ComputeCommand::Acceptance(parse_acceptance(&args[1..])?)),
        other => Err(ComputeCliError::new(format!(
            "unknown compute verb: {other}"
        ))),
    }
}

fn strip_verb(args: &[String]) -> &[String] {
    if args.first().is_some_and(|arg| arg == "compute") {
        &args[1..]
    } else {
        args
    }
}

fn parse_selection(verb: &str, args: &[String]) -> Result<Selection, ComputeCliError> {
    let mut output = OutputMode::Text;
    let mut selector = None;
    let mut max_devices = 16;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--json" => output = OutputMode::Json,
            "--max-devices" => {
                max_devices = bounded_usize(take_value(args, &mut i, "--max-devices")?)?;
                if max_devices == 0 || max_devices > MAX_DEVICES {
                    return Err(ComputeCliError::new("max-devices is outside policy"));
                }
            }
            value if value.starts_with('-') => {
                return Err(ComputeCliError::new(format!(
                    "unknown {verb} option: {value}"
                )));
            }
            value => {
                checked_selector(value)?;
                if selector.replace(value.to_owned()).is_some() {
                    return Err(ComputeCliError::new(format!(
                        "{verb} accepts at most one selector"
                    )));
                }
            }
        }
        i += 1;
    }
    Ok(Selection {
        selector,
        output,
        max_devices,
    })
}

fn parse_profile(args: &[String]) -> Result<ProfileRequest, ComputeCliError> {
    let mut request = ProfileRequest {
        action: ProfileAction::List,
        key: None,
        adapter: "modeled-adapter".to_owned(),
        driver: "modeled-driver".to_owned(),
        backend: "modeled".to_owned(),
        now_tick: 0,
        output: OutputMode::Text,
        max_profile_bytes: 8192,
    };
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "list" => request.action = ProfileAction::List,
            "read" => request.action = ProfileAction::Read,
            "save" => request.action = ProfileAction::Save,
            "--json" => request.output = OutputMode::Json,
            "--key" => request.key = Some(checked_value(take_value(args, &mut i, "--key")?)?),
            "--adapter" => request.adapter = checked_value(take_value(args, &mut i, "--adapter")?)?,
            "--driver" => request.driver = checked_value(take_value(args, &mut i, "--driver")?)?,
            "--backend" => request.backend = checked_value(take_value(args, &mut i, "--backend")?)?,
            "--now" => request.now_tick = bounded_u64(take_value(args, &mut i, "--now")?)?,
            "--max-profile-bytes" => {
                request.max_profile_bytes =
                    bounded_usize(take_value(args, &mut i, "--max-profile-bytes")?)?;
                if request.max_profile_bytes == 0 || request.max_profile_bytes > MAX_PROFILE_BYTES {
                    return Err(ComputeCliError::new("max-profile-bytes is outside policy"));
                }
            }
            value if value.starts_with('-') => {
                return Err(ComputeCliError::new(format!(
                    "unknown profile option: {value}"
                )));
            }
            value => {
                return Err(ComputeCliError::new(format!(
                    "unknown profile action: {value}"
                )));
            }
        }
        i += 1;
    }
    Ok(request)
}

fn parse_acceptance(args: &[String]) -> Result<AcceptanceRequest, ComputeCliError> {
    let Some(action) = args.first() else {
        return Err(ComputeCliError::new("acceptance requires an action"));
    };
    let mut request = AcceptanceRequest {
        action: match action.as_str() {
            "capture" => AcceptanceAction::Capture,
            "verify" => AcceptanceAction::Verify,
            "import" => AcceptanceAction::Import,
            other => {
                return Err(ComputeCliError::new(format!(
                    "unknown acceptance action: {other}"
                )));
            }
        },
        manifest: None,
        source: String::new(),
        target: None,
        output: None,
        input: None,
    };
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--manifest" => {
                request.manifest = Some(checked_path(take_value(args, &mut i, "--manifest")?)?)
            }
            "--source" => request.source = checked_hash(take_value(args, &mut i, "--source")?)?,
            "--target" => {
                request.target = Some(checked_capability(take_value(args, &mut i, "--target")?)?)
            }
            "--output" => {
                request.output = Some(checked_path(take_value(args, &mut i, "--output")?)?)
            }
            value if value.starts_with('-') => {
                return Err(ComputeCliError::new(format!(
                    "unknown acceptance option: {value}"
                )));
            }
            value => {
                let path = checked_path(value.to_owned())?;
                if request.input.replace(path).is_some() {
                    return Err(ComputeCliError::new(
                        "acceptance accepts at most one input artifact",
                    ));
                }
            }
        }
        i += 1;
    }
    if request.source.is_empty() {
        return Err(ComputeCliError::new("acceptance requires --source"));
    }
    match request.action {
        AcceptanceAction::Capture => {
            if request.manifest.is_none()
                || request.target.is_none()
                || request.output.is_none()
                || request.input.is_some()
            {
                return Err(ComputeCliError::new(
                    "acceptance capture requires --manifest, --target, and --output only",
                ));
            }
        }
        AcceptanceAction::Verify | AcceptanceAction::Import => {
            if request.input.is_none()
                || request.manifest.is_some()
                || request.target.is_some()
                || request.output.is_some()
            {
                return Err(ComputeCliError::new(
                    "acceptance verify/import requires one input artifact",
                ));
            }
        }
    }
    Ok(request)
}

fn parse_recipe(args: &[String]) -> Result<RecipeRequest, ComputeCliError> {
    let mut output = OutputMode::Text;
    let mut id = "inspect-compute-device".to_owned();
    for arg in args {
        match arg.as_str() {
            "--json" => output = OutputMode::Json,
            value if value.starts_with('-') => {
                return Err(ComputeCliError::new(format!(
                    "unknown recipe option: {value}"
                )));
            }
            value => id = checked_value(value.to_owned())?,
        }
    }
    if id != "inspect-compute-device" {
        return Err(ComputeCliError::new(format!(
            "unknown compute recipe: {id}"
        )));
    }
    Ok(RecipeRequest { id, output })
}

fn take_value(args: &[String], i: &mut usize, flag: &str) -> Result<String, ComputeCliError> {
    *i += 1;
    args.get(*i)
        .filter(|value| !value.starts_with('-'))
        .cloned()
        .ok_or_else(|| ComputeCliError::new(format!("{flag} requires a value")))
}

fn checked_value(value: String) -> Result<String, ComputeCliError> {
    checked_selector(&value)?;
    Ok(value)
}

fn checked_selector(value: &str) -> Result<(), ComputeCliError> {
    if value.is_empty() || value.len() > MAX_SELECTOR_BYTES || value.contains("..") {
        return Err(ComputeCliError::new("selector is outside policy"));
    }
    if !value
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '/' | '.'))
    {
        return Err(ComputeCliError::new(
            "selector contains unsupported characters",
        ));
    }
    Ok(())
}

fn checked_path(value: String) -> Result<String, ComputeCliError> {
    if value.is_empty()
        || value.len() > 240
        || value.contains('\0')
        || value.contains('\n')
        || value.contains('\r')
    {
        return Err(ComputeCliError::new("path is outside acceptance policy"));
    }
    Ok(value)
}

fn checked_capability(value: String) -> Result<String, ComputeCliError> {
    if value.is_empty()
        || value.len() > MAX_SELECTOR_BYTES
        || value.contains("..")
        || !value
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, ':' | '-' | '_' | '/' | '.'))
    {
        return Err(ComputeCliError::new(
            "target capability is outside acceptance policy",
        ));
    }
    Ok(value)
}

fn checked_hash(value: String) -> Result<String, ComputeCliError> {
    if value.len() != 40 || !value.chars().all(|ch| ch.is_ascii_hexdigit()) {
        return Err(ComputeCliError::new("source must be a 40-hex commit"));
    }
    Ok(value.to_ascii_lowercase())
}

fn bounded_usize(value: String) -> Result<usize, ComputeCliError> {
    value
        .parse::<usize>()
        .map_err(|_| ComputeCliError::new("numeric ceiling must be an unsigned integer"))
}

fn bounded_u64(value: String) -> Result<u64, ComputeCliError> {
    value
        .parse::<u64>()
        .map_err(|_| ComputeCliError::new("tick must be an unsigned integer"))
}