diff --git a/CHANGELOG.d/analysis-run-create-cli.md b/CHANGELOG.d/analysis-run-create-cli.md new file mode 100644 index 000000000..f9fcd3aee --- /dev/null +++ b/CHANGELOG.d/analysis-run-create-cli.md @@ -0,0 +1 @@ +- `tepp_api` loopback `tepp-analysis-runs create` submits metric-free analysis runs (ADR 0034). Create CLI stdout refuses RMSE/bias/coverage/SE-gate/scientific-acceptance keys. Not GET-by-id, not scientific-acceptance CLI, not collection list, not cancel CLI, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 1f61318fa..dc20e73b6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -17,6 +17,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Analysis-run collection HTTP doctoring | [`docs/research/analysis-run-collection-http.md`](docs/research/analysis-run-collection-http.md) | | Analysis-run collection CLI doctoring | [`docs/research/analysis-run-collection-cli.md`](docs/research/analysis-run-collection-cli.md) | | Analysis-run cancel CLI doctoring | [`docs/research/analysis-run-cancel-cli.md`](docs/research/analysis-run-cancel-cli.md) | +| Analysis-run create CLI doctoring | [`docs/research/analysis-run-create-cli.md`](docs/research/analysis-run-create-cli.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | | Security policy | [`SECURITY.md`](SECURITY.md) | diff --git a/crates/tepp_api/src/analysis_run_create_cli.rs b/crates/tepp_api/src/analysis_run_create_cli.rs new file mode 100644 index 000000000..a01c547a5 --- /dev/null +++ b/crates/tepp_api/src/analysis_run_create_cli.rs @@ -0,0 +1,974 @@ +//! Operator loopback CLI for analysis-run create POST. +//! +//! GAP-003A tenth slice: operators run `tepp-analysis-runs create` to submit +//! metric-free analysis runs without writing raw HTTP. Stdout stays metric-free +//! `202 Accepted`. `tepp.scientific_acceptance.v1` never appears. This module +//! does not duplicate GET-by-id (#359), lifecycle POST (#360), cancel HTTP +//! (#361), scientific-acceptance CLI (#362), collection GET (#368), collection +//! CLI list (#371), cancel CLI (#378), retry HTTP (#369), stored-request GET +//! (#377), or consumer-parity cancel (#373). Persistence remains GAP-003B. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; + +use crate::analysis_run_cancel_http::refuse_metrics_on_cancel_payload; +use crate::lineageweave_http::consumer_is_supported; +use crate::live_http::map_io_error; +use crate::naruon_http::{NARUON_ANALYSIS_RUN_PATH, header_is_credential}; +use crate::wire::require_nonempty; +use crate::{ + AnalysisRunAccepted, AnalysisRunLiveService, AnalysisRunRequest, ApiError, + NARUON_LIVE_IO_TIMEOUT, NaruonLiveResponse, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; + +/// Supported operator verbs for the loopback create CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AnalysisRunCreateCliVerb { + /// `POST /v1/analysis-runs`. + Create, +} + +impl AnalysisRunCreateCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "create" => Ok(Self::Create), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Create => "create", + } + } +} + +/// One operator CLI invocation against a loopback create POST listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AnalysisRunCreateCliInvocation { + /// CLI verb to execute. + pub verb: AnalysisRunCreateCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published modular consumer (`naruon` or `lineageweave`). + pub consumer: String, + /// Exact request idempotency key of the create body. + pub idempotency_key: String, + /// Typed metric-free `AnalysisRunRequest` JSON. Empty POST is refused. + pub body: String, +} + +impl AnalysisRunCreateCliInvocation { + /// Parse argv plus stdin body into a validated loopback create invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, an unpublished consumer, credential-shaped flags, + /// empty or metric bodies, or a typed body whose idempotency key does not + /// match the flag. + pub fn from_args(args: I, body: impl Into) -> Result + where + I: IntoIterator, + S: AsRef, + { + let tokens: Vec = args + .into_iter() + .map(|token| token.as_ref().to_owned()) + .collect(); + let (verb_token, rest) = tokens.split_first().ok_or(ApiError::InvalidWirePayload)?; + let verb = AnalysisRunCreateCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile create body. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] for empty, unpublished, metric-bearing, + /// or mismatched fields. + pub fn validate(&self) -> Result<(), ApiError> { + require_loopback_host(&self.host)?; + require_nonempty(&self.consumer)?; + if !consumer_is_supported(&self.consumer) { + return Err(ApiError::InvalidWirePayload); + } + require_nonempty(&self.idempotency_key)?; + require_nonempty(&self.body)?; + refuse_scientific_acceptance_schema(&self.body)?; + refuse_metrics_on_cancel_payload(&self.body)?; + let request = AnalysisRunRequest::from_json(&self.body)?; + if request.idempotency_key != self.idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + consumer: Option, + idempotency_key: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + consumer: None, + idempotency_key: None, + }; + let mut index = 0; + while index < rest.len() { + let flag = rest[index].as_str(); + if !flag.starts_with("--") { + return Err(ApiError::InvalidWirePayload); + } + let name = &flag[2..]; + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + let slot = match name { + "host" => &mut flags.host, + "consumer" => &mut flags.consumer, + "idempotency-key" => &mut flags.idempotency_key, + _ => return Err(ApiError::InvalidWirePayload), + }; + if slot.is_some() || index + 1 >= rest.len() { + return Err(ApiError::InvalidWirePayload); + } + let value = rest[index + 1].as_str(); + require_nonempty(value)?; + *slot = Some(value.to_owned()); + index += 2; + } + Ok(flags) +} + +fn assemble_invocation( + verb: AnalysisRunCreateCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = AnalysisRunCreateCliInvocation { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| crate::NARUON_CONSUMER_CODE.to_owned()), + idempotency_key: flags.idempotency_key.ok_or(ApiError::InvalidWirePayload)?, + body, + }; + invocation.validate()?; + Ok(invocation) +} + +fn require_loopback_host(host: &str) -> Result { + let addr: SocketAddr = host.parse().map_err(|_| ApiError::InvalidWirePayload)?; + if addr.ip().is_loopback() { + Ok(addr) + } else { + Err(ApiError::AuthorizationDenied) + } +} + +/// Compose one HTTP/1.1 create POST for a validated CLI invocation. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`AnalysisRunCreateCliInvocation::validate`]. +pub fn compose_analysis_run_create_cli_http( + invocation: &AnalysisRunCreateCliInvocation, +) -> Result { + invocation.validate()?; + Ok(format!( + "POST {NARUON_ANALYSIS_RUN_PATH} HTTP/1.1\r\nHost: {}\r\ncontent-type: application/json\r\ntepp-consumer: {}\r\ntepp-contract-version: 1\r\nidempotency-key: {}\r\ncontent-length: {}\r\n\r\n{}", + invocation.host, + invocation.consumer, + invocation.idempotency_key, + invocation.body.len(), + invocation.body + )) +} + +/// Dispatch one create CLI invocation against an in-process loopback service. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_analysis_run_create_cli( + service: &mut AnalysisRunLiveService, + invocation: &AnalysisRunCreateCliInvocation, +) -> Result { + let request = compose_analysis_run_create_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one create CLI invocation over loopback TCP against `tepp-loopback`. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_analysis_run_create_cli( + invocation: &AnalysisRunCreateCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_analysis_run_create_cli_http(invocation)?; + let mut stream = TcpStream::connect(addr).map_err(|error| map_io_error(&error))?; + stream + .set_read_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .set_write_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .write_all(request.as_bytes()) + .map_err(|error| map_io_error(&error))?; + stream.flush().map_err(|error| map_io_error(&error))?; + let mut bytes = Vec::new(); + stream + .read_to_end(&mut bytes) + .map_err(|error| map_io_error(&error))?; + parse_http_response(&bytes) +} + +/// Filter CLI stdout so create receipts never print scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a receipt carries metric keys, +/// `tepp.scientific_acceptance.v1`, or a non-accepted success body. +pub fn render_analysis_run_create_cli_stdout( + invocation: &AnalysisRunCreateCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance_schema(&response.body)?; + refuse_metrics_on_cancel_payload(&response.body)?; + if !(200..300).contains(&response.status_code) { + return Ok(response.body.clone()); + } + let accepted = AnalysisRunAccepted::from_json(&response.body)?; + if accepted.run_state != "accepted" || accepted.idempotency_key != invocation.idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + accepted.to_json() +} + +fn refuse_scientific_acceptance_schema(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +fn parse_http_response(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes).map_err(|_| ApiError::InvalidWirePayload)?; + let (header_block, body) = text + .split_once("\r\n\r\n") + .ok_or(ApiError::InvalidWirePayload)?; + let mut lines = header_block.split("\r\n"); + let status_line = lines.next().ok_or(ApiError::InvalidWirePayload)?; + let mut parts = status_line.split(' '); + if parts.next() != Some("HTTP/1.1") { + return Err(ApiError::InvalidWirePayload); + } + let code = parts + .next() + .ok_or(ApiError::InvalidWirePayload)? + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?; + let reason_phrase = static_reason(code)?; + let mut content_length = None; + for line in lines { + let (name, value) = line.split_once(':').ok_or(ApiError::InvalidWirePayload)?; + if name.eq_ignore_ascii_case("content-length") { + if content_length.is_some() { + return Err(ApiError::InvalidWirePayload); + } + content_length = Some( + value + .trim() + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?, + ); + } + } + let declared = content_length.ok_or(ApiError::InvalidWirePayload)?; + if declared != body.len() { + return Err(ApiError::InvalidWirePayload); + } + Ok(NaruonLiveResponse { + status_code: code, + reason_phrase, + body: body.to_owned(), + }) +} + +fn static_reason(code: u16) -> Result<&'static str, ApiError> { + match code { + 200 => Ok("OK"), + 202 => Ok("Accepted"), + 400 => Ok("Bad Request"), + 403 => Ok("Forbidden"), + 413 => Ok("Payload Too Large"), + 422 => Ok("Unprocessable Entity"), + _ => Err(ApiError::InvalidWirePayload), + } +} + +/// Read stdin leftover bytes on a non-terminal; empty create POST is refused. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_analysis_run_create_cli_stdin( + stdin_is_terminal: bool, + mut stdin: impl Read, +) -> Result { + if stdin_is_terminal { + Ok(String::new()) + } else { + let mut body = String::new(); + stdin + .read_to_string(&mut body) + .map_err(|_| ApiError::InvalidWirePayload)?; + Ok(body) + } +} + +#[cfg(test)] +#[allow(clippy::too_many_lines)] +mod tests { + use super::{ + AnalysisRunCreateCliInvocation, AnalysisRunCreateCliVerb, SCIENTIFIC_ACCEPTANCE_SCHEMA, + compose_analysis_run_create_cli_http, dispatch_analysis_run_create_cli, + execute_analysis_run_create_cli, parse_http_response, read_analysis_run_create_cli_stdin, + render_analysis_run_create_cli_stdout, static_reason, + }; + use crate::{ + ANALYSIS_RUN_CONTRACT_VERSION, AnalysisRunAccepted, AnalysisRunLiveService, + AnalysisRunRequest, ApiError, LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, + NaruonLiveResponse, + }; + + fn request(idempotency_key: &str) -> AnalysisRunRequest { + AnalysisRunRequest { + contract_version: ANALYSIS_RUN_CONTRACT_VERSION, + idempotency_key: idempotency_key.into(), + tenant_workspace_id: "cli-create-tenant".into(), + snapshot_id: "cli-create-snapshot".into(), + knowledge_cutoff: "2026-08-01T00:00:00Z".into(), + model_contract_version: "tepp-analysis-run-v1".into(), + output_profile: "calibrated_event_measurement".into(), + } + } + + fn request_json(idempotency_key: &str) -> String { + request(idempotency_key).to_json().expect("json") + } + + fn create_invocation(idempotency_key: &str) -> AnalysisRunCreateCliInvocation { + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + idempotency_key, + ], + request_json(idempotency_key), + ) + .expect("create") + } + + #[test] + fn verbs_parse_and_reject_unknown_tokens() { + assert_eq!( + AnalysisRunCreateCliVerb::parse("create").expect("create"), + AnalysisRunCreateCliVerb::Create + ); + assert_eq!(AnalysisRunCreateCliVerb::Create.as_str(), "create"); + assert_eq!( + AnalysisRunCreateCliVerb::parse("CREATE"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliVerb::parse("cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliVerb::parse("status"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn from_args_refuses_empty_unknown_host_and_credential_flags() { + assert_eq!( + AnalysisRunCreateCliInvocation::from_args(Vec::::new(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args(["nope"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args(["create"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args(["create", "--host", "127.0.0.1:18081"], "") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "8.8.8.8:80", + "--idempotency-key", + "idem-1" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "not-a-socket", + "--idempotency-key", + "idem-1" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--authorization", + "secret" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--pretty" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "extra" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--run-id", + "tepp-run-1" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--page-limit", + "1" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--consumer", + "other" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--host", + "127.0.0.1:9" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + r#"{"rmse":1.0}"# + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + format!(r#"{{"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"#) + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + request_json("other-key") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + ["create", "--host", "127.0.0.1:18081", "--idempotency-key"], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--github-token", + "secret" + ], + request_json("idem-1") + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + } + + #[test] + fn create_assembles_default_consumer_and_typed_body() { + let create = create_invocation("idem-1"); + assert_eq!(create.verb, AnalysisRunCreateCliVerb::Create); + assert_eq!(create.consumer, NARUON_CONSUMER_CODE); + assert!(!create.body.is_empty()); + let http = compose_analysis_run_create_cli_http(&create).expect("http"); + assert!(http.starts_with("POST /v1/analysis-runs HTTP/1.1")); + assert!(http.contains("tepp-consumer: naruon")); + assert!(http.contains("idempotency-key: idem-1")); + assert!(http.contains(&format!("content-length: {}", create.body.len()))); + assert!(!http.contains("authorization")); + assert!(!http.contains("copilot")); + assert!(!http.contains("tepp-page-cursor")); + assert!(!http.contains("/cancel")); + assert!(!http.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + + let with_consumer = AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + "idem-lw", + ], + request_json("idem-lw"), + ) + .expect("lineageweave"); + assert_eq!(with_consumer.consumer, LINEAGEWEAVE_CONSUMER_CODE); + let lw_http = compose_analysis_run_create_cli_http(&with_consumer).expect("lw http"); + assert!(lw_http.contains("tepp-consumer: lineageweave")); + assert!(lw_http.contains("idempotency-key: idem-lw")); + } + + #[test] + fn dispatch_creates_accepted_runs_without_scientific_acceptance() { + let mut service = AnalysisRunLiveService::new(); + let invocation = create_invocation("cli-create-idem-1"); + let created = dispatch_analysis_run_create_cli(&mut service, &invocation).expect("create"); + assert_eq!(created.status_code, 202); + let stdout = render_analysis_run_create_cli_stdout(&invocation, &created).expect("stdout"); + assert!(!stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("terminal_result")); + let accepted = AnalysisRunAccepted::from_json(&stdout).expect("accepted"); + assert_eq!(accepted.run_state, "accepted"); + assert_eq!(accepted.idempotency_key, "cli-create-idem-1"); + assert!(!accepted.run_id.is_empty()); + + let replay = dispatch_analysis_run_create_cli(&mut service, &invocation).expect("replay"); + assert_eq!(replay.status_code, 202); + let replay_stdout = + render_analysis_run_create_cli_stdout(&invocation, &replay).expect("replay stdout"); + let replay_accepted = AnalysisRunAccepted::from_json(&replay_stdout).expect("replay"); + assert_eq!(replay_accepted.run_id, accepted.run_id); + + let other = AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + "cli-create-idem-1", + ], + request_json("cli-create-idem-1"), + ) + .expect("other consumer"); + let isolated = dispatch_analysis_run_create_cli(&mut service, &other).expect("isolated"); + assert_eq!(isolated.status_code, 202); + let isolated_stdout = + render_analysis_run_create_cli_stdout(&other, &isolated).expect("isolated stdout"); + let isolated_accepted = AnalysisRunAccepted::from_json(&isolated_stdout).expect("isolated"); + assert_ne!(isolated_accepted.run_id, accepted.run_id); + assert!(!isolated_stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + + let conflict_body = { + let mut conflict = request("cli-create-idem-1"); + conflict.snapshot_id = "other-snapshot".into(); + conflict.to_json().expect("conflict json") + }; + let conflict = AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "cli-create-idem-1", + ], + conflict_body, + ) + .expect("conflict invocation"); + let refused = dispatch_analysis_run_create_cli(&mut service, &conflict).expect("conflict"); + assert_eq!(refused.status_code, 400); + let refused_stdout = + render_analysis_run_create_cli_stdout(&conflict, &refused).expect("conflict stdout"); + assert!(refused_stdout.contains("invalid_wire_payload") || !refused_stdout.is_empty()); + assert!(!refused_stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + } + + #[test] + fn render_refuses_metrics_scientific_acceptance_and_empty_bodies() { + let create = create_invocation("idem-1"); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"idem-1","rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: format!( + r#"{{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"idem-1","schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"# + ), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"cancelled","idempotency_key":"idem-1"}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"other"}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let error_stdout = render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: r#"{"error_code":"invalid_wire_payload"}"#.into(), + }, + ) + .expect("error"); + assert!(error_stdout.contains("invalid_wire_payload")); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: format!(r#"{{"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"#), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: r#"{"rmse":0.1}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let accepted_ok = render_analysis_run_create_cli_stdout( + &create, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"idem-1"}"#.into(), + }, + ) + .expect("accepted"); + assert!(accepted_ok.contains("\"run_state\":\"accepted\"")); + assert!(!accepted_ok.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + } + + #[test] + fn execute_over_tcp_and_parse_response_failures() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let addr = service.local_addr().expect("addr"); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let mut invocation = create_invocation("cli-create-tcp"); + invocation.host = addr.to_string(); + let response = execute_analysis_run_create_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 202); + handle.join().expect("join"); + + invocation.host = "127.0.0.1:1".into(); + assert_eq!( + execute_analysis_run_create_cli(&invocation).unwrap_err(), + ApiError::InvalidWirePayload + ); + + let parsed = parse_http_response(b"HTTP/1.1 202 Accepted\r\ncontent-length: 2\r\n\r\n{}") + .expect("parse"); + assert_eq!(parsed.status_code, 202); + assert_eq!( + parse_http_response(b"not-http").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.0 202 Accepted\r\ncontent-length: 2\r\n\r\n{}") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 299 Mystery\r\ncontent-length: 2\r\n\r\n{}") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response( + b"HTTP/1.1 202 Accepted\r\ncontent-length: 2\r\ncontent-length: 2\r\n\r\n{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 202 Accepted\r\ncontent-length: 9\r\n\r\n{}") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 202 Accepted\r\nbad-header\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(&[0xff, 0xfe]).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!(static_reason(200).expect("200"), "OK"); + assert_eq!(static_reason(202).expect("202"), "Accepted"); + assert_eq!(static_reason(400).expect("400"), "Bad Request"); + assert_eq!(static_reason(403).expect("403"), "Forbidden"); + assert_eq!(static_reason(413).expect("413"), "Payload Too Large"); + assert_eq!(static_reason(422).expect("422"), "Unprocessable Entity"); + assert_eq!( + static_reason(500).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1\r\ncontent-length: 0\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 abc OK\r\ncontent-length: 0\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 202 Accepted\r\ncontent-length: x\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 202 Accepted\r\nhost: 127.0.0.1\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn stdin_reader_skips_terminal_and_reads_otherwise() { + let empty = read_analysis_run_create_cli_stdin(true, std::io::empty()).expect("tty"); + assert!(empty.is_empty()); + let piped = read_analysis_run_create_cli_stdin(false, std::io::Cursor::new(b"leftover")) + .expect("piped"); + assert_eq!(piped, "leftover"); + let piped_empty = + read_analysis_run_create_cli_stdin(false, std::io::Cursor::new(b"")).expect("empty"); + assert!(piped_empty.is_empty()); + } +} diff --git a/crates/tepp_api/src/bin/tepp_analysis_runs.rs b/crates/tepp_api/src/bin/tepp_analysis_runs.rs index f792c7db6..8d1a6e371 100644 --- a/crates/tepp_api/src/bin/tepp_analysis_runs.rs +++ b/crates/tepp_api/src/bin/tepp_analysis_runs.rs @@ -1,14 +1,16 @@ -//! Operator CLI for loopback analysis-run collection GET and cancel POST. +//! Operator CLI for loopback analysis-run collection GET, cancel POST, and create POST. use std::io::{self, IsTerminal}; use std::process::ExitCode; use tepp_api::{ AnalysisRunCancelCliInvocation, AnalysisRunCollectionCliInvocation, - AnalysisRunCollectionCliVerb, ApiError, execute_analysis_run_cancel_cli, - execute_analysis_run_collection_cli, read_analysis_run_cancel_cli_stdin, - read_analysis_run_collection_cli_stdin, render_analysis_run_cancel_cli_stdout, - render_analysis_run_collection_cli_stdout, + AnalysisRunCollectionCliVerb, AnalysisRunCreateCliInvocation, ApiError, + execute_analysis_run_cancel_cli, execute_analysis_run_collection_cli, + execute_analysis_run_create_cli, read_analysis_run_cancel_cli_stdin, + read_analysis_run_collection_cli_stdin, read_analysis_run_create_cli_stdin, + render_analysis_run_cancel_cli_stdout, render_analysis_run_collection_cli_stdout, + render_analysis_run_create_cli_stdout, }; fn main() -> ExitCode { @@ -23,6 +25,7 @@ fn run() -> Result<(), ApiError> { match args.first().map(String::as_str) { Some("list") => run_list(&args), Some("cancel") => run_cancel(&args), + Some("create") => run_create(&args), _ => Err(ApiError::InvalidWirePayload), } } @@ -57,3 +60,16 @@ fn run_cancel(args: &[String]) -> Result<(), ApiError> { Err(ApiError::InvalidWirePayload) } } + +fn run_create(args: &[String]) -> Result<(), ApiError> { + let body = read_analysis_run_create_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = AnalysisRunCreateCliInvocation::from_args(args, body)?; + let response = execute_analysis_run_create_cli(&invocation)?; + let stdout = render_analysis_run_create_cli_stdout(&invocation, &response)?; + println!("{stdout}"); + if (200..300).contains(&response.status_code) { + Ok(()) + } else { + Err(ApiError::InvalidWirePayload) + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 41d535c39..4535c5faf 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -17,6 +17,7 @@ mod analysis_run_cancel_cli; mod analysis_run_cancel_http; mod analysis_run_collection_cli; mod analysis_run_collection_http; +mod analysis_run_create_cli; mod analysis_run_live; mod analysis_run_status_http; mod authorization; @@ -133,6 +134,20 @@ pub use analysis_run_collection_http::parse_collection_page_cursor; pub use analysis_run_collection_http::parse_collection_page_limit; /// Refuse scientific-metric keys on a collection payload. pub use analysis_run_collection_http::refuse_metrics_on_collection_payload; +/// One validated create CLI invocation. +pub use analysis_run_create_cli::AnalysisRunCreateCliInvocation; +/// Loopback create CLI verb. +pub use analysis_run_create_cli::AnalysisRunCreateCliVerb; +/// Compose loopback create POST bytes for a CLI invocation. +pub use analysis_run_create_cli::compose_analysis_run_create_cli_http; +/// Dispatch a create CLI invocation against an in-process listener. +pub use analysis_run_create_cli::dispatch_analysis_run_create_cli; +/// Execute a create CLI invocation over loopback TCP. +pub use analysis_run_create_cli::execute_analysis_run_create_cli; +/// Read leftover stdin for the create CLI. +pub use analysis_run_create_cli::read_analysis_run_create_cli_stdin; +/// Render metric-free create CLI stdout. +pub use analysis_run_create_cli::render_analysis_run_create_cli_stdout; /// Consumer-neutral loopback analysis-run service. pub use analysis_run_live::AnalysisRunLiveService; /// Analysis-run status HTTP exchange re-exports. diff --git a/crates/tepp_api/tests/analysis_run_create_cli_contract.rs b/crates/tepp_api/tests/analysis_run_create_cli_contract.rs new file mode 100644 index 000000000..bbad614a2 --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_create_cli_contract.rs @@ -0,0 +1,98 @@ +//! Contract tests for the analysis-run create loopback CLI. + +use tepp_api::{ + ANALYSIS_RUN_CONTRACT_VERSION, AnalysisRunCreateCliInvocation, AnalysisRunCreateCliVerb, + AnalysisRunRequest, ApiError, NARUON_CONSUMER_CODE, compose_analysis_run_create_cli_http, +}; + +fn request_json(idempotency_key: &str) -> String { + AnalysisRunRequest { + contract_version: ANALYSIS_RUN_CONTRACT_VERSION, + idempotency_key: idempotency_key.into(), + tenant_workspace_id: "cli-create-contract-tenant".into(), + snapshot_id: "cli-create-contract-snapshot".into(), + knowledge_cutoff: "2026-08-01T00:00:00Z".into(), + model_contract_version: "tepp-analysis-run-v1".into(), + output_profile: "calibrated_event_measurement".into(), + } + .to_json() + .expect("json") +} + +#[test] +fn create_cli_is_metric_free_post_without_credentials() { + assert_eq!( + AnalysisRunCreateCliVerb::parse("create").expect("create"), + AnalysisRunCreateCliVerb::Create + ); + let invocation = AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + ], + request_json("idem-1"), + ) + .expect("invocation"); + assert_eq!(invocation.consumer, NARUON_CONSUMER_CODE); + let http = compose_analysis_run_create_cli_http(&invocation).expect("http"); + assert!(http.starts_with("POST /v1/analysis-runs HTTP/1.1")); + assert!(http.contains("idempotency-key: idem-1")); + assert!(!http.contains("authorization")); + assert!(!http.contains("copilot")); + assert!(!http.contains("tepp.scientific_acceptance.v1")); + assert!(!http.contains("/cancel")); +} + +#[test] +fn create_cli_refuses_non_loopback_unknown_verbs_and_metric_bodies() { + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "8.8.8.8:80", + "--idempotency-key", + "idem-1" + ], + request_json("idem-1") + ), + Err(ApiError::AuthorizationDenied) + ); + assert_eq!( + AnalysisRunCreateCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliVerb::parse("cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + r#"{"rmse":1.0}"# + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCreateCliInvocation::from_args( + [ + "create", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + "" + ), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 2adcfab25..02c916ab9 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -90,6 +90,9 @@ operator-visible client for that collection GET; it does not duplicate the scientific-acceptance `tepp-analysis-run` CLI. The loopback `tepp-analysis-runs cancel` CLI is the operator-visible client for `POST /v1/analysis-runs/{run_id}/cancel`; cancel stdout stays metric-free and +never prints `tepp.scientific_acceptance.v1`. The loopback +`tepp-analysis-runs create` CLI is the operator-visible client for +`POST /v1/analysis-runs`; create stdout stays metric-free `202 Accepted` and never prints `tepp.scientific_acceptance.v1`. The stacked `analysis_engine` slice provides the first executable service-side diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 4955ee6ab..d0b47ea2a 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -57,6 +57,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | loopback analysis-run collection GET | ADR 0031; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs` on `AnalysisRunLiveService`: metric-free enumeration of accepted/running/cancelled/terminal runs; collection bodies refuse scientific-acceptance and RMSE keys; GET-by-id remains a later slice | active-PR | | loopback analysis-run collection CLI | ADR 0032; API contract; RFC 9110 | `tepp_api` `tepp-analysis-runs list` CLI: operator-visible metric-free collection client; `tepp.scientific_acceptance.v1` never prints; not GET-by-id and not the scientific-acceptance CLI | active-PR | | loopback analysis-run cancel CLI | ADR 0033; API contract; RFC 9110 | `tepp_api` `tepp-analysis-runs cancel` CLI: operator-visible metric-free client of `POST /v1/analysis-runs/{run_id}/cancel`; `tepp.scientific_acceptance.v1` never prints; not GET-by-id, not collection list, and not the scientific-acceptance CLI | active-PR | +| loopback analysis-run create CLI | ADR 0034; API contract; RFC 9110 | `tepp_api` `tepp-analysis-runs create` CLI: operator-visible metric-free client of `POST /v1/analysis-runs`; `tepp.scientific_acceptance.v1` never prints; not GET-by-id, not collection list, not cancel CLI, and not the scientific-acceptance CLI | active-PR | | executable cutoff-safe analysis-run readiness | ADR 0021; temporal research; API terminal-result contract | stacked `analysis_engine` PR on #157: availability cutoff, snapshot binding, multiple-membership aggregation, digest-bound artifact, realistic end-to-end tests | active-PR | | delayed-reporting cutoff eligibility in truth corpora | ADR 0002; research | `tepp_simulation` eligible-at-cutoff filter on the active PR | active-PR | | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); HTTP service remaining accepted-target | partial | diff --git a/docs/adr/0034-analysis-run-create-cli.md b/docs/adr/0034-analysis-run-create-cli.md new file mode 100644 index 000000000..f804ba6c2 --- /dev/null +++ b/docs/adr/0034-analysis-run-create-cli.md @@ -0,0 +1,73 @@ +# ADR 0034 — Analysis-run create loopback CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0018 for the operator-visible create client. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0033 remain on live GAP-003A engine-library, terminal-wire DTO, GET-by-id, lifecycle-POST, cancel-HTTP, scientific-acceptance CLI, collection-GET, collection-CLI, and cancel-CLI slices. + +## Context + +ADR 0018 accepts `POST /v1/analysis-runs` on the loopback listener, but operators still had to write raw HTTP/1.1 to submit a metric-free analysis run. Duplicating create HTTP, GET-by-id, lifecycle POST, cancel HTTP, the scientific-acceptance CLI (`tepp-analysis-run` on live #362), collection GET, collection CLI `list`, or cancel CLI would collide with live PRs. + +## Decision + +`tepp_api` extends the loopback-only `tepp-analysis-runs` CLI: + +- `create` POSTs `/v1/analysis-runs` with `--idempotency-key` and a typed `AnalysisRunRequest` stdin body. +- Empty stdin is refused. The body's idempotency key must match the flag. +- Stdout is metric-free `202 Accepted`: `run_id`, `run_state=accepted`, and `idempotency_key`. +- `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, report, and `terminal_result` never appear. +- Non-loopback hosts, unpublished consumers, credential-shaped flags, collection pagination flags, cancel `--run-id`, unknown verbs, mismatched keys, and metric bodies fail closed. +- Persistence, Compose recovery, and psychometric execution remain GAP-003B. + +## Alternatives considered + +1. **Keep raw HTTP as the only create path** — rejected because operators still guess framing after ADR 0018. +2. **Add `create` onto the live scientific-acceptance CLI (#362)** — rejected because that head already owns create/running/terminal/status for the scientific-acceptance profile and is stacked on GET-by-id, not the collection/cancel operator binary. +3. **Open a second `tepp-analysis-runs` binary beside collection CLI list (#371) and cancel CLI (#378)** — rejected because the operator-visible command is the same binary. +4. **Persist created rows in PostgreSQL** — rejected as GAP-003B / live draft #287. +5. **Loopback create CLI with the same metric-free gates as ADR 0018** — accepted. + +## Consequences + +- Operators can submit metric-free analysis runs on the same loopback listener that lists and cancels them without writing HTTP. +- Accepted receipts cannot be mistaken for a succeeded scientific-acceptance result. +- CLI success is not release evidence. + +## Failure and recovery + +Non-loopback hosts return authorization denied. Unknown verbs, metric keys, mismatched idempotency keys, unpublished consumers, credential flags, empty stdin, and collection/cancel flags fail closed. Conflicting idempotent bodies remain refused by ADR 0018. The in-memory registry is not durable. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- The CLI remains loopback-only and size-bounded. +- Process exit 0 on an accepted receipt is not measurement evidence and is not an ADR 0014 claim. + +## Compatibility and migration + +Cancel HTTP, collection GET, collection CLI `list`, cancel CLI, create POST, temporal-context, and project-history paths are unchanged. The scientific-acceptance CLI binary name `tepp-analysis-run` remains owned by ADR 0030 / #362. Production adapters may replace loopback while preserving metric-free accepted receipts. + +## Verification + +Falsifiable evidence: + +- CLI create JSON has no RMSE/bias/coverage/SE-gate/scientific-acceptance keys and no `terminal_result`; +- CLI create of a valid request is metric-free `accepted` and replay is idempotent; +- another consumer cannot collide with the first consumer's idempotency key; +- non-loopback host, credential flags, collection/cancel flags, metric stdin, empty stdin, and unknown verbs fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes the create verb from `tepp-analysis-runs`; collection `list`, cancel, and create HTTP remain valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on create, or treat CLI success as an ADR 0014 claim. + +## Related authority + +- ADR 0018 owns consumer-scoped ingress and metric-free `202 Accepted`. +- ADR 0032 owns `tepp-analysis-runs list`. +- ADR 0033 owns `tepp-analysis-runs cancel`. +- ADR 0030 owns the scientific-acceptance loopback CLI (live #362). +- ADR 0014 owns scientific claim promotion. +- ADR 0011 owns standalone/modular HTTP boundaries. +- RFC 9110 owns POST semantics (Fielding, Nottingham, & Reschke, 2022). It does not authorize scientific claims. diff --git a/docs/adr/README.md b/docs/adr/README.md index 592ab1107..4abb0073c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -34,6 +34,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0031](0031-analysis-run-collection-get.md) | Loopback GET analysis-run collection is metric-free enumeration | Accepted | active-PR | Complements ADR 0018/0029; does not supersede ADR 0014. ADR 0026–0030 live on other GAP-003A PRs. | | [0032](0032-analysis-run-collection-cli.md) | Loopback `tepp-analysis-runs list` is metric-free collection client | Accepted | active-PR | Complements ADR 0031; does not supersede ADR 0014. ADR 0026–0031 live on other GAP-003A PRs. | | [0033](0033-analysis-run-cancel-cli.md) | Loopback `tepp-analysis-runs cancel` is metric-free cancel client | Accepted | active-PR | Complements ADR 0029/0032; does not supersede ADR 0014. ADR 0026–0032 live on other GAP-003A PRs. | +| [0034](0034-analysis-run-create-cli.md) | Loopback `tepp-analysis-runs create` is metric-free create client | Accepted | active-PR | Complements ADR 0018/0032/0033; does not supersede ADR 0014. ADR 0026–0033 live on other GAP-003A PRs. | | [0023](0023-lineage-criterion-anchor-contract.md) | TEPP-owned Event Lineage criterion anchor | Accepted | active-PR | PR #237 publishes the strict accepted/rejected artifact and identities; estimator execution remains fail-closed future work. | | [0024](0024-independent-topic-importance-anchor.md) | Posterior topic-context producer contract | Accepted | contract-only active-PR | Strict DTO/schema only; the current estimator does not emit it. fast-mlsirm owns case-deletion influence. | | [0001](0001-rust-first-modular-msa.md) | Rust-first numerical core and CPU `f64` reference | Accepted | partial | ADR 0011 owns cross-service/MSA authority; 0001 retains numerical/backend authority. | @@ -148,6 +149,7 @@ Use the narrowest owning ADR when decisions overlap: - **analysis-run collection GET:** ADR 0031. - **analysis-run collection CLI:** ADR 0032. - **analysis-run cancel CLI:** ADR 0033. +- **analysis-run create CLI:** ADR 0034. ## Change and supersession rule diff --git a/docs/connectors/naruon-artifact-consumer.md b/docs/connectors/naruon-artifact-consumer.md index 502f61d34..1deeb25c9 100644 --- a/docs/connectors/naruon-artifact-consumer.md +++ b/docs/connectors/naruon-artifact-consumer.md @@ -29,6 +29,7 @@ TEPP remains the scientific authority for estimation, recovery metrics, temporal | HTTP analysis-run collection | `tepp_api` `naruon_analysis_run_collection_exchange` → `GET /v1/analysis-runs` | naruon → TEPP | | CLI analysis-run collection | `tepp_api` `tepp-analysis-runs list` → loopback `GET /v1/analysis-runs` | naruon → TEPP | | CLI analysis-run cancel | `tepp_api` `tepp-analysis-runs cancel` → loopback `POST /v1/analysis-runs/{run_id}/cancel` | naruon → TEPP | +| CLI analysis-run create | `tepp_api` `tepp-analysis-runs create` → loopback `POST /v1/analysis-runs` | naruon → TEPP | | HTTP analysis-run cancel | `tepp_api` `naruon_analysis_run_cancel_exchange` → `POST /v1/analysis-runs/{run_id}/cancel` | naruon → TEPP | | HTTP export authorize | `tepp_api` `naruon_export_exchange` → `POST /v1/exports` | naruon → TEPP | | Live loopback POST | `tepp_api` `NaruonLiveService` → `POST /v1/analysis-runs` and `/v1/exports` | naruon → TEPP | @@ -55,6 +56,7 @@ When naruon requests an export, TEPP evaluates `AnalyticalPurpose::ModularServic - lexical method codes (`tfidf`, `bm25`, `keyword`) claiming TEPP inference → reject; - scientific-metric keys (`rmse`, `bias`, `coverage`, `se_gate`, `scientific_acceptance`, `report`) on a cancel body → reject; - scientific-metric keys (`rmse`, `bias`, `coverage`, `se_gate`, `scientific_acceptance`, `report`, `terminal_result`) on a collection body → reject; +- scientific-metric keys (`rmse`, `bias`, `coverage`, `se_gate`, `scientific_acceptance`, `report`) on a create CLI body or accepted receipt → reject; - cancel of a succeeded, failed, or unknown analysis run → reject. ## Authority sources diff --git a/docs/research/analysis-run-create-cli.md b/docs/research/analysis-run-create-cli.md new file mode 100644 index 000000000..33966c07e --- /dev/null +++ b/docs/research/analysis-run-create-cli.md @@ -0,0 +1,64 @@ +# Analysis-run create CLI (doctoring) + +## Scope + +`tepp-analysis-runs create` is the operator-visible client of loopback +`POST /v1/analysis-runs`. HTTP method, path, and header semantics follow +current HTTP semantics (Fielding, Nottingham, & Reschke, 2022). Fail-closed +refusal of non-loopback hosts, unpublished consumers, review/Copilot/GitHub +credential flags, and scientific-authority promotion is repository contract +authority (ADR 0034; ADR 0018; ADR 0011), not an RFC inference rule. + +CLI stdout is metric-free `AnalysisRunAccepted` JSON with `run_state=accepted`. +The receipt carries `run_id`, `run_state`, and `idempotency_key` only. +Process exit 0 is not a completed temporal model, calibrated score, theta +estimate, uncertainty statement, or scientific claim. +`tepp.scientific_acceptance.v1` never appears. + +## Authority + +### External standards (HTTP only) + +Fielding, R., Nottingham, M., & Reschke, J. (Eds.). (2022). *HTTP semantics* +(RFC 9110). IETF. https://doi.org/10.17487/RFC9110 + +RFC 9110 §9.3.3 describes POST as a method for processing the enclosed +representation according to the resource's own semantics. TEPP maps that +processing onto a bounded, consumer-scoped create of a metric-free analysis +run. The RFC does not define psychometric acceptance, RMSE, or claim +promotion. + +### Internal contract evidence + +- `docs/adr/0034-analysis-run-create-cli.md` — this client +- `docs/adr/0018-consumer-scoped-analysis-run-ingress.md` — closed consumer + registry and metric-free `202 Accepted` +- `docs/adr/0032-analysis-run-collection-cli.md` — distinct `list` verb on the + same `tepp-analysis-runs` binary +- `docs/adr/0033-analysis-run-cancel-cli.md` — distinct `cancel` verb on the + same `tepp-analysis-runs` binary +- `docs/adr/0030-scientific-acceptance-loopback-cli.md` — distinct + `tepp-analysis-run` scientific-acceptance CLI on live #362 +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — CLI + success is not a scientific claim +- `docs/API_CONTRACT.md` — documented create resource +- `crates/tepp_api/tests/analysis_run_create_cli_contract.rs` — + fail-closed create CLI proofs + +## Verification + +- `tepp-analysis-runs create` of a valid request returns metric-free accepted + status without RMSE/bias/coverage/SE-gate keys or + `tepp.scientific_acceptance.v1`; +- replay of the same create is idempotent; +- another consumer cannot collide with the first consumer's idempotency key; +- non-loopback hosts, credential flags, collection pagination flags, cancel + `--run-id`, metric stdin, empty stdin, and unknown verbs fail closed; +- review, Copilot, GitHub, and bearer flags remain `AuthorizationDenied`. + +## Non-claims + +This slice does not implement GET-by-id, running/terminal POST, collection GET, +collection CLI list, cancel HTTP, cancel CLI, scientific-acceptance CLI verbs, +consumer-parity cancel, persistence, production TLS, Leiden consensus, or an +ADR 0014 scientific claim-promotion package.