From a4409f96aa6123d12f26f8df59843aa92596a81e Mon Sep 17 00:00:00 2001 From: Seongho Bae <8172694+seonghobae@users.noreply.github.com> Date: Mon, 31 Aug 2026 19:40:40 +0000 Subject: [PATCH] feat(api): query cutoff-safe temporal context via loopback CLI LineageWeave operators can POST /v1/temporal-context through `tepp-temporal-context query` against tepp-loopback without writing raw HTTP. Metric-free association_not_causal JSON only. tepp.scientific_acceptance.v1 never appears. Does not infer causality. Not analysis-run CLIs. Not export CLI. Stacked on protected main. --- CHANGELOG.d/temporal-context-cli.md | 1 + DOCUMENTATION.md | 1 + crates/tepp_api/Cargo.toml | 6 + .../tepp_api/src/bin/tepp_temporal_context.rs | 37 ++ crates/tepp_api/src/lib.rs | 15 + crates/tepp_api/src/temporal_context_cli.rs | 561 ++++++++++++++++++ .../tests/temporal_context_cli_contract.rs | 65 ++ docs/API_CONTRACT.md | 5 +- docs/TRACEABILITY.md | 1 + docs/adr/0027-temporal-context-cli.md | 67 +++ docs/adr/README.md | 2 + docs/research/temporal-context-cli.md | 54 ++ 12 files changed, 814 insertions(+), 1 deletion(-) create mode 100644 CHANGELOG.d/temporal-context-cli.md create mode 100644 crates/tepp_api/src/bin/tepp_temporal_context.rs create mode 100644 crates/tepp_api/src/temporal_context_cli.rs create mode 100644 crates/tepp_api/tests/temporal_context_cli_contract.rs create mode 100644 docs/adr/0027-temporal-context-cli.md create mode 100644 docs/research/temporal-context-cli.md diff --git a/CHANGELOG.d/temporal-context-cli.md b/CHANGELOG.d/temporal-context-cli.md new file mode 100644 index 00000000..6af9d232 --- /dev/null +++ b/CHANGELOG.d/temporal-context-cli.md @@ -0,0 +1 @@ +- `tepp_api` loopback `tepp-temporal-context query` posts a cutoff-safe LineageWeave temporal-context request to `tepp-loopback` (`POST /v1/temporal-context`, ADR 0027). Metric-free `association_not_causal` JSON only. `tepp.scientific_acceptance.v1` never appears. Does not infer causality. Not analysis-run CLIs, not export CLI, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6fa4b968..68242a80 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -11,6 +11,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Architecture | [`ARCHITECTURE.md`](ARCHITECTURE.md) | | Modular/API integration contract | [`docs/API_CONTRACT.md`](docs/API_CONTRACT.md) | | naruon modular consumer contract | [`docs/connectors/naruon-artifact-consumer.md`](docs/connectors/naruon-artifact-consumer.md) | +| Temporal-context CLI doctoring | [`docs/research/temporal-context-cli.md`](docs/research/temporal-context-cli.md) | | contextual-orchestrator interpretation port | [`docs/connectors/contextual-orchestrator-interpretation-port.md`](docs/connectors/contextual-orchestrator-interpretation-port.md) | | Orchestrator live HTTP doctoring | [`docs/research/orchestrator-live-http.md`](docs/research/orchestrator-live-http.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | diff --git a/crates/tepp_api/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c43..a6825b85 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-temporal-context" +path = "src/bin/tepp_temporal_context.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/bin/tepp_temporal_context.rs b/crates/tepp_api/src/bin/tepp_temporal_context.rs new file mode 100644 index 00000000..2e4bdc75 --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_temporal_context.rs @@ -0,0 +1,37 @@ +//! Operator CLI for loopback `LineageWeave` temporal-context POST. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + ApiError, TemporalContextCliInvocation, execute_temporal_context_cli, + read_temporal_context_cli_stdin, render_temporal_context_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(); + match args.first().map(String::as_str) { + Some("query") => run_query(&args), + _ => Err(ApiError::InvalidWirePayload), + } +} + +fn run_query(args: &[String]) -> Result<(), ApiError> { + let body = read_temporal_context_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = TemporalContextCliInvocation::from_args(args, body)?; + let response = execute_temporal_context_cli(&invocation)?; + let stdout = render_temporal_context_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 876703eb..c3359971 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -31,6 +31,7 @@ mod project_history; mod project_journey; mod provider_payload; mod temporal_context; +mod temporal_context_cli; mod wire; /// Terminal analysis-result contract version constant. @@ -282,3 +283,17 @@ pub use temporal_context::TemporalContextTimelineEvent; pub use temporal_context::TemporalTransitionGapCandidate; /// Build a cutoff-safe, non-causal temporal context. pub use temporal_context::build_temporal_context; +/// One validated temporal-context CLI invocation. +pub use temporal_context_cli::TemporalContextCliInvocation; +/// Loopback temporal-context CLI verb. +pub use temporal_context_cli::TemporalContextCliVerb; +/// Compose loopback temporal-context POST bytes for a CLI invocation. +pub use temporal_context_cli::compose_temporal_context_cli_http; +/// Dispatch a temporal-context CLI invocation against an in-process listener. +pub use temporal_context_cli::dispatch_temporal_context_cli; +/// Execute a temporal-context CLI invocation over loopback TCP. +pub use temporal_context_cli::execute_temporal_context_cli; +/// Read leftover stdin for the temporal-context CLI. +pub use temporal_context_cli::read_temporal_context_cli_stdin; +/// Render temporal-context CLI stdout with metric-free gates. +pub use temporal_context_cli::render_temporal_context_cli_stdout; diff --git a/crates/tepp_api/src/temporal_context_cli.rs b/crates/tepp_api/src/temporal_context_cli.rs new file mode 100644 index 00000000..8063258a --- /dev/null +++ b/crates/tepp_api/src/temporal_context_cli.rs @@ -0,0 +1,561 @@ +//! Operator loopback CLI for `LineageWeave` temporal-context POST. +//! +//! Operator-visible client of `POST /v1/temporal-context` on +//! `AnalysisRunLiveService` / `tepp-loopback` (ADR 0002 / ADR 0011). Operators +//! run `tepp-temporal-context query` without writing raw HTTP. Bodies stay +//! cutoff-safe and metric-free. `tepp.scientific_acceptance.v1` never appears. +//! The CLI does not infer causality. This module does not duplicate +//! analysis-run CLIs, export CLI, GET-by-id, Leiden, or GAP-010 Figma/export. +//! Persistence remains GAP-003B. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; + +use crate::live_http::map_io_error; +use crate::naruon_http::header_is_credential; +use crate::wire::require_nonempty; +use crate::{ + AnalysisRunLiveService, ApiError, LINEAGEWEAVE_CONSUMER_CODE, NARUON_LIVE_IO_TIMEOUT, + NaruonLiveResponse, TEMPORAL_ASSOCIATION_CLAIM_BOUNDARY, TEMPORAL_CONTEXT_PATH, + TemporalContextRequest, TemporalContextResponse, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; +const FORBIDDEN_CONTEXT_KEYS: [&str; 12] = [ + "rmse", + "rmse_standard_error", + "mean_bias", + "bias_standard_error", + "interval_coverage", + "coverage_wilson_lower", + "coverage_wilson_upper", + "temporal_order_accuracy", + "se_gate_accepted", + "scientific_acceptance", + "causal_score", + "causality", +]; + +/// Supported operator verbs for the loopback temporal-context CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TemporalContextCliVerb { + /// `POST /v1/temporal-context`. + Query, +} + +impl TemporalContextCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "query" => Ok(Self::Query), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Query => "query", + } + } +} + +/// One operator CLI invocation against a loopback temporal-context listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TemporalContextCliInvocation { + /// CLI verb to execute. + pub verb: TemporalContextCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Validated cutoff-safe temporal-context request. + pub request: TemporalContextRequest, +} + +impl TemporalContextCliInvocation { + /// Parse argv plus stdin JSON into a validated loopback query invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing flags, a + /// non-loopback host, credential-shaped flags, unpublished consumers, + /// metric keys, or an invalid temporal-context 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 = TemporalContextCliVerb::parse(verb_token)?; + let host = parse_host(rest)?; + let body = body.into(); + refuse_scientific_acceptance(&body)?; + refuse_metrics(&body)?; + let request = TemporalContextRequest::from_json(&body)?; + let invocation = Self { + verb, + host, + request, + }; + invocation.validate()?; + Ok(invocation) + } + + /// Reject a non-loopback host or a non-`LineageWeave` consumer. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] when the consumer is not `LineageWeave`. + pub fn validate(&self) -> Result<(), ApiError> { + require_loopback_host(&self.host)?; + if self.request.consumer_code != LINEAGEWEAVE_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) + } +} + +fn parse_host(rest: &[String]) -> Result { + let mut host = 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); + } + if name != "host" { + return Err(ApiError::InvalidWirePayload); + } + if host.is_some() || index + 1 >= rest.len() { + return Err(ApiError::InvalidWirePayload); + } + let value = rest[index + 1].as_str(); + require_nonempty(value)?; + host = Some(value.to_owned()); + index += 2; + } + host.ok_or(ApiError::InvalidWirePayload) +} + +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 temporal-context POST for a validated CLI invocation. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`TemporalContextCliInvocation::validate`]. +pub fn compose_temporal_context_cli_http( + invocation: &TemporalContextCliInvocation, +) -> Result { + invocation.validate()?; + let body = invocation.request.to_json()?; + refuse_scientific_acceptance(&body)?; + refuse_metrics(&body)?; + Ok(format!( + "POST {TEMPORAL_CONTEXT_PATH} HTTP/1.1\r\nHost: {}\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: {}\r\n\r\n{body}", + invocation.host, + body.len() + )) +} + +/// Dispatch one temporal-context CLI invocation against an in-process listener. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_temporal_context_cli( + service: &mut AnalysisRunLiveService, + invocation: &TemporalContextCliInvocation, +) -> Result { + let request = compose_temporal_context_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one temporal-context CLI invocation over loopback TCP. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_temporal_context_cli( + invocation: &TemporalContextCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_temporal_context_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 temporal context never prints scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when the body is empty, carries +/// metric or causal-score keys, or is not a cutoff-safe association response. +pub fn render_temporal_context_cli_stdout( + invocation: &TemporalContextCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance(&response.body)?; + refuse_metrics(&response.body)?; + if (200..300).contains(&response.status_code) { + let parsed = TemporalContextResponse::from_json(&response.body)?; + if parsed.claim_boundary != TEMPORAL_ASSOCIATION_CLAIM_BOUNDARY { + return Err(ApiError::InvalidWirePayload); + } + } + Ok(response.body.clone()) +} + +fn refuse_scientific_acceptance(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +fn refuse_metrics(payload: &str) -> Result<(), ApiError> { + if payload.trim().is_empty() { + return Ok(()); + } + let value: serde_json::Value = + serde_json::from_str(payload).map_err(|_| ApiError::InvalidWirePayload)?; + let Some(object) = value.as_object() else { + return Err(ApiError::InvalidWirePayload); + }; + if FORBIDDEN_CONTEXT_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + 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; query requires JSON. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_temporal_context_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::{ + SCIENTIFIC_ACCEPTANCE_SCHEMA, TemporalContextCliInvocation, TemporalContextCliVerb, + compose_temporal_context_cli_http, dispatch_temporal_context_cli, + execute_temporal_context_cli, parse_http_response, read_temporal_context_cli_stdin, + render_temporal_context_cli_stdout, static_reason, + }; + use crate::{ + AnalysisRunLiveService, ApiError, LINEAGEWEAVE_CONSUMER_CODE, NaruonLiveResponse, + TEMPORAL_ASSOCIATION_CLAIM_BOUNDARY, TemporalContextEvent, TemporalContextRequest, + }; + + fn query_body() -> String { + TemporalContextRequest { + contract_version: 1, + consumer_code: LINEAGEWEAVE_CONSUMER_CODE.into(), + knowledge_cutoff: "2026-08-20T00:00:00Z".into(), + subject_post_id: None, + events: vec![TemporalContextEvent { + event_id: "event-1".into(), + source_post_id: "post-1".into(), + event_type_code: "order_awarded".into(), + event_label: "Order awarded".into(), + event_time: "2026-08-01T09:00:00Z".into(), + available_time: "2026-08-01T10:00:00Z".into(), + project_reference: None, + actor_references: vec!["actor-1".into()], + }], + } + .to_json() + .expect("json") + } + + fn query_args() -> [&'static str; 3] { + ["query", "--host", "127.0.0.1:18081"] + } + + #[test] + fn verbs_parse_and_reject_unknown_tokens() { + assert_eq!( + TemporalContextCliVerb::parse("query").expect("verb"), + TemporalContextCliVerb::Query + ); + assert_eq!(TemporalContextCliVerb::Query.as_str(), "query"); + assert_eq!( + TemporalContextCliVerb::parse("QUERY"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + TemporalContextCliVerb::parse("cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + TemporalContextCliVerb::parse("authorize"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn from_args_refuses_host_credentials_and_metrics() { + assert_eq!( + TemporalContextCliInvocation::from_args(Vec::::new(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextCliInvocation::from_args(["query"], query_body()).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextCliInvocation::from_args( + ["query", "--host", "8.8.8.8:80"], + query_body() + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + TemporalContextCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--authorization", + "secret" + ], + query_body() + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + TemporalContextCliInvocation::from_args(query_args(), r#"{"rmse":1.0}"#).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextCliInvocation::from_args(query_args(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn compose_posts_temporal_context_without_credentials_or_metrics() { + let invocation = + TemporalContextCliInvocation::from_args(query_args(), query_body()).expect("inv"); + let http = compose_temporal_context_cli_http(&invocation).expect("http"); + assert!(http.starts_with("POST /v1/temporal-context HTTP/1.1")); + assert!(http.contains("tepp-consumer: lineageweave")); + assert!(!http.contains("idempotency-key")); + assert!(!http.contains("authorization")); + assert!(!http.contains("/analysis-runs")); + assert!(!http.contains("/v1/exports")); + assert!(!http.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!http.contains("rmse")); + } + + #[test] + fn dispatch_returns_association_not_causal_without_scientific_acceptance() { + let mut service = AnalysisRunLiveService::new(); + let invocation = + TemporalContextCliInvocation::from_args(query_args(), query_body()).expect("inv"); + let got = dispatch_temporal_context_cli(&mut service, &invocation).expect("dispatch"); + assert_eq!(got.status_code, 200); + let stdout = render_temporal_context_cli_stdout(&invocation, &got).expect("stdout"); + assert!(stdout.contains(TEMPORAL_ASSOCIATION_CLAIM_BOUNDARY)); + assert!(stdout.contains("candidate_not_causal") || stdout.contains("timeline_events")); + assert!(!stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("causal_score")); + } + + #[test] + fn render_refuses_metrics_schema_and_empty_bodies() { + let invocation = + TemporalContextCliInvocation::from_args(query_args(), query_body()).expect("inv"); + assert_eq!( + render_temporal_context_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_temporal_context_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"claim_boundary":"association_not_causal","rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_temporal_context_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: format!(r#"{{"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"#), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[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 = + TemporalContextCliInvocation::from_args(query_args(), query_body()).expect("inv"); + invocation.host = addr.to_string(); + let response = execute_temporal_context_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_temporal_context_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!(static_reason(200).expect("200"), "OK"); + assert_eq!( + static_reason(500).unwrap_err(), + ApiError::InvalidWirePayload + ); + let empty = read_temporal_context_cli_stdin(true, std::io::empty()).expect("tty"); + assert!(empty.is_empty()); + let piped = + read_temporal_context_cli_stdin(false, std::io::Cursor::new(b"{}")).expect("piped"); + assert_eq!(piped, "{}"); + } +} diff --git a/crates/tepp_api/tests/temporal_context_cli_contract.rs b/crates/tepp_api/tests/temporal_context_cli_contract.rs new file mode 100644 index 00000000..4e380b5f --- /dev/null +++ b/crates/tepp_api/tests/temporal_context_cli_contract.rs @@ -0,0 +1,65 @@ +//! Contract tests for the `LineageWeave` temporal-context loopback CLI. + +use tepp_api::{ + ApiError, LINEAGEWEAVE_CONSUMER_CODE, TemporalContextCliInvocation, TemporalContextCliVerb, + TemporalContextEvent, TemporalContextRequest, compose_temporal_context_cli_http, +}; + +fn query_body() -> String { + TemporalContextRequest { + contract_version: 1, + consumer_code: LINEAGEWEAVE_CONSUMER_CODE.into(), + knowledge_cutoff: "2026-08-20T00:00:00Z".into(), + subject_post_id: None, + events: vec![TemporalContextEvent { + event_id: "event-1".into(), + source_post_id: "post-1".into(), + event_type_code: "order_awarded".into(), + event_label: "Order awarded".into(), + event_time: "2026-08-01T09:00:00Z".into(), + available_time: "2026-08-01T10:00:00Z".into(), + project_reference: None, + actor_references: vec!["actor-1".into()], + }], + } + .to_json() + .expect("json") +} + +#[test] +fn temporal_context_cli_is_metric_free_post_without_credentials() { + assert_eq!( + TemporalContextCliVerb::parse("query").expect("verb"), + TemporalContextCliVerb::Query + ); + let invocation = TemporalContextCliInvocation::from_args( + ["query", "--host", "127.0.0.1:18081"], + query_body(), + ) + .expect("invocation"); + let http = compose_temporal_context_cli_http(&invocation).expect("http"); + assert!(http.starts_with("POST /v1/temporal-context HTTP/1.1")); + assert!(http.contains("tepp-consumer: lineageweave")); + assert!(!http.contains("authorization")); + assert!(!http.contains("tepp.scientific_acceptance.v1")); + assert!(!http.contains("/analysis-runs")); +} + +#[test] +fn temporal_context_cli_refuses_non_loopback_unknown_verbs_and_metrics() { + assert_eq!( + TemporalContextCliInvocation::from_args(["query", "--host", "8.8.8.8:80"], query_body()), + Err(ApiError::AuthorizationDenied) + ); + assert_eq!( + TemporalContextCliVerb::parse("cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + TemporalContextCliInvocation::from_args( + ["query", "--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 b76b688e..216c3f99 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -89,7 +89,10 @@ not a substitute for approved topic or psychometric estimators. only events whose availability time is at or before `knowledge_cutoff`, orders them by event time and opaque event ID, and emits adjacent forward temporal associations plus `candidate_not_causal` transition gaps. It does not infer -causality, mutate TEPP state, or return a completed psychometric result. +causality, mutate TEPP state, or return a completed psychometric result. The +loopback `tepp-temporal-context query` CLI is the operator-visible client for +that POST; stdout stays metric-free with `claim_boundary` `association_not_causal`, +and `tepp.scientific_acceptance.v1` never appears. The typed status/read contract returns `accepted`, `running`, `succeeded`, or `failed`. Accepted and running statuses contain no measurement result. A diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 2b783c2a..cb0e8347 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -53,6 +53,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | PostgreSQL bitemporal/lineage persistence | ADR 0013; Architecture/ERD | `persistence_postgres` migration contracts, in-memory adapters, live SQL session/document SQL port, tenant RLS (`0002` + session GUC/role helpers), `DATABASE_URL` SQLx gate, optional session-affine `live-sqlx` `PgPool` driver, exact-head live PostgreSQL CI with isolation proof, append-only immutability triggers (`0004`), temporal interval ordering CHECKs (`0005`), typed membership assignment (`0006` implemented-main), event-relation/mention/instance SQL (#37–#39 implemented-main), source-artifact SQL (#40 implemented-main), audit-event SQL (#41 implemented-main), concurrent document-write stress (#43 implemented-main), backup/restore integrity revalidation (#44 implemented-main), `revision_order` later-revision system-time ordering implemented-main, entity/project target SQL on PR #131; remaining physical ERD constraints | partial | | known-truth temporal/event simulation manifests | PRD; TRD; Test Strategy | `tepp_simulation` on protected main; recovery metrics in `validation_core` | implemented-main | | 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 LineageWeave temporal-context CLI | ADR 0027; API contract; RFC 9110; ADR 0002/0011 | `tepp_api` `tepp-temporal-context query` CLI against `tepp-loopback` (`POST /v1/temporal-context`); metric-free `association_not_causal` JSON; `tepp.scientific_acceptance.v1` never appears; does not infer causality | 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/0027-temporal-context-cli.md b/docs/adr/0027-temporal-context-cli.md new file mode 100644 index 00000000..a34abf94 --- /dev/null +++ b/docs/adr/0027-temporal-context-cli.md @@ -0,0 +1,67 @@ +# ADR 0027 — LineageWeave temporal-context loopback CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0002 and ADR 0011 for the operator-visible temporal-context client. Does not supersede ADR 0014 claim-promotion authority. This ADR number is unique on protected main; other live PRs may reuse 0027 on unrelated GAP-003A stacks (GET-by-id status). + +## Context + +Protected main already serves `POST /v1/temporal-context` on `AnalysisRunLiveService` / `tepp-loopback`, but LineageWeave operators still had to write raw HTTP/1.1. Duplicating analysis-run CLIs (#362/#371/#378/#385/#392/#394/#395/#397/#400/#401/#403/#406), export CLI (#410), export retrieval GET (#411), GET-by-id, Leiden, Driver p.16, or GAP-010 Figma/export would collide with live PRs. + +## Decision + +`tepp_api` publishes a loopback-only `tepp-temporal-context query` verb: + +- `query` POSTs `/v1/temporal-context` to `tepp-loopback` with `--host`. Stdin is `TemporalContextRequest` JSON. Consumer is `lineageweave` only. +- No `idempotency-key` header. Temporal-context is a bounded read, not a durable analysis-run create. +- Stdout is the cutoff-safe `TemporalContextResponse`. `claim_boundary` remains `association_not_causal`. `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, and `causal_score` keys never appear. +- The CLI does not infer causality, mutate TEPP state, or return a completed psychometric result. +- Non-loopback hosts, credential-shaped flags, unknown verbs, empty stdin, unpublished consumers, and metric keys fail closed. +- This slice does not implement project-history CLI, export CLI, or analysis-run HTTP. + +## Alternatives considered + +1. **Keep raw HTTP as the only temporal-context path** — rejected because operators still guess framing after ADR 0011. +2. **Add `query` onto `tepp-analysis-runs`** — rejected because temporal-context is a LineageWeave read, not an analysis-run verb. +3. **Return scientific-acceptance on ordered events** — rejected because temporal-context bodies must stay metric-free. +4. **Loopback temporal-context CLI against `tepp-loopback`** — accepted. + +## Consequences + +- Operators can request a cutoff-safe temporal context without writing HTTP. +- Temporal-context stdout cannot be mistaken for a succeeded scientific-acceptance result or a causal score. +- CLI success is not release evidence and is not an ADR 0014 claim. + +## Failure and recovery + +Non-loopback hosts return authorization denied. Unknown verbs, empty stdin, credential flags, naruon consumer codes, and events unavailable at cutoff fail closed. The in-memory listener is not durable. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- The CLI remains loopback-only. Event identities stay opaque; free-text PII is not introduced. +- Process exit 0 on query is not measurement evidence and is not a causal claim. + +## Compatibility and migration + +`POST /v1/analysis-runs`, `POST /v1/exports`, `POST /v1/project-histories`, and `tepp-loopback` paths are unchanged. Project-history CLI remains a later slice. + +## Verification + +Falsifiable evidence: + +- CLI query of a cutoff-safe LineageWeave body returns `association_not_causal` with no RMSE/bias/coverage/SE-gate/`tepp.scientific_acceptance.v1`/`causal_score` keys; +- non-loopback host, credential flags, empty stdin, unknown verbs, and metric keys fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes `tepp-temporal-context`; `POST /v1/temporal-context` remains valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on temporal-context, infer causality, or treat CLI success as an ADR 0014 claim. + +## Related authority + +- ADR 0002 owns six-clock temporal eligibility. +- ADR 0011 owns standalone/modular HTTP boundaries. +- ADR 0014 owns scientific claim promotion. +- 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 1254c807..86d35d80 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -30,6 +30,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0022](0022-deterministic-analysis-run-execution.md) | Deterministic cutoff-safe analysis-run execution | Accepted | active-PR | Closes the first executable product path from accepted run to digest-bound terminal result without claiming estimator authority. | | [0024](0024-lineage-pair-criterion-and-project-journey-posterior.md) | Independent Event Lineage pair criterion and posterior Project Journey | Proposed | active-PR | Strict artifacts preserve criterion/event-time draws, branches, ties, and CPU/GPU receipts without claiming the scientific estimator is complete. | | [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. | +| [0027](0027-temporal-context-cli.md) | Loopback `tepp-temporal-context query` is LineageWeave POST /v1/temporal-context client | Accepted | active-PR | Complements ADR 0002/0011; does not supersede ADR 0014. Unique on protected main. Does not infer causality. | | [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. | @@ -140,6 +141,7 @@ Use the narrowest owning ADR when decisions overlap: - **accepted-run execution and terminal artifact production:** ADR 0022. - **independent lineage criterion and posterior Project Journey:** ADR 0023. - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. +- **LineageWeave temporal-context CLI:** ADR 0027. ## Change and supersession rule diff --git a/docs/research/temporal-context-cli.md b/docs/research/temporal-context-cli.md new file mode 100644 index 00000000..97c1ad72 --- /dev/null +++ b/docs/research/temporal-context-cli.md @@ -0,0 +1,54 @@ +# Temporal-context CLI (doctoring) + +## Scope + +`tepp-temporal-context query` is the operator-visible client of loopback +`POST /v1/temporal-context` on `AnalysisRunLiveService` / `tepp-loopback`. +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 0027; +ADR 0002; ADR 0011; ADR 0014), not an RFC inference rule. + +CLI stdout is the cutoff-safe `TemporalContextResponse`. +`claim_boundary` remains `association_not_causal`. +`tepp.scientific_acceptance.v1` never appears. Process exit 0 is not a +completed temporal model, calibrated score, theta estimate, uncertainty +statement, causal inference, or scientific claim. + +## 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. TEPP maps that processing onto a bounded, cutoff-safe +temporal-context read. The RFC does not define psychometric acceptance, RMSE, +causality, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0027-temporal-context-cli.md` — this client +- `docs/adr/0002-six-clock-temporal-semantics.md` — cutoff eligibility +- `docs/adr/0011-standalone-modular-msa-boundary.md` — modular HTTP boundary +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — CLI + success is not a scientific claim +- `crates/tepp_api/tests/temporal_context_cli_contract.rs` — fail-closed + temporal-context CLI proofs + +## Verification + +- `tepp-temporal-context query` of a cutoff-safe LineageWeave body returns + `association_not_causal` without RMSE/bias/coverage/SE-gate keys, + `causal_score`, or `tepp.scientific_acceptance.v1`; +- non-loopback hosts, credential flags, empty stdin, and unknown verbs fail + closed. + +## Non-claims + +This slice does not implement project-history CLI, export CLI, analysis-run +CLIs, GET-by-id, wait CLI, lookup CLI, persistence, production TLS, Leiden +consensus, GAP-010 Figma/export, causal inference, or an ADR 0014 scientific +claim-promotion package.