diff --git a/CHANGELOG.d/temporal-context-retrieval-cli.md b/CHANGELOG.d/temporal-context-retrieval-cli.md new file mode 100644 index 000000000..20c5285d0 --- /dev/null +++ b/CHANGELOG.d/temporal-context-retrieval-cli.md @@ -0,0 +1 @@ +- `tepp-temporal-context-get get` mints LineageWeave `GET /v1/temporal-context/{idempotency_key}` onto spawned `tepp-loopback` TCP (ADR 0084). Metric-free `inference_status=temporal_association_only` receipts. Event labels and actor lists never appear. Does not infer causality. Naruon refused. `NaruonLiveService` stays POST-only. Does not re-open collection GET or cancel lineages. Not GAP-010 Figma/export, not persistence. diff --git a/CHANGELOG.d/temporal-context-retrieval-get.md b/CHANGELOG.d/temporal-context-retrieval-get.md new file mode 100644 index 000000000..e6ed769af --- /dev/null +++ b/CHANGELOG.d/temporal-context-retrieval-get.md @@ -0,0 +1 @@ +- `GET /v1/temporal-context/{idempotency_key}` returns one accepted LineageWeave temporal-context identity on `tepp-loopback` (ADR 0083). Metric-free `inference_status=temporal_association_only`. Event labels and actor lists never appear. Does not infer causality. Naruon refused. `NaruonLiveService` stays POST-only. Does not re-open collection GET or cancel lineages. Not GAP-010 Figma/export, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6fa4b9683..83e5a72f8 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -13,6 +13,8 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | naruon modular consumer contract | [`docs/connectors/naruon-artifact-consumer.md`](docs/connectors/naruon-artifact-consumer.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) | +| Temporal-context GET-by-id doctoring | [`docs/research/temporal-context-retrieval-get.md`](docs/research/temporal-context-retrieval-get.md) | +| Temporal-context retrieval CLI doctoring | [`docs/research/temporal-context-retrieval-cli.md`](docs/research/temporal-context-retrieval-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..1824d6ba3 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-get" +path = "src/bin/tepp_temporal_context_get.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/analysis_run_live.rs b/crates/tepp_api/src/analysis_run_live.rs index 6768c6ef1..caa53ef0a 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -19,8 +19,10 @@ use crate::naruon_http::NARUON_ANALYSIS_RUN_PATH; use crate::{ AnalysisRunAccepted, AnalysisRunRequest, ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, ErrorEnvelope, NARUON_LIVE_IO_TIMEOUT, NaruonLiveResponse, PROJECT_HISTORY_PATH, - ProjectHistoryProjection, ProjectHistoryRequest, TEMPORAL_CONTEXT_PATH, TemporalContextRequest, + ProjectHistoryProjection, ProjectHistoryRequest, TEMPORAL_CONTEXT_PATH, + TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS, TemporalContextRequest, TemporalContextRetrieved, build_temporal_context, project_history_projection, requests_are_idempotent_matches, + temporal_context_retrieval_path_id, }; const MAX_LIVE_REQUEST_BODY_BYTES: usize = DEFAULT_PROJECT_HISTORY_BYTE_LIMIT; @@ -41,6 +43,7 @@ pub struct AnalysisRunLiveService { next_request_serial: u64, accepted_runs: HashMap, accepted_project_histories: HashMap, + accepted_temporal_contexts: HashMap, } impl Default for AnalysisRunLiveService { @@ -60,6 +63,7 @@ impl AnalysisRunLiveService { next_request_serial: 1, accepted_runs: HashMap::new(), accepted_project_histories: HashMap::new(), + accepted_temporal_contexts: HashMap::new(), } } @@ -143,6 +147,10 @@ impl AnalysisRunLiveService { let (header_block, body) = split_request_with_limit(request, MAX_LIVE_REQUEST_BODY_BYTES)?; let mut lines = header_block.split("\r\n"); let (method, path) = parse_request_line(lines.next().unwrap_or(""))?; + let headers = parse_headers(&mut lines)?; + if method == "GET" { + return self.get_temporal_context(path, &headers, body); + } if method != "POST" || (path != NARUON_ANALYSIS_RUN_PATH && path != TEMPORAL_CONTEXT_PATH @@ -150,19 +158,13 @@ impl AnalysisRunLiveService { { return Err(ApiError::InvalidWirePayload); } - let headers = parse_headers(&mut lines)?; let consumer = require_headers( &headers, self.bound_addr, path == NARUON_ANALYSIS_RUN_PATH || path == PROJECT_HISTORY_PATH, )?; if path == TEMPORAL_CONTEXT_PATH { - if consumer != LINEAGEWEAVE_CONSUMER_CODE { - return Err(ApiError::InvalidWirePayload); - } - let context_request = TemporalContextRequest::from_json(body)?; - let response = build_temporal_context(&context_request)?; - return Ok(json_response(200, "OK", response.to_json()?)); + return self.accept_temporal_context(consumer, &headers, body); } if path == PROJECT_HISTORY_PATH { return self.accept_project_history(consumer, &headers, body); @@ -170,6 +172,60 @@ impl AnalysisRunLiveService { self.accept_analysis_run(consumer, &headers, body) } + fn accept_temporal_context( + &mut self, + consumer: &str, + headers: &HashMap, + body: &str, + ) -> Result { + if consumer != LINEAGEWEAVE_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + let context_request = TemporalContextRequest::from_json(body)?; + if let Some(idempotency_key) = headers.get("idempotency-key") { + let item = TemporalContextRetrieved::new( + idempotency_key.clone(), + context_request.knowledge_cutoff.clone(), + TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS, + )?; + let replay_key = format!("{consumer}\u{1f}{idempotency_key}"); + if let Some(stored) = self.accepted_temporal_contexts.get(&replay_key) { + if stored.knowledge_cutoff != item.knowledge_cutoff { + return Err(ApiError::InvalidWirePayload); + } + } else { + self.accepted_temporal_contexts.insert(replay_key, item); + } + } + let response = build_temporal_context(&context_request)?; + Ok(json_response(200, "OK", response.to_json()?)) + } + + fn get_temporal_context( + &self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + if !body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + if headers.contains_key("idempotency-key") { + return Err(ApiError::InvalidWirePayload); + } + let idempotency_key = temporal_context_retrieval_path_id(path)?; + let consumer = require_headers(headers, self.bound_addr, false)?; + if consumer != LINEAGEWEAVE_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + let replay_key = format!("{consumer}\u{1f}{idempotency_key}"); + let stored = self + .accepted_temporal_contexts + .get(&replay_key) + .ok_or(ApiError::InvalidWirePayload)?; + Ok(json_response(200, "OK", stored.to_json()?)) + } + fn accept_analysis_run( &mut self, consumer: &str, @@ -320,6 +376,7 @@ mod tests { DEFAULT_ANALYSIS_RUN_BYTE_LIMIT, ErrorEnvelope, LINEAGEWEAVE_CONSUMER_CODE, NARUON_ANALYSIS_RUN_PATH, NARUON_CONSUMER_CODE, NARUON_LIVE_HEADER_BYTE_LIMIT, NARUON_LIVE_HEADER_COUNT_LIMIT, NARUON_LIVE_IO_TIMEOUT, TEMPORAL_CONTEXT_PATH, + TemporalContextRetrieved, }; fn sample_run() -> AnalysisRunRequest { @@ -734,6 +791,58 @@ mod tests { assert_eq!(replay.body, accepted.body); } + #[test] + fn temporal_context_get_by_id_is_metric_free_and_fail_closed() { + let temporal_body = r#"{"contract_version":1,"consumer_code":"lineageweave","knowledge_cutoff":"2026-08-20T00:00:00Z","subject_post_id":null,"events":[{"event_id":"event-1","source_post_id":"post-1","event_type_code":"order_awarded","event_label":"Order awarded","event_time":"2026-08-01T09:00:00Z","available_time":"2026-08-01T10:00:00Z","project_reference":null,"actor_references":["actor-1"]}]}"#; + let mut service = AnalysisRunLiveService::new(); + let posted = format!( + "POST {TEMPORAL_CONTEXT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\nidempotency-key: idem-a\r\ncontent-length: {}\r\n\r\n{temporal_body}", + temporal_body.len() + ); + assert_eq!(service.handle_http_request(&posted).status_code, 200); + let got = service.handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH}/idem-a HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ), + ); + assert_eq!(got.status_code, 200, "{}", got.body); + assert!(!got.body.contains("event_label")); + assert!(!got.body.contains("rmse")); + let row = TemporalContextRetrieved::from_json(&got.body).expect("row"); + assert_eq!(row.idempotency_key, "idem-a"); + assert_eq!(row.inference_status, "temporal_association_only"); + assert_eq!( + service + .handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ) + ) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH}/idem-a HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {NARUON_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ) + ) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH}/missing HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ) + ) + .status_code, + 400 + ); + } + #[test] fn parser_helpers_cover_framing_header_and_limit_edges() { assert_eq!( diff --git a/crates/tepp_api/src/bin/tepp_temporal_context_get.rs b/crates/tepp_api/src/bin/tepp_temporal_context_get.rs new file mode 100644 index 000000000..75b701fcf --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_temporal_context_get.rs @@ -0,0 +1,30 @@ +//! Operator CLI for loopback `LineageWeave` temporal-context GET-by-id. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + execute_temporal_context_retrieval_cli, read_temporal_context_retrieval_cli_stdin, + render_temporal_context_retrieval_cli_stdout, ApiError, TemporalContextRetrievalCliInvocation, +}; + +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 body = read_temporal_context_retrieval_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = TemporalContextRetrievalCliInvocation::from_args(&args, body)?; + let response = execute_temporal_context_retrieval_cli(&invocation)?; + let stdout = render_temporal_context_retrieval_cli_stdout(&invocation, &response)?; + println!("{stdout}"); + if response.status_code == 200 { + Ok(()) + } else { + Err(ApiError::InvalidWirePayload) + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 876703ebc..3c3c760c2 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -31,6 +31,8 @@ mod project_history; mod project_journey; mod provider_payload; mod temporal_context; +mod temporal_context_retrieval_cli; +mod temporal_context_retrieval_http; mod wire; /// Terminal analysis-result contract version constant. @@ -282,3 +284,35 @@ 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; +/// Maximum opaque idempotency-key length on the retrieval path. +pub use temporal_context_retrieval_http::TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN; +/// Supported temporal-context retrieval contract version. +pub use temporal_context_retrieval_http::TEMPORAL_CONTEXT_RETRIEVAL_CONTRACT_VERSION; +/// Fixed non-causal claim boundary echoed on every retrieval. +pub use temporal_context_retrieval_http::TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS; +/// One metric-free identity projection for an accepted temporal-context POST. +pub use temporal_context_retrieval_http::TemporalContextRetrieved; +/// Build a provider-owned `GET` temporal-context retrieval exchange. +pub use temporal_context_retrieval_http::lineageweave_temporal_context_retrieval_exchange; +/// Refuse retrieval JSON that already carries scientific-metric or evidence keys. +pub use temporal_context_retrieval_http::refuse_metrics_on_temporal_context_retrieval_payload; +/// Extract the opaque idempotency key from `GET /v1/temporal-context/{key}`. +pub use temporal_context_retrieval_http::temporal_context_retrieval_path_id; +/// Refuse an empty, oversized, slash, NUL, or control-bearing identity. +pub use temporal_context_retrieval_http::validate_temporal_context_registry_identity; +/// Supported operator verbs for the loopback temporal-context retrieval CLI. +pub use temporal_context_retrieval_cli::TemporalContextRetrievalCliVerb; +/// One operator CLI invocation against a loopback GET-by-id listener. +pub use temporal_context_retrieval_cli::TemporalContextRetrievalCliInvocation; +/// Compose one HTTP/1.1 retrieval GET from the typed `LineageWeave` exchange. +pub use temporal_context_retrieval_cli::compose_temporal_context_retrieval_cli_http; +/// Dispatch one retrieval CLI invocation against an in-process listener. +pub use temporal_context_retrieval_cli::dispatch_temporal_context_retrieval_cli; +/// Execute one retrieval CLI invocation over loopback TCP. +pub use temporal_context_retrieval_cli::execute_temporal_context_retrieval_cli; +/// Render a typed retrieval GET exchange as HTTP/1.1 for a loopback listener. +pub use temporal_context_retrieval_cli::loopback_http1_from_temporal_context_retrieval_exchange; +/// Read stdin leftover bytes on a non-terminal; retrieval GET admits empty. +pub use temporal_context_retrieval_cli::read_temporal_context_retrieval_cli_stdin; +/// Filter CLI stdout so retrieval never prints scientific acceptance. +pub use temporal_context_retrieval_cli::render_temporal_context_retrieval_cli_stdout; diff --git a/crates/tepp_api/src/temporal_context_retrieval_cli.rs b/crates/tepp_api/src/temporal_context_retrieval_cli.rs new file mode 100644 index 000000000..514c720c2 --- /dev/null +++ b/crates/tepp_api/src/temporal_context_retrieval_cli.rs @@ -0,0 +1,672 @@ +//! Operator loopback CLI for `LineageWeave` temporal-context GET-by-id. +//! +//! GAP-003A unique slice: operators run `tepp-temporal-context-get get` to mint +//! `lineageweave_temporal_context_retrieval_exchange` onto spawned +//! `tepp-loopback` TCP. Stdout is one metric-free +//! `temporal_association_only` identity. `tepp.scientific_acceptance.v1` +//! never appears. Event labels and actor lists stay off stdout. The CLI does +//! not infer causality. Naruon is refused on this `LineageWeave`-owned +//! adapter. `NaruonLiveService` stays POST-only. Dedicated binary so it does +//! not collide with `tepp-temporal-context` (#414). This module does not +//! duplicate GET-by-id HTTP (#451), temporal-context CLI (#414), collection +//! GET/CLI (closed #449/#450), project-history retrieval CLI (#431), cancel +//! lineages, Leiden, or GAP-010 Figma/export. Persistence remains GAP-003B. + +use std::collections::HashSet; +use std::fmt::Write as _; +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::temporal_context_retrieval_http::validate_temporal_context_registry_identity; +use crate::wire::require_nonempty; +use crate::{ + lineageweave_temporal_context_retrieval_exchange, + refuse_metrics_on_temporal_context_retrieval_payload, temporal_context_retrieval_path_id, + AnalysisRunLiveService, ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, + LINEAGEWEAVE_CONSUMER_CODE, NARUON_LIVE_HEADER_BYTE_LIMIT, NARUON_LIVE_HEADER_COUNT_LIMIT, + NARUON_LIVE_IO_TIMEOUT, NaruonHttpExchange, NaruonLiveResponse, TemporalContextRetrieved, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; +const MAXIMUM_HTTP_RESPONSE_BYTES: usize = + NARUON_LIVE_HEADER_BYTE_LIMIT + 4 + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT; + +/// Supported operator verbs for the loopback temporal-context retrieval CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TemporalContextRetrievalCliVerb { + /// `GET /v1/temporal-context/{idempotency_key}`. + Get, +} + +impl TemporalContextRetrievalCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "get" => Ok(Self::Get), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Get => "get", + } + } +} + +/// One operator CLI invocation against a loopback GET-by-id listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TemporalContextRetrievalCliInvocation { + /// CLI verb to execute. + pub verb: TemporalContextRetrievalCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published HTTPS origin used to mint the typed retrieval exchange. + pub origin: String, + /// Published modular consumer. Retrieval GET admits `lineageweave` only. + pub consumer: String, + /// Opaque idempotency key that minted the stored identity. + pub idempotency_key: String, + /// JSON body. Retrieval GET requires empty. + pub body: String, +} + +impl TemporalContextRetrievalCliInvocation { + /// Parse argv plus stdin body into a validated loopback retrieval invocation. + /// + /// Empty stdin is admitted. Nonempty leftover stdin fails closed. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, a non-`https` origin, an unpublished or naruon + /// consumer, credential-shaped flags, a hostile identity, 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 = TemporalContextRetrievalCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile GET body. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`] for + /// empty, unpublished, naruon, nonempty-body, or hostile identities. + pub fn validate(&self) -> Result<(), ApiError> { + require_loopback_host(&self.host)?; + require_nonempty(&self.origin)?; + if !self.origin.starts_with("https://") { + return Err(ApiError::InvalidWirePayload); + } + require_nonempty(&self.consumer)?; + if self.consumer != LINEAGEWEAVE_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + validate_temporal_context_registry_identity(&self.idempotency_key)?; + if !self.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_temporal_context_retrieval_payload(&self.body)?; + refuse_event_pii(&self.body)?; + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + origin: Option, + consumer: Option, + idempotency_key: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + origin: 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, + "origin" => &mut flags.origin, + "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: TemporalContextRetrievalCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = TemporalContextRetrievalCliInvocation { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + origin: flags.origin.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| LINEAGEWEAVE_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) + } +} + +/// Render a typed retrieval GET exchange as HTTP/1.1 for a loopback listener. +/// +/// # Errors +/// +/// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host or a +/// credential-bearing header, and [`ApiError::InvalidWirePayload`] when the +/// exchange is not a GET `/v1/temporal-context/{idempotency_key}` with an +/// empty body. +pub fn loopback_http1_from_temporal_context_retrieval_exchange( + exchange: &NaruonHttpExchange, + loopback_host: &str, +) -> Result { + let _addr = require_loopback_host(loopback_host)?; + let host = loopback_host.trim(); + if exchange.method != "GET" { + return Err(ApiError::InvalidWirePayload); + } + if !exchange.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + let rest = exchange + .target_url + .strip_prefix("https://") + .ok_or(ApiError::InvalidWirePayload)?; + let path = rest + .find('/') + .map(|index| &rest[index..]) + .ok_or(ApiError::InvalidWirePayload)?; + let _idempotency_key = temporal_context_retrieval_path_id(path)?; + let mut seen = HashSet::with_capacity(exchange.headers.len()); + let mut has_content_type = false; + let mut has_consumer = false; + let mut has_contract = false; + for (name, value) in &exchange.headers { + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + if name.eq_ignore_ascii_case("idempotency-key") { + return Err(ApiError::InvalidWirePayload); + } + if !valid_http_field_name(name) + || value.chars().any(char::is_control) + || !seen.insert(name.to_ascii_lowercase()) + { + return Err(ApiError::InvalidWirePayload); + } + let valid = match name.to_ascii_lowercase().as_str() { + "content-type" => { + has_content_type = true; + value == "application/json" + } + "tepp-consumer" => { + has_consumer = true; + value == LINEAGEWEAVE_CONSUMER_CODE + } + "tepp-contract-version" => { + has_contract = true; + value == "1" + } + _ => false, + }; + if !valid { + return Err(ApiError::InvalidWirePayload); + } + } + if !has_content_type || !has_consumer || !has_contract { + return Err(ApiError::InvalidWirePayload); + } + let mut request = String::new(); + write!( + request, + "{} {path} HTTP/1.1\r\nHost: {host}\r\n", + exchange.method + ) + .map_err(|_| ApiError::InvalidWirePayload)?; + for (name, value) in &exchange.headers { + write!(request, "{name}: {value}\r\n").map_err(|_| ApiError::InvalidWirePayload)?; + } + write!(request, "content-length: 0\r\n\r\n").map_err(|_| ApiError::InvalidWirePayload)?; + Ok(request) +} + +/// Compose one HTTP/1.1 retrieval GET from the typed `LineageWeave` exchange. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`TemporalContextRetrievalCliInvocation::validate`]. +pub fn compose_temporal_context_retrieval_cli_http( + invocation: &TemporalContextRetrievalCliInvocation, +) -> Result { + invocation.validate()?; + let exchange = lineageweave_temporal_context_retrieval_exchange( + &invocation.origin, + &invocation.idempotency_key, + )?; + loopback_http1_from_temporal_context_retrieval_exchange(&exchange, &invocation.host) +} + +/// Dispatch one retrieval CLI invocation against an in-process listener. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_temporal_context_retrieval_cli( + service: &mut AnalysisRunLiveService, + invocation: &TemporalContextRetrievalCliInvocation, +) -> Result { + let request = compose_temporal_context_retrieval_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one retrieval CLI invocation over loopback TCP. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_temporal_context_retrieval_cli( + invocation: &TemporalContextRetrievalCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_temporal_context_retrieval_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 bytes = read_bounded(&mut stream, MAXIMUM_HTTP_RESPONSE_BYTES)?; + parse_http_response(&bytes) +} + +/// Filter CLI stdout so retrieval never prints scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a receipt carries metric keys, +/// event labels, actor lists, or `tepp.scientific_acceptance.v1`. +pub fn render_temporal_context_retrieval_cli_stdout( + invocation: &TemporalContextRetrievalCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance(&response.body)?; + refuse_metrics_on_temporal_context_retrieval_payload(&response.body)?; + refuse_event_pii(&response.body)?; + if response.status_code != 200 { + return Err(ApiError::InvalidWirePayload); + } + let retrieved = TemporalContextRetrieved::from_json(&response.body)?; + if retrieved.idempotency_key != invocation.idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + retrieved.to_json() +} + +fn refuse_scientific_acceptance(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +fn refuse_event_pii(body: &str) -> Result<(), ApiError> { + if body.contains("event_label") + || body.contains("actor_references") + || body.contains("timeline_events") + || body.contains("evidence_text") + { + 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)?; + if header_block.len() > NARUON_LIVE_HEADER_BYTE_LIMIT { + return Err(ApiError::LimitExceeded); + } + let mut lines = header_block.split("\r\n"); + let status_line = lines.next().ok_or(ApiError::InvalidWirePayload)?; + let (version, status) = status_line + .split_once(' ') + .ok_or(ApiError::InvalidWirePayload)?; + if version != "HTTP/1.1" { + return Err(ApiError::InvalidWirePayload); + } + let (code, reason) = status.split_once(' ').ok_or(ApiError::InvalidWirePayload)?; + let code = code + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?; + let reason_phrase = match code { + 200 => "OK", + 202 => "Accepted", + 400 => "Bad Request", + 403 => "Forbidden", + 413 => "Payload Too Large", + 422 => "Unprocessable Entity", + _ => return Err(ApiError::InvalidWirePayload), + }; + if reason != reason_phrase { + return Err(ApiError::InvalidWirePayload); + } + let mut content_length = None; + let mut seen = HashSet::new(); + for (index, line) in lines.enumerate() { + if index >= NARUON_LIVE_HEADER_COUNT_LIMIT { + return Err(ApiError::LimitExceeded); + } + let (name, value) = line.split_once(':').ok_or(ApiError::InvalidWirePayload)?; + if !valid_http_field_name(name) + || value + .chars() + .any(|character| character.is_control() && character != '\t') + || !seen.insert(name.to_ascii_lowercase()) + || name.eq_ignore_ascii_case("transfer-encoding") + { + return Err(ApiError::InvalidWirePayload); + } + if name.eq_ignore_ascii_case("content-length") { + content_length = Some( + value + .trim() + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?, + ); + } + } + let declared = content_length.ok_or(ApiError::InvalidWirePayload)?; + if declared > DEFAULT_PROJECT_HISTORY_BYTE_LIMIT { + return Err(ApiError::LimitExceeded); + } + if declared != body.len() { + return Err(ApiError::InvalidWirePayload); + } + Ok(NaruonLiveResponse { + status_code: code, + reason_phrase, + body: body.to_owned(), + }) +} + +/// Read stdin leftover bytes on a non-terminal; retrieval GET admits empty. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read and +/// [`ApiError::LimitExceeded`] when leftover stdin exceeds the wire limit. +pub fn read_temporal_context_retrieval_cli_stdin( + stdin_is_terminal: bool, + mut stdin: impl Read, +) -> Result { + if stdin_is_terminal { + Ok(String::new()) + } else { + let bytes = read_bounded(&mut stdin, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT)?; + String::from_utf8(bytes).map_err(|_| ApiError::InvalidWirePayload) + } +} + +fn read_bounded(reader: &mut impl Read, maximum_bytes: usize) -> Result, ApiError> { + let mut bytes = Vec::new(); + reader + .take((maximum_bytes + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|error| map_io_error(&error))?; + if bytes.len() > maximum_bytes { + return Err(ApiError::LimitExceeded); + } + Ok(bytes) +} + +fn valid_http_field_name(name: &str) -> bool { + !name.is_empty() + && name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) + }) +} + +#[cfg(test)] +mod tests { + use super::{ + compose_temporal_context_retrieval_cli_http, + loopback_http1_from_temporal_context_retrieval_exchange, + read_temporal_context_retrieval_cli_stdin, TemporalContextRetrievalCliInvocation, + TemporalContextRetrievalCliVerb, + }; + use crate::{ + lineageweave_temporal_context_retrieval_exchange, ApiError, LINEAGEWEAVE_CONSUMER_CODE, + NaruonHttpExchange, + }; + + const ORIGIN: &str = "https://tepp.example.test"; + + fn get_args() -> [&'static str; 9] { + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + "idem-a", + ] + } + + #[test] + fn from_args_mints_get_and_refuses_fail_closed_hosts() { + assert_eq!( + TemporalContextRetrievalCliVerb::parse("get").expect("get"), + TemporalContextRetrievalCliVerb::Get + ); + assert_eq!(TemporalContextRetrievalCliVerb::Get.as_str(), "get"); + assert_eq!( + TemporalContextRetrievalCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + let get = TemporalContextRetrievalCliInvocation::from_args(get_args(), "").expect("get"); + let http = compose_temporal_context_retrieval_cli_http(&get).expect("http"); + assert!(http.starts_with("GET /v1/temporal-context/idem-a HTTP/1.1")); + assert!(http.contains("tepp-consumer: lineageweave")); + assert!(http.contains("content-length: 0")); + assert!(!http.contains("idempotency-key:")); + assert!(!http.contains("authorization")); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "8.8.8.8:80", + "--origin", + ORIGIN, + "--idempotency-key", + "idem-a" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "localhost:18081", + "--origin", + ORIGIN, + "--idempotency-key", + "idem-a" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--authorization", + "secret", + "--idempotency-key", + "idem-a" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + } + + #[test] + fn from_args_refuses_naruon_body_slash_and_non_get() { + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + "naruon", + "--idempotency-key", + "idem-a" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args(get_args(), "{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--idempotency-key", + "a/b" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert!( + read_temporal_context_retrieval_cli_stdin(true, std::io::empty()) + .expect("tty") + .is_empty() + ); + let exchange = + lineageweave_temporal_context_retrieval_exchange(ORIGIN, "idem-a").expect("ex"); + let posted = NaruonHttpExchange { + method: "POST", + target_url: exchange.target_url, + headers: exchange.headers, + body: exchange.body, + }; + assert_eq!( + loopback_http1_from_temporal_context_retrieval_exchange(&posted, "127.0.0.1:18081") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } +} diff --git a/crates/tepp_api/src/temporal_context_retrieval_http.rs b/crates/tepp_api/src/temporal_context_retrieval_http.rs new file mode 100644 index 000000000..6bf4bdcbc --- /dev/null +++ b/crates/tepp_api/src/temporal_context_retrieval_http.rs @@ -0,0 +1,383 @@ +//! Provider-owned temporal-context GET-by-id contracts. +//! +//! GAP-003A unique slice: `GET /v1/temporal-context/{idempotency_key}` returns +//! one accepted metric-free `LineageWeave` identity on +//! `AnalysisRunLiveService` / `tepp-loopback` so operators who hold a stored +//! key do not replay POST. `tepp.scientific_acceptance.v1` never appears. Event +//! labels, actor lists, and timeline events stay off the retrieval. The +//! retrieval does not infer causality. This module does not re-open collection +//! GET (#449 closed), collection CLI (#450 closed), temporal-context CLI +//! (#414), project-history GET-by-id (#429), interpretation-run GET-by-id +//! (#438), export retrieval GET (#411), cancel lineages, or GAP-010 +//! Figma/export. Persistence remains GAP-003B. `NaruonLiveService` stays +//! POST-only. + +use crate::naruon_http::{NaruonHttpExchange, compose_https_target}; +use crate::wire::{ + from_json, require_byte_limit, require_contract_version, require_nonempty, to_json, +}; +use crate::{ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, TEMPORAL_CONTEXT_PATH}; +use serde::{Deserialize, Serialize}; + +/// Supported temporal-context retrieval contract version. +pub const TEMPORAL_CONTEXT_RETRIEVAL_CONTRACT_VERSION: u16 = 1; + +/// Maximum opaque idempotency-key length on the retrieval path. +pub const TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN: usize = 128; + +/// Fixed non-causal claim boundary echoed on every retrieval. +pub const TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS: &str = "temporal_association_only"; + +const FORBIDDEN_RETRIEVAL_KEYS: [&str; 16] = [ + "rmse", + "rmse_standard_error", + "mean_bias", + "bias_standard_error", + "interval_coverage", + "coverage_wilson_lower", + "coverage_wilson_upper", + "temporal_order_accuracy", + "se_gate_accepted", + "se_gate_k", + "scientific_acceptance", + "report", + "terminal_result", + "evidence_text", + "findings", + "causal_score", +]; + +/// One metric-free identity projection for an accepted temporal-context POST. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct TemporalContextRetrieved { + /// Semantic contract version for this payload family. + pub contract_version: u16, + /// Exact request idempotency key that minted the stored identity. + pub idempotency_key: String, + /// Knowledge cutoff applied to the stored identity. + pub knowledge_cutoff: String, + /// Fixed claim boundary: sequence is association, not causation. + pub inference_status: String, +} + +impl TemporalContextRetrieved { + /// Construct a validated metric-free retrieval identity. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities, slash/NUL, an + /// oversized key, or a causal inference status. + pub fn new( + idempotency_key: impl Into, + knowledge_cutoff: impl Into, + inference_status: impl Into, + ) -> Result { + let retrieved = Self { + contract_version: TEMPORAL_CONTEXT_RETRIEVAL_CONTRACT_VERSION, + idempotency_key: idempotency_key.into(), + knowledge_cutoff: knowledge_cutoff.into(), + inference_status: inference_status.into(), + }; + retrieved.validate()?; + Ok(retrieved) + } + + /// Parse and validate a retrieval payload with the default byte limit. + /// + /// # Errors + /// + /// Returns wire, version, limit, metric-key, or field-validation errors. + pub fn from_json(payload: &str) -> Result { + Self::from_json_with_limit(payload, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT) + } + + /// Parse and validate a retrieval payload with a caller-supplied limit. + /// + /// # Errors + /// + /// Returns wire, version, limit, metric-key, or field-validation errors. + pub fn from_json_with_limit(payload: &str, maximum_bytes: usize) -> Result { + require_byte_limit(payload, maximum_bytes)?; + refuse_metrics_on_temporal_context_retrieval_payload(payload)?; + let retrieved: Self = from_json(payload)?; + retrieved.validate()?; + Ok(retrieved) + } + + /// Serialize this retrieval after complete validation. + /// + /// # Errors + /// + /// Returns validation or serialization errors. + pub fn to_json(&self) -> Result { + self.validate()?; + let payload = to_json(self)?; + require_byte_limit(&payload, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT)?; + refuse_metrics_on_temporal_context_retrieval_payload(&payload)?; + Ok(payload) + } + + fn validate(&self) -> Result<(), ApiError> { + require_contract_version( + self.contract_version, + TEMPORAL_CONTEXT_RETRIEVAL_CONTRACT_VERSION, + )?; + validate_temporal_context_registry_identity(&self.idempotency_key)?; + require_nonempty(&self.knowledge_cutoff)?; + if self.inference_status != TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) + } +} + +/// Refuse an empty, oversized, slash, NUL, or control-bearing identity. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`]. +pub fn validate_temporal_context_registry_identity(identity: &str) -> Result<(), ApiError> { + require_nonempty(identity)?; + if identity.contains('/') || identity.contains('\0') || identity.chars().any(char::is_control) + { + return Err(ApiError::InvalidWirePayload); + } + if identity.len() > TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(()) +} + +/// Extract the opaque idempotency key from `GET /v1/temporal-context/{key}`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for the collection path, extra +/// segments, a hostile encoding, or an empty identity, and +/// [`ApiError::LimitExceeded`] when the decoded identity exceeds +/// [`TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN`]. +pub fn temporal_context_retrieval_path_id(path: &str) -> Result { + let remainder = path + .strip_prefix(TEMPORAL_CONTEXT_PATH) + .ok_or(ApiError::InvalidWirePayload)?; + let encoded = remainder + .strip_prefix('/') + .ok_or(ApiError::InvalidWirePayload)?; + if encoded.is_empty() || encoded.contains('/') { + return Err(ApiError::InvalidWirePayload); + } + let idempotency_key = decode_path_segment(encoded)?; + validate_temporal_context_registry_identity(&idempotency_key)?; + Ok(idempotency_key) +} + +/// Refuse retrieval JSON that already carries scientific-metric or evidence keys. +/// +/// Empty payloads are admitted for the GET request body. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a forbidden metric, evidence, +/// event-label, actor, or causal-score key is present. +pub fn refuse_metrics_on_temporal_context_retrieval_payload(payload: &str) -> Result<(), ApiError> { + if payload.trim().is_empty() { + return Ok(()); + } + if payload.contains("tepp.scientific_acceptance.v1") + || payload.contains("event_label") + || payload.contains("actor_references") + || payload.contains("timeline_events") + { + return Err(ApiError::InvalidWirePayload); + } + let value: serde_json::Value = + serde_json::from_str(payload).map_err(|_| ApiError::InvalidWirePayload)?; + if !value.is_object() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_json(&value) +} + +fn refuse_metrics_on_json(value: &serde_json::Value) -> Result<(), ApiError> { + match value { + serde_json::Value::Object(object) => { + if FORBIDDEN_RETRIEVAL_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + for nested in object.values() { + refuse_metrics_on_json(nested)?; + } + Ok(()) + } + serde_json::Value::Array(items) => { + for nested in items { + refuse_metrics_on_json(nested)?; + } + Ok(()) + } + _ => Ok(()), + } +} + +/// Build a provider-owned `GET` temporal-context retrieval exchange. +/// +/// The builder refuses non-`https` origins and empty or oversized identities. +/// It does not inject credentials. The GET body is empty. The identity +/// travels in the path. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a non-`https` origin or empty +/// identity, and [`ApiError::LimitExceeded`] when the identity exceeds +/// [`TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN`] bytes. +pub fn lineageweave_temporal_context_retrieval_exchange( + origin: &str, + idempotency_key: &str, +) -> Result { + validate_temporal_context_registry_identity(idempotency_key)?; + let encoded_id = encode_path_segment(idempotency_key); + let target_path = format!("{TEMPORAL_CONTEXT_PATH}/{encoded_id}"); + let target_url = compose_https_target(origin, &target_path)?; + Ok(NaruonHttpExchange { + method: "GET", + target_url, + headers: vec![ + ("content-type".into(), "application/json".into()), + ("tepp-consumer".into(), "lineageweave".into()), + ("tepp-contract-version".into(), "1".into()), + ], + body: String::new(), + }) +} + +fn encode_path_segment(value: &str) -> String { + let mut out = String::with_capacity(value.len() + value.len() / 2); + let hex = b"0123456789ABCDEF"; + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(byte as char); + } + _ => { + out.push('%'); + out.push(hex[usize::from(byte >> 4)] as char); + out.push(hex[usize::from(byte & 0x0F)] as char); + } + } + } + out +} + +fn decode_path_segment(value: &str) -> Result { + let mut out = Vec::with_capacity(value.len()); + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' => { + if index + 2 >= bytes.len() { + return Err(ApiError::InvalidWirePayload); + } + let hi = from_hex(bytes[index + 1])?; + let lo = from_hex(bytes[index + 2])?; + out.push((hi << 4) | lo); + index += 3; + } + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(bytes[index]); + index += 1; + } + _ => return Err(ApiError::InvalidWirePayload), + } + } + let decoded = String::from_utf8(out).map_err(|_| ApiError::InvalidWirePayload)?; + if decoded.chars().any(char::is_control) { + return Err(ApiError::InvalidWirePayload); + } + Ok(decoded) +} + +fn from_hex(byte: u8) -> Result { + match byte { + b'0'..=b'9' => Ok(byte - b'0'), + b'A'..=b'F' => Ok(byte - b'A' + 10), + b'a'..=b'f' => Ok(byte - b'a' + 10), + _ => Err(ApiError::InvalidWirePayload), + } +} + +#[cfg(test)] +mod tests { + use super::{ + TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN, TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS, + TemporalContextRetrieved, lineageweave_temporal_context_retrieval_exchange, + refuse_metrics_on_temporal_context_retrieval_payload, temporal_context_retrieval_path_id, + }; + use crate::ApiError; + + #[test] + fn retrieval_round_trips_and_refuses_hostile_shapes() { + let retrieved = TemporalContextRetrieved::new( + "idem-a", + "2026-08-20T00:00:00Z", + TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS, + ) + .expect("row"); + let json = retrieved.to_json().expect("json"); + assert_eq!( + TemporalContextRetrieved::from_json(&json).expect("decode"), + retrieved + ); + assert!(!json.contains("rmse")); + assert!(!json.contains("event_label")); + assert!(!json.contains("actor_references")); + assert_eq!( + TemporalContextRetrieved::new( + "a/b", + "2026-08-20T00:00:00Z", + TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + TemporalContextRetrieved::new( + "a".repeat(TEMPORAL_CONTEXT_RETRIEVAL_ID_MAX_LEN + 1), + "2026-08-20T00:00:00Z", + TEMPORAL_CONTEXT_RETRIEVAL_INFERENCE_STATUS + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + temporal_context_retrieval_path_id("/v1/temporal-context"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + temporal_context_retrieval_path_id("/v1/temporal-context/idem-a/extra"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + temporal_context_retrieval_path_id("/v1/temporal-context/idem-a").expect("id"), + "idem-a" + ); + assert_eq!( + refuse_metrics_on_temporal_context_retrieval_payload(r#"{"rmse":1}"#), + Err(ApiError::InvalidWirePayload) + ); + let exchange = lineageweave_temporal_context_retrieval_exchange( + "https://tepp.example.test", + "idem-a", + ) + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert!(exchange.target_url.ends_with("/v1/temporal-context/idem-a")); + assert!(exchange.body.is_empty()); + assert_eq!( + lineageweave_temporal_context_retrieval_exchange("http://insecure.example", "idem-a"), + Err(ApiError::InvalidWirePayload) + ); + } +} diff --git a/crates/tepp_api/tests/temporal_context_retrieval_cli_contract.rs b/crates/tepp_api/tests/temporal_context_retrieval_cli_contract.rs new file mode 100644 index 000000000..09578cd46 --- /dev/null +++ b/crates/tepp_api/tests/temporal_context_retrieval_cli_contract.rs @@ -0,0 +1,123 @@ +//! Contract tests for `tepp-temporal-context-get get`. + +use tepp_api::{ + compose_temporal_context_retrieval_cli_http, dispatch_temporal_context_retrieval_cli, + execute_temporal_context_retrieval_cli, render_temporal_context_retrieval_cli_stdout, + AnalysisRunLiveService, ApiError, LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, + NaruonLiveResponse, TEMPORAL_CONTEXT_PATH, TemporalContextRetrieved, + TemporalContextRetrievalCliInvocation, +}; + +const ORIGIN: &str = "https://tepp.example.test"; +const TEMPORAL_BODY: &str = r#"{"contract_version":1,"consumer_code":"lineageweave","knowledge_cutoff":"2026-08-20T00:00:00Z","subject_post_id":null,"events":[{"event_id":"event-1","source_post_id":"post-1","event_type_code":"order_awarded","event_label":"Order awarded","event_time":"2026-08-01T09:00:00Z","available_time":"2026-08-01T10:00:00Z","project_reference":null,"actor_references":["actor-1"]}]}"#; + +fn post_http(idempotency_key: &str) -> String { + format!( + "POST {TEMPORAL_CONTEXT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\nidempotency-key: {idempotency_key}\r\ncontent-length: {}\r\n\r\n{TEMPORAL_BODY}", + TEMPORAL_BODY.len() + ) +} + +fn get_invocation(host: &str, key: &str) -> TemporalContextRetrievalCliInvocation { + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + host, + "--origin", + ORIGIN, + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + key, + ], + "", + ) + .expect("get") +} + +#[test] +fn dispatch_gets_one_metric_free_identity() { + let mut service = AnalysisRunLiveService::new(); + assert_eq!( + service.handle_http_request(&post_http("idem-cli")).status_code, + 200 + ); + let listed = dispatch_temporal_context_retrieval_cli( + &mut service, + &get_invocation("127.0.0.1:18081", "idem-cli"), + ) + .expect("get"); + assert_eq!(listed.status_code, 200, "{}", listed.body); + let stdout = render_temporal_context_retrieval_cli_stdout( + &get_invocation("127.0.0.1:18081", "idem-cli"), + &listed, + ) + .expect("out"); + assert!(!stdout.contains("tepp.scientific_acceptance.v1")); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("event_label")); + assert!(!stdout.contains("actor_references")); + let row = TemporalContextRetrieved::from_json(&stdout).expect("row"); + assert_eq!(row.idempotency_key, "idem-cli"); + assert_eq!(row.inference_status, "temporal_association_only"); +} + +#[test] +fn render_refuses_metrics_naruon_and_empty_bodies() { + let get = get_invocation("127.0.0.1:18081", "idem-cli"); + assert_eq!( + render_temporal_context_retrieval_cli_stdout( + &get, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + TemporalContextRetrievalCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + NARUON_CONSUMER_CODE, + "--idempotency-key", + "idem-cli" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let http = compose_temporal_context_retrieval_cli_http(&get).expect("http"); + assert!(http.starts_with("GET /v1/temporal-context/idem-cli HTTP/1.1")); +} + +#[test] +fn execute_over_tcp_retrieves_authorized_identity() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + assert_eq!( + service + .handle_http_request(&post_http("idem-tcp")) + .status_code, + 200 + ); + let addr = service.local_addr().expect("addr"); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let invocation = get_invocation(&addr.to_string(), "idem-tcp"); + let response = execute_temporal_context_retrieval_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 200, "{}", response.body); + let stdout = render_temporal_context_retrieval_cli_stdout(&invocation, &response).expect("out"); + let row = TemporalContextRetrieved::from_json(&stdout).expect("row"); + assert_eq!(row.idempotency_key, "idem-tcp"); + handle.join().expect("join"); +} diff --git a/crates/tepp_api/tests/temporal_context_retrieval_http_contract.rs b/crates/tepp_api/tests/temporal_context_retrieval_http_contract.rs new file mode 100644 index 000000000..f0dfefbbf --- /dev/null +++ b/crates/tepp_api/tests/temporal_context_retrieval_http_contract.rs @@ -0,0 +1,73 @@ +//! Contract tests for loopback `GET /v1/temporal-context/{idempotency_key}`. + +use std::io::{Read, Write}; + +use tepp_api::{ + AnalysisRunLiveService, LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, TEMPORAL_CONTEXT_PATH, + TemporalContextRetrieved, +}; + +const TEMPORAL_BODY: &str = r#"{"contract_version":1,"consumer_code":"lineageweave","knowledge_cutoff":"2026-08-20T00:00:00Z","subject_post_id":null,"events":[{"event_id":"event-1","source_post_id":"post-1","event_type_code":"order_awarded","event_label":"Order awarded","event_time":"2026-08-01T09:00:00Z","available_time":"2026-08-01T10:00:00Z","project_reference":null,"actor_references":["actor-1"]}]}"#; + +fn post_http(idempotency_key: &str) -> String { + format!( + "POST {TEMPORAL_CONTEXT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\nidempotency-key: {idempotency_key}\r\ncontent-length: {}\r\n\r\n{TEMPORAL_BODY}", + TEMPORAL_BODY.len() + ) +} + +#[test] +fn get_by_id_returns_metric_free_identity() { + let mut service = AnalysisRunLiveService::new(); + assert_eq!( + service.handle_http_request(&post_http("idem-b")).status_code, + 200 + ); + let got = service.handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH}/idem-b HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ), + ); + assert_eq!(got.status_code, 200, "{}", got.body); + let row = TemporalContextRetrieved::from_json(&got.body).expect("row"); + assert_eq!(row.idempotency_key, "idem-b"); + assert!(!got.body.contains("event_label")); + assert!(!got.body.contains("actor_references")); + assert!(!got.body.contains("tepp.scientific_acceptance.v1")); +} + +#[test] +fn get_by_id_refuses_naruon_and_serves_over_tcp() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + assert_eq!( + service.handle_http_request(&post_http("idem-tcp")).status_code, + 200 + ); + assert_eq!( + service + .handle_http_request( + &format!( + "GET {TEMPORAL_CONTEXT_PATH}/idem-tcp HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {NARUON_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ) + ) + .status_code, + 400 + ); + let addr = service.local_addr().expect("addr"); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let request = format!( + "GET {TEMPORAL_CONTEXT_PATH}/idem-tcp HTTP/1.1\r\nHost: {addr}\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + ); + let mut stream = std::net::TcpStream::connect(addr).expect("connect"); + stream.write_all(request.as_bytes()).expect("write"); + stream.flush().expect("flush"); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).expect("read"); + let text = String::from_utf8(bytes).expect("utf8"); + assert!(text.contains("HTTP/1.1 200"), "{text}"); + assert!(text.contains("idem-tcp"), "{text}"); + assert!(!text.contains("event_label"), "{text}"); + handle.join().expect("join"); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index b76b688e1..7fd742ca4 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -65,6 +65,7 @@ GET /v1/evidence-imports/{import_id} POST /v1/interpretation-runs POST /v1/analysis-runs POST /v1/temporal-context +GET /v1/temporal-context/{idempotency_key} GET /v1/analysis-runs/{run_id} POST /v1/analysis-runs/{run_id}/cancel GET /v1/model-artifacts/{artifact_id} @@ -90,6 +91,12 @@ 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. +`GET /v1/temporal-context/{idempotency_key}` returns one metric-free identity +minted when that POST carries an `idempotency-key` header (ADR 0083). Published +`tepp-temporal-context-get get` mints that retrieval GET onto spawned +`tepp-loopback` TCP (ADR 0084). Event labels, actor lists, and +`tepp.scientific_acceptance.v1` never appear. Naruon is refused. +`NaruonLiveService` stays POST-only. Collection GET stays closed. 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 2b783c2ab..09d0f0252 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -53,6 +53,8 @@ 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 GET-by-id | ADR 0083; API contract; RFC 9110; ADR 0002/0014 | `tepp_api` `GET /v1/temporal-context/{idempotency_key}` on `tepp-loopback`; metric-free `inference_status=temporal_association_only` identity; `tepp.scientific_acceptance.v1` never appears; does not infer causality; does not re-open collection GET | active-PR | +| loopback LineageWeave temporal-context retrieval CLI | ADR 0084; API contract; RFC 9110; ADR 0083/0002/0014 | `tepp-temporal-context-get get` mints that GET onto spawned `tepp-loopback` TCP; metric-free `inference_status=temporal_association_only`; event labels and actor lists never appear; 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/0083-temporal-context-retrieval-get.md b/docs/adr/0083-temporal-context-retrieval-get.md new file mode 100644 index 000000000..bf7f958e1 --- /dev/null +++ b/docs/adr/0083-temporal-context-retrieval-get.md @@ -0,0 +1,89 @@ +# ADR 0083 — Loopback temporal-context GET-by-id + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-09-01 +**Supersedes:** None; complements `POST /v1/temporal-context`. Does not +re-open collection GET (#449 closed as fold-into-landing-vehicle) or cancel +lineages closed as unsafe mutation. Does not supersede ADR 0014. Unique versus +protected main; 0026–0082 were assigned on live or closed sibling GAP-003A +PRs. + +## Context + +`POST /v1/temporal-context` returns one cutoff-safe association page. Operators +who hold an idempotency key still had no loopback GET-by-id. Collection GET +(#449) was closed as a standalone list route. Cancel HTTP/CLI lineages were +closed as unauthenticated destructive operations. Duplicating temporal-context +CLI (#414), project-history GET-by-id (#429), interpretation-run GET-by-id +(#438), export retrieval GET (#411), Leiden, or GAP-010 Figma/export would +collide with live PRs. Naruon is refused; `NaruonLiveService` stays POST-only. + +## Decision + +Publish `GET /v1/temporal-context/{idempotency_key}` on +`AnalysisRunLiveService` / `tepp-loopback`: + +- Extra-segment path parse. Slash/NUL/control identities fail closed. +- Empty body. Present `idempotency-key` header fails closed (identity is in + the path). +- Collection path `GET /v1/temporal-context` stays refused. +- Retrieval JSON is a metric-free identity with + `inference_status=temporal_association_only`. Event labels, actor lists, + timeline events, evidence text, findings, RMSE, and + `tepp.scientific_acceptance.v1` never appear. +- POST remains compute-and-return. An optional `idempotency-key` header mints + the identity for later GET-by-id. + +## Alternatives considered + +1. **Re-open collection GET (#449)** — rejected; closed as + fold-into-landing-vehicle. +2. **Re-open cancel HTTP** — rejected; closed as unsafe mutation. +3. **Loopback GET-by-id** — accepted. + +## Consequences + +- Operators can retrieve one accepted identity without POST replay. +- HTTP 200 is not measurement evidence and is not a causal claim. + +## Failure and recovery + +Non-LineageWeave consumers, nonempty GET bodies, collection path, extra +segments, slash/NUL identities, missing keys, credential flags, and metric +keys fail closed. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers. Event labels and actor lists stay off the retrieval. +- HTTP 200 is not an ADR 0014 claim. + +## Compatibility and migration + +POST without an idempotency header remains valid. Collection GET stays closed. +`NaruonLiveService` POST-only remains unchanged. Persistence remains GAP-003B. + +## Verification + +- `GET /v1/temporal-context/{idempotency_key}` of an accepted identity returns + a metric-free row without RMSE/event-label/actor/`tepp.scientific_acceptance.v1`; +- naruon, collection path, extra segments, slash/NUL, nonempty body, and + missing keys fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review + remain required. + +## Rollback and supersession + +Rollback removes GET-by-id; POST remains valid. A superseding ADR is required +to persist the registry, bind a public address, re-open collection GET as a +standalone route, emit scientific-acceptance, open naruon, add GET to +`NaruonLiveService`, or treat retrieval success as an ADR 0014 claim. + +## Related authority + +- ADR 0002 owns six-clock temporal semantics. +- ADR 0027 owns the temporal-context CLI (live #414). +- ADR 0066 owns project-history GET-by-id (live #429). +- ADR 0071 owns interpretation-run GET-by-id (live #438). +- ADR 0014 owns scientific claim promotion. +- RFC 9110 owns GET semantics (Fielding, Nottingham, & Reschke, 2022). diff --git a/docs/adr/0084-temporal-context-retrieval-cli.md b/docs/adr/0084-temporal-context-retrieval-cli.md new file mode 100644 index 000000000..0a770a690 --- /dev/null +++ b/docs/adr/0084-temporal-context-retrieval-cli.md @@ -0,0 +1,88 @@ +# ADR 0084 — Loopback temporal-context retrieval CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-09-01 +**Supersedes:** None; complements ADR 0083 for operator-visible GET-by-id. +Does not re-open collection GET/CLI (#449/#450) or cancel lineages. Does not +supersede ADR 0014. Unique versus protected main; 0026–0083 occupied. + +## Context + +ADR 0083 retrieves one accepted temporal-context identity on +`AnalysisRunLiveService`. Operators still had no published binary that mints +that GET onto spawned `tepp-loopback` TCP. Duplicating GET-by-id HTTP (#451), +temporal-context CLI (#414), project-history retrieval CLI (#431), export +retrieval CLI (#417), interpretation-run retrieval CLI (#439), Leiden, Driver +p.16, or GAP-010 Figma/export would collide with live PRs. Naruon is refused; +`NaruonLiveService` stays POST-only. + +## Decision + +Publish `tepp-temporal-context-get get`: + +- Pattern: `from_args` + typed `lineageweave_temporal_context_retrieval_exchange` + + `loopback_http1_from_temporal_context_retrieval_exchange` + + `dispatch`/`execute`/`render` + published `[[bin]]`. +- Empty stdin is admitted. Nonempty leftover stdin fails closed. +- Public bind, `localhost` host, `http` origin, unpublished consumer, slash/NUL + identities, and credential flags fail closed. +- Identity travels as `--idempotency-key`. Present `idempotency-key` HTTP + header on the minted GET fails closed. +- Stdout is one metric-free identity with + `inference_status=temporal_association_only`. Event labels, actor lists, + timeline events, evidence text, findings, RMSE, and + `tepp.scientific_acceptance.v1` never appear. +- Dedicated binary so it does not collide with `tepp-temporal-context` (#414). + +## Alternatives considered + +1. **Reuse `tepp-temporal-context`** — rejected; that CLI is POST. +2. **Add GET to `NaruonLiveService`** — rejected; POST-only. +3. **Published `tepp-temporal-context-get get`** — accepted. + +## Consequences + +- Operators can retrieve one accepted identity without a second GET-by-id PR. +- HTTP 200 is not measurement evidence and is not a causal claim. + +## Failure and recovery + +Non-LineageWeave consumers, nonempty leftover stdin, slash/NUL identities, +credential flags, public bind, and metric keys fail closed. TCP execute does +not fall back to an empty in-process listener. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers. Event labels and actor lists stay off stdout. +- HTTP 200 is not an ADR 0014 claim. + +## Compatibility and migration + +GET-by-id HTTP, POST `/v1/temporal-context`, and `NaruonLiveService` POST-only +remain unchanged. Collection GET stays closed. Persistence remains GAP-003B. + +## Verification + +- `tepp-temporal-context-get get` of an accepted identity returns a metric-free + row without RMSE/event-label/actor/`tepp.scientific_acceptance.v1`; +- naruon, nonempty leftover stdin, `localhost`, `http` origin, public bind, + slash/NUL, and unknown keys fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review + remain required. + +## Rollback and supersession + +Rollback removes the published binary; GET-by-id HTTP remains valid. A +superseding ADR is required to persist the registry, bind a public address, +re-open collection GET, emit scientific-acceptance, open naruon, add GET to +`NaruonLiveService`, or treat retrieval success as an ADR 0014 claim. + +## Related authority + +- ADR 0083 owns loopback temporal-context GET-by-id. +- ADR 0027 owns the temporal-context CLI (live #414). +- ADR 0067 owns project-history retrieval CLI (live #431). +- ADR 0072 owns interpretation-run retrieval CLI (live #439). +- ADR 0014 owns scientific claim promotion. +- RFC 9110 owns GET semantics (Fielding, Nottingham, & Reschke, 2022). diff --git a/docs/adr/README.md b/docs/adr/README.md index 1254c8079..6913d76a6 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -30,6 +30,8 @@ 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. | +| [0083](0083-temporal-context-retrieval-get.md) | Loopback temporal-context GET-by-id | Accepted | active-PR | Complements `POST /v1/temporal-context`; `GET /v1/temporal-context/{idempotency_key}` returns one metric-free LineageWeave identity. Unique versus protected main (0026–0082 occupied on live or closed sibling PRs). Does not re-open collection GET or cancel lineages. | +| [0084](0084-temporal-context-retrieval-cli.md) | Loopback temporal-context retrieval CLI | Accepted | active-PR | Complements ADR 0083; published `tepp-temporal-context-get get` mints LineageWeave `GET /v1/temporal-context/{idempotency_key}` onto spawned `tepp-loopback` TCP. Unique versus protected main (0026–0083 occupied). | | [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. | diff --git a/docs/research/temporal-context-retrieval-cli.md b/docs/research/temporal-context-retrieval-cli.md new file mode 100644 index 000000000..e5e14b08a --- /dev/null +++ b/docs/research/temporal-context-retrieval-cli.md @@ -0,0 +1,48 @@ +# Temporal-context retrieval CLI (doctoring) + +## Scope + +`tepp-temporal-context-get get` is the operator-visible loopback CLI that mints +a typed LineageWeave `GET /v1/temporal-context/{idempotency_key}` onto spawned +`tepp-loopback` TCP. HTTP method, path, and header semantics follow current +HTTP semantics (Fielding, Nottingham, & Reschke, 2022). Fail-closed refusal of +unpublished consumers, nonempty leftover stdin, `localhost`, `http` origin, +slash/NUL identities, credential flags, public bind, and scientific-authority +promotion is repository contract authority (ADR 0084; ADR 0083; ADR 0014), not +an RFC inference rule. + +Stdout is metric-free with `inference_status=temporal_association_only`. Event +labels, actor lists, timeline events, evidence text, findings, and +`tepp.scientific_acceptance.v1` never appear. HTTP 200 is not a completed +psychometric result, 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 + +### Internal contract evidence + +- `docs/adr/0084-temporal-context-retrieval-cli.md` — this CLI +- `docs/adr/0083-temporal-context-retrieval-get.md` — GET-by-id HTTP +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — HTTP + 200 is not a scientific claim +- `crates/tepp_api/tests/temporal_context_retrieval_cli_contract.rs` + +## Verification + +- `tepp-temporal-context-get get` of an accepted identity returns a metric-free + row without RMSE, event labels, actor lists, or + `tepp.scientific_acceptance.v1`; +- naruon, nonempty leftover stdin, `localhost`, `http` origin, slash/NUL, and + public bind fail closed; +- `NaruonLiveService` still refuses GET. + +## Non-claims + +This slice does not re-open collection GET (#449), cancel lineages, GAP-010 +Figma/export, persistence, production TLS, Leiden consensus, causal inference, +or an ADR 0014 scientific claim-promotion package. diff --git a/docs/research/temporal-context-retrieval-get.md b/docs/research/temporal-context-retrieval-get.md new file mode 100644 index 000000000..0e5531d5b --- /dev/null +++ b/docs/research/temporal-context-retrieval-get.md @@ -0,0 +1,48 @@ +# Temporal-context GET-by-id (doctoring) + +## Scope + +`GET /v1/temporal-context/{idempotency_key}` is the operator-visible loopback +retrieval of one accepted LineageWeave temporal-context identity on +`AnalysisRunLiveService` / `tepp-loopback`. HTTP method, path, and header +semantics follow current HTTP semantics (Fielding, Nottingham, & Reschke, +2022). Fail-closed refusal of unpublished consumers, collection path, extra +segments, slash/NUL identities, nonempty leftover bodies, credential flags, +public bind, and scientific-authority promotion is repository contract +authority (ADR 0083; ADR 0002; ADR 0014), not an RFC inference rule. + +The retrieval is metric-free with `inference_status=temporal_association_only`. +Event labels, actor lists, timeline events, evidence text, findings, and +`tepp.scientific_acceptance.v1` never appear. HTTP 200 is not a completed +psychometric result, 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 + +### Internal contract evidence + +- `docs/adr/0083-temporal-context-retrieval-get.md` — this GET-by-id +- `docs/adr/0002-six-clock-temporal-semantics.md` — cutoff-safe association +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — HTTP + 200 is not a scientific claim +- `crates/tepp_api/tests/temporal_context_retrieval_http_contract.rs` + +## Verification + +- `GET /v1/temporal-context/{idempotency_key}` of an accepted identity returns + a metric-free row without RMSE, event labels, actor lists, or + `tepp.scientific_acceptance.v1`; +- naruon, collection path, extra segments, slash/NUL, and missing keys fail + closed; +- `NaruonLiveService` still refuses GET. + +## Non-claims + +This slice does not re-open collection GET (#449), cancel lineages, GAP-010 +Figma/export, persistence, production TLS, Leiden consensus, causal inference, +or an ADR 0014 scientific claim-promotion package.