diff --git a/CHANGELOG.md b/CHANGELOG.md index de8176b81..d4187b5fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ To move to 1.0, read the [migration guide](docs/site/migration/to-1-0.md). ## [Unreleased] ### Features Added +- `prismpm ` (#441): the Rust CLI groups its commands under the modules of `model/modules.toml`, as `prism-code` does: `prismpm images build|inspect|pull|push|verify|export-browser`, `prismpm verify check|attestation|signature|release|replay|model|conformance|acceptance|browser-publication`, `prismpm auth attest|sign|sign-evidence`, `prismpm system lock|update|fetch|authority|clean`, `prismpm containers run|status` and `prismpm client generate|completion|template`. Each group verb runs its flat command with the same arguments, output and result schema, and the flat commands stay. The table is the `[[group]]` rows of `model/commands.toml`: the model gate checks that each names a registered command, the CLI parses its groups from the same rows, and `CONTRACTS.md` lists them. `prismpm ` prints the module's verbs; an unknown verb is `PP1001`. A module that is also a command (`verify`) is a group only when the next word is one of its verbs. - The developer view of #346 is a LexLean model (#347, experimental): `bindings/src/Foundation/Views/V1/Developer.lex.tex` declares the developer glossary once, each Docker-aligned term over the canonical term it names, the other words of the surface and the deprecated aliases. Its certified export runs in `cargo xtask check-developer-view` (part of `cargo xtask validate`), which checks every verb, flag, namespace and method of the `prism-code` surface against it and renders [docs/developer-glossary.md](docs/developer-glossary.md). Canonical model terms, schema identifiers, predicate URIs and error codes do not change; the renamed `prism-code` spellings are in its own changelog. - `COMPLIANCE.md` shows the Rust runtime (#449, #298): `sdk/npm/conformance/runtimes.json` registers `prism-conformance-shim`, the npm conformance suite job builds it and runs the suite against it beside prism-code, and the matrix shows both runtimes passing all 24 `verify` checks. `prism.verify.pullClosure` makes every trust decision a pull needs, and signing moves to `auth` (`auth.identities.from`), so the pending `auth.mjs` to `attest.mjs` cut in `model/modules.toml` is made; see the prism-code CHANGELOG. - `prismpm generate --lang --out ` (#289, experimental): the Rust CLI writes the same bindings and typed client as `prism-code generate`, byte for byte apart from the generator each file header names, beside the same `prism-generate.json` record, and a run whose record and files are in place writes nothing. Every decision is the LexLean model `bindings/src/Foundation/Bindings/V1`: the new `Source.lex.tex` reads the WIT world and the model document into the code model (the WIT subset, the world's exports and memory, the application's class name, the numeric profile's operations), and `Generate.lex.tex` joins it to the JS, Python and Rust writers. `cargo xtask bindings-package` exports the three roots and vendors them into the crate, so the published `prismpm` carries them and the unpublished `prism-bindings` crate is gone. A holo generate cannot bind is `PP3201`; an output directory holding a file generate did not write is `PP3202`. diff --git a/CONTRACTS.md b/CONTRACTS.md index 69467f678..d7811883c 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -125,3 +125,38 @@ All JSON content uses UTF-8, sorted object keys, shortest canonical integers, no | `verify-browser-publication` | `never` | `true` | `prismpm/browser-publication-integrity/2` | | `verify-release` | `never` | `true` | `prismpm/signature-closure-result/1` | | `verify-signature` | `verified-local-evidence` | `true` | `prismpm/signature-result/1` | + +## Command groups + +`prismpm ` runs the command beside it, with the same arguments, output and result schema (#441). The groups are named after the nine modules of `model/modules.toml`; the flat commands stay as aliases. A module that is also a command (`verify`) is a group only when the next word is one of its verbs. + +| Group verb | Command | +| --- | --- | +| `prismpm auth attest` | `prismpm attest` | +| `prismpm auth sign` | `prismpm sign` | +| `prismpm auth sign-evidence` | `prismpm sign-evidence` | +| `prismpm client completion` | `prismpm completion` | +| `prismpm client generate` | `prismpm generate` | +| `prismpm client template` | `prismpm template` | +| `prismpm containers run` | `prismpm run` | +| `prismpm containers status` | `prismpm status` | +| `prismpm images build` | `prismpm build` | +| `prismpm images export-browser` | `prismpm export-browser` | +| `prismpm images inspect` | `prismpm inspect` | +| `prismpm images pull` | `prismpm pull` | +| `prismpm images push` | `prismpm push` | +| `prismpm images verify` | `prismpm check` | +| `prismpm system authority` | `prismpm authority` | +| `prismpm system clean` | `prismpm clean` | +| `prismpm system fetch` | `prismpm fetch` | +| `prismpm system lock` | `prismpm lock` | +| `prismpm system update` | `prismpm update` | +| `prismpm verify acceptance` | `prismpm replay-acceptance` | +| `prismpm verify attestation` | `prismpm verify-attestation` | +| `prismpm verify browser-publication` | `prismpm verify-browser-publication` | +| `prismpm verify check` | `prismpm check` | +| `prismpm verify conformance` | `prismpm conformance` | +| `prismpm verify model` | `prismpm verify` | +| `prismpm verify release` | `prismpm verify-release` | +| `prismpm verify replay` | `prismpm replay` | +| `prismpm verify signature` | `prismpm verify-signature` | diff --git a/crates/model/src/codegen.rs b/crates/model/src/codegen.rs index 54dbc86d5..50cad9ca8 100644 --- a/crates/model/src/codegen.rs +++ b/crates/model/src/codegen.rs @@ -307,5 +307,19 @@ pub fn render_contracts(model: &Model) -> String { ); } } + let _ = writeln!(w); + let _ = writeln!(w, "## Command groups"); + let _ = writeln!(w); + let _ = writeln!(w, "`prismpm ` runs the command beside it, with the same arguments, output and result schema (#441). The groups are named after the nine modules of `model/modules.toml`; the flat commands stay as aliases. A module that is also a command (`verify`) is a group only when the next word is one of its verbs."); + let _ = writeln!(w); + let _ = writeln!(w, "| Group verb | Command |"); + let _ = writeln!(w, "| --- | --- |"); + for row in &model.commands.group { + let _ = writeln!( + w, + "| `prismpm {} {}` | `prismpm {}` |", + row.module, row.verb, row.command + ); + } out } diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index b9e56817e..8436be1f2 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -508,6 +508,26 @@ pub fn repo_root() -> PathBuf { mod tests { use super::Model; + #[test] + fn command_groups_run_registered_commands_in_order() { + let model = Model::load_from_repo_root().expect("load repository model"); + model.commands.check().expect("the committed groups hold"); + assert!(!model.commands.group.is_empty()); + let planted = |edit: fn(&mut super::Commands)| { + let mut commands = model.commands.clone(); + edit(&mut commands); + commands.check().is_err() + }; + assert!(planted(|c| c.group[0].command = "nonexistent".into())); + assert!(planted(|c| c.group[0].verb = "Upper".into())); + assert!(planted(|c| c.group[0].module = "-x".into())); + assert!(planted(|c| c.group.swap(0, 1))); + assert!(planted(|c| { + let first = c.group[0].clone(); + c.group.insert(0, first); + })); + } + #[test] fn control_coverage_counts_are_separate_and_fixed() { let model = Model::load_from_repo_root().expect("load repository model"); diff --git a/crates/model/src/registry.rs b/crates/model/src/registry.rs index e4ae81ea5..8999c7dba 100644 --- a/crates/model/src/registry.rs +++ b/crates/model/src/registry.rs @@ -550,6 +550,21 @@ pub struct Commands { pub spec: String, /// Stable public command contracts. pub command: Vec, + /// Module groups (#441): `prismpm ` names a command above. + #[serde(default)] + pub group: Vec, +} + +/// One group verb: `prismpm ` runs `prismpm `. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandGroup { + /// One of the nine modules of model/modules.toml. + pub module: String, + /// The verb under the module. + pub verb: String, + /// The command it runs: a command name, then any of its subcommands. + pub command: String, } /// One stable public command contract. @@ -663,6 +678,41 @@ impl Commands { "public command contract is incomplete or noncanonical".to_owned(), )); } + self.check_groups(&names) + } + + /// Group rows are sorted and unique by module and verb, use lowercase + /// kebab-case words, and run a registered command. A module that is also a + /// command keeps that command: its group verbs must not be the command's + /// own subcommands. + fn check_groups(&self, names: &[&str]) -> Result<(), ModelError> { + let word = |text: &str| { + !text.is_empty() + && !text.starts_with('-') + && !text.ends_with('-') + && text.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') + }; + let bad = |row: &CommandGroup, why: &str| { + Err(ModelError::Inconsistent(format!( + "command group `{} {}` {why}", + row.module, row.verb + ))) + }; + let mut previous: Option<(&str, &str)> = None; + for row in &self.group { + let key = (row.module.as_str(), row.verb.as_str()); + if previous.is_some_and(|previous| previous >= key) { + return bad(row, "is out of order or repeated"); + } + previous = Some(key); + if !word(&row.module) || !word(&row.verb) { + return bad(row, "is not lowercase kebab-case"); + } + let mut words = row.command.split(' '); + if !words.clone().all(word) || !words.next().is_some_and(|head| names.contains(&head)) { + return bad(row, "does not run a registered command"); + } + } Ok(()) } } diff --git a/crates/prismpm/src/cli.rs b/crates/prismpm/src/cli.rs index 0cffba6c6..700e12027 100644 --- a/crates/prismpm/src/cli.rs +++ b/crates/prismpm/src/cli.rs @@ -7,9 +7,10 @@ use crate::controller::{ use crate::error::PrismError; use crate::holo::canonical::encode_value; use crate::holo::provenance::BuildProvenance; -use clap::{error::ErrorKind, CommandFactory, Parser, Subcommand, ValueEnum}; +use clap::{error::ErrorKind, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; use serde::Serialize; use serde_json::json; +use std::ffi::OsString; use std::io::Write; use std::path::{Component, Path, PathBuf}; use std::process::ExitCode; @@ -693,6 +694,146 @@ fn write_line(mut stream: impl Write, bytes: &[u8]) -> Result<(), PrismError> { .map_err(|error| PrismError::new("PP9001", format!("write CLI output: {error}"))) } +/// One module group verb (#441): `prismpm ` runs `prismpm `. +#[derive(Debug, serde::Deserialize)] +struct GroupVerb { + module: String, + verb: String, + command: String, +} + +/// The module groups, read from model/commands.toml, the one table both the +/// model gate and this parser read. +fn groups() -> &'static [GroupVerb] { + static GROUPS: std::sync::OnceLock> = std::sync::OnceLock::new(); + GROUPS.get_or_init(|| { + #[derive(serde::Deserialize)] + struct Table { + #[serde(default)] + group: Vec, + } + toml::from_str::(include_str!("../model/commands.toml")) + .map(|table| table.group) + .unwrap_or_default() + }) +} + +/// The group modules in table order, each once. +fn group_modules() -> Vec<&'static str> { + let mut modules: Vec<&str> = Vec::new(); + for row in groups() { + if modules.last() != Some(&row.module.as_str()) { + modules.push(&row.module); + } + } + modules +} + +/// The usage lines of every group, as `prismpm --help` and `prismpm ` print them. +fn group_help(module: Option<&str>) -> String { + let mut lines = vec![if module.is_some() { + "Verbs:".to_owned() + } else { + "Module groups (the flat commands above stay as aliases):".to_owned() + }]; + for row in groups() + .iter() + .filter(|row| module.is_none_or(|m| m == row.module)) + { + let head = format!(" prismpm {} {}", row.module, row.verb); + lines.push(format!("{head:<44}same as prismpm {}", row.command)); + } + lines.join("\n") +} + +/// The index of the command word: the first argument after the program name +/// that is not a global option or its value. +fn command_index(args: &[OsString]) -> Option { + let mut index = 1; + while let Some(argument) = args.get(index) { + let text = argument.to_str()?; + match text { + "--json" => index += 1, + "-p" | "--project" | "--config" => index += 2, + _ if text.starts_with("--project=") + || text.starts_with("--config=") + || (text.starts_with("-p") && text.len() > 2) => + { + index += 1 + } + _ => return Some(index), + } + } + None +} + +/// What the arguments ask of a module group. +#[derive(Debug, PartialEq, Eq)] +enum GroupRequest { + /// Not a group: parse the arguments as they are. + None, + /// The arguments with the group verb replaced by its command. + Expanded(Vec), + /// `prismpm ` or `prismpm --help`: print the module's verbs. + Help(String), + /// `prismpm `. + Unknown(String), +} + +/// Resolve `prismpm ...` to `prismpm ...`. A word +/// after the module that is not one of its verbs leaves a module that is also +/// a command (`verify`) to that command. +fn group_request(args: &[OsString]) -> GroupRequest { + let Some(index) = command_index(args) else { + return GroupRequest::None; + }; + let Some(module) = args[index].to_str() else { + return GroupRequest::None; + }; + let mut verbs = groups() + .iter() + .filter(|row| row.module == module) + .peekable(); + if verbs.peek().is_none() { + return GroupRequest::None; + } + let next = args.get(index + 1).and_then(|word| word.to_str()); + if let Some(row) = verbs.find(|row| Some(row.verb.as_str()) == next) { + let mut expanded = args[..index].to_vec(); + expanded.extend(row.command.split(' ').map(OsString::from)); + expanded.extend_from_slice(&args[index + 2..]); + return GroupRequest::Expanded(expanded); + } + let is_command = Cli::command() + .get_subcommands() + .any(|command| command.get_name() == module); + if is_command { + return GroupRequest::None; + } + let help = format!( + "Usage: prismpm {module} [ARGS]...\n\n{}", + group_help(Some(module)) + ); + match next { + None | Some("-h" | "--help" | "help") => GroupRequest::Help(help), + Some(verb) => GroupRequest::Unknown(format!( + "error: unrecognized verb '{verb}' for 'prismpm {module}'\n\n{help}" + )), + } +} + +/// Parse the arguments, with the module groups expanded and listed in the help. +fn parse_cli(args: Vec) -> Result { + let args = match group_request(&args) { + GroupRequest::Expanded(expanded) => expanded, + _ => args, + }; + let matches = Cli::command() + .after_help(group_help(None)) + .try_get_matches_from(args)?; + Cli::from_arg_matches(&matches) +} + fn completion(shell: CompletionShell) -> Result { let command = Cli::command(); let names = command @@ -717,6 +858,12 @@ fn completion(shell: CompletionShell) -> Result { "executable commands disagree with model/commands.toml", )); } + let mut names = names; + for module in group_modules() { + if !names.contains(&module) { + names.push(module); + } + } let words = names.join(" "); Ok(match shell { CompletionShell::Bash => format!( @@ -1605,7 +1752,29 @@ fn inspection_summary(inspection: &serde_json::Value) -> String { #[must_use] pub fn run() -> ExitCode { let machine_requested = std::env::args().any(|argument| argument == "--json"); - let cli = match Cli::try_parse() { + let args = std::env::args_os().collect::>(); + match group_request(&args) { + GroupRequest::Help(help) => { + let _ = write_line(std::io::stdout().lock(), help.as_bytes()); + return ExitCode::SUCCESS; + } + GroupRequest::Unknown(message) => { + if machine_requested { + let first = message.lines().next().unwrap_or_default(); + let diagnostic = PrismError::new("PP1001", first.trim_start_matches("error: ")); + let envelope = + json!({"diagnostic": diagnostic, "schema": "prismpm/error-result/1"}); + let bytes = canonical(&envelope) + .unwrap_or_else(|_| b"{\"schema\":\"prismpm/error-result/1\"}".to_vec()); + let _ = write_line(std::io::stdout().lock(), &bytes); + } else { + let _ = write_line(std::io::stderr().lock(), message.as_bytes()); + } + return ExitCode::from(2); + } + GroupRequest::None | GroupRequest::Expanded(_) => {} + } + let cli = match parse_cli(args) { Ok(cli) => cli, Err(error) => { if matches!( @@ -1685,6 +1854,7 @@ pub fn run() -> ExitCode { mod tests { use super::{build_provenance, inspection_summary, Cli, Commands}; use crate::holo::provenance::BuildProvenance; + use clap::CommandFactory; use clap::Parser; #[test] @@ -2146,4 +2316,131 @@ mod tests { .is_err()); assert!(Cli::try_parse_from(["prismpm", "verify-attestation"]).is_err()); } + + fn group_args(arguments: &[&str]) -> Vec { + arguments.iter().map(std::ffi::OsString::from).collect() + } + + fn parse_group(arguments: &[&str]) -> Commands { + super::parse_cli(group_args(arguments)).unwrap().command + } + + #[test] + fn every_group_is_a_module_and_runs_a_command() { + let modules: toml::Value = toml::from_str(include_str!("../model/modules.toml")).unwrap(); + let modules = modules["module"] + .as_array() + .unwrap() + .iter() + .map(|row| row["name"].as_str().unwrap()) + .collect::>(); + let commands = Cli::command() + .get_subcommands() + .map(|command| command.get_name().to_owned()) + .collect::>(); + assert!( + super::groups().len() >= 20, + "model/commands.toml has its groups" + ); + for row in super::groups() { + assert!( + modules.contains(&row.module.as_str()), + "{} is a module", + row.module + ); + let head = row.command.split(' ').next().unwrap(); + assert!( + commands.iter().any(|name| name == head), + "{} is a command", + row.command + ); + // The group verb expands to exactly its command and nothing else. + let super::GroupRequest::Expanded(expanded) = + super::group_request(&group_args(&["prismpm", &row.module, &row.verb, "x"])) + else { + panic!("{} {} is not expanded", row.module, row.verb); + }; + let mut expected = vec!["prismpm"]; + expected.extend(row.command.split(' ')); + expected.push("x"); + assert_eq!(expanded, group_args(&expected)); + } + } + + #[test] + fn group_verbs_run_their_flat_commands() { + assert!(matches!( + parse_group(&["prismpm", "images", "verify", "app.holo"]), + Commands::Check { holo: Some(_), .. } + )); + assert!(matches!( + parse_group(&[ + "prismpm", + "--json", + "-p", + "dir", + "verify", + "attestation", + "app.holo" + ]), + Commands::VerifyAttestation { .. } + )); + assert!(matches!( + parse_group(&["prismpm", "--project=dir", "system", "lock", "check"]), + Commands::Lock { + command: Some(super::LockCommands::Check), + .. + } + )); + assert!(matches!( + parse_group(&["prismpm", "images", "inspect", "app.holo", "--json"]), + Commands::Inspect { .. } + )); + // The flat verbs stay, and `verify` alone is still the model verification. + assert!(matches!( + parse_group(&["prismpm", "verify"]), + Commands::Verify + )); + assert!(matches!( + parse_group(&["prismpm", "check", "app.holo"]), + Commands::Check { .. } + )); + } + + #[test] + fn a_group_without_a_verb_prints_its_verbs() { + let request = super::group_request(&group_args(&["prismpm", "images"])); + let super::GroupRequest::Help(help) = request else { + panic!("{request:?}"); + }; + assert!(help.contains("prismpm images verify")); + assert!(help.contains("same as prismpm check")); + assert!(!help.contains("prismpm verify attestation")); + assert!(matches!( + super::group_request(&group_args(&["prismpm", "images", "--help"])), + super::GroupRequest::Help(_) + )); + assert!(matches!( + super::group_request(&group_args(&["prismpm", "images", "ls"])), + super::GroupRequest::Unknown(_) + )); + // `verify` is a command too, so an unknown word goes to that command. + assert_eq!( + super::group_request(&group_args(&["prismpm", "verify", "--help"])), + super::GroupRequest::None + ); + let top = Cli::command() + .after_help(super::group_help(None)) + .render_help() + .to_string(); + assert!(top.contains("prismpm containers run")); + } + + #[test] + fn completion_offers_the_group_modules() { + let script = super::completion(super::CompletionShell::Bash).unwrap(); + for module in ["images", "containers", "system", "auth", "client"] { + assert!(script.contains(module), "{module}"); + } + } } diff --git a/model/commands.toml b/model/commands.toml index 2c2597ca7..d75156205 100644 --- a/model/commands.toml +++ b/model/commands.toml @@ -219,3 +219,146 @@ name = "verify-signature" mutates = "verified-local-evidence" requires_digest = true result_schema = "prismpm/signature-result/1" + +# Module groups (#441): `prismpm ` runs `prismpm `. +# Sorted by module, then verb. The modules are those of model/modules.toml. + +[[group]] +module = "auth" +verb = "attest" +command = "attest" + +[[group]] +module = "auth" +verb = "sign" +command = "sign" + +[[group]] +module = "auth" +verb = "sign-evidence" +command = "sign-evidence" + +[[group]] +module = "client" +verb = "completion" +command = "completion" + +[[group]] +module = "client" +verb = "generate" +command = "generate" + +[[group]] +module = "client" +verb = "template" +command = "template" + +[[group]] +module = "containers" +verb = "run" +command = "run" + +[[group]] +module = "containers" +verb = "status" +command = "status" + +[[group]] +module = "images" +verb = "build" +command = "build" + +[[group]] +module = "images" +verb = "export-browser" +command = "export-browser" + +[[group]] +module = "images" +verb = "inspect" +command = "inspect" + +[[group]] +module = "images" +verb = "pull" +command = "pull" + +[[group]] +module = "images" +verb = "push" +command = "push" + +[[group]] +module = "images" +verb = "verify" +command = "check" + +[[group]] +module = "system" +verb = "authority" +command = "authority" + +[[group]] +module = "system" +verb = "clean" +command = "clean" + +[[group]] +module = "system" +verb = "fetch" +command = "fetch" + +[[group]] +module = "system" +verb = "lock" +command = "lock" + +[[group]] +module = "system" +verb = "update" +command = "update" + +[[group]] +module = "verify" +verb = "acceptance" +command = "replay-acceptance" + +[[group]] +module = "verify" +verb = "attestation" +command = "verify-attestation" + +[[group]] +module = "verify" +verb = "browser-publication" +command = "verify-browser-publication" + +[[group]] +module = "verify" +verb = "check" +command = "check" + +[[group]] +module = "verify" +verb = "conformance" +command = "conformance" + +[[group]] +module = "verify" +verb = "model" +command = "verify" + +[[group]] +module = "verify" +verb = "release" +command = "verify-release" + +[[group]] +module = "verify" +verb = "replay" +command = "replay" + +[[group]] +module = "verify" +verb = "signature" +command = "verify-signature"