feat: complete Epic 1 production foundation

This commit is contained in:
bsodfather committed 2026-08-25 01:24:11 +03:00
1 parent 767428436d
commit 182bde8ac0
298 files changed
+35711 -5291

No files matched your search

+135 -19
View File
@@ -2,12 +2,18 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use time::OffsetDateTime;
use crate::{AgentId, OperationId, WorkspaceId};
use crate::{
AgentId, ExecutionErrorCode, ExecutionStage, OperationId, OutcomeCertainty, Retryability,
WorkspaceId,
};
pub const INVOCATION_PREVIEW_MAX_BYTES: usize = 16 * 1024;
pub const INVOCATION_PREVIEW_MAX_DEPTH: usize = 12;
pub const INVOCATION_PREVIEW_MAX_OBJECT_FIELDS: usize = 64;
pub const INVOCATION_PREVIEW_MAX_ARRAY_ITEMS: usize = 64;
pub fn sanitize_invocation_preview(value: &Value) -> Value {
let redacted = redact_sensitive_fields(value);
let redacted = redact_sensitive_fields(value, 0);
let Ok(encoded) = serde_json::to_vec(&redacted) else {
return Value::Null;
};
@@ -17,27 +23,63 @@ pub fn sanitize_invocation_preview(value: &Value) -> Value {
let preview = String::from_utf8_lossy(&encoded[..INVOCATION_PREVIEW_MAX_BYTES]).into_owned();
json!({
"truncated": true,
"reason": "max_bytes",
"original_bytes": encoded.len(),
"preview": preview,
})
}
fn redact_sensitive_fields(value: &Value) -> Value {
fn truncation_marker(reason: &'static str, omitted: usize) -> Value {
json!({
"truncated": true,
"reason": reason,
"omitted": omitted,
})
}
fn redact_sensitive_fields(value: &Value, depth: usize) -> Value {
if depth >= INVOCATION_PREVIEW_MAX_DEPTH {
return truncation_marker("max_depth", 1);
}
match value {
Value::Object(object) => Value::Object(
object
Value::Object(object) => {
let mut redacted = Map::new();
let mut omitted = 0usize;
for (index, (key, value)) in object.iter().enumerate() {
if index >= INVOCATION_PREVIEW_MAX_OBJECT_FIELDS {
omitted += 1;
continue;
}
let value = if is_sensitive_key(key) {
Value::String("[REDACTED]".to_owned())
} else {
redact_sensitive_fields(value, depth + 1)
};
redacted.insert(key.clone(), value);
}
if omitted > 0 {
redacted.insert(
"_crank_truncated".to_owned(),
truncation_marker("max_object_fields", omitted),
);
}
Value::Object(redacted)
}
Value::Array(items) => {
let mut redacted = items
.iter()
.map(|(key, value)| {
let value = if is_sensitive_key(key) {
Value::String("[REDACTED]".to_owned())
} else {
redact_sensitive_fields(value)
};
(key.clone(), value)
})
.collect::<Map<String, Value>>(),
),
Value::Array(items) => Value::Array(items.iter().map(redact_sensitive_fields).collect()),
.take(INVOCATION_PREVIEW_MAX_ARRAY_ITEMS)
.map(|value| redact_sensitive_fields(value, depth + 1))
.collect::<Vec<_>>();
let omitted = items.len().saturating_sub(redacted.len());
if omitted > 0 {
redacted.push(truncation_marker("max_array_items", omitted));
}
Value::Array(redacted)
}
Value::String(value) if looks_like_sensitive_value(value) => {
Value::String("[REDACTED]".to_owned())
}
_ => value.clone(),
}
}
@@ -63,6 +105,22 @@ fn is_sensitive_key(key: &str) -> bool {
.any(|sensitive| compact.contains(sensitive))
}
fn looks_like_sensitive_value(value: &str) -> bool {
let trimmed = value.trim();
let lower = trimmed.to_ascii_lowercase();
lower.starts_with("bearer ")
|| lower.starts_with("basic ")
|| lower.contains("password=")
|| lower.contains("token=")
|| lower.contains("secret=")
|| lower.contains("api_key=")
|| lower.contains("apikey=")
|| lower.contains("authorization:")
|| trimmed.starts_with("sk_")
|| trimmed.starts_with("crk_")
|| trimmed.contains("SECRET_")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationSource {
@@ -111,7 +169,10 @@ pub struct InvocationLog {
pub id: crate::ids::InvocationLogId,
pub workspace_id: WorkspaceId,
pub agent_id: Option<AgentId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub platform_api_key_id: Option<crate::ids::PlatformApiKeyId>,
pub operation_id: OperationId,
pub operation_version: Option<u32>,
pub source: InvocationSource,
pub level: InvocationLevel,
pub status: InvocationStatus,
@@ -122,6 +183,10 @@ pub struct InvocationLog {
pub status_code: Option<u16>,
pub duration_ms: u64,
pub error_kind: Option<String>,
pub execution_stage: Option<ExecutionStage>,
pub execution_error_code: Option<ExecutionErrorCode>,
pub retryability: Option<Retryability>,
pub outcome_certainty: Option<OutcomeCertainty>,
pub request_preview: Value,
pub response_preview: Value,
#[serde(with = "time::serde::rfc3339")]
@@ -148,10 +213,12 @@ mod tests {
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use super::{
INVOCATION_PREVIEW_MAX_BYTES, InvocationLevel, InvocationLog, InvocationSource,
InvocationStatus, UsagePeriod, sanitize_invocation_preview,
INVOCATION_PREVIEW_MAX_ARRAY_ITEMS, INVOCATION_PREVIEW_MAX_BYTES,
INVOCATION_PREVIEW_MAX_DEPTH, INVOCATION_PREVIEW_MAX_OBJECT_FIELDS, InvocationLevel,
InvocationLog, InvocationSource, InvocationStatus, UsagePeriod,
sanitize_invocation_preview,
};
use crate::{AgentId, OperationId, WorkspaceId, ids::InvocationLogId};
use crate::{AgentId, OperationId, OutcomeCertainty, WorkspaceId, ids::InvocationLogId};
fn timestamp(value: &str) -> OffsetDateTime {
OffsetDateTime::parse(value, &Rfc3339).unwrap()
@@ -163,7 +230,9 @@ mod tests {
id: InvocationLogId::new("log_01"),
workspace_id: WorkspaceId::new("ws_01"),
agent_id: Some(AgentId::new("agent_01")),
platform_api_key_id: None,
operation_id: OperationId::new("op_01"),
operation_version: Some(1),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Info,
status: InvocationStatus::Ok,
@@ -174,6 +243,10 @@ mod tests {
status_code: Some(200),
duration_ms: 123,
error_kind: None,
execution_stage: None,
execution_error_code: None,
retryability: None,
outcome_certainty: Some(OutcomeCertainty::Certain),
request_preview: json!({"input": "value"}),
response_preview: json!({"ok": true}),
created_at: timestamp("2026-04-19T12:34:56Z"),
@@ -202,6 +275,8 @@ mod tests {
"api_key": "key",
"refreshToken": "token",
"client_secret_value": "secret",
"body": "Bearer SECRET_APPROVAL_CANARY",
"neutral": "token=SECRET_APPROVAL_CANARY",
"value": 42
}
}));
@@ -210,6 +285,8 @@ mod tests {
assert_eq!(preview["nested"]["api_key"], "[REDACTED]");
assert_eq!(preview["nested"]["refreshToken"], "[REDACTED]");
assert_eq!(preview["nested"]["client_secret_value"], "[REDACTED]");
assert_eq!(preview["nested"]["body"], "[REDACTED]");
assert_eq!(preview["nested"]["neutral"], "[REDACTED]");
assert_eq!(preview["nested"]["value"], 42);
}
@@ -220,6 +297,45 @@ mod tests {
}));
assert_eq!(preview["truncated"], true);
assert_eq!(preview["reason"], "max_bytes");
assert!(preview["original_bytes"].as_u64().unwrap() > INVOCATION_PREVIEW_MAX_BYTES as u64);
}
#[test]
fn bounds_preview_depth_fields_and_array_items() {
let mut nested = json!({"secret_token": "SECRET_VALUE"});
for _ in 0..(INVOCATION_PREVIEW_MAX_DEPTH + 4) {
nested = json!({ "nested": nested });
}
let deep_preview = sanitize_invocation_preview(&nested);
assert!(
serde_json::to_string(&deep_preview)
.unwrap()
.contains("\"reason\":\"max_depth\"")
);
assert!(
!serde_json::to_string(&deep_preview)
.unwrap()
.contains("SECRET_VALUE")
);
let wide = serde_json::Value::Object(
(0..(INVOCATION_PREVIEW_MAX_OBJECT_FIELDS + 5))
.map(|index| (format!("field_{index:03}"), json!(index)))
.collect(),
);
let wide_preview = sanitize_invocation_preview(&wide);
assert_eq!(
wide_preview["_crank_truncated"]["reason"],
"max_object_fields"
);
let array_preview = sanitize_invocation_preview(&json!(
(0..(INVOCATION_PREVIEW_MAX_ARRAY_ITEMS + 3)).collect::<Vec<_>>()
));
assert_eq!(
array_preview.as_array().unwrap().last().unwrap()["reason"],
"max_array_items"
);
}
}