diff --git a/CHANGELOG.d/analysis-run-collection-cli.md b/CHANGELOG.d/analysis-run-collection-cli.md new file mode 100644 index 000000000..abd6d8431 --- /dev/null +++ b/CHANGELOG.d/analysis-run-collection-cli.md @@ -0,0 +1 @@ +- `tepp_api` loopback `tepp-analysis-runs list` enumerates metric-free accepted, running, cancelled, and terminal runs (ADR 0032). Collection CLI stdout refuses RMSE/bias/coverage/SE-gate/scientific-acceptance keys. Not GET-by-id, not scientific-acceptance CLI, not persistence. diff --git a/CHANGELOG.md b/CHANGELOG.md index b55a4f9c4..3df3d7446 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,8 @@ All notable changes to TEPP are documented here. The format follows Keep a Chang ## [Unreleased] +- `tepp_api` publishes `tepp-analysis-runs list` as the loopback client of `GET /v1/analysis-runs` (ADR 0032). Operators enumerate accepted, running, cancelled, and terminal runs as metric-free collection rows without writing raw HTTP. CLI stdout refuses RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result` keys. Not GET-by-id, not the scientific-acceptance CLI, and not an ADR 0014 claim. + - `tepp_api` serves `GET /v1/analysis-runs` on the shared loopback listener (ADR 0031). Operators enumerate accepted, running, cancelled, and terminal runs as metric-free collection rows. Collection bodies refuse RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result` keys. GET-by-id and running/terminal POST remain later GAP-003A slices; this is not an ADR 0014 claim. - `tepp_api` serves `POST /v1/analysis-runs/{run_id}/cancel` on the shared loopback listener (ADR 0029). Accepted and running runs become metric-free `cancelled` status. Succeeded, failed, and unknown runs cannot be cancelled. Cancel bodies refuse RMSE/bias/coverage/SE-gate/scientific-acceptance keys. GET status and running/terminal POST remain later GAP-003A slices; this is not an ADR 0014 claim. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index b29d53702..ca980638c 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -15,6 +15,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Orchestrator live HTTP doctoring | [`docs/research/orchestrator-live-http.md`](docs/research/orchestrator-live-http.md) | | Analysis-run cancel HTTP doctoring | [`docs/research/analysis-run-cancel-http.md`](docs/research/analysis-run-cancel-http.md) | | 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) | | 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/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c433..b3c3d43f4 100644 --- a/crates/tepp_api/Cargo.toml +++ b/crates/tepp_api/Cargo.toml @@ -29,5 +29,11 @@ path = "src/bin/tepp_loopback.rs" test = false bench = false +[[bin]] +name = "tepp-analysis-runs" +path = "src/bin/tepp_analysis_runs.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/analysis_run_collection_cli.rs b/crates/tepp_api/src/analysis_run_collection_cli.rs new file mode 100644 index 000000000..4d02bd1ac --- /dev/null +++ b/crates/tepp_api/src/analysis_run_collection_cli.rs @@ -0,0 +1,890 @@ +//! Operator loopback CLI for analysis-run collection GET. +//! +//! GAP-003A eighth slice: operators run `tepp-analysis-runs list` to enumerate +//! accepted, running, cancelled, and terminal runs without writing raw HTTP or +//! guessing run identities. Stdout stays metric-free. `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), or the +//! collection GET listener (#368). Persistence remains GAP-003B. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; + +use crate::analysis_run_collection_http::{ + parse_collection_page_cursor, parse_collection_page_limit, refuse_metrics_on_collection_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::{ + AnalysisRunCollection, AnalysisRunLiveService, ApiError, NARUON_LIVE_IO_TIMEOUT, + NaruonLiveResponse, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; + +/// Supported operator verbs for the loopback collection CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AnalysisRunCollectionCliVerb { + /// `GET /v1/analysis-runs`. + List, +} + +impl AnalysisRunCollectionCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "list" => Ok(Self::List), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::List => "list", + } + } +} + +/// One operator CLI invocation against a loopback collection GET listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AnalysisRunCollectionCliInvocation { + /// CLI verb to execute. + pub verb: AnalysisRunCollectionCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published modular consumer (`naruon` or `lineageweave`). + pub consumer: String, + /// Optional exclusive page cursor (`tepp-page-cursor`). + pub page_cursor: Option, + /// Optional page limit (`tepp-page-limit`). + pub page_limit: Option, + /// JSON body. Collection GET requires empty. + pub body: String, +} + +impl AnalysisRunCollectionCliInvocation { + /// Parse argv plus stdin body into a validated loopback collection invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, an unpublished consumer, credential-shaped flags, + /// hostile pagination, or a nonempty body. + 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 = AnalysisRunCollectionCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile page flags. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`] for + /// empty, unpublished, or out-of-bounds 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); + } + if !self.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_collection_payload(&self.body)?; + parse_collection_page_limit(self.page_limit.as_deref())?; + parse_collection_page_cursor(self.page_cursor.as_deref())?; + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + consumer: Option, + page_cursor: Option, + page_limit: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + consumer: None, + page_cursor: None, + page_limit: 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, + "page-cursor" => &mut flags.page_cursor, + "page-limit" => &mut flags.page_limit, + _ => 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: AnalysisRunCollectionCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = AnalysisRunCollectionCliInvocation { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| crate::NARUON_CONSUMER_CODE.to_owned()), + page_cursor: flags.page_cursor, + page_limit: flags.page_limit, + 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 collection GET for a validated CLI invocation. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`AnalysisRunCollectionCliInvocation::validate`]. +pub fn compose_analysis_run_collection_cli_http( + invocation: &AnalysisRunCollectionCliInvocation, +) -> Result { + invocation.validate()?; + let mut request = format!( + "GET {NARUON_ANALYSIS_RUN_PATH} HTTP/1.1\r\nHost: {}\r\ncontent-type: application/json\r\ntepp-consumer: {}\r\ntepp-contract-version: 1\r\n", + invocation.host, invocation.consumer + ); + if let Some(cursor) = &invocation.page_cursor { + request.push_str("tepp-page-cursor: "); + request.push_str(cursor); + request.push_str("\r\n"); + } + if let Some(limit) = &invocation.page_limit { + request.push_str("tepp-page-limit: "); + request.push_str(limit); + request.push_str("\r\n"); + } + request.push_str("content-length: 0\r\n\r\n"); + Ok(request) +} + +/// Dispatch one collection CLI invocation against an in-process loopback service. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_analysis_run_collection_cli( + service: &mut AnalysisRunLiveService, + invocation: &AnalysisRunCollectionCliInvocation, +) -> Result { + let request = compose_analysis_run_collection_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one collection CLI invocation over loopback TCP against `tepp-loopback`. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_analysis_run_collection_cli( + invocation: &AnalysisRunCollectionCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_analysis_run_collection_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 collection pages never print scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a receipt carries metric keys +/// or `tepp.scientific_acceptance.v1`. +pub fn render_analysis_run_collection_cli_stdout( + invocation: &AnalysisRunCollectionCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance_schema(&response.body)?; + if !(200..300).contains(&response.status_code) { + refuse_metrics_on_collection_payload(&response.body)?; + return Ok(response.body.clone()); + } + let collection = AnalysisRunCollection::from_json(&response.body)?; + collection.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; collection GET refuses a body. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_analysis_run_collection_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::{ + AnalysisRunCollectionCliInvocation, AnalysisRunCollectionCliVerb, + SCIENTIFIC_ACCEPTANCE_SCHEMA, compose_analysis_run_collection_cli_http, + dispatch_analysis_run_collection_cli, execute_analysis_run_collection_cli, + parse_http_response, read_analysis_run_collection_cli_stdin, + render_analysis_run_collection_cli_stdout, static_reason, + }; + use crate::{ + ANALYSIS_RUN_COLLECTION_MAX_LIMIT, ANALYSIS_RUN_CONTRACT_VERSION, AnalysisRunAccepted, + AnalysisRunCollection, AnalysisRunLiveService, AnalysisRunRequest, ApiError, + LINEAGEWEAVE_CONSUMER_CODE, NARUON_ANALYSIS_RUN_PATH, 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-collection-tenant".into(), + snapshot_id: "cli-collection-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 create_http(run: &AnalysisRunRequest, consumer: &str, host: &str) -> String { + let body = run.to_json().expect("json"); + format!( + "POST {NARUON_ANALYSIS_RUN_PATH} HTTP/1.1\r\nHost: {host}\r\ncontent-type: application/json\r\ntepp-consumer: {consumer}\r\ntepp-contract-version: 1\r\nidempotency-key: {}\r\ncontent-length: {}\r\n\r\n{body}", + run.idempotency_key, + body.len() + ) + } + + fn list_invocation() -> AnalysisRunCollectionCliInvocation { + AnalysisRunCollectionCliInvocation::from_args(["list", "--host", "127.0.0.1:18081"], "") + .expect("list") + } + + #[test] + fn verbs_parse_and_reject_unknown_tokens() { + assert_eq!( + AnalysisRunCollectionCliVerb::parse("list").expect("list"), + AnalysisRunCollectionCliVerb::List + ); + assert_eq!(AnalysisRunCollectionCliVerb::List.as_str(), "list"); + assert_eq!( + AnalysisRunCollectionCliVerb::parse("LIST"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCollectionCliVerb::parse("create"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCollectionCliVerb::parse("status"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn from_args_refuses_empty_unknown_host_and_credential_flags() { + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(Vec::::new(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["nope"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["list"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["list", "--host"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["list", "--host", "8.8.8.8:80"], "") + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["list", "--host", "not-a-socket"], "") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--authorization", + "secret" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--pretty"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "extra"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--run-id", + "tepp-run-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081"], + "{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--host", "127.0.0.1:9"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--consumer", "other"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--page-limit", "0"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--page-limit", + &(ANALYSIS_RUN_COLLECTION_MAX_LIMIT + 1).to_string() + ], + "" + ) + .unwrap_err(), + ApiError::LimitExceeded + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--page-limit", "two"], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--page-cursor", ""], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn list_assembles_default_consumer_and_optional_page_headers() { + let list = list_invocation(); + assert_eq!(list.verb, AnalysisRunCollectionCliVerb::List); + assert_eq!(list.consumer, NARUON_CONSUMER_CODE); + assert!(list.page_cursor.is_none()); + assert!(list.page_limit.is_none()); + let http = compose_analysis_run_collection_cli_http(&list).expect("http"); + assert!(http.starts_with("GET /v1/analysis-runs HTTP/1.1")); + assert!(http.contains("tepp-consumer: naruon")); + assert!(!http.contains("idempotency-key")); + assert!(!http.contains("tepp-page-cursor")); + assert!(!http.contains("tepp-page-limit")); + + let paged = AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--page-cursor", + "tepp-run-1", + "--page-limit", + "8", + ], + "", + ) + .expect("paged"); + assert_eq!(paged.consumer, LINEAGEWEAVE_CONSUMER_CODE); + let paged_http = compose_analysis_run_collection_cli_http(&paged).expect("paged http"); + assert!(paged_http.contains("tepp-page-cursor: tepp-run-1")); + assert!(paged_http.contains("tepp-page-limit: 8")); + assert!(paged_http.contains("tepp-consumer: lineageweave")); + } + + #[test] + fn dispatch_lists_created_and_cancelled_runs_without_scientific_acceptance() { + let mut service = AnalysisRunLiveService::new(); + let first = request("cli-collection-idem-1"); + let created = service.handle_http_request(&create_http( + &first, + NARUON_CONSUMER_CODE, + "127.0.0.1:18081", + )); + assert_eq!(created.status_code, 202); + let accepted = AnalysisRunAccepted::from_json(&created.body).expect("accepted"); + + let empty_before_second = + dispatch_analysis_run_collection_cli(&mut service, &list_invocation()) + .expect("list one"); + assert_eq!(empty_before_second.status_code, 200); + let listed = + render_analysis_run_collection_cli_stdout(&list_invocation(), &empty_before_second) + .expect("stdout"); + assert!(!listed.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!listed.contains("rmse")); + assert!(!listed.contains("terminal_result")); + let page = AnalysisRunCollection::from_json(&listed).expect("page"); + assert_eq!(page.runs.len(), 1); + assert_eq!(page.runs[0].run_id, accepted.run_id); + assert_eq!( + page.runs[0].run_state, + crate::AnalysisRunStatusState::Accepted + ); + + let second = request("cli-collection-idem-2"); + let created_second = service.handle_http_request(&create_http( + &second, + NARUON_CONSUMER_CODE, + "127.0.0.1:18081", + )); + let accepted_second = + AnalysisRunAccepted::from_json(&created_second.body).expect("accepted second"); + let cancel = format!( + "POST {NARUON_ANALYSIS_RUN_PATH}/{}/cancel HTTP/1.1\r\nHost: 127.0.0.1:18081\r\ncontent-type: application/json\r\ntepp-consumer: {NARUON_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\nidempotency-key: {}\r\ncontent-length: 0\r\n\r\n", + accepted_second.run_id, second.idempotency_key + ); + let cancelled = service.handle_http_request(&cancel); + assert_eq!(cancelled.status_code, 200); + + let paged = AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081", "--page-limit", "1"], + "", + ) + .expect("limit 1"); + let first_page = + dispatch_analysis_run_collection_cli(&mut service, &paged).expect("page 1"); + let first_json = + render_analysis_run_collection_cli_stdout(&paged, &first_page).expect("page 1 stdout"); + let first_collection = AnalysisRunCollection::from_json(&first_json).expect("first page"); + assert_eq!(first_collection.runs.len(), 1); + let cursor = first_collection.next_cursor.expect("cursor"); + let second_page_invocation = AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--page-cursor", + cursor.as_str(), + "--page-limit", + "1", + ], + "", + ) + .expect("page 2"); + let second_page = + dispatch_analysis_run_collection_cli(&mut service, &second_page_invocation) + .expect("page 2"); + let second_json = + render_analysis_run_collection_cli_stdout(&second_page_invocation, &second_page) + .expect("page 2 stdout"); + let second_collection = + AnalysisRunCollection::from_json(&second_json).expect("second page"); + assert_eq!(second_collection.runs.len(), 1); + assert!( + second_collection + .runs + .iter() + .any(|row| row.run_state == crate::AnalysisRunStatusState::Cancelled) + || first_collection + .runs + .iter() + .any(|row| row.run_state == crate::AnalysisRunStatusState::Cancelled) + ); + + let other = AnalysisRunCollectionCliInvocation::from_args( + [ + "list", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + ], + "", + ) + .expect("other consumer"); + let isolated = + dispatch_analysis_run_collection_cli(&mut service, &other).expect("isolated"); + let isolated_stdout = + render_analysis_run_collection_cli_stdout(&other, &isolated).expect("isolated stdout"); + let isolated_page = AnalysisRunCollection::from_json(&isolated_stdout).expect("empty"); + assert!(isolated_page.runs.is_empty()); + } + + #[test] + fn render_refuses_metrics_scientific_acceptance_and_empty_bodies() { + let list = list_invocation(); + assert_eq!( + render_analysis_run_collection_cli_stdout( + &list, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_collection_cli_stdout( + &list, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"contract_version":1,"runs":[],"rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_collection_cli_stdout( + &list, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: format!( + r#"{{"contract_version":1,"runs":[],"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"# + ), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let error_stdout = render_analysis_run_collection_cli_stdout( + &list, + &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_collection_cli_stdout( + &list, + &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_collection_cli_stdout( + &list, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: r#"{"rmse":0.1}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let empty_ok = render_analysis_run_collection_cli_stdout( + &list, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"contract_version":1,"runs":[]}"#.into(), + }, + ) + .expect("empty"); + assert!(empty_ok.contains("\"runs\":[]")); + } + + #[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 = list_invocation(); + invocation.host = addr.to_string(); + let response = execute_analysis_run_collection_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 200); + handle.join().expect("join"); + + invocation.host = "127.0.0.1:1".into(); + assert_eq!( + execute_analysis_run_collection_cli(&invocation).unwrap_err(), + ApiError::InvalidWirePayload + ); + + let parsed = + parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").expect("parse"); + assert_eq!(parsed.status_code, 200); + assert_eq!( + parse_http_response(b"not-http").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.0 200 OK\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 200 OK\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 200 OK\r\ncontent-length: 9\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\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 200 OK\r\ncontent-length: x\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\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_collection_cli_stdin(true, std::io::empty()).expect("tty"); + assert!(empty.is_empty()); + let piped = + read_analysis_run_collection_cli_stdin(false, std::io::Cursor::new(b"leftover")) + .expect("piped"); + assert_eq!(piped, "leftover"); + let piped_empty = read_analysis_run_collection_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 new file mode 100644 index 000000000..87682715b --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_analysis_runs.rs @@ -0,0 +1,36 @@ +//! Operator CLI for loopback analysis-run collection GET. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + AnalysisRunCollectionCliInvocation, AnalysisRunCollectionCliVerb, ApiError, + execute_analysis_run_collection_cli, read_analysis_run_collection_cli_stdin, + render_analysis_run_collection_cli_stdout, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(_) => ExitCode::FAILURE, + } +} + +fn run() -> Result<(), ApiError> { + let args: Vec = std::env::args().skip(1).collect(); + let verb = + AnalysisRunCollectionCliVerb::parse(args.first().ok_or(ApiError::InvalidWirePayload)?)?; + let body = read_analysis_run_collection_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = AnalysisRunCollectionCliInvocation::from_args(&args, body)?; + if invocation.verb != verb { + return Err(ApiError::InvalidWirePayload); + } + let response = execute_analysis_run_collection_cli(&invocation)?; + let stdout = render_analysis_run_collection_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 2acf87810..ed5df35e7 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -14,6 +14,7 @@ mod analysis_result; mod analysis_run; mod analysis_run_cancel_http; +mod analysis_run_collection_cli; mod analysis_run_collection_http; mod analysis_run_live; mod analysis_run_status_http; @@ -81,6 +82,20 @@ pub use analysis_run_cancel_http::AnalysisRunCancelRequest; pub use analysis_run_cancel_http::naruon_analysis_run_cancel_exchange; /// Refuse scientific-metric keys on a cancel payload. pub use analysis_run_cancel_http::refuse_metrics_on_cancel_payload; +/// One validated collection CLI invocation. +pub use analysis_run_collection_cli::AnalysisRunCollectionCliInvocation; +/// Loopback collection CLI verb. +pub use analysis_run_collection_cli::AnalysisRunCollectionCliVerb; +/// Compose loopback collection GET bytes for a CLI invocation. +pub use analysis_run_collection_cli::compose_analysis_run_collection_cli_http; +/// Dispatch a collection CLI invocation against an in-process listener. +pub use analysis_run_collection_cli::dispatch_analysis_run_collection_cli; +/// Execute a collection CLI invocation over loopback TCP. +pub use analysis_run_collection_cli::execute_analysis_run_collection_cli; +/// Read leftover stdin for the collection CLI. +pub use analysis_run_collection_cli::read_analysis_run_collection_cli_stdin; +/// Render metric-free collection CLI stdout. +pub use analysis_run_collection_cli::render_analysis_run_collection_cli_stdout; /// Analysis-run collection contract version constant. pub use analysis_run_collection_http::ANALYSIS_RUN_COLLECTION_CONTRACT_VERSION; /// Maximum exclusive collection cursor length. diff --git a/crates/tepp_api/tests/analysis_run_collection_cli_contract.rs b/crates/tepp_api/tests/analysis_run_collection_cli_contract.rs new file mode 100644 index 000000000..25da1c764 --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_collection_cli_contract.rs @@ -0,0 +1,49 @@ +//! Contract tests for the analysis-run collection loopback CLI. + +use tepp_api::{ + ANALYSIS_RUN_COLLECTION_CONTRACT_VERSION, AnalysisRunCollection, + AnalysisRunCollectionCliInvocation, AnalysisRunCollectionCliVerb, ApiError, + NARUON_CONSUMER_CODE, compose_analysis_run_collection_cli_http, +}; + +#[test] +fn collection_cli_list_is_metric_free_get_without_credentials() { + assert_eq!( + AnalysisRunCollectionCliVerb::parse("list").expect("list"), + AnalysisRunCollectionCliVerb::List + ); + let invocation = + AnalysisRunCollectionCliInvocation::from_args(["list", "--host", "127.0.0.1:18081"], "") + .expect("invocation"); + assert_eq!(invocation.consumer, NARUON_CONSUMER_CODE); + let http = compose_analysis_run_collection_cli_http(&invocation).expect("http"); + assert!(http.starts_with("GET /v1/analysis-runs HTTP/1.1")); + assert!(!http.contains("authorization")); + assert!(!http.contains("idempotency-key")); + assert!(!http.contains("copilot")); + assert_eq!( + ANALYSIS_RUN_COLLECTION_CONTRACT_VERSION, + AnalysisRunCollection::new(Vec::new(), None) + .expect("empty") + .contract_version + ); +} + +#[test] +fn collection_cli_refuses_non_loopback_unknown_verbs_and_metric_bodies() { + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args(["list", "--host", "8.8.8.8:80"], ""), + Err(ApiError::AuthorizationDenied) + ); + assert_eq!( + AnalysisRunCollectionCliVerb::parse("create"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunCollectionCliInvocation::from_args( + ["list", "--host", "127.0.0.1:18081"], + r#"{"rmse":1.0}"# + ), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 88782097a..f9304407e 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -85,7 +85,9 @@ succeeded, failed, and unknown runs fail closed. `GET /v1/analysis-runs` on the loopback listener returns a metric-free collection of those states so operators do not guess run identities. Collection bodies never carry `tepp.scientific_acceptance.v1`. GET-by-id remains a later slice on this -protected-main lineage. +protected-main lineage. The loopback `tepp-analysis-runs list` CLI is the +operator-visible client for that collection GET; it does not duplicate the +scientific-acceptance `tepp-analysis-run` CLI. The stacked `analysis_engine` slice provides the first executable service-side path behind these DTOs. It consumes a bounded identity-free snapshot, excludes diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index b4509e6fd..5840d5fd6 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -55,6 +55,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | 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); request-bound terminal result active in PR #157; HTTP service remains accepted-target; the `orchestrator_live` loopback interpretation listener is on this PR | partial | | loopback analysis-run cancel HTTP | ADR 0029; API contract; RFC 9110 | `tepp_api` `POST /v1/analysis-runs/{run_id}/cancel` on `AnalysisRunLiveService`: metric-free cancelled status for accepted/running runs; succeeded/failed/unknown refuse; GET status remains a later slice | active-PR | | 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 | | 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/0032-analysis-run-collection-cli.md b/docs/adr/0032-analysis-run-collection-cli.md new file mode 100644 index 000000000..642605492 --- /dev/null +++ b/docs/adr/0032-analysis-run-collection-cli.md @@ -0,0 +1,70 @@ +# ADR 0032 — Analysis-run collection loopback CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0031 for the operator-visible collection client. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0031 remain on live GAP-003A engine-library, terminal-wire DTO, GET-by-id, lifecycle-POST, cancel, scientific-acceptance CLI, and collection-GET slices. + +## Context + +ADR 0031 serves `GET /v1/analysis-runs` on the loopback listener, but operators still had to write raw HTTP/1.1 to enumerate accepted, running, cancelled, or terminal runs. Duplicating the collection GET listener, GET-by-id, lifecycle POST, cancel HTTP, or the scientific-acceptance CLI (`tepp-analysis-run` on live #362) would collide with live PRs. + +## Decision + +`tepp_api` publishes a loopback-only `tepp-analysis-runs` CLI: + +- `list` GETs `/v1/analysis-runs` with optional `tepp-page-cursor` / `tepp-page-limit`. +- Stdout is the metric-free collection page: `run_id`, `run_state`, `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, GET-by-id flags, nonempty stdin, unknown verbs, and hostile pagination fail closed. +- Persistence, Compose recovery, and psychometric execution remain GAP-003B. + +## Alternatives considered + +1. **Keep raw HTTP as the only collection path** — rejected because operators still guess framing after ADR 0031. +2. **Add `list` onto the live scientific-acceptance CLI (#362)** — rejected because that head already owns create/running/terminal/status and is stacked on GET-by-id, not collection GET. +3. **Persist listed rows in PostgreSQL** — rejected as GAP-003B / live draft #287. +4. **Loopback collection CLI with the same metric-free gates as ADR 0031** — accepted. + +## Consequences + +- Operators can enumerate runs on the same loopback listener that created them without writing HTTP. +- Collection pages 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, nonempty bodies, unknown cursors, zero or non-integer limits, unpublished consumers, and credential flags fail closed. 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 a collection page is not measurement evidence and is not an ADR 0014 claim. + +## Compatibility and migration + +Collection GET, create POST, cancel 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 collection rows. + +## Verification + +Falsifiable evidence: + +- CLI list JSON has no RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result` keys; +- CLI list returns accepted and cancelled rows for one consumer and does not leak another consumer's runs; +- non-loopback host, credential flags, GET-by-id flags, nonempty 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 `tepp-analysis-runs` binary and client module; collection GET remains valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on the list, or treat CLI success as an ADR 0014 claim. + +## Related authority + +- ADR 0031 owns loopback collection GET. +- ADR 0030 owns the scientific-acceptance loopback CLI (live #362). +- ADR 0029 owns loopback cancel. +- ADR 0018 owns consumer-scoped ingress and metric-free `202 Accepted`. +- ADR 0014 owns scientific claim promotion. +- ADR 0011 owns standalone/modular HTTP boundaries. +- RFC 9110 owns GET semantics (Fielding, Nottingham, & Reschke, 2022). It does not authorize scientific claims. diff --git a/docs/adr/README.md b/docs/adr/README.md index b4111e69c..82318039c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -32,6 +32,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0025](0025-macos-native-rust-mlx-metal-boundary.md) | macOS-native Rust-owned MLX Metal execution | Accepted | accepted-target | Compose authenticates to a native host service; Linux never claims Metal, and actual backend/parity receipts fail closed. | | [0029](0029-analysis-run-cancel-http.md) | Loopback POST analysis-run cancel is metric-free cancelled status | Accepted | active-PR | Complements ADR 0018; does not supersede ADR 0014. ADR 0026–0028 live on other GAP-003A PRs. | | [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. | | [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. | @@ -144,6 +145,7 @@ Use the narrowest owning ADR when decisions overlap: - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. - **analysis-run cancel HTTP:** ADR 0029. - **analysis-run collection GET:** ADR 0031. +- **analysis-run collection CLI:** ADR 0032. ## Change and supersession rule diff --git a/docs/connectors/naruon-artifact-consumer.md b/docs/connectors/naruon-artifact-consumer.md index 5bdc328a1..0bdd58d9d 100644 --- a/docs/connectors/naruon-artifact-consumer.md +++ b/docs/connectors/naruon-artifact-consumer.md @@ -27,6 +27,7 @@ TEPP remains the scientific authority for estimation, recovery metrics, temporal | purpose-bound export auth | `tepp_api` `authorize_export` with `ModularServiceConsumer` | TEPP gate | | HTTP analysis-run create | `tepp_api` `naruon_analysis_run_exchange` → `POST /v1/analysis-runs` | naruon → TEPP | | 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 | | 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 | diff --git a/docs/research/analysis-run-collection-cli.md b/docs/research/analysis-run-collection-cli.md new file mode 100644 index 000000000..30b281dc5 --- /dev/null +++ b/docs/research/analysis-run-collection-cli.md @@ -0,0 +1,56 @@ +# Analysis-run collection CLI (doctoring) + +## Scope + +`tepp-analysis-runs list` is the operator-visible client of loopback +`GET /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 0032; ADR 0031; ADR 0018; ADR 0011), not an RFC inference rule. + +CLI stdout is metric-free `AnalysisRunCollection` JSON. Each row 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.1 describes GET as a method for retrieving the target resource's +current state. TEPP maps that retrieval onto a bounded, consumer-scoped +collection of metric-free run rows. The RFC does not define psychometric +acceptance, RMSE, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0032-analysis-run-collection-cli.md` — this client +- `docs/adr/0031-analysis-run-collection-get.md` — collection GET listener +- `docs/adr/0030-scientific-acceptance-loopback-cli.md` — distinct + `tepp-analysis-run` scientific-acceptance CLI on live #362 +- `docs/adr/0018-consumer-scoped-analysis-run-ingress.md` — closed consumer + registry and metric-free `202 Accepted` +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — CLI + success is not a scientific claim +- `docs/API_CONTRACT.md` — documented collection resource +- `crates/tepp_api/tests/analysis_run_collection_cli_contract.rs` — + fail-closed collection CLI proofs + +## Verification + +- `tepp-analysis-runs list` of accepted and cancelled runs returns metric-free + rows without RMSE/bias/coverage/SE-gate keys or `tepp.scientific_acceptance.v1`; +- another consumer cannot read the first consumer's rows; +- non-loopback hosts, credential flags, GET-by-id flags, nonempty 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, cancel CLI, +scientific-acceptance CLI verbs, persistence, production TLS, Leiden consensus, +or an ADR 0014 scientific claim-promotion package.