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..89442a8ed 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -13,6 +13,7 @@ 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) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | | Security policy | [`SECURITY.md`](SECURITY.md) | diff --git a/crates/tepp_api/src/analysis_run_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/lib.rs b/crates/tepp_api/src/lib.rs index 876703ebc..49bd78a09 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_retrieval_http; mod wire; /// Terminal analysis-result contract version constant. @@ -282,3 +283,19 @@ 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; 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_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..bf5a88784 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,10 @@ 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). 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..1cfe3e59e 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 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 | | 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/README.md b/docs/adr/README.md index 1254c8079..126199cab 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. | +| [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. | | [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-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.