From 8b94894c4908bb187d5f9fa98d5f8064b41aeb95 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 01:21:38 +0800 Subject: [PATCH 1/2] Give agent data types ownership of shared behavior --- AGENTS.md | 7 + .../src/agents/antigravity/schema/mod.rs | 27 + .../agents/antigravity/schema/tool_call.rs | 26 + .../agents/antigravity/schema/tool_calls.rs | 17 + .../transcript_record.rs} | 70 +-- bt-daemon/src/agents/schema.rs | 264 -------- bt-daemon/src/agents/schema/command_hook.rs | 20 + .../src/agents/schema/cursor_command_hook.rs | 27 + .../src/agents/schema/cursor_hook_entries.rs | 11 + .../src/agents/schema/cursor_hook_entry.rs | 18 + bt-daemon/src/agents/schema/cursor_hooks.rs | 68 +++ bt-daemon/src/agents/schema/hook_file.rs | 13 + bt-daemon/src/agents/schema/hook_group.rs | 12 + bt-daemon/src/agents/schema/mod.rs | 40 ++ .../src/agents/schema/opencode_config.rs | 56 ++ .../src/agents/schema/opencode_plugin.rs | 31 + .../src/agents/schema/plugin_manifest.rs | 10 + bt-daemon/src/agents/schema/repository.rs | 21 + bt-daemon/src/agents/schema/tests.rs | 134 +++++ bt-daemon/src/agents/usage.rs | 562 ------------------ .../src/agents/usage/camel_case_usage.rs | 69 +++ bt-daemon/src/agents/usage/mod.rs | 108 ++++ bt-daemon/src/agents/usage/opencode_tokens.rs | 32 + bt-daemon/src/agents/usage/pi_usage.rs | 33 + bt-daemon/src/agents/usage/provider_usage.rs | 88 +++ .../src/agents/usage/snake_case_usage.rs | 138 +++++ bt-daemon/src/agents/usage/token_metrics.rs | 39 ++ bt-daemon/src/agents/usage/usage_metrics.rs | 97 +++ bt-daemon/src/command_output.rs | 23 +- .../src/command_output/auth_diagnostic.rs | 66 ++ bt-daemon/src/dispatch.rs | 14 +- bt-daemon/src/hook.rs | 3 +- bt-daemon/src/journal.rs | 33 +- bt-daemon/src/managed_run/opencode.rs | 7 +- bt-daemon/src/pipeline/translation.rs | 4 +- bt-daemon/src/route.rs | 56 +- bt-daemon/src/server/claude_transcripts.rs | 12 +- bt-daemon/src/server/ingress.rs | 2 +- bt-daemon/src/server/maintenance.rs | 2 +- bt-daemon/src/server/recovery.rs | 4 +- bt-daemon/src/setup/cursor/hooks.rs | 54 +- bt-daemon/src/setup/opencode.rs | 38 +- bt-daemon/src/trace_runtime.rs | 82 +-- .../src/transcript_import/antigravity.rs | 15 +- .../claude_child_reference.rs | 5 + .../src/transcript_mirror/grok_references.rs | 17 + .../mod.rs} | 105 +--- .../src/transcript_mirror/observation.rs | 7 + bt-daemon/src/transcript_mirror/payload.rs | 156 +++++ bt-daemon/src/transcript_mirror/reference.rs | 35 ++ bt-daemon/src/transcript_mirror/snapshot.rs | 5 + bt-daemon/src/translate/antigravity.rs | 48 +- bt-daemon/src/translate/claude.rs | 31 +- bt-daemon/src/translate/codex.rs | 18 +- bt-daemon/src/translate/opencode.rs | 191 +----- .../src/translate/opencode/permission.rs | 163 +++++ bt-daemon/src/translate/opencode_v2.rs | 124 +--- .../src/translate/opencode_v2/context.rs | 229 +++++++ bt-daemon/src/translate/opencode_v2/event.rs | 151 +---- bt-daemon/src/translate/opencode_v2/span.rs | 4 +- .../src/translate/opencode_v2/tool_content.rs | 34 ++ bt-daemon/src/translate/pi.rs | 391 +----------- .../src/translate/pi/assistant_message.rs | 136 +++++ bt-daemon/src/translate/pi/compaction.rs | 144 +++++ bt-daemon/src/translate/pi/event.rs | 103 ++++ bt-daemon/src/translate/tool.rs | 29 +- bt-daemon/src/translate/tool/skill_load.rs | 39 ++ bt-daemon/src/wire/auth_selection.rs | 48 ++ bt-daemon/src/wire/auth_source.rs | 22 + bt-daemon/src/wire/backend_auth.rs | 19 + bt-daemon/src/wire/capture_context.rs | 16 + bt-daemon/src/wire/envelope.rs | 520 +--------------- bt-daemon/src/wire/envelope_tests.rs | 220 +++++++ bt-daemon/src/wire/flush_mode.rs | 11 + bt-daemon/src/wire/mod.rs | 30 +- bt-daemon/src/wire/process_identity.rs | 14 + bt-daemon/src/wire/redacted_envelope.rs | 53 ++ bt-daemon/src/wire/session_config.rs | 37 ++ bt-daemon/src/wire/session_route.rs | 119 ++++ bt-daemon/src/wire/trace_destination.rs | 54 ++ docs/architecture/dto-ownership/README.md | 48 ++ .../dto-ownership/agent-config.md | 345 +++++++++++ .../dto-ownership/core-runtime.md | 308 ++++++++++ .../architecture/dto-ownership/translators.md | 356 +++++++++++ 84 files changed, 4175 insertions(+), 2663 deletions(-) create mode 100644 bt-daemon/src/agents/antigravity/schema/mod.rs create mode 100644 bt-daemon/src/agents/antigravity/schema/tool_call.rs create mode 100644 bt-daemon/src/agents/antigravity/schema/tool_calls.rs rename bt-daemon/src/agents/antigravity/{schema.rs => schema/transcript_record.rs} (59%) delete mode 100644 bt-daemon/src/agents/schema.rs create mode 100644 bt-daemon/src/agents/schema/command_hook.rs create mode 100644 bt-daemon/src/agents/schema/cursor_command_hook.rs create mode 100644 bt-daemon/src/agents/schema/cursor_hook_entries.rs create mode 100644 bt-daemon/src/agents/schema/cursor_hook_entry.rs create mode 100644 bt-daemon/src/agents/schema/cursor_hooks.rs create mode 100644 bt-daemon/src/agents/schema/hook_file.rs create mode 100644 bt-daemon/src/agents/schema/hook_group.rs create mode 100644 bt-daemon/src/agents/schema/mod.rs create mode 100644 bt-daemon/src/agents/schema/opencode_config.rs create mode 100644 bt-daemon/src/agents/schema/opencode_plugin.rs create mode 100644 bt-daemon/src/agents/schema/plugin_manifest.rs create mode 100644 bt-daemon/src/agents/schema/repository.rs create mode 100644 bt-daemon/src/agents/schema/tests.rs delete mode 100644 bt-daemon/src/agents/usage.rs create mode 100644 bt-daemon/src/agents/usage/camel_case_usage.rs create mode 100644 bt-daemon/src/agents/usage/mod.rs create mode 100644 bt-daemon/src/agents/usage/opencode_tokens.rs create mode 100644 bt-daemon/src/agents/usage/pi_usage.rs create mode 100644 bt-daemon/src/agents/usage/provider_usage.rs create mode 100644 bt-daemon/src/agents/usage/snake_case_usage.rs create mode 100644 bt-daemon/src/agents/usage/token_metrics.rs create mode 100644 bt-daemon/src/agents/usage/usage_metrics.rs create mode 100644 bt-daemon/src/command_output/auth_diagnostic.rs create mode 100644 bt-daemon/src/transcript_mirror/claude_child_reference.rs create mode 100644 bt-daemon/src/transcript_mirror/grok_references.rs rename bt-daemon/src/{transcript_mirror.rs => transcript_mirror/mod.rs} (80%) create mode 100644 bt-daemon/src/transcript_mirror/observation.rs create mode 100644 bt-daemon/src/transcript_mirror/payload.rs create mode 100644 bt-daemon/src/transcript_mirror/reference.rs create mode 100644 bt-daemon/src/transcript_mirror/snapshot.rs create mode 100644 bt-daemon/src/translate/opencode/permission.rs create mode 100644 bt-daemon/src/translate/opencode_v2/context.rs create mode 100644 bt-daemon/src/translate/opencode_v2/tool_content.rs create mode 100644 bt-daemon/src/translate/pi/assistant_message.rs create mode 100644 bt-daemon/src/translate/pi/compaction.rs create mode 100644 bt-daemon/src/translate/pi/event.rs create mode 100644 bt-daemon/src/translate/tool/skill_load.rs create mode 100644 bt-daemon/src/wire/auth_selection.rs create mode 100644 bt-daemon/src/wire/auth_source.rs create mode 100644 bt-daemon/src/wire/backend_auth.rs create mode 100644 bt-daemon/src/wire/capture_context.rs create mode 100644 bt-daemon/src/wire/envelope_tests.rs create mode 100644 bt-daemon/src/wire/flush_mode.rs create mode 100644 bt-daemon/src/wire/process_identity.rs create mode 100644 bt-daemon/src/wire/redacted_envelope.rs create mode 100644 bt-daemon/src/wire/session_config.rs create mode 100644 bt-daemon/src/wire/session_route.rs create mode 100644 bt-daemon/src/wire/trace_destination.rs create mode 100644 docs/architecture/dto-ownership/README.md create mode 100644 docs/architecture/dto-ownership/agent-config.md create mode 100644 docs/architecture/dto-ownership/core-runtime.md create mode 100644 docs/architecture/dto-ownership/translators.md diff --git a/AGENTS.md b/AGENTS.md index 7e83ef3c..32b6cc20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,13 @@ that flexibility; do not use an opaque JSON fallback for a known schema merely to avoid modeling it. Preserve native format variants and unknown extensions explicitly when introducing shared types. +Put shared schema interpretation, validated lookup, lossless edits, and common +projections on the type that owns those rules. Keep filesystem, credential, +process, and event-ordering policy in the services that coordinate them. Organize +shared schemas around one primary owner per file, with small private companion +types alongside that owner. Keep single-use transport shapes data-only when +methods would merely duplicate field access. + Install the pinned tools with [mise](https://mise.jdx.dev). `mise install` reads `.tool-versions` and `mise.toml`, then runs `make install-deps`: diff --git a/bt-daemon/src/agents/antigravity/schema/mod.rs b/bt-daemon/src/agents/antigravity/schema/mod.rs new file mode 100644 index 00000000..c4987942 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/mod.rs @@ -0,0 +1,27 @@ +//! Antigravity native records shared by live translation and transcript import. +use serde::Deserialize; + +mod tool_call; +mod tool_calls; +mod transcript_record; + +pub(crate) use tool_call::ToolCall; +pub(crate) use tool_calls::ToolCalls; +pub(crate) use transcript_record::TranscriptRecord; + +pub(crate) fn optional_integer<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Integer { + Number(i64), + Text(String), + } + Option::::deserialize(deserializer)? + .map(|value| match value { + Integer::Number(value) => Ok(value), + Integer::Text(value) => value.parse().map_err(serde::de::Error::custom), + }) + .transpose() +} diff --git a/bt-daemon/src/agents/antigravity/schema/tool_call.rs b/bt-daemon/src/agents/antigravity/schema/tool_call.rs new file mode 100644 index 00000000..ee178fb6 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/tool_call.rs @@ -0,0 +1,26 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct ToolCall { + #[serde(default, alias = "tool_name", alias = "toolName")] + pub name: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "arguments", + alias = "input", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub args: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "result", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub output: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} diff --git a/bt-daemon/src/agents/antigravity/schema/tool_calls.rs b/bt-daemon/src/agents/antigravity/schema/tool_calls.rs new file mode 100644 index 00000000..f7961339 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/tool_calls.rs @@ -0,0 +1,17 @@ +use super::ToolCall; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ToolCalls { + Many(Vec), + One(ToolCall), +} +impl ToolCalls { + pub fn iter(&self) -> std::slice::Iter<'_, ToolCall> { + match self { + Self::Many(calls) => calls.iter(), + Self::One(call) => std::slice::from_ref(call).iter(), + } + } +} diff --git a/bt-daemon/src/agents/antigravity/schema.rs b/bt-daemon/src/agents/antigravity/schema/transcript_record.rs similarity index 59% rename from bt-daemon/src/agents/antigravity/schema.rs rename to bt-daemon/src/agents/antigravity/schema/transcript_record.rs index 115993c7..37f6fb63 100644 --- a/bt-daemon/src/agents/antigravity/schema.rs +++ b/bt-daemon/src/agents/antigravity/schema/transcript_record.rs @@ -1,4 +1,4 @@ -//! Antigravity native records shared by live translation and transcript import. +use super::{optional_integer, ToolCalls}; use crate::agents::usage::ProviderUsage; use crate::json::Extensions; use serde::{Deserialize, Serialize}; @@ -46,59 +46,29 @@ pub(crate) struct TranscriptRecord { pub extra: Extensions, } -pub(crate) fn optional_integer<'de, D: serde::Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - #[derive(Deserialize)] - #[serde(untagged)] - enum Integer { - Number(i64), - Text(String), +impl TranscriptRecord { + pub fn normalized_kind(&self) -> &str { + self.kind + .strip_prefix("CORTEX_STEP_TYPE_") + .unwrap_or(&self.kind) } - Option::::deserialize(deserializer)? - .map(|value| match value { - Integer::Number(value) => Ok(value), - Integer::Text(value) => value.parse().map_err(serde::de::Error::custom), - }) - .transpose() -} -#[derive(Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ToolCalls { - Many(Vec), - One(ToolCall), -} -impl ToolCalls { - pub fn iter(&self) -> std::slice::Iter<'_, ToolCall> { - match self { - Self::Many(calls) => calls.iter(), - Self::One(call) => std::slice::from_ref(call).iter(), - } + /// Native formats use three alternative content fields. Explicit null is + /// still content and must not accidentally expose a lower-priority field. + pub fn message_content(&self) -> Value { + self.content + .as_ref() + .or(self.message.as_ref()) + .or(self.text.as_ref()) + .cloned() + .unwrap_or(Value::Null) } -} -#[derive(Clone, Serialize, Deserialize)] -pub(crate) struct ToolCall { - #[serde(default, alias = "tool_name", alias = "toolName")] - pub name: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - alias = "arguments", - alias = "input", - deserialize_with = "crate::agents::schema::deserialize_present" - )] - pub args: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - alias = "result", - deserialize_with = "crate::agents::schema::deserialize_present" - )] - pub output: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, + pub fn created_at_ms(&self) -> Option { + chrono::DateTime::parse_from_rfc3339(self.created_at.as_deref()?) + .ok() + .map(|timestamp| timestamp.timestamp_millis()) + } } #[cfg(test)] diff --git a/bt-daemon/src/agents/schema.rs b/bt-daemon/src/agents/schema.rs deleted file mode 100644 index 7e554edc..00000000 --- a/bt-daemon/src/agents/schema.rs +++ /dev/null @@ -1,264 +0,0 @@ -//! Schemas shared by capture, setup, managed runs, and transcript import. -//! -//! Unknown extension fields are preserved when editing an agent-owned file. -//! Known fields are decoded here and used as concrete Rust values internally. -use crate::json::Field; -use serde::{Deserialize, Serialize}; -use serde_json::{Map, Value}; -use std::collections::BTreeMap; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub(crate) struct HookFile { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub version: Field, - pub hooks: BTreeMap>, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub(crate) struct HookGroup { - pub hooks: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub matcher: Option, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CommandHook { - #[serde(rename = "type")] - pub kind: String, - pub command: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub command_windows: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub args: Option>, - #[serde(rename = "async", skip_serializing_if = "Option::is_none")] - pub asynchronous: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub status_message: Option, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -pub(crate) struct OpenCodeConfig { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub model: Field, - #[serde( - default, - skip_serializing_if = "Option::is_none", - deserialize_with = "deserialize_present" - )] - pub plugin: Option>, - #[serde(flatten)] - pub extra: Map, -} - -/// OpenCode also accepts plugin tuples with provider-specific options. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum OpenCodePlugin { - Package(String), - Configured((String, Value)), -} -impl OpenCodePlugin { - pub fn package(&self) -> Option<&str> { - match self { - Self::Package(package) => Some(package), - Self::Configured(_) => None, - } - } -} - -#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -pub(crate) struct CursorHooks { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub version: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - deserialize_with = "deserialize_present" - )] - pub hooks: Option>, - #[serde(flatten)] - pub extra: Map, -} - -/// Unrecognized native hook definitions belong to the user, and survive edits. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum CursorHookEntries { - Entries(Vec), - Other(Value), -} -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum CursorHookEntry { - Command(CursorCommandHook), - Other(Value), -} -impl CursorHookEntry { - pub fn command(&self) -> Option<&str> { - match self { - Self::Command(hook) => Some(&hook.command), - Self::Other(_) => None, - } - } -} -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CursorCommandHook { - pub command: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub fail_closed: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matcher: Option, - #[serde(flatten)] - pub extra: Map, -} -impl CursorCommandHook { - pub fn capture(command: String, matcher: Option) -> Self { - Self { - command, - timeout: Some(10), - fail_closed: Some(false), - matcher, - extra: Map::new(), - } - } -} - -/// The manifest identity fields used by setup and capture version detection. -#[derive(Debug, Deserialize)] -pub(crate) struct PluginManifest { - pub name: Option, - pub version: Option, - pub repository: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(untagged)] -pub(crate) enum Repository { - Url(String), - Package { - #[serde(rename = "type")] - _kind: Option, - #[serde(rename = "url")] - _url: String, - }, -} -impl Repository { - pub fn url(&self) -> Option<&str> { - match self { - Self::Url(url) => Some(url), - Self::Package { .. } => None, - } - } -} - -/// Preserve explicit null for opaque JSON fields while a missing field remains -/// None. Used only when native null has different semantics from absence. -pub(crate) fn deserialize_present<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - T::deserialize(deserializer).map(Some) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn hook_file_round_trips_extensions_and_rejects_malformed_commands() { - let raw = json!({"future": true, "hooks": {"Stop": [{ - "matcher": "*", "futureGroup": [1], "hooks": [{ - "type": "command", "command": "bt trace hook", "commandWindows": "bt.exe trace hook", - "futureHook": {"enabled": true} - }] - }]}}); - let parsed: HookFile = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - assert!(serde_json::from_value::>(json!({ - "hooks": {"Stop": [{"hooks": [{"type":"command","command":42}]}]} - })) - .is_err()); - } - - #[test] - fn opencode_config_preserves_configured_plugins_and_extensions() { - let raw = - json!({"plugin": ["other", ["custom", {"setting": true}]], "model": "vendor/model"}); - let mut config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); - config - .plugin - .as_mut() - .unwrap() - .push(OpenCodePlugin::Package("tracing".into())); - let encoded = serde_json::to_value(config).unwrap(); - assert_eq!(encoded["plugin"][1], raw["plugin"][1]); - assert_eq!(encoded["model"], raw["model"]); - assert!(serde_json::from_value::(json!({"plugin": "invalid"})).is_err()); - } - - #[test] - fn cursor_preserves_unrecognized_user_hooks_when_adding_capture() { - let raw = json!({"version":1,"hooks":{"stop":[{"command":42},{"type":"future","data":true}]},"future":true}); - let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); - let CursorHookEntries::Entries(entries) = - config.hooks.as_mut().unwrap().get_mut("stop").unwrap() - else { - panic!() - }; - entries.push(CursorHookEntry::Command(CursorCommandHook::capture( - "bt trace hook".into(), - None, - ))); - let encoded = serde_json::to_value(config).unwrap(); - assert_eq!(encoded["hooks"]["stop"][0], raw["hooks"]["stop"][0]); - assert_eq!(encoded["hooks"]["stop"][1], raw["hooks"]["stop"][1]); - assert_eq!(encoded["future"], true); - } - - #[test] - fn known_config_fields_are_typed_without_normalizing_missing_or_null() { - for raw in [ - serde_json::json!({"hooks":{}}), - serde_json::json!({"hooks":{},"version":null}), - serde_json::json!({"hooks":{},"version":1}), - ] { - let file: HookFile = serde_json::from_value(raw.clone()).unwrap(); - assert!(!file.extra.contains_key("version")); - assert_eq!(serde_json::to_value(file).unwrap(), raw); - } - for raw in [ - serde_json::json!({}), - serde_json::json!({"model":null}), - serde_json::json!({"model":"vendor/model"}), - ] { - let config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); - assert!(!config.extra.contains_key("model")); - assert_eq!(serde_json::to_value(config).unwrap(), raw); - } - assert!(serde_json::from_value::(serde_json::json!({"model":42})).is_err()); - } - - #[test] - fn manifests_accept_both_plugin_and_npm_repository_shapes() { - for repository in [ - json!("https://github.com/org/repo"), - json!({"type":"git","url":"git+https://github.com/org/repo.git"}), - ] { - let manifest: PluginManifest = serde_json::from_value( - json!({"name":"plugin","version":"1.2.3","repository":repository}), - ) - .unwrap(); - assert_eq!(manifest.version.as_deref(), Some("1.2.3")); - } - } -} diff --git a/bt-daemon/src/agents/schema/command_hook.rs b/bt-daemon/src/agents/schema/command_hook.rs new file mode 100644 index 00000000..d5cf7ccd --- /dev/null +++ b/bt-daemon/src/agents/schema/command_hook.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CommandHook { + #[serde(rename = "type")] + pub kind: String, + pub command: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub command_windows: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub args: Option>, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub asynchronous: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub status_message: Option, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/cursor_command_hook.rs b/bt-daemon/src/agents/schema/cursor_command_hook.rs new file mode 100644 index 00000000..1e591329 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_command_hook.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CursorCommandHook { + pub command: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub fail_closed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub matcher: Option, + #[serde(flatten)] + pub extra: Map, +} +impl CursorCommandHook { + pub fn capture(command: String, matcher: Option) -> Self { + Self { + command, + timeout: Some(10), + fail_closed: Some(false), + matcher, + extra: Map::new(), + } + } +} diff --git a/bt-daemon/src/agents/schema/cursor_hook_entries.rs b/bt-daemon/src/agents/schema/cursor_hook_entries.rs new file mode 100644 index 00000000..4c718e21 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hook_entries.rs @@ -0,0 +1,11 @@ +use super::CursorHookEntry; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Unrecognized native hook definitions belong to the user, and survive edits. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum CursorHookEntries { + Entries(Vec), + Other(Value), +} diff --git a/bt-daemon/src/agents/schema/cursor_hook_entry.rs b/bt-daemon/src/agents/schema/cursor_hook_entry.rs new file mode 100644 index 00000000..8e06dc53 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hook_entry.rs @@ -0,0 +1,18 @@ +use super::CursorCommandHook; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum CursorHookEntry { + Command(CursorCommandHook), + Other(Value), +} +impl CursorHookEntry { + pub fn command(&self) -> Option<&str> { + match self { + Self::Command(hook) => Some(&hook.command), + Self::Other(_) => None, + } + } +} diff --git a/bt-daemon/src/agents/schema/cursor_hooks.rs b/bt-daemon/src/agents/schema/cursor_hooks.rs new file mode 100644 index 00000000..557c641d --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hooks.rs @@ -0,0 +1,68 @@ +use super::{deserialize_present, CursorCommandHook, CursorHookEntries, CursorHookEntry}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub(crate) struct CursorHooks { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_present" + )] + pub hooks: Option>, + #[serde(flatten)] + pub extra: Map, +} + +impl CursorHooks { + /// Compare the complete known registration, including timeout and matcher. + pub fn contains_registration(&self, event: &str, expected: &CursorCommandHook) -> bool { + matches!(self.hooks.as_ref().and_then(|hooks| hooks.get(event)), Some(CursorHookEntries::Entries(entries)) + if entries.iter().any(|entry| matches!(entry, CursorHookEntry::Command(hook) if hook == expected))) + } + + /// Filter known commands without changing unknown event or entry formats. + pub fn retain_commands(&mut self, mut keep: impl FnMut(&str) -> bool) { + if let Some(hooks) = &mut self.hooks { + for entries in hooks.values_mut() { + if let CursorHookEntries::Entries(entries) = entries { + entries.retain(|entry| entry.command().is_none_or(&mut keep)); + } + } + } + } + + /// Replace one command's registrations, or remove them without creating a + /// missing hook map/event. Unknown event formats cannot be safely edited. + pub fn replace_registration( + &mut self, + event: &str, + command: &str, + replacement: Option, + ) -> anyhow::Result<()> { + if replacement.is_none() + && self + .hooks + .as_ref() + .is_none_or(|hooks| !hooks.contains_key(event)) + { + return Ok(()); + } + let entries = self + .hooks + .get_or_insert_with(Default::default) + .entry(event.to_owned()) + .or_insert_with(|| CursorHookEntries::Entries(Vec::new())); + let CursorHookEntries::Entries(entries) = entries else { + anyhow::bail!("Cursor hook event `{event}` must be an array"); + }; + entries.retain(|entry| entry.command() != Some(command)); + if let Some(replacement) = replacement { + entries.push(CursorHookEntry::Command(replacement)); + } + Ok(()) + } +} diff --git a/bt-daemon/src/agents/schema/hook_file.rs b/bt-daemon/src/agents/schema/hook_file.rs new file mode 100644 index 00000000..4aff033c --- /dev/null +++ b/bt-daemon/src/agents/schema/hook_file.rs @@ -0,0 +1,13 @@ +use crate::json::Field; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct HookFile { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub version: Field, + pub hooks: BTreeMap>, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/hook_group.rs b/bt-daemon/src/agents/schema/hook_group.rs new file mode 100644 index 00000000..256562ea --- /dev/null +++ b/bt-daemon/src/agents/schema/hook_group.rs @@ -0,0 +1,12 @@ +use super::CommandHook; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct HookGroup { + pub hooks: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub matcher: Option, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/mod.rs b/bt-daemon/src/agents/schema/mod.rs new file mode 100644 index 00000000..893948d6 --- /dev/null +++ b/bt-daemon/src/agents/schema/mod.rs @@ -0,0 +1,40 @@ +//! Schemas shared by capture, setup, managed runs, and transcript import. +//! +//! Unknown extension fields are preserved when editing an agent-owned file. +//! Known fields are decoded here and used as concrete Rust values internally. +use serde::Deserialize; + +mod command_hook; +mod cursor_command_hook; +mod cursor_hook_entries; +mod cursor_hook_entry; +mod cursor_hooks; +mod hook_file; +mod hook_group; +mod opencode_config; +mod opencode_plugin; +mod plugin_manifest; +mod repository; + +pub(crate) use command_hook::CommandHook; +pub(crate) use cursor_command_hook::CursorCommandHook; +pub(crate) use cursor_hook_entries::CursorHookEntries; +pub(crate) use cursor_hook_entry::CursorHookEntry; +pub(crate) use cursor_hooks::CursorHooks; +pub(crate) use hook_file::HookFile; +pub(crate) use hook_group::HookGroup; +pub(crate) use opencode_config::OpenCodeConfig; +pub(crate) use opencode_plugin::OpenCodePlugin; +pub(crate) use plugin_manifest::PluginManifest; +pub(crate) use repository::Repository; + +/// Preserve explicit null for opaque JSON fields while a missing field remains +/// None. Used only when native null has different semantics from absence. +pub(crate) fn deserialize_present<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) +} + +#[cfg(test)] +mod tests; diff --git a/bt-daemon/src/agents/schema/opencode_config.rs b/bt-daemon/src/agents/schema/opencode_config.rs new file mode 100644 index 00000000..400b2546 --- /dev/null +++ b/bt-daemon/src/agents/schema/opencode_config.rs @@ -0,0 +1,56 @@ +use super::{deserialize_present, OpenCodePlugin}; +use crate::json::Field; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub(crate) struct OpenCodeConfig { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub model: Field, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_present" + )] + pub(super) plugin: Option>, + #[serde(flatten)] + pub extra: Map, +} + +impl OpenCodeConfig { + pub fn find_plugin( + &self, + mut matches: impl FnMut(&OpenCodePlugin) -> bool, + ) -> Option<&OpenCodePlugin> { + self.plugin.as_ref()?.iter().find(|plugin| matches(plugin)) + } + + /// Preserve absence when removing plugins from an unconfigured document. + pub fn retain_plugins(&mut self, keep: impl FnMut(&OpenCodePlugin) -> bool) { + if let Some(plugins) = &mut self.plugin { + plugins.retain(keep); + } + } + + pub fn replace_plugin( + &mut self, + mut matches: impl FnMut(&OpenCodePlugin) -> bool, + plugin: OpenCodePlugin, + ) { + self.retain_plugins(|entry| !matches(entry)); + self.plugin.get_or_insert_with(Vec::new).push(plugin); + } + + /// Managed runs add an exact spec only once; differently configured specs + /// are left alone because their options belong to the user's invocation. + pub fn ensure_plugin(&mut self, package: String) { + if self + .find_plugin(|plugin| plugin.package() == Some(&package)) + .is_none() + { + self.plugin + .get_or_insert_with(Vec::new) + .push(OpenCodePlugin::Package(package)); + } + } +} diff --git a/bt-daemon/src/agents/schema/opencode_plugin.rs b/bt-daemon/src/agents/schema/opencode_plugin.rs new file mode 100644 index 00000000..259a38b7 --- /dev/null +++ b/bt-daemon/src/agents/schema/opencode_plugin.rs @@ -0,0 +1,31 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// OpenCode also accepts plugin tuples with provider-specific options. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum OpenCodePlugin { + Package(String), + Configured((String, Value)), +} +impl OpenCodePlugin { + pub fn package(&self) -> Option<&str> { + match self { + Self::Package(package) => Some(package), + Self::Configured(_) => None, + } + } +} + +impl OpenCodePlugin { + /// Match a plain package entry, including a version suffix. Configured + /// tuples carry caller-owned options and are deliberately not replaced. + pub fn matches_package(&self, package: &str) -> bool { + self.package().is_some_and(|entry| { + entry == package + || entry + .strip_prefix(package) + .is_some_and(|suffix| suffix.starts_with('@')) + }) + } +} diff --git a/bt-daemon/src/agents/schema/plugin_manifest.rs b/bt-daemon/src/agents/schema/plugin_manifest.rs new file mode 100644 index 00000000..7c948786 --- /dev/null +++ b/bt-daemon/src/agents/schema/plugin_manifest.rs @@ -0,0 +1,10 @@ +use super::Repository; +use serde::Deserialize; + +/// The manifest identity fields used by setup and capture version detection. +#[derive(Debug, Deserialize)] +pub(crate) struct PluginManifest { + pub name: Option, + pub version: Option, + pub repository: Option, +} diff --git a/bt-daemon/src/agents/schema/repository.rs b/bt-daemon/src/agents/schema/repository.rs new file mode 100644 index 00000000..ba39a0b7 --- /dev/null +++ b/bt-daemon/src/agents/schema/repository.rs @@ -0,0 +1,21 @@ +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub(crate) enum Repository { + Url(String), + Package { + #[serde(rename = "type")] + _kind: Option, + #[serde(rename = "url")] + _url: String, + }, +} +impl Repository { + pub fn url(&self) -> Option<&str> { + match self { + Self::Url(url) => Some(url), + Self::Package { .. } => None, + } + } +} diff --git a/bt-daemon/src/agents/schema/tests.rs b/bt-daemon/src/agents/schema/tests.rs new file mode 100644 index 00000000..7698a44f --- /dev/null +++ b/bt-daemon/src/agents/schema/tests.rs @@ -0,0 +1,134 @@ +use super::*; +use serde_json::json; + +#[test] +fn hook_file_round_trips_extensions_and_rejects_malformed_commands() { + let raw = json!({"future": true, "hooks": {"Stop": [{ + "matcher": "*", "futureGroup": [1], "hooks": [{ + "type": "command", "command": "bt trace hook", "commandWindows": "bt.exe trace hook", + "futureHook": {"enabled": true} + }] + }]}}); + let parsed: HookFile = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + assert!(serde_json::from_value::>(json!({ + "hooks": {"Stop": [{"hooks": [{"type":"command","command":42}]}]} + })) + .is_err()); +} + +#[test] +fn opencode_config_preserves_configured_plugins_and_extensions() { + let raw = json!({"plugin": ["other", ["custom", {"setting": true}]], "model": "vendor/model"}); + let mut config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); + config + .plugin + .as_mut() + .unwrap() + .push(OpenCodePlugin::Package("tracing".into())); + let encoded = serde_json::to_value(config).unwrap(); + assert_eq!(encoded["plugin"][1], raw["plugin"][1]); + assert_eq!(encoded["model"], raw["model"]); + assert!(serde_json::from_value::(json!({"plugin": "invalid"})).is_err()); +} + +#[test] +fn cursor_preserves_unrecognized_user_hooks_when_adding_capture() { + let raw = json!({"version":1,"hooks":{"stop":[{"command":42},{"type":"future","data":true}]},"future":true}); + let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); + let CursorHookEntries::Entries(entries) = + config.hooks.as_mut().unwrap().get_mut("stop").unwrap() + else { + panic!() + }; + entries.push(CursorHookEntry::Command(CursorCommandHook::capture( + "bt trace hook".into(), + None, + ))); + let encoded = serde_json::to_value(config).unwrap(); + assert_eq!(encoded["hooks"]["stop"][0], raw["hooks"]["stop"][0]); + assert_eq!(encoded["hooks"]["stop"][1], raw["hooks"]["stop"][1]); + assert_eq!(encoded["future"], true); +} + +#[test] +fn known_config_fields_are_typed_without_normalizing_missing_or_null() { + for raw in [ + serde_json::json!({"hooks":{}}), + serde_json::json!({"hooks":{},"version":null}), + serde_json::json!({"hooks":{},"version":1}), + ] { + let file: HookFile = serde_json::from_value(raw.clone()).unwrap(); + assert!(!file.extra.contains_key("version")); + assert_eq!(serde_json::to_value(file).unwrap(), raw); + } + for raw in [ + serde_json::json!({}), + serde_json::json!({"model":null}), + serde_json::json!({"model":"vendor/model"}), + ] { + let config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); + assert!(!config.extra.contains_key("model")); + assert_eq!(serde_json::to_value(config).unwrap(), raw); + } + assert!(serde_json::from_value::(serde_json::json!({"model":42})).is_err()); +} + +#[test] +fn manifests_accept_both_plugin_and_npm_repository_shapes() { + for repository in [ + json!("https://github.com/org/repo"), + json!({"type":"git","url":"git+https://github.com/org/repo.git"}), + ] { + let manifest: PluginManifest = serde_json::from_value( + json!({"name":"plugin","version":"1.2.3","repository":repository}), + ) + .unwrap(); + assert_eq!(manifest.version.as_deref(), Some("1.2.3")); + } +} + +#[test] +fn cursor_registration_edits_preserve_unknown_entries_and_absent_events() { + let mut absent = CursorHooks::default(); + absent.replace_registration("stop", "owned", None).unwrap(); + assert!(absent.hooks.is_none()); + + let raw = json!({"hooks":{"stop":[{"type":"future","payload":true},{"command":"owned"},{"command":"owned"},{"command":"foreign"}],"future":{"new":true}}}); + let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); + let expected = CursorCommandHook::capture("owned".into(), None); + config + .replace_registration("stop", "owned", Some(expected.clone())) + .unwrap(); + assert!(config.contains_registration("stop", &expected)); + config.retain_commands(|command| command != "owned"); + let before = serde_json::to_value(&config).unwrap(); + assert_eq!( + before["hooks"]["stop"], + json!([{"type":"future","payload":true},{"command":"foreign"}]) + ); + assert_eq!(before["hooks"]["future"], raw["hooks"]["future"]); + assert!(config + .replace_registration("future", "owned", Some(expected)) + .is_err()); + assert_eq!(serde_json::to_value(config).unwrap(), before); +} + +#[test] +fn opencode_plugin_edits_preserve_configured_options_and_exact_specs() { + let mut absent = OpenCodeConfig::default(); + absent.retain_plugins(|_| false); + assert!(absent.plugin.is_none()); + + let raw = json!({"plugin":[["@vendor/plugin",{"setting":null}],"@vendor/plugin@1","@vendor/plugin-other"],"model":null}); + let mut config: OpenCodeConfig = serde_json::from_value(raw).unwrap(); + config.replace_plugin( + |plugin| plugin.matches_package("@vendor/plugin"), + OpenCodePlugin::Package("@vendor/plugin@2".into()), + ); + config.ensure_plugin("@vendor/plugin@2".into()); + assert_eq!( + serde_json::to_value(config).unwrap(), + json!({"plugin":[["@vendor/plugin",{"setting":null}],"@vendor/plugin-other","@vendor/plugin@2"],"model":null}) + ); +} diff --git a/bt-daemon/src/agents/usage.rs b/bt-daemon/src/agents/usage.rs deleted file mode 100644 index 0f202535..00000000 --- a/bt-daemon/src/agents/usage.rs +++ /dev/null @@ -1,562 +0,0 @@ -//! Native usage schemas shared by agent capture, transcript parsing, and reducers. -//! -//! Agents usually normalize providers themselves. The enum identifies the wire -//! format, not a guessed provider identity: OpenAI-compatible and Anthropic -//! payloads can share field names. Only explicitly modeled usage fields become -//! metrics. Unknown extensions round-trip as opaque JSON and are never scanned. -use crate::json::Extensions; -use serde::{Deserialize, Serialize}; -use serde_json::value::RawValue; -use std::collections::BTreeMap; - -#[derive(Debug, Clone, Serialize)] -#[serde(untagged)] -pub(crate) enum ProviderUsage { - SnakeCase(Box), - CamelCase(Box), - Unknown(Extensions), -} - -impl<'de> Deserialize<'de> for ProviderUsage { - fn deserialize>(deserializer: D) -> Result { - // Inspect field names only at the decoding boundary. Optional-only - // untagged structs would otherwise accept and swallow other variants. - let raw = Box::::deserialize(deserializer)?; - let fields: BTreeMap = - serde_json::from_str(raw.get()).map_err(serde::de::Error::custom)?; - let snake = SNAKE_FIELDS.iter().any(|field| fields.contains_key(*field)); - let camel = CAMEL_FIELDS.iter().any(|field| fields.contains_key(*field)); - match (snake, camel) { - (true, false) => serde_json::from_str(raw.get()) - .map(Self::SnakeCase) - .map_err(serde::de::Error::custom), - (false, true) => serde_json::from_str(raw.get()) - .map(Self::CamelCase) - .map_err(serde::de::Error::custom), - (false, false) => serde_json::from_str(raw.get()) - .map(Self::Unknown) - .map_err(serde::de::Error::custom), - (true, true) => Err(serde::de::Error::custom( - "mixed snake_case and camelCase usage fields", - )), - } - } -} -impl ProviderUsage { - pub fn metrics(&self) -> UsageMetrics { - match self { - Self::SnakeCase(usage) => usage.metrics(), - Self::CamelCase(usage) => usage.metrics(), - Self::Unknown(_) => UsageMetrics::default(), - } - } -} - -const SNAKE_FIELDS: &[&str] = &[ - "input_tokens", - "prompt_tokens", - "output_tokens", - "completion_tokens", - "total_tokens", - "tokens", - "cached_input_tokens", - "prompt_cached_tokens", - "cache_read_tokens", - "cache_read_input_tokens", - "cache_creation_input_tokens", - "prompt_cache_creation_tokens", - "reasoning_output_tokens", - "completion_reasoning_tokens", - "reasoning_tokens", - "thinking_tokens", - "input_tokens_details", - "prompt_tokens_details", - "output_tokens_details", - "completion_tokens_details", - "cache_creation", -]; -const CAMEL_FIELDS: &[&str] = &[ - "inputTokens", - "promptTokens", - "outputTokens", - "completionTokens", - "totalTokens", - "cachedReadTokens", - "cacheReadTokens", - "cacheCreationTokens", - "reasoningTokens", - "thinkingTokens", - "apiDurationMs", - "costUsdTicks", - "modelCalls", - "modelUsage", -]; - -/// Snake-case input/output usage (Codex/OpenAI-compatible and Claude fields). -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SnakeCaseUsage { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub estimated_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct TokenDetails { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_write_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct CacheCreation { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub ephemeral_5m_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub ephemeral_1h_input_tokens: Option, -} -/// Camel-case counters emitted by Antigravity and Grok's ACP transcripts. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CamelCaseUsage { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_duration_ms: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd_ticks: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_calls: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_usage: Option>, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -/// Typed normalized metrics for the readers that historically emit floats. -#[derive(Debug, Clone, Default, Serialize)] -pub(crate) struct UsageMetrics { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub estimated_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_duration_ms: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd_ticks: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_calls: Option, -} -impl UsageMetrics { - pub fn is_empty(&self) -> bool { - [ - self.prompt_tokens, - self.completion_tokens, - self.tokens, - self.prompt_cached_tokens, - self.prompt_cache_creation_tokens, - self.completion_reasoning_tokens, - self.thinking_tokens, - self.cost, - self.estimated_cost, - self.api_duration_ms, - self.cost_usd_ticks, - self.model_calls, - ] - .iter() - .all(Option::is_none) - } - pub fn with_total(mut self) -> Self { - if self.tokens.is_none() { - self.tokens = self - .prompt_tokens - .zip(self.completion_tokens) - .map(|(p, c)| p + c); - } - self - } - pub fn observe(&mut self, other: Self) { - if other.prompt_tokens.is_some() { - self.prompt_tokens = other.prompt_tokens; - } - if other.completion_tokens.is_some() { - self.completion_tokens = other.completion_tokens; - } - if other.tokens.is_some() { - self.tokens = other.tokens; - } - if other.prompt_cached_tokens.is_some() { - self.prompt_cached_tokens = other.prompt_cached_tokens; - } - if other.prompt_cache_creation_tokens.is_some() { - self.prompt_cache_creation_tokens = other.prompt_cache_creation_tokens; - } - if other.completion_reasoning_tokens.is_some() { - self.completion_reasoning_tokens = other.completion_reasoning_tokens; - } - if other.thinking_tokens.is_some() { - self.thinking_tokens = other.thinking_tokens; - } - if other.cost.is_some() { - self.cost = other.cost; - } - if other.estimated_cost.is_some() { - self.estimated_cost = other.estimated_cost; - } - if other.api_duration_ms.is_some() { - self.api_duration_ms = other.api_duration_ms; - } - if other.cost_usd_ticks.is_some() { - self.cost_usd_ticks = other.cost_usd_ticks; - } - if other.model_calls.is_some() { - self.model_calls = other.model_calls; - } - } -} -impl SnakeCaseUsage { - pub fn metrics(&self) -> UsageMetrics { - let input_details = self.input_tokens_details.as_ref(); - let prompt_details = self.prompt_tokens_details.as_ref(); - let output_details = self.output_tokens_details.as_ref(); - let completion_details = self.completion_tokens_details.as_ref(); - UsageMetrics { - prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), - completion_tokens: self - .output_tokens - .or(self.completion_tokens) - .map(|n| n as f64), - tokens: self.total_tokens.or(self.tokens).map(|n| n as f64), - prompt_cached_tokens: self - .cached_input_tokens - .or(self.prompt_cached_tokens) - .or_else(|| input_details.and_then(|d| d.cached_tokens)) - .or_else(|| prompt_details.and_then(|d| d.cached_tokens)) - .or(self.cache_read_tokens) - .or(self.cache_read_input_tokens) - .map(|n| n as f64), - prompt_cache_creation_tokens: self - .prompt_cache_creation_tokens - .or_else(|| { - input_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) - }) - .or_else(|| { - prompt_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) - }) - .or(self.cache_creation_input_tokens) - .map(|n| n as f64), - completion_reasoning_tokens: self - .reasoning_output_tokens - .or(self.completion_reasoning_tokens) - .or(self.reasoning_tokens) - .or_else(|| output_details.and_then(|d| d.reasoning_tokens)) - .or_else(|| completion_details.and_then(|d| d.reasoning_tokens)) - .map(|n| n as f64), - thinking_tokens: self.thinking_tokens.map(|n| n as f64), - cost: self.cost, - estimated_cost: self - .cost - .or(self.estimated_cost) - .or(self.total_cost) - .or(self.cost_usd), - ..UsageMetrics::default() - } - } - pub fn is_empty(&self) -> bool { - self.metrics().is_empty() - && self.extra.is_empty() - && self.cache_creation.is_none() - && self.input_tokens_details.is_none() - && self.prompt_tokens_details.is_none() - && self.output_tokens_details.is_none() - && self.completion_tokens_details.is_none() - } -} -impl CamelCaseUsage { - pub fn metrics(&self) -> UsageMetrics { - UsageMetrics { - prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), - completion_tokens: self - .output_tokens - .or(self.completion_tokens) - .map(|n| n as f64), - tokens: self.total_tokens.map(|n| n as f64), - prompt_cached_tokens: self - .cached_read_tokens - .or(self.cache_read_tokens) - .map(|n| n as f64), - prompt_cache_creation_tokens: self.cache_creation_tokens.map(|n| n as f64), - completion_reasoning_tokens: self.reasoning_tokens.map(|n| n as f64), - thinking_tokens: self.thinking_tokens.map(|n| n as f64), - api_duration_ms: self - .api_duration_ms - .as_ref() - .and_then(serde_json::Number::as_f64), - cost_usd_ticks: self - .cost_usd_ticks - .as_ref() - .and_then(serde_json::Number::as_f64), - model_calls: self.model_calls.map(|n| n as f64), - ..UsageMetrics::default() - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -pub(crate) struct TokenMetrics { - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub tokens: Option, -} - -impl TokenMetrics { - pub(crate) fn add(&mut self, other: &Self) { - fn add(to: &mut Option, from: Option) { - if let Some(from) = from { - *to = Some(to.unwrap_or(0).saturating_add(from)); - } - } - add(&mut self.prompt_tokens, other.prompt_tokens); - add(&mut self.completion_tokens, other.completion_tokens); - add(&mut self.prompt_cached_tokens, other.prompt_cached_tokens); - add( - &mut self.prompt_cache_creation_tokens, - other.prompt_cache_creation_tokens, - ); - add( - &mut self.completion_reasoning_tokens, - other.completion_reasoning_tokens, - ); - add(&mut self.tokens, other.tokens); - } -} - -#[derive(Clone, Default, Serialize, Deserialize)] -pub(crate) struct OpenCodeTokens { - #[serde(default)] - pub input: i64, - #[serde(default)] - pub output: i64, - #[serde(default)] - pub reasoning: i64, - #[serde(default)] - pub cache: OpenCodeCacheTokens, -} -#[derive(Clone, Default, Serialize, Deserialize)] -pub(crate) struct OpenCodeCacheTokens { - #[serde(default)] - pub read: i64, - #[serde(default)] - pub write: i64, -} - -/// Pi normalizes provider usage before forwarding events to the daemon. -#[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -pub(crate) struct PiUsage { - #[serde(default)] - pub input: i64, - #[serde(default)] - pub output: i64, - // Pi reports `reasoning` as a subset of `output`, and only for providers - // that expose the breakdown. - #[serde(default)] - pub reasoning: Option, - #[serde(default)] - pub cache_read: i64, - // `cacheWrite1h` is the subset of `cacheWrite` written with 1h retention. - #[serde(default)] - pub cache_write: i64, - #[serde(default)] - pub cache_write1h: Option, - #[serde(default)] - pub total_tokens: Option, - #[serde(default)] - pub cost: Option, -} - -#[derive(Default, Deserialize, Serialize)] -pub(crate) struct PiCost { - #[serde(default)] - pub total: Option, -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn provider_usage_selects_the_wire_format_and_round_trips_extensions() { - for (raw, camel) in [ - ( - json!({"input_tokens":10,"output_tokens":2,"future":{"deep":[true,null]}}), - false, - ), - ( - json!({"inputTokens":10,"outputTokens":2,"future":{"deep":[true,null]}}), - true, - ), - (json!({"inputTokens":10,"outputTokens":2,"cost":0.25}), true), - ( - json!({"prompt_tokens":10,"completion_tokens":2,"future":{"deep":[true,null]}}), - false, - ), - ] { - let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(matches!(&usage, ProviderUsage::CamelCase(_)), camel); - assert_eq!(usage.metrics().prompt_tokens, Some(10.0)); - assert_eq!(usage.metrics().completion_tokens, Some(2.0)); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - } - } - - #[test] - fn unknown_usage_is_opaque_and_malformed_known_usage_is_an_error() { - let raw = json!({"vendorExtension":{"inputTokens":999}}); - let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); - assert!(matches!(&usage, ProviderUsage::Unknown(_))); - assert!(usage.metrics().is_empty()); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - for raw in [ - json!({"inputTokens":"10"}), - json!({"output_tokens":{}}), - json!({"input_tokens":1,"outputTokens":2}), - json!({"input_tokens":-1}), - ] { - assert!(serde_json::from_value::(raw).is_err()); - } - } - - #[test] - fn codex_alias_precedence_details_and_cost_remain_typed() { - let usage: SnakeCaseUsage = serde_json::from_value(json!({ - "input_tokens":10,"prompt_tokens":999,"output_tokens":2, - "cached_input_tokens":3,"input_tokens_details":{"cached_tokens":999,"cache_write_tokens":4}, - "output_tokens_details":{"reasoning_tokens":1},"cost":0.25,"total_cost":99 - })).unwrap(); - let metrics = usage.metrics().with_total(); - assert_eq!(metrics.prompt_tokens, Some(10.0)); - assert_eq!(metrics.tokens, Some(12.0)); - assert_eq!(metrics.prompt_cached_tokens, Some(3.0)); - assert_eq!(metrics.prompt_cache_creation_tokens, Some(4.0)); - assert_eq!(metrics.completion_reasoning_tokens, Some(1.0)); - assert_eq!(metrics.estimated_cost, Some(0.25)); - } - - #[test] - fn grok_per_model_usage_is_typed_and_preserves_partial_counts() { - let raw = - json!({"inputTokens":10,"modelUsage":{"model-a":{"outputTokens":2,"future":null}}}); - let usage: CamelCaseUsage = serde_json::from_value(raw.clone()).unwrap(); - let model = &usage.model_usage.as_ref().unwrap()["model-a"]; - assert_eq!(model.input_tokens, None); - assert_eq!(model.output_tokens, Some(2)); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - } - - #[test] - fn both_opencode_protocols_keep_the_same_cache_counter_shape() { - let tokens: OpenCodeTokens = serde_json::from_value(json!({ - "input":5,"output":2,"reasoning":1,"cache":{"read":3,"write":4} - })) - .unwrap(); - assert_eq!(tokens.input + tokens.cache.read + tokens.cache.write, 12); - assert_eq!(tokens.output, 2); - assert_eq!(tokens.reasoning, 1); - } -} diff --git a/bt-daemon/src/agents/usage/camel_case_usage.rs b/bt-daemon/src/agents/usage/camel_case_usage.rs new file mode 100644 index 00000000..dfc1146b --- /dev/null +++ b/bt-daemon/src/agents/usage/camel_case_usage.rs @@ -0,0 +1,69 @@ +use super::UsageMetrics; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Camel-case counters emitted by Antigravity and Grok's ACP transcripts. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CamelCaseUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd_ticks: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_calls: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_usage: Option>, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +impl CamelCaseUsage { + pub fn metrics(&self) -> UsageMetrics { + UsageMetrics { + prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), + completion_tokens: self + .output_tokens + .or(self.completion_tokens) + .map(|n| n as f64), + tokens: self.total_tokens.map(|n| n as f64), + prompt_cached_tokens: self + .cached_read_tokens + .or(self.cache_read_tokens) + .map(|n| n as f64), + prompt_cache_creation_tokens: self.cache_creation_tokens.map(|n| n as f64), + completion_reasoning_tokens: self.reasoning_tokens.map(|n| n as f64), + thinking_tokens: self.thinking_tokens.map(|n| n as f64), + api_duration_ms: self + .api_duration_ms + .as_ref() + .and_then(serde_json::Number::as_f64), + cost_usd_ticks: self + .cost_usd_ticks + .as_ref() + .and_then(serde_json::Number::as_f64), + model_calls: self.model_calls.map(|n| n as f64), + ..UsageMetrics::default() + } + } +} diff --git a/bt-daemon/src/agents/usage/mod.rs b/bt-daemon/src/agents/usage/mod.rs new file mode 100644 index 00000000..2066b0c6 --- /dev/null +++ b/bt-daemon/src/agents/usage/mod.rs @@ -0,0 +1,108 @@ +//! Native usage schemas shared by agent capture, transcript parsing, and reducers. +//! +//! Agents usually normalize providers themselves. The enum identifies the wire +//! format, not a guessed provider identity: OpenAI-compatible and Anthropic +//! payloads can share field names. Only explicitly modeled usage fields become +//! metrics. Unknown extensions round-trip as opaque JSON and are never scanned. + +mod camel_case_usage; +mod opencode_tokens; +mod pi_usage; +mod provider_usage; +mod snake_case_usage; +mod token_metrics; +mod usage_metrics; + +pub(crate) use camel_case_usage::CamelCaseUsage; +pub(crate) use opencode_tokens::OpenCodeTokens; +pub(crate) use pi_usage::PiUsage; +pub(crate) use provider_usage::ProviderUsage; +pub(crate) use snake_case_usage::SnakeCaseUsage; +pub(crate) use token_metrics::TokenMetrics; +pub(crate) use usage_metrics::UsageMetrics; + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn provider_usage_selects_the_wire_format_and_round_trips_extensions() { + for (raw, camel) in [ + ( + json!({"input_tokens":10,"output_tokens":2,"future":{"deep":[true,null]}}), + false, + ), + ( + json!({"inputTokens":10,"outputTokens":2,"future":{"deep":[true,null]}}), + true, + ), + (json!({"inputTokens":10,"outputTokens":2,"cost":0.25}), true), + ( + json!({"prompt_tokens":10,"completion_tokens":2,"future":{"deep":[true,null]}}), + false, + ), + ] { + let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(matches!(&usage, ProviderUsage::CamelCase(_)), camel); + assert_eq!(usage.metrics().prompt_tokens, Some(10.0)); + assert_eq!(usage.metrics().completion_tokens, Some(2.0)); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + } + } + + #[test] + fn unknown_usage_is_opaque_and_malformed_known_usage_is_an_error() { + let raw = json!({"vendorExtension":{"inputTokens":999}}); + let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); + assert!(matches!(&usage, ProviderUsage::Unknown(_))); + assert!(usage.metrics().is_empty()); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + for raw in [ + json!({"inputTokens":"10"}), + json!({"output_tokens":{}}), + json!({"input_tokens":1,"outputTokens":2}), + json!({"input_tokens":-1}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } + + #[test] + fn codex_alias_precedence_details_and_cost_remain_typed() { + let usage: SnakeCaseUsage = serde_json::from_value(json!({ + "input_tokens":10,"prompt_tokens":999,"output_tokens":2, + "cached_input_tokens":3,"input_tokens_details":{"cached_tokens":999,"cache_write_tokens":4}, + "output_tokens_details":{"reasoning_tokens":1},"cost":0.25,"total_cost":99 + })).unwrap(); + let metrics = usage.metrics().with_total(); + assert_eq!(metrics.prompt_tokens, Some(10.0)); + assert_eq!(metrics.tokens, Some(12.0)); + assert_eq!(metrics.prompt_cached_tokens, Some(3.0)); + assert_eq!(metrics.prompt_cache_creation_tokens, Some(4.0)); + assert_eq!(metrics.completion_reasoning_tokens, Some(1.0)); + assert_eq!(metrics.estimated_cost, Some(0.25)); + } + + #[test] + fn grok_per_model_usage_is_typed_and_preserves_partial_counts() { + let raw = + json!({"inputTokens":10,"modelUsage":{"model-a":{"outputTokens":2,"future":null}}}); + let usage: CamelCaseUsage = serde_json::from_value(raw.clone()).unwrap(); + let model = &usage.model_usage.as_ref().unwrap()["model-a"]; + assert_eq!(model.input_tokens, None); + assert_eq!(model.output_tokens, Some(2)); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + } + + #[test] + fn both_opencode_protocols_keep_the_same_cache_counter_shape() { + let tokens: OpenCodeTokens = serde_json::from_value(json!({ + "input":5,"output":2,"reasoning":1,"cache":{"read":3,"write":4} + })) + .unwrap(); + assert_eq!(tokens.input + tokens.cache.read + tokens.cache.write, 12); + assert_eq!(tokens.output, 2); + assert_eq!(tokens.reasoning, 1); + } +} diff --git a/bt-daemon/src/agents/usage/opencode_tokens.rs b/bt-daemon/src/agents/usage/opencode_tokens.rs new file mode 100644 index 00000000..e3e4cbb5 --- /dev/null +++ b/bt-daemon/src/agents/usage/opencode_tokens.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Serialize, Deserialize)] +pub(crate) struct OpenCodeTokens { + #[serde(default)] + pub input: i64, + #[serde(default)] + pub output: i64, + #[serde(default)] + pub reasoning: i64, + #[serde(default)] + pub cache: OpenCodeCacheTokens, +} + +impl OpenCodeTokens { + /// OpenCode reports uncached input separately from cache reads and writes. + pub fn prompt_tokens(&self) -> i64 { + self.input + self.cache.read + self.cache.write + } + + pub fn total_tokens(&self) -> i64 { + self.prompt_tokens() + self.output + self.reasoning + } +} + +#[derive(Clone, Default, Serialize, Deserialize)] +pub(crate) struct OpenCodeCacheTokens { + #[serde(default)] + pub read: i64, + #[serde(default)] + pub write: i64, +} diff --git a/bt-daemon/src/agents/usage/pi_usage.rs b/bt-daemon/src/agents/usage/pi_usage.rs new file mode 100644 index 00000000..c14a6d5c --- /dev/null +++ b/bt-daemon/src/agents/usage/pi_usage.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +/// Pi normalizes provider usage before forwarding events to the daemon. +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(crate) struct PiUsage { + #[serde(default)] + pub input: i64, + #[serde(default)] + pub output: i64, + // Pi reports `reasoning` as a subset of `output`, and only for providers + // that expose the breakdown. + #[serde(default)] + pub reasoning: Option, + #[serde(default)] + pub cache_read: i64, + // `cacheWrite1h` is the subset of `cacheWrite` written with 1h retention. + #[serde(default)] + pub cache_write: i64, + #[serde(default)] + pub cache_write1h: Option, + #[serde(default)] + pub total_tokens: Option, + #[serde(default)] + pub cost: Option, +} + +#[derive(Default, Deserialize, Serialize)] +pub(crate) struct PiCost { + #[serde(default)] + pub total: Option, +} diff --git a/bt-daemon/src/agents/usage/provider_usage.rs b/bt-daemon/src/agents/usage/provider_usage.rs new file mode 100644 index 00000000..8a9d4330 --- /dev/null +++ b/bt-daemon/src/agents/usage/provider_usage.rs @@ -0,0 +1,88 @@ +use super::{CamelCaseUsage, SnakeCaseUsage, UsageMetrics}; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, Serialize)] +#[serde(untagged)] +pub(crate) enum ProviderUsage { + SnakeCase(Box), + CamelCase(Box), + Unknown(Extensions), +} + +impl<'de> Deserialize<'de> for ProviderUsage { + fn deserialize>(deserializer: D) -> Result { + // Inspect field names only at the decoding boundary. Optional-only + // untagged structs would otherwise accept and swallow other variants. + let raw = Box::::deserialize(deserializer)?; + let fields: BTreeMap = + serde_json::from_str(raw.get()).map_err(serde::de::Error::custom)?; + let snake = SNAKE_FIELDS.iter().any(|field| fields.contains_key(*field)); + let camel = CAMEL_FIELDS.iter().any(|field| fields.contains_key(*field)); + match (snake, camel) { + (true, false) => serde_json::from_str(raw.get()) + .map(Self::SnakeCase) + .map_err(serde::de::Error::custom), + (false, true) => serde_json::from_str(raw.get()) + .map(Self::CamelCase) + .map_err(serde::de::Error::custom), + (false, false) => serde_json::from_str(raw.get()) + .map(Self::Unknown) + .map_err(serde::de::Error::custom), + (true, true) => Err(serde::de::Error::custom( + "mixed snake_case and camelCase usage fields", + )), + } + } +} +impl ProviderUsage { + pub fn metrics(&self) -> UsageMetrics { + match self { + Self::SnakeCase(usage) => usage.metrics(), + Self::CamelCase(usage) => usage.metrics(), + Self::Unknown(_) => UsageMetrics::default(), + } + } +} + +const SNAKE_FIELDS: &[&str] = &[ + "input_tokens", + "prompt_tokens", + "output_tokens", + "completion_tokens", + "total_tokens", + "tokens", + "cached_input_tokens", + "prompt_cached_tokens", + "cache_read_tokens", + "cache_read_input_tokens", + "cache_creation_input_tokens", + "prompt_cache_creation_tokens", + "reasoning_output_tokens", + "completion_reasoning_tokens", + "reasoning_tokens", + "thinking_tokens", + "input_tokens_details", + "prompt_tokens_details", + "output_tokens_details", + "completion_tokens_details", + "cache_creation", +]; +const CAMEL_FIELDS: &[&str] = &[ + "inputTokens", + "promptTokens", + "outputTokens", + "completionTokens", + "totalTokens", + "cachedReadTokens", + "cacheReadTokens", + "cacheCreationTokens", + "reasoningTokens", + "thinkingTokens", + "apiDurationMs", + "costUsdTicks", + "modelCalls", + "modelUsage", +]; diff --git a/bt-daemon/src/agents/usage/snake_case_usage.rs b/bt-daemon/src/agents/usage/snake_case_usage.rs new file mode 100644 index 00000000..5d6d67ad --- /dev/null +++ b/bt-daemon/src/agents/usage/snake_case_usage.rs @@ -0,0 +1,138 @@ +use super::UsageMetrics; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +/// Snake-case input/output usage (Codex/OpenAI-compatible and Claude fields). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SnakeCaseUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub estimated_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct TokenDetails { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct CacheCreation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ephemeral_5m_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ephemeral_1h_input_tokens: Option, +} +impl SnakeCaseUsage { + pub fn metrics(&self) -> UsageMetrics { + let input_details = self.input_tokens_details.as_ref(); + let prompt_details = self.prompt_tokens_details.as_ref(); + let output_details = self.output_tokens_details.as_ref(); + let completion_details = self.completion_tokens_details.as_ref(); + UsageMetrics { + prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), + completion_tokens: self + .output_tokens + .or(self.completion_tokens) + .map(|n| n as f64), + tokens: self.total_tokens.or(self.tokens).map(|n| n as f64), + prompt_cached_tokens: self + .cached_input_tokens + .or(self.prompt_cached_tokens) + .or_else(|| input_details.and_then(|d| d.cached_tokens)) + .or_else(|| prompt_details.and_then(|d| d.cached_tokens)) + .or(self.cache_read_tokens) + .or(self.cache_read_input_tokens) + .map(|n| n as f64), + prompt_cache_creation_tokens: self + .prompt_cache_creation_tokens + .or_else(|| { + input_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) + }) + .or_else(|| { + prompt_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) + }) + .or(self.cache_creation_input_tokens) + .map(|n| n as f64), + completion_reasoning_tokens: self + .reasoning_output_tokens + .or(self.completion_reasoning_tokens) + .or(self.reasoning_tokens) + .or_else(|| output_details.and_then(|d| d.reasoning_tokens)) + .or_else(|| completion_details.and_then(|d| d.reasoning_tokens)) + .map(|n| n as f64), + thinking_tokens: self.thinking_tokens.map(|n| n as f64), + cost: self.cost, + estimated_cost: self + .cost + .or(self.estimated_cost) + .or(self.total_cost) + .or(self.cost_usd), + ..UsageMetrics::default() + } + } + pub fn is_empty(&self) -> bool { + self.metrics().is_empty() + && self.extra.is_empty() + && self.cache_creation.is_none() + && self.input_tokens_details.is_none() + && self.prompt_tokens_details.is_none() + && self.output_tokens_details.is_none() + && self.completion_tokens_details.is_none() + } +} diff --git a/bt-daemon/src/agents/usage/token_metrics.rs b/bt-daemon/src/agents/usage/token_metrics.rs new file mode 100644 index 00000000..05bd2e30 --- /dev/null +++ b/bt-daemon/src/agents/usage/token_metrics.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub(crate) struct TokenMetrics { + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +impl TokenMetrics { + pub(crate) fn add(&mut self, other: &Self) { + fn add(to: &mut Option, from: Option) { + if let Some(from) = from { + *to = Some(to.unwrap_or(0).saturating_add(from)); + } + } + add(&mut self.prompt_tokens, other.prompt_tokens); + add(&mut self.completion_tokens, other.completion_tokens); + add(&mut self.prompt_cached_tokens, other.prompt_cached_tokens); + add( + &mut self.prompt_cache_creation_tokens, + other.prompt_cache_creation_tokens, + ); + add( + &mut self.completion_reasoning_tokens, + other.completion_reasoning_tokens, + ); + add(&mut self.tokens, other.tokens); + } +} diff --git a/bt-daemon/src/agents/usage/usage_metrics.rs b/bt-daemon/src/agents/usage/usage_metrics.rs new file mode 100644 index 00000000..c4d392bc --- /dev/null +++ b/bt-daemon/src/agents/usage/usage_metrics.rs @@ -0,0 +1,97 @@ +use serde::Serialize; + +/// Typed normalized metrics for the readers that historically emit floats. +#[derive(Debug, Clone, Default, Serialize)] +pub(crate) struct UsageMetrics { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub estimated_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd_ticks: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_calls: Option, +} +impl UsageMetrics { + pub fn is_empty(&self) -> bool { + [ + self.prompt_tokens, + self.completion_tokens, + self.tokens, + self.prompt_cached_tokens, + self.prompt_cache_creation_tokens, + self.completion_reasoning_tokens, + self.thinking_tokens, + self.cost, + self.estimated_cost, + self.api_duration_ms, + self.cost_usd_ticks, + self.model_calls, + ] + .iter() + .all(Option::is_none) + } + pub fn with_total(mut self) -> Self { + if self.tokens.is_none() { + self.tokens = self + .prompt_tokens + .zip(self.completion_tokens) + .map(|(p, c)| p + c); + } + self + } + pub fn observe(&mut self, other: Self) { + if other.prompt_tokens.is_some() { + self.prompt_tokens = other.prompt_tokens; + } + if other.completion_tokens.is_some() { + self.completion_tokens = other.completion_tokens; + } + if other.tokens.is_some() { + self.tokens = other.tokens; + } + if other.prompt_cached_tokens.is_some() { + self.prompt_cached_tokens = other.prompt_cached_tokens; + } + if other.prompt_cache_creation_tokens.is_some() { + self.prompt_cache_creation_tokens = other.prompt_cache_creation_tokens; + } + if other.completion_reasoning_tokens.is_some() { + self.completion_reasoning_tokens = other.completion_reasoning_tokens; + } + if other.thinking_tokens.is_some() { + self.thinking_tokens = other.thinking_tokens; + } + if other.cost.is_some() { + self.cost = other.cost; + } + if other.estimated_cost.is_some() { + self.estimated_cost = other.estimated_cost; + } + if other.api_duration_ms.is_some() { + self.api_duration_ms = other.api_duration_ms; + } + if other.cost_usd_ticks.is_some() { + self.cost_usd_ticks = other.cost_usd_ticks; + } + if other.model_calls.is_some() { + self.model_calls = other.model_calls; + } + } +} diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index cb401e61..355280ec 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -4,6 +4,9 @@ //! the output shape to this crate so every front-end reports daemon commands //! consistently and JSON mode never falls back to human prose. +mod auth_diagnostic; +pub use auth_diagnostic::AuthDiagnostic; + use crate::wire::{SessionRoute, StatusResult, TraceDestination}; use serde::Serialize; use std::path::PathBuf; @@ -101,22 +104,6 @@ pub struct ImportSummary { pub finalized: bool, } -#[derive(Debug, Clone, Serialize)] -pub struct AuthDiagnostic { - pub status: String, - pub source: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub kind: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub profile: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub org_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at_ms: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, -} - #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum DaemonStatus { @@ -157,9 +144,7 @@ impl DaemonDiagnostic { /// The daemon answered and could not authenticate the route. pub fn auth_failed(&self) -> bool { - self.auth - .as_ref() - .is_some_and(|auth| auth.status == "error") + self.auth.as_ref().is_some_and(AuthDiagnostic::is_error) } } diff --git a/bt-daemon/src/command_output/auth_diagnostic.rs b/bt-daemon/src/command_output/auth_diagnostic.rs new file mode 100644 index 00000000..a4269929 --- /dev/null +++ b/bt-daemon/src/command_output/auth_diagnostic.rs @@ -0,0 +1,66 @@ +use crate::wire::{AuthSelection, AuthSource}; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct AuthDiagnostic { + pub status: String, + pub source: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub org_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl AuthDiagnostic { + pub(crate) fn source_label(selection: &AuthSelection) -> &'static str { + match selection.effective_source() { + AuthSource::SavedProfile => "saved_profile", + AuthSource::Environment => "environment", + AuthSource::Auto => "command_context", + } + } + + pub(crate) fn ready( + selection: AuthSelection, + org_name: Option, + expires_at_ms: Option, + ) -> Self { + Self { + status: "ready".into(), + source: Self::source_label(&selection).into(), + kind: None, + profile: selection.profile, + org_name, + expires_at_ms, + error: None, + } + } + + pub(crate) fn unconfirmed(status: &str, source: &str, error: Option) -> Self { + Self { + status: status.into(), + source: source.into(), + kind: None, + profile: None, + org_name: None, + expires_at_ms: None, + error, + } + } + + /// Authentication resolved successfully in the reporting process. + pub fn is_ready(&self) -> bool { + self.status == "ready" + } + + /// Authentication was checked and failed, rather than remaining unknown. + pub fn is_error(&self) -> bool { + self.status == "error" + } +} diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index f27facaa..a75875e4 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -437,11 +437,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & let Ok(fields) = TranscriptPayload::decode(&env.payload) else { return; }; - if fields.claude_mirrors.is_some() - || fields.mirror.is_some() - || fields.snapshot.is_some() - || fields.replay.is_some() - { + if fields.has_claude_capture() { return; } // Claude writes the subagent's ancestry alongside its transcript by the @@ -482,13 +478,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & } let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); let mut mirrors = std::collections::BTreeMap::new(); - for path in [ - fields.transcript_path.as_deref(), - fields.agent_transcript_path.as_deref(), - ] - .into_iter() - .flatten() - { + for path in fields.native_paths() { if mirrors.contains_key(path) { continue; } diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 39c63019..faa97004 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -7,7 +7,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; use crate::args::HookArgs; use crate::client::{forward_envelope, HostInfo}; -use crate::route::apply_additional_metadata; use crate::wire::{self, Envelope, SessionRoute}; use crate::{paths, settings}; @@ -287,7 +286,7 @@ async fn capture_hook( if route.destination.is_none() { anyhow::bail!("trace destination is not configured for {}", args.source); } - apply_additional_metadata(&mut route, args.additional_metadata.as_deref())?; + route.apply_additional_metadata(args.additional_metadata.as_deref())?; let mut env = build_hook_envelope(&args, route, payload, session_id, event); if let Some(context) = &managed_context { env.managed_run_id = Some(context.managed_run_id.clone()); diff --git a/bt-daemon/src/journal.rs b/bt-daemon/src/journal.rs index 8ddcde93..01211698 100644 --- a/bt-daemon/src/journal.rs +++ b/bt-daemon/src/journal.rs @@ -5,7 +5,7 @@ //! Managed-run acceptance records remain separate so flush can discover //! pipelines after the daemon that accepted them has restarted or idle-exited. -use crate::wire::{BackendAuth, Envelope, RedactedEnvelope, SessionRoute}; +use crate::wire::SessionRoute; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -187,39 +187,10 @@ pub async fn gc_old_managed_runs(data_dir: &Path, max_age: std::time::Duration) } } -/// Reconstruct a translator-usable [`Envelope`] from a redacted journal entry. -/// The live token is gone (redacted), so `auth.token` is empty — fine for -/// rebuilding translator state; the sink must be re-supplied live credentials -/// if replay needs to actually deliver. -pub fn envelope_from_redacted(r: RedactedEnvelope) -> Envelope { - let route = r.route; - let config = route.as_ref().map(|route| { - route.with_auth(BackendAuth { - token: String::new(), - api_url: None, - app_url: None, - org_name: route.auth.org_name.clone(), - org_id: None, - }) - }); - Envelope { - source: r.source, - source_version: r.source_version, - plugin_version: r.plugin_version, - session_id: r.session_id, - event: r.event, - ts_ms: r.ts_ms, - managed_run_id: r.managed_run_id, - capture: r.capture, - payload: r.payload, - route, - config, - } -} - #[cfg(test)] mod tests { use super::*; + use crate::wire::Envelope; #[test] fn pi_journaled_request_configuration_replays_unchanged() { diff --git a/bt-daemon/src/managed_run/opencode.rs b/bt-daemon/src/managed_run/opencode.rs index 26d06b8c..041059e9 100644 --- a/bt-daemon/src/managed_run/opencode.rs +++ b/bt-daemon/src/managed_run/opencode.rs @@ -1,7 +1,7 @@ //! OpenCode managed runs add the tracing plugin to inline config. use super::{Injection, ManagedRun}; -use crate::agents::schema::{OpenCodeConfig, OpenCodePlugin}; +use crate::agents::schema::OpenCodeConfig; use crate::agents::OpenCode; use crate::args::RunHookCommand; use std::ffi::OsString; @@ -74,7 +74,6 @@ fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result OpenCodeConfig::default(), }; - let plugins = config.plugin.get_or_insert_with(Vec::new); let plugin = crate::env::var("BRAINTRUST_TRACE_OPENCODE_PLUGIN_SPEC").unwrap_or_else(|| { if v2 { "@braintrust/trace-opencode" @@ -83,9 +82,7 @@ fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result { - SourceEvent::Event(Box::new(crate::journal::envelope_from_redacted(event))) - } + EventRecord::Event(event) => SourceEvent::Event(Box::new(event.into_envelope())), EventRecord::Control(control) => SourceEvent::Control(control), }; Ok(Some(SourceRecord { diff --git a/bt-daemon/src/route.rs b/bt-daemon/src/route.rs index 9b49f83d..a97365cf 100644 --- a/bt-daemon/src/route.rs +++ b/bt-daemon/src/route.rs @@ -3,47 +3,9 @@ use std::path::PathBuf; +#[cfg(test)] use crate::wire::SessionRoute; -/// Apply one invocation-local JSON metadata override to a non-secret route. -/// -/// The route is then carried unchanged through live hooks, managed runs, and -/// transcript import. Keeping validation here gives every public command the -/// same contract and prevents individual agent shims from parsing JSON. -pub(crate) fn apply_additional_metadata( - route: &mut SessionRoute, - additional_metadata: Option<&str>, -) -> anyhow::Result<()> { - let Some(metadata) = additional_metadata else { - return Ok(()); - }; - let value: serde_json::Value = serde_json::from_str(metadata) - .map_err(|e| anyhow::anyhow!("invalid --additional-metadata JSON: {e}"))?; - if !value.is_object() { - anyhow::bail!("--additional-metadata must be a JSON object"); - } - route.additional_metadata = Some(value); - Ok(()) -} - -/// Apply invocation-local root-span tags to a route. Trim whitespace and reject -/// empty tags here; the set keeps route tags unique. -pub(crate) fn apply_tags(route: &mut SessionRoute, tags: &[String]) -> anyhow::Result<()> { - if tags.is_empty() { - return Ok(()); - } - let mut normalized = std::collections::BTreeSet::new(); - for tag in tags { - let tag = tag.trim(); - if tag.is_empty() { - anyhow::bail!("--tag must not be empty"); - } - normalized.insert(tag.to_string()); - } - route.tags = normalized; - Ok(()) -} - pub(crate) fn resolve_span_plugin_paths(paths: &[PathBuf]) -> anyhow::Result> { let paths: Vec<_> = paths .iter() @@ -95,15 +57,19 @@ mod tests { additional_metadata: Some(serde_json::json!({"saved": true})), ..SessionRoute::default() }; - apply_additional_metadata(&mut route, Some(r#"{"run_id":"123"}"#)).unwrap(); + route + .apply_additional_metadata(Some(r#"{"run_id":"123"}"#)) + .unwrap(); assert_eq!( route.additional_metadata, Some(serde_json::json!({"run_id": "123"})) ); - let error = apply_additional_metadata(&mut route, Some("[]")).unwrap_err(); + let error = route.apply_additional_metadata(Some("[]")).unwrap_err(); assert!(error.to_string().contains("must be a JSON object")); - let error = apply_additional_metadata(&mut route, Some("not-json")).unwrap_err(); + let error = route + .apply_additional_metadata(Some("not-json")) + .unwrap_err(); assert!(error .to_string() .contains("invalid --additional-metadata JSON")); @@ -115,13 +81,15 @@ mod tests { tags: ["saved".into()].into_iter().collect(), ..SessionRoute::default() }; - apply_tags(&mut route, &[" ci ".into(), "ci".into(), "docs".into()]).unwrap(); + route + .apply_tags(&[" ci ".into(), "ci".into(), "docs".into()]) + .unwrap(); assert_eq!( route.tags, ["ci".into(), "docs".into()].into_iter().collect() ); - let error = apply_tags(&mut route, &[" ".into()]).unwrap_err(); + let error = route.apply_tags(&[" ".into()]).unwrap_err(); assert!(error.to_string().contains("must not be empty")); } } diff --git a/bt-daemon/src/server/claude_transcripts.rs b/bt-daemon/src/server/claude_transcripts.rs index e14f6fc1..fc7a6196 100644 --- a/bt-daemon/src/server/claude_transcripts.rs +++ b/bt-daemon/src/server/claude_transcripts.rs @@ -42,16 +42,8 @@ impl Daemon { return; }; let through = fields - .claude_mirrors - .as_ref() - .and_then(|mirrors| mirrors.get(path)) - .or_else(|| { - fields - .mirror - .as_ref() - .filter(|mirror| mirror.path.as_deref() == Some(path)) - }) - .and_then(|mirror| mirror.through); + .claude_reference(path) + .and_then(|reference| reference.through); #[derive(serde::Serialize)] struct PollPayload<'a> { transcript_path: &'a str, diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index 6aa6a6b6..381507f4 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -122,7 +122,7 @@ async fn next_evicted_event( .ok_or_else(|| anyhow::anyhow!("replay range ends inside a record"))?; anyhow::ensure!(entry.id <= through, "invalid replay end boundary"); if let EventRecord::Event(redacted) = entry.record { - let mut env = journal::envelope_from_redacted(redacted); + let mut env = redacted.into_envelope(); let Some(source) = daemon.translators.canonical_source(&env.source) else { continue; }; diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index b6e22ec4..a6b44521 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -197,7 +197,7 @@ async fn retained_references(data_dir: &std::path::Path) -> anyhow::Result) -> Vec

= HashMap::new(); if let Ok(Some(template)) = events.identity().await { - let env = journal::envelope_from_redacted(template); + let env = template.into_envelope(); daemon.remember_claude_transcripts(&env); if let Some(route) = &env.route { latest_by_route.insert( @@ -64,7 +64,7 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

{ - let mut env = journal::envelope_from_redacted(redacted); + let mut env = redacted.into_envelope(); let Some(source) = daemon.translators.canonical_source(&env.source) else { before = through; continue; diff --git a/bt-daemon/src/setup/cursor/hooks.rs b/bt-daemon/src/setup/cursor/hooks.rs index 9a4b06c8..6f96fa56 100644 --- a/bt-daemon/src/setup/cursor/hooks.rs +++ b/bt-daemon/src/setup/cursor/hooks.rs @@ -5,9 +5,7 @@ //! marked with their process identity, which later runs remove once that //! process has exited. -use crate::agents::schema::{ - CursorCommandHook, CursorHookEntries, CursorHookEntry, CursorHooks, HookFile, -}; +use crate::agents::schema::{CursorCommandHook, CursorHooks, HookFile}; #[cfg(test)] use crate::setup::common::load_object; use crate::setup::common::{edit_json, load_json, FileAccess}; @@ -125,8 +123,7 @@ fn capture_entry_is_registered(config: &CursorHooks, event: &str, command: &str) let Ok(expected) = capture_registration(event, command) else { return false; }; - matches!(config.hooks.as_ref().and_then(|hooks| hooks.get(event)), Some(CursorHookEntries::Entries(entries)) - if entries.iter().any(|entry| matches!(entry, CursorHookEntry::Command(entry) if entry == &expected))) + config.contains_registration(event, &expected) } fn powershell_encoded_command(script: &str) -> String { @@ -186,17 +183,9 @@ fn remove_stale_managed_hooks( config: &mut CursorHooks, mut process_is_alive: impl FnMut(&ProcessIdentity) -> bool, ) { - let Some(hooks) = &mut config.hooks else { - return; - }; - for entries in hooks.values_mut() { - if let CursorHookEntries::Entries(entries) = entries { - entries.retain(|entry| { - managed_process_identity(entry.command().unwrap_or_default()) - .is_none_or(|identity| process_is_alive(&identity)) - }); - } - } + config.retain_commands(|command| { + managed_process_identity(command).is_none_or(|identity| process_is_alive(&identity)) + }); } #[cfg(test)] @@ -215,36 +204,23 @@ fn apply_specs( config.version.get_or_insert(1); } if enable || config.hooks.is_some() { - let hooks = config.hooks.get_or_insert_with(Default::default); let persistent = specs == persistent_specs()?; if persistent { - for entries in hooks.values_mut() { - if let CursorHookEntries::Entries(entries) = entries { - entries.retain(|entry| !entry.command().is_some_and(is_persistent_command)); - } - } + config.retain_commands(|command| !is_persistent_command(command)); } for (event, command) in specs { - if !enable && !hooks.contains_key(event) { - continue; - } - let entries = hooks - .entry(event.clone()) - .or_insert_with(|| CursorHookEntries::Entries(Vec::new())); - let CursorHookEntries::Entries(entries) = entries else { - anyhow::bail!( - "Cursor hook event `{event}` must be an array: {}", - path.display() - ); - }; - entries.retain(|entry| entry.command() != Some(command.as_str())); - if enable { - entries.push(CursorHookEntry::Command(if persistent { + let replacement = if enable { + Some(if persistent { capture_registration(event, command)? } else { CursorCommandHook::capture(command.clone(), None) - })); - } + }) + } else { + None + }; + config + .replace_registration(event, command, replacement) + .map_err(|error| anyhow::anyhow!("{error}: {}", path.display()))?; } } Ok(()) diff --git a/bt-daemon/src/setup/opencode.rs b/bt-daemon/src/setup/opencode.rs index b472eb94..ec71a000 100644 --- a/bt-daemon/src/setup/opencode.rs +++ b/bt-daemon/src/setup/opencode.rs @@ -30,26 +30,17 @@ fn config_path() -> PathBuf { } fn is_ours(plugin: &OpenCodePlugin) -> bool { - plugin.package().is_some_and(|plugin| { - plugin == PACKAGE - || plugin - .strip_prefix(PACKAGE) - .is_some_and(|version| version.starts_with('@')) - }) -} - -/// Replace any entry for the plugin with the bundled major version. -fn pin_plugin(plugins: &mut Vec) -> anyhow::Result<()> { - plugins.retain(|plugin| !is_ours(plugin)); - plugins.push(OpenCodePlugin::Package(plugin_spec()?)); - Ok(()) + plugin.matches_package(PACKAGE) } fn enable_at(path: &Path) -> anyhow::Result<()> { edit_json( path, FileAccess::Inherited, - |config: &mut OpenCodeConfig, _| pin_plugin(config.plugin.get_or_insert_with(Vec::new)), + |config: &mut OpenCodeConfig, _| { + config.replace_plugin(is_ours, OpenCodePlugin::Package(plugin_spec()?)); + Ok(()) + }, ) } @@ -61,12 +52,11 @@ fn update_at(path: &Path) -> anyhow::Result<()> { if !existed { bail!(NOT_INSTALLED); } - let plugins = config - .plugin - .as_mut() - .filter(|plugins| plugins.iter().any(is_ours)) - .ok_or_else(|| anyhow::anyhow!(NOT_INSTALLED))?; - pin_plugin(plugins) + if config.find_plugin(is_ours).is_none() { + bail!(NOT_INSTALLED); + } + config.replace_plugin(is_ours, OpenCodePlugin::Package(plugin_spec()?)); + Ok(()) }, ) } @@ -76,9 +66,7 @@ fn disable_at(path: &Path) -> anyhow::Result<()> { path, FileAccess::Inherited, |config: &mut OpenCodeConfig, _| { - if let Some(plugins) = &mut config.plugin { - plugins.retain(|plugin| !is_ours(plugin)); - } + config.retain_plugins(|plugin| !is_ours(plugin)); Ok(()) }, ) @@ -107,9 +95,7 @@ impl Setup for OpenCode { }; let expected = plugin_spec().ok(); config - .plugin - .as_ref() - .and_then(|plugins| plugins.iter().find(|plugin| is_ours(plugin))) + .find_plugin(is_ours) .and_then(OpenCodePlugin::package) .is_some_and(|plugin| Some(plugin) != expected.as_deref()) } diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 816ca498..8cc4ee8d 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -5,9 +5,11 @@ //! behavior, setup, managed runs, imports, and output contracts stay here with //! the coding-agent integrations. -use crate::route::{apply_additional_metadata, apply_tags, resolve_span_plugin_paths}; +use crate::route::resolve_span_plugin_paths; use crate::trace_command::{DoctorAgent, DoctorArgs, SettingsScope, SetupAgent, TraceCommand}; -use crate::wire::{AuthSelection, AuthSource, SessionConfig, SessionRoute, TraceDestination}; +#[cfg(test)] +use crate::wire::AuthSource; +use crate::wire::{AuthSelection, SessionConfig, SessionRoute, TraceDestination}; use crate::{ braintrust_serve_options, paths, run_disable, run_enable, run_import, run_serve, run_status, run_traced_with_host, shutdown_daemon, AuthDiagnostic, AuthLease, AuthProvider, @@ -62,46 +64,6 @@ impl HostRouteSelection { } } -fn auth_source_label(selection: &AuthSelection) -> &'static str { - match selection.effective_source() { - AuthSource::SavedProfile => "saved_profile", - AuthSource::Environment => "environment", - AuthSource::Auto => "command_context", - } -} - -fn ready_auth_diagnostic( - selection: AuthSelection, - org_name: Option, - expires_at_ms: Option, -) -> AuthDiagnostic { - AuthDiagnostic { - status: "ready".into(), - source: auth_source_label(&selection).into(), - kind: None, - profile: selection.profile, - org_name, - expires_at_ms, - error: None, - } -} - -fn unconfirmed_auth_diagnostic( - status: &str, - source: &str, - error: Option, -) -> AuthDiagnostic { - AuthDiagnostic { - status: status.into(), - source: source.into(), - kind: None, - profile: None, - org_name: None, - expires_at_ms: None, - error, - } -} - /// Host-owned services used by the integration runtime. /// /// Implementations resolve Braintrust profiles and destination choices but do @@ -137,14 +99,14 @@ pub trait TraceHostServices: Send + Sync { .await { Ok(lease) => { - ready_auth_diagnostic(lease.selection, lease.auth.org_name, lease.expires_at_ms) + AuthDiagnostic::ready(lease.selection, lease.auth.org_name, lease.expires_at_ms) } Err(error) => AuthDiagnostic { profile: selection.profile.clone(), org_name: selection.org_name.clone(), - ..unconfirmed_auth_diagnostic( + ..AuthDiagnostic::unconfirmed( "error", - auth_source_label(selection), + AuthDiagnostic::source_label(selection), Some(error.to_string()), ) }, @@ -410,20 +372,20 @@ async fn diagnose_daemon_auth(socket: &Path, selection: &AuthSelection) -> AuthD }); // The route already shows what was requested; report only what the // daemon actually resolved. - let source = auth_source_label(selection); + let source = AuthDiagnostic::source_label(selection); match result { Err(error) if error .downcast_ref::() .is_some_and(|error| error.code == crate::wire::error_code::METHOD_NOT_FOUND) => { - unconfirmed_auth_diagnostic("unsupported", source, None) + AuthDiagnostic::unconfirmed("unsupported", source, None) } - Err(error) => unconfirmed_auth_diagnostic("unknown", source, Some(error.to_string())), + Err(error) => AuthDiagnostic::unconfirmed("unknown", source, Some(error.to_string())), Ok(result) if result.error.is_some() => { - unconfirmed_auth_diagnostic("error", source, result.error) + AuthDiagnostic::unconfirmed("error", source, result.error) } - Ok(result) => ready_auth_diagnostic( + Ok(result) => AuthDiagnostic::ready( result.selection.unwrap_or_else(|| selection.clone()), result.org_name, result.expires_at_ms, @@ -450,7 +412,7 @@ fn daemon_warnings( } let mut warnings = Vec::new(); match &daemon.auth { - Some(daemon_auth) if daemon_auth.status == "error" => { + Some(daemon_auth) if daemon_auth.is_error() => { warnings.push(format!( "the running tracing daemon cannot authenticate, so it rejects {display_name} events: {}", daemon_auth.error.as_deref().unwrap_or("unknown error") @@ -461,7 +423,7 @@ fn daemon_warnings( ); } } - Some(daemon_auth) if daemon_auth.status == "ready" && auth.status == "ready" => { + Some(daemon_auth) if daemon_auth.is_ready() && auth.is_ready() => { for (label, shell, daemon) in [ ("profile", &auth.profile, &daemon_auth.profile), ("organization", &auth.org_name, &daemon_auth.org_name), @@ -625,7 +587,7 @@ async fn doctor_output_at( let local_auth = async { match &route { Some(route) => host.services.diagnose_auth(&route.auth).await, - None => unconfirmed_auth_diagnostic( + None => AuthDiagnostic::unconfirmed( "unresolved", "unresolved", Some("route is unresolved".into()), @@ -643,7 +605,7 @@ async fn doctor_output_at( // what separates divergent credential views from failures both processes // share. Skip it when the local check already failed. let resolves_locally = match &route { - Some(route) if daemon.auth_failed() && auth.status == "ready" => { + Some(route) if daemon.auth_failed() && auth.is_ready() => { let local = HostAuthProvider { services: host.services.clone(), }; @@ -729,8 +691,8 @@ async fn run_install_command( }, ) .await?; - apply_additional_metadata(&mut route, args.additional_metadata.as_deref())?; - apply_tags(&mut route, &args.tags)?; + route.apply_additional_metadata(args.additional_metadata.as_deref())?; + route.apply_tags(&args.tags)?; if !args.plugin.is_empty() { route.span_plugins = resolve_span_plugin_paths(&args.plugin)?; } @@ -946,8 +908,8 @@ pub async fn run_trace_with_matches( }, ) .await?; - apply_additional_metadata(&mut route, import_args.additional_metadata.as_deref())?; - apply_tags(&mut route, &import_args.tags)?; + route.apply_additional_metadata(import_args.additional_metadata.as_deref())?; + route.apply_tags(&import_args.tags)?; // Resolve credentials up front, interactively if needed, so the // daemon can authenticate this route when it delivers. session_config(&host, &route).await?; @@ -1032,7 +994,7 @@ pub async fn run_trace_with_matches( } else { None }; - apply_additional_metadata(&mut route, run_args.additional_metadata.as_deref())?; + route.apply_additional_metadata(run_args.additional_metadata.as_deref())?; if let Some(mut metadata) = inherited_metadata { if let Some(overlay) = route.additional_metadata.take() { crate::settings::merge_json(&mut metadata, overlay); @@ -1040,7 +1002,7 @@ pub async fn run_trace_with_matches( route.additional_metadata = Some(metadata); } let inherited_tags = run_args.inherit.then(|| route.tags.clone()); - apply_tags(&mut route, &run_args.tags)?; + route.apply_tags(&run_args.tags)?; if let Some(tags) = inherited_tags { route.tags.extend(tags); } diff --git a/bt-daemon/src/transcript_import/antigravity.rs b/bt-daemon/src/transcript_import/antigravity.rs index 71d1689a..182a81bf 100644 --- a/bt-daemon/src/transcript_import/antigravity.rs +++ b/bt-daemon/src/transcript_import/antigravity.rs @@ -131,7 +131,7 @@ pub(super) fn envelopes( for (index, record) in records.iter().enumerate() { let record_type = record.kind.as_str(); let step = record.step_index.unwrap_or(index as i64); - let ts = created_at_ms(record).unwrap_or(start_ms); + let ts = record.created_at_ms().unwrap_or(start_ms); if record_type == "PLANNER_RESPONSE" { let before = index .checked_sub(1) @@ -240,7 +240,10 @@ fn is_tool_result(record: &AntigravityRecord) -> bool { } fn timestamp_bounds_created(records: &[AntigravityRecord]) -> (i64, i64) { - let timestamps = records.iter().filter_map(created_at_ms).collect::>(); + let timestamps = records + .iter() + .filter_map(AntigravityRecord::created_at_ms) + .collect::>(); timestamps .iter() .copied() @@ -252,11 +255,3 @@ fn timestamp_bounds_created(records: &[AntigravityRecord]) -> (i64, i64) { } }) } - -fn created_at_ms(record: &AntigravityRecord) -> Option { - record - .created_at - .as_deref() - .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok()) - .map(|value| value.timestamp_millis()) -} diff --git a/bt-daemon/src/transcript_mirror/claude_child_reference.rs b/bt-daemon/src/transcript_mirror/claude_child_reference.rs new file mode 100644 index 00000000..bf85554e --- /dev/null +++ b/bt-daemon/src/transcript_mirror/claude_child_reference.rs @@ -0,0 +1,5 @@ +#[derive(serde::Deserialize)] +pub(crate) struct ClaudeChildReference { + pub path: String, + pub through: Option, +} diff --git a/bt-daemon/src/transcript_mirror/grok_references.rs b/bt-daemon/src/transcript_mirror/grok_references.rs new file mode 100644 index 00000000..bf3bb415 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/grok_references.rs @@ -0,0 +1,17 @@ +use super::Reference; + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct GrokReferences { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updates: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub events: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, +} + +impl GrokReferences { + pub fn is_empty(&self) -> bool { + self.updates.is_none() && self.events.is_none() && self.system_prompt.is_none() + } +} diff --git a/bt-daemon/src/transcript_mirror.rs b/bt-daemon/src/transcript_mirror/mod.rs similarity index 80% rename from bt-daemon/src/transcript_mirror.rs rename to bt-daemon/src/transcript_mirror/mod.rs index 21462d81..c3666305 100644 --- a/bt-daemon/src/transcript_mirror.rs +++ b/bt-daemon/src/transcript_mirror/mod.rs @@ -20,100 +20,19 @@ use std::path::{Path, PathBuf}; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; use uuid::Uuid; -/// Journaled transcript reference. An empty object records captured absence. -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct Reference { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub path: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mirror: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub through: Option, -} - -impl Reference { - pub fn captured(path: &str, mirror: &Path, through: u64) -> Self { - Self { - path: Some(path.to_owned()), - mirror: Some(mirror.to_string_lossy().into_owned()), - through: Some(through), - } - } - pub fn read_path(&self) -> Option<&str> { - self.mirror.as_deref().or(self.path.as_deref()) - } -} - -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct GrokReferences { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub updates: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub events: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub system_prompt: Option, -} - -impl GrokReferences { - pub fn is_empty(&self) -> bool { - self.updates.is_none() && self.events.is_none() && self.system_prompt.is_none() - } -} +mod claude_child_reference; +mod grok_references; +mod observation; +mod payload; +mod reference; +mod snapshot; -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct Observation { - pub path: Option, - pub observed_bytes: Option, - pub full_path: Option, - pub full_observed_bytes: Option, -} - -#[derive(Debug, Clone, serde::Deserialize)] -pub(crate) struct Snapshot { - pub path: String, - pub contents: String, -} - -/// Decode the known capture protocol once at the envelope boundary. Native -/// agent data remains in the raw journal and is decoded by its own translator. -#[derive(Default, serde::Deserialize)] -pub(crate) struct TranscriptPayload { - #[serde(default, alias = "transcriptPath")] - pub transcript_path: Option, - pub agent_transcript_path: Option, - pub agent_id: Option, - #[serde(rename = "_bt_claude_children")] - pub claude_children: Option>, - pub cwd: Option, - #[serde(rename = "_bt_transcript_mirror")] - pub mirror: Option, - #[serde(rename = "_bt_claude_transcript_mirrors")] - pub claude_mirrors: Option>, - #[serde(rename = "_bt_grok_transcript_mirrors")] - pub grok_mirrors: Option, - #[serde(rename = "_bt_transcript_observation")] - pub observation: Option, - #[serde(rename = "_bt_transcript_snapshot")] - pub snapshot: Option, - #[serde(rename = "_bt_transcript_replay")] - pub replay: Option, - #[serde(rename = "_bt_import_through_offset")] - pub import_through_offset: Option, - #[serde(rename = "_bt_import_through_ms")] - pub import_through_ms: Option, -} - -#[derive(serde::Deserialize)] -pub(crate) struct ClaudeChildReference { - pub path: String, - pub through: Option, -} - -impl TranscriptPayload { - pub fn decode(payload: &serde_json::Value) -> serde_json::Result { - serde::Deserialize::deserialize(payload) - } -} +pub(crate) use claude_child_reference::ClaudeChildReference; +pub(crate) use grok_references::GrokReferences; +pub(crate) use observation::Observation; +pub(crate) use payload::TranscriptPayload; +pub(crate) use reference::Reference; +pub(crate) use snapshot::Snapshot; /// Namespace for mirror file names (distinct from the span-id namespace). const NAMESPACE: Uuid = Uuid::from_u128(0x3d51_9a02_7c64_4b8f_9e17_a2c5_0d63_88f1); diff --git a/bt-daemon/src/transcript_mirror/observation.rs b/bt-daemon/src/transcript_mirror/observation.rs new file mode 100644 index 00000000..51e3fd46 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/observation.rs @@ -0,0 +1,7 @@ +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct Observation { + pub path: Option, + pub observed_bytes: Option, + pub full_path: Option, + pub full_observed_bytes: Option, +} diff --git a/bt-daemon/src/transcript_mirror/payload.rs b/bt-daemon/src/transcript_mirror/payload.rs new file mode 100644 index 00000000..1b999e7e --- /dev/null +++ b/bt-daemon/src/transcript_mirror/payload.rs @@ -0,0 +1,156 @@ +use super::{ClaudeChildReference, GrokReferences, Observation, Reference, Snapshot}; + +/// Decode the known capture protocol once at the envelope boundary. Native +/// agent data remains in the raw journal and is decoded by its own translator. +#[derive(Default, serde::Deserialize)] +pub(crate) struct TranscriptPayload { + #[serde(default, alias = "transcriptPath")] + pub transcript_path: Option, + pub agent_transcript_path: Option, + pub agent_id: Option, + #[serde(rename = "_bt_claude_children")] + pub claude_children: Option>, + pub cwd: Option, + #[serde(rename = "_bt_transcript_mirror")] + pub mirror: Option, + #[serde(rename = "_bt_claude_transcript_mirrors")] + pub claude_mirrors: Option>, + #[serde(rename = "_bt_grok_transcript_mirrors")] + pub grok_mirrors: Option, + #[serde(rename = "_bt_transcript_observation")] + pub observation: Option, + #[serde(rename = "_bt_transcript_snapshot")] + pub snapshot: Option, + #[serde(rename = "_bt_transcript_replay")] + pub replay: Option, + #[serde(rename = "_bt_import_through_offset")] + pub import_through_offset: Option, + #[serde(rename = "_bt_import_through_ms")] + pub import_through_ms: Option, +} + +impl TranscriptPayload { + pub fn decode(payload: &serde_json::Value) -> serde_json::Result { + serde::Deserialize::deserialize(payload) + } + + /// Modern Claude observations include a map even when capture found no + /// readable files. Its presence must prevent a later native-file reread. + pub fn has_claude_capture(&self) -> bool { + self.claude_mirrors.is_some() + || self.mirror.is_some() + || self.snapshot.is_some() + || self.replay.is_some() + } + + /// The latest observation for the poller, including the legacy single + /// reference format. Readers still distinguish a modern map's absence + /// from a missing entry so captured absence never falls back to live data. + pub fn claude_reference(&self, path: &str) -> Option<&Reference> { + self.claude_mirrors + .as_ref() + .and_then(|mirrors| mirrors.get(path)) + .or_else(|| self.matching_mirror(path)) + } + + pub fn matching_mirror(&self, path: &str) -> Option<&Reference> { + self.mirror + .as_ref() + .filter(|mirror| mirror.matches_path(path)) + } + + pub fn snapshot_for(&self, path: &str) -> Option<&str> { + self.snapshot + .as_ref() + .filter(|snapshot| snapshot.path == path) + .map(|snapshot| snapshot.contents.as_str()) + } + + pub fn native_paths(&self) -> impl Iterator { + [ + self.transcript_path.as_deref(), + self.agent_transcript_path.as_deref(), + ] + .into_iter() + .flatten() + } + + /// Codex stop hooks must read the child transcript; other hooks prefer + /// the main path. A captured mirror takes precedence in either case. + pub fn codex_read_path(&self, subagent_stop: bool) -> Option<&str> { + self.mirror + .as_ref() + .and_then(|reference| reference.mirror.as_deref()) + .or_else(|| { + if subagent_stop { + self.agent_transcript_path.as_deref() + } else { + self.transcript_path + .as_deref() + .or(self.agent_transcript_path.as_deref()) + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn codex_selects_captured_or_native_path_for_the_event_scope() { + for (raw, main, child) in [ + ( + json!({"transcript_path":"main","agent_transcript_path":"child"}), + Some("main"), + Some("child"), + ), + (json!({"transcript_path":"main"}), Some("main"), None), + ( + json!({"agent_transcript_path":"child"}), + Some("child"), + Some("child"), + ), + ( + json!({"transcript_path":"main","_bt_transcript_mirror":{"mirror":"captured","through":12}}), + Some("captured"), + Some("captured"), + ), + ] { + let payload = TranscriptPayload::decode(&raw).unwrap(); + assert_eq!(payload.codex_read_path(false), main); + assert_eq!(payload.codex_read_path(true), child); + } + } + + #[test] + fn captured_absence_and_legacy_references_keep_their_meaning() { + let payload = TranscriptPayload::decode(&json!({ + "_bt_claude_transcript_mirrors":{}, + "_bt_transcript_mirror":{"path":"main","mirror":"legacy","through":42}, + "_bt_transcript_snapshot":{"path":"main","contents":"snapshot"} + })) + .unwrap(); + assert!(payload.has_claude_capture()); + assert!(payload + .claude_mirrors + .as_ref() + .unwrap() + .get("main") + .is_none()); + // Pollers can reuse a legacy checkpoint; readers still treat the + // explicit empty modern capture as absence instead of falling back. + assert_eq!( + payload.claude_reference("main").unwrap().captured_prefix(), + Some(("legacy", 42)) + ); + assert!(payload.claude_reference("child").is_none()); + assert_eq!(payload.snapshot_for("main"), Some("snapshot")); + assert_eq!(payload.snapshot_for("child"), None); + let absent = TranscriptPayload::decode(&json!({"_bt_transcript_mirror":{}})).unwrap(); + assert!(absent.has_claude_capture()); + assert!(absent.mirror.unwrap().captured_prefix().is_none()); + assert!(!TranscriptPayload::default().has_claude_capture()); + } +} diff --git a/bt-daemon/src/transcript_mirror/reference.rs b/bt-daemon/src/transcript_mirror/reference.rs new file mode 100644 index 00000000..9f0ba8a0 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/reference.rs @@ -0,0 +1,35 @@ +use std::path::Path; + +/// Journaled transcript reference. An empty object records captured absence. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct Reference { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mirror: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub through: Option, +} + +impl Reference { + pub fn captured(path: &str, mirror: &Path, through: u64) -> Self { + Self { + path: Some(path.to_owned()), + mirror: Some(mirror.to_string_lossy().into_owned()), + through: Some(through), + } + } + pub fn read_path(&self) -> Option<&str> { + self.mirror.as_deref().or(self.path.as_deref()) + } + + /// Only a daemon mirror with a recorded byte boundary is safe for a + /// captured read. An empty reference records absence, not a live fallback. + pub fn captured_prefix(&self) -> Option<(&str, u64)> { + Some((self.mirror.as_deref()?, self.through?)) + } + + pub fn matches_path(&self, path: &str) -> bool { + self.path.as_deref() == Some(path) + } +} diff --git a/bt-daemon/src/transcript_mirror/snapshot.rs b/bt-daemon/src/transcript_mirror/snapshot.rs new file mode 100644 index 00000000..331aab27 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/snapshot.rs @@ -0,0 +1,5 @@ +#[derive(Debug, Clone, serde::Deserialize)] +pub(crate) struct Snapshot { + pub path: String, + pub contents: String, +} diff --git a/bt-daemon/src/translate/antigravity.rs b/bt-daemon/src/translate/antigravity.rs index ed983c25..0f765d01 100644 --- a/bt-daemon/src/translate/antigravity.rs +++ b/bt-daemon/src/translate/antigravity.rs @@ -198,7 +198,7 @@ impl AntigravityTranslator { } fn observe_record(&mut self, record: TranscriptRecord, ts_ms: i64, ops: &mut Vec) { - let record_type = normalized_record_type(&record); + let record_type = record.normalized_kind().to_owned(); let source = &record.source; if let Some(step) = record.step_index { self.records_by_step.insert(step, record.clone()); @@ -207,7 +207,7 @@ impl AntigravityTranslator { if record_type == "USER_INPUT" && (source.is_empty() || source == "USER_EXPLICIT" || source == "USER") { - self.start_turn(clean_user_input(record_content(&record)), ts_ms, ops); + self.start_turn(clean_user_input(record.message_content()), ts_ms, ops); } if record_type == "CHECKPOINT" { @@ -608,8 +608,8 @@ fn transcript_source(event: &Envelope) -> Option { }; let snapshot = fields .snapshot - .filter(|value| value.path == path) - .map(|value| value.contents); + .filter(|snapshot| snapshot.path == path) + .map(|snapshot| snapshot.contents); Some(TranscriptSource { path: path.to_owned(), through, @@ -666,14 +666,6 @@ fn read_records( records } -fn normalized_record_type(record: &TranscriptRecord) -> String { - let record_type = &record.kind; - record_type - .strip_prefix("CORTEX_STEP_TYPE_") - .unwrap_or(record_type) - .to_string() -} - fn transcript_message( record: &TranscriptRecord, record_type: &str, @@ -687,9 +679,9 @@ fn transcript_message( _ => return None, }; let content = match role { - "user" => clean_user_input(record_content(record)), - "tool" => clean_tool_content(record_content(record)), - _ => record_content(record), + "user" => clean_user_input(record.message_content()), + "tool" => clean_tool_content(record.message_content()), + _ => record.message_content(), }; if role == "system" && content.is_null() { return None; @@ -704,16 +696,6 @@ fn transcript_message( }) } -fn record_content(record: &TranscriptRecord) -> Value { - record - .content - .as_ref() - .or(record.message.as_ref()) - .or(record.text.as_ref()) - .cloned() - .unwrap_or(Value::Null) -} - fn clean_user_input(content: Value) -> Value { let Value::String(text) = content else { return content; @@ -745,7 +727,7 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { .tool_calls .as_ref() .and_then(|calls| calls.iter().next()); - let record_type = normalized_record_type(record); + let record_type = record.normalized_kind().to_owned(); let name = call.and_then(|call| call.name.clone()).or_else(|| { (!matches!(record_type.as_str(), "USER_INPUT" | "PLANNER_RESPONSE")) .then(|| record_type.to_ascii_lowercase()) @@ -753,14 +735,14 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { let input = call.and_then(|call| call.args.clone()); let output = call .and_then(|call| call.output.clone()) - .or_else(|| nonempty_value(clean_tool_content(record_content(record)))); + .or_else(|| nonempty_value(clean_tool_content(record.message_content()))); let error = record .error .clone() .filter(|error| !error.is_empty()) .or_else(|| { (record_type == "ERROR_MESSAGE") - .then(|| record_content(record)) + .then(|| record.message_content()) .and_then(|content| content.as_str().map(str::to_owned)) }) .or_else(|| { @@ -768,7 +750,7 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { .status .as_ref() .filter(|status| matches!(status.to_ascii_lowercase().as_str(), "error" | "failed")) - .map(|status| match record_content(record) { + .map(|status| match record.message_content() { Value::String(content) if !content.is_empty() => content, _ => status.clone(), }) @@ -807,17 +789,11 @@ fn planned_tool_start(records: &[TranscriptRecord], name: Option<&str>, step: i6 .as_ref()? .iter() .any(|call| call.name.as_deref() == Some(name)) - .then(|| parse_created_at(record)) + .then(|| record.created_at_ms()) .flatten() }) } -fn parse_created_at(record: &TranscriptRecord) -> Option { - chrono::DateTime::parse_from_rfc3339(record.created_at.as_deref()?) - .ok() - .map(|timestamp| timestamp.timestamp_millis()) -} - fn token_metrics(records: &[TranscriptRecord]) -> Option { let mut metrics = UsageMetrics::default(); for usage in records.iter().filter_map(|record| record.usage.as_ref()) { diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index dc23fd29..3722d146 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -9,8 +9,8 @@ use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY}; use super::tool::{ - add_tool_approval, explicit_skill_metadata, insert_skill_metadata, nonempty_error_text, - prompt_skill_names, push_unique, skill_file_load, skill_md_paths, SkillLoad, ToolApproval, + add_tool_approval, explicit_skill_metadata, nonempty_error_text, prompt_skill_names, + push_unique, skill_file_load, skill_md_paths, SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -2541,10 +2541,7 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec Vec Vec { read_snapshot_bounded(contents, offset, None, through) @@ -2619,7 +2607,7 @@ fn tool_metadata( } } if let Some(skill) = skill { - insert_skill_metadata(&mut metadata, skill, requested_skills); + skill.insert_metadata(&mut metadata, requested_skills); } Value::Object(metadata) } @@ -2743,10 +2731,7 @@ fn command_output(cwd: &str, command: &str, args: &[&str]) -> Option { fn tool_span_name(tool: &str, input: &Value, skill: Option<&SkillLoad>) -> String { if let Some(skill) = skill { - return skill - .name - .as_ref() - .map_or_else(|| "skill".into(), |name| format!("skill: {name}")); + return skill.display_name(); } match tool { "Read" | "Write" | "Edit" | "MultiEdit" => string_field(input, "file_path") diff --git a/bt-daemon/src/translate/codex.rs b/bt-daemon/src/translate/codex.rs index 806db3f9..40abc68d 100644 --- a/bt-daemon/src/translate/codex.rs +++ b/bt-daemon/src/translate/codex.rs @@ -20,9 +20,9 @@ use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet}; use super::tool::{ - add_tool_approval, compile_skill_regex, explicit_skill_metadata, insert_skill_metadata, - is_skill_name, prompt_skill_names, push_unique, skill_md_paths, tool_approval_metadata, - SkillLoad, ToolApproval, + add_tool_approval, compile_skill_regex, explicit_skill_metadata, is_skill_name, + prompt_skill_names, push_unique, skill_md_paths, tool_approval_metadata, SkillLoad, + ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -1203,7 +1203,7 @@ impl CodexTranslator { if let Some(skill_name) = &skill.name { name = format!("skill: {skill_name}"); } - insert_skill_metadata(&mut metadata, skill, &explicit_skills); + skill.insert_metadata(&mut metadata, &explicit_skills); } if let Some(permission) = permission { metadata.insert("permission".into(), permission); @@ -1692,13 +1692,9 @@ fn is_injected_user_context(text: &str) -> bool { fn effective_transcript_path(event: &Envelope) -> Option { let fields = TranscriptPayload::decode(&event.payload).ok()?; - fields.mirror.and_then(|mirror| mirror.mirror).or_else(|| { - if event.event == "SubagentStop" { - fields.agent_transcript_path - } else { - fields.transcript_path.or(fields.agent_transcript_path) - } - }) + fields + .codex_read_path(event.event == "SubagentStop") + .map(str::to_owned) } impl Scope { diff --git a/bt-daemon/src/translate/opencode.rs b/bt-daemon/src/translate/opencode.rs index fcd64dec..9e7ba3b7 100644 --- a/bt-daemon/src/translate/opencode.rs +++ b/bt-daemon/src/translate/opencode.rs @@ -1,11 +1,14 @@ //! OpenCode translator. The JavaScript package forwards native hook payloads; //! this module owns span construction, correlation, and recovery. +mod permission; +use permission::{PermissionProperties, PermissionRequest}; + use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet}; use super::tool::{ - error_text, insert_skill_metadata, prompt_skill_names, push_unique, skill_file_load, - skill_md_paths, with_tool_approval, SkillLoad, ToolApproval, + error_text, prompt_skill_names, push_unique, skill_file_load, skill_md_paths, + with_tool_approval, SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -220,100 +223,6 @@ impl From for ToolAfter { } } -#[derive(Clone, Default, Deserialize, Serialize)] -struct PermissionToolRecord { - #[serde(default, rename = "sessionID")] - session_id: Option, - #[serde(default, rename = "callID")] - call_id: Option, - #[serde(default)] - name: Option, - #[serde(default)] - tool: Option, - #[serde(default)] - input: Option, -} - -#[derive(Clone, Deserialize)] -#[serde(untagged)] -#[derive(Serialize)] -enum PermissionTool { - Name(String), - Record(PermissionToolRecord), -} - -#[derive(Clone, Default, Deserialize, Serialize)] -struct PermissionFields { - #[serde(default)] - id: Option, - #[serde(default, rename = "sessionID")] - session_id: Option, - #[serde(default, rename = "callID")] - call_id: Option, - #[serde(default)] - tool: Option, - #[serde(default, rename = "toolName")] - tool_name: Option, - #[serde(default, rename = "permission")] - permission: Option, - #[serde(default)] - input: Option, - #[serde(default)] - args: Option, - #[serde(default)] - title: Option, - #[serde(default, rename = "type", alias = "permissionType")] - permission_type: Option, -} - -#[derive(Deserialize)] -#[serde(untagged)] -#[derive(Serialize)] -enum PermissionPayload { - Record(Box), - Kind(String), -} - -#[derive(Default, Deserialize, Serialize)] -struct PermissionProperties { - #[serde(default)] - permission: Option, - #[serde(default)] - info: Option, - #[serde(default, rename = "permissionID")] - permission_id: Option, - #[serde(default, rename = "requestID")] - request_id: Option, - #[serde(default)] - reply: Option, - #[serde(default)] - response: Option, - #[serde(default)] - status: Option, - #[serde(flatten)] - direct: PermissionFields, -} - -impl PermissionTool { - fn record(&self) -> Option<&PermissionToolRecord> { - match self { - Self::Record(record) => Some(record), - Self::Name(_) => None, - } - } - - fn name(&self) -> Option<&str> { - match self { - Self::Name(name) => Some(name), - Self::Record(_) => None, - } - } -} - -fn permission_properties(payload: &Value) -> Option { - decode(payload.get("properties").unwrap_or(payload)) -} - #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[derive(Serialize)] @@ -570,16 +479,6 @@ impl MessageHistory { } } -#[derive(Clone, Default, Serialize, Deserialize)] -struct PermissionRequest { - id: Option, - session_id: Option, - call_id: Option, - tool: Option, - input: Option, - title: Option, - permission_type: Option, -} #[derive(Serialize, Deserialize)] struct OpenCodeTranslator { daemon_session_id: String, @@ -611,10 +510,10 @@ impl AgentTranslator for OpenCodeTranslator { .map(ToolAfter::from) .map(|tool| self.tool_after(tool, event.ts_ms)) .unwrap_or_default(), - "permission.asked" => permission_properties(&event.payload) + "permission.asked" => PermissionProperties::decode(&event.payload) .map(|permission| self.permission_asked(permission)) .unwrap_or_default(), - "permission.replied" => permission_properties(&event.payload) + "permission.replied" => PermissionProperties::decode(&event.payload) .map(|permission| self.permission_replied(permission, event.ts_ms)) .unwrap_or_default(), "session.idle" => self.finish_session_event(event, false, None), @@ -1038,7 +937,7 @@ impl OpenCodeTranslator { let tokens = info.tokens.as_ref().cloned().unwrap_or_default(); let cache_read = tokens.cache.read; let cache_write = tokens.cache.write; - let prompt = tokens.input + cache_read + cache_write; + let prompt = tokens.prompt_tokens(); let completion = tokens.output; let reasoning = tokens.reasoning; let content = state.output_parts.remove(mid).unwrap_or_default(); @@ -1121,7 +1020,7 @@ impl OpenCodeTranslator { output: Some(Value::Array(vec![assistant])), metadata: Some(metadata), metrics: Some( - json!({"prompt_tokens":prompt,"completion_tokens":completion,"tokens":prompt+completion+reasoning,"prompt_cached_tokens":cache_read,"prompt_cache_creation_tokens":cache_write,"reasoning_tokens":reasoning}), + json!({"prompt_tokens":prompt,"completion_tokens":completion,"tokens":tokens.total_tokens(),"prompt_cached_tokens":cache_read,"prompt_cache_creation_tokens":cache_write,"reasoning_tokens":reasoning}), ), error: info.error.as_ref().map(|error| format_error(Some(error))), tags: (info.summary || info.compaction).then(|| vec!["compaction".into()]), @@ -1152,7 +1051,7 @@ impl OpenCodeTranslator { .tool_args .get(&call) .and_then(|args| skill_load(&tool, args)) - .map_or_else(|| tool.clone(), |skill| skill_span_name(&skill)); + .map_or_else(|| tool.clone(), |skill| skill.display_name()); return vec![SpanOp::Insert(SpanRow { span_id: ids::span_id(&self.daemon_session_id, &format!("tool:{sid}:{call}")), root_span_id: s.effective_root_span_id.clone(), @@ -1203,7 +1102,7 @@ impl OpenCodeTranslator { let args = s.tool_args.remove(&call); let skill = args.as_ref().and_then(|args| skill_load(&tool, args)); let name = if let Some(skill) = &skill { - skill_span_name(skill) + skill.display_name() } else { event .result @@ -1217,7 +1116,7 @@ impl OpenCodeTranslator { Some(ToolApproval::Approved), ); if let (Some(skill), Some(fields)) = (&skill, metadata.as_object_mut()) { - insert_skill_metadata(fields, skill, &s.requested_skills); + skill.insert_metadata(fields, &s.requested_skills); } let had_start = s.tool_starts.contains_key(&call); let parent_span_id = s.tool_parent_span_ids.remove(&call).unwrap_or(turn); @@ -1256,56 +1155,8 @@ impl OpenCodeTranslator { }] } - fn permission_record(properties: &PermissionProperties) -> PermissionRequest { - let permission_kind = match &properties.permission { - Some(PermissionPayload::Kind(kind)) => Some(kind.clone()), - _ => None, - }; - let source = match &properties.permission { - Some(PermissionPayload::Record(record)) => record, - _ => properties.info.as_ref().unwrap_or(&properties.direct), - }; - let tool_record = source.tool.as_ref().and_then(PermissionTool::record); - PermissionRequest { - id: source - .id - .clone() - .or_else(|| properties.direct.id.clone()) - .or_else(|| properties.permission_id.clone()) - .or_else(|| properties.request_id.clone()), - session_id: source - .session_id - .clone() - .or_else(|| properties.direct.session_id.clone()) - .or_else(|| tool_record.and_then(|tool| tool.session_id.clone())), - call_id: source - .call_id - .clone() - .or_else(|| tool_record.and_then(|tool| tool.call_id.clone())), - tool: source - .tool - .as_ref() - .and_then(PermissionTool::name) - .map(str::to_owned) - .or_else(|| source.tool_name.clone()) - .or_else(|| tool_record.and_then(|tool| tool.name.clone())) - .or_else(|| tool_record.and_then(|tool| tool.tool.clone())) - // OpenCode's native permission events put the requested tool - // kind in `permission`, separate from `tool.callID`. - .or_else(|| source.permission.clone()) - .or(permission_kind), - input: source - .input - .clone() - .or_else(|| source.args.clone()) - .or_else(|| tool_record.and_then(|tool| tool.input.clone())), - title: source.title.clone(), - permission_type: source.permission_type.clone(), - } - } - fn permission_asked(&mut self, properties: PermissionProperties) -> Vec { - let request = Self::permission_record(&properties); + let request = properties.request(); if let Some(id) = &request.id { self.permission_requests.insert(id.clone(), request); } @@ -1313,13 +1164,8 @@ impl OpenCodeTranslator { } fn permission_replied(&mut self, properties: PermissionProperties, ts_ms: i64) -> Vec { - let reply = properties - .reply - .as_deref() - .or(properties.response.as_deref()) - .or(properties.status.as_deref()) - .unwrap_or(""); - let direct = Self::permission_record(&properties); + let reply = properties.reply(); + let direct = properties.request(); let request = direct .id .as_ref() @@ -1570,13 +1416,6 @@ pub(super) fn requested_skills(input: &str) -> Vec { names } -fn skill_span_name(skill: &SkillLoad) -> String { - skill - .name - .as_ref() - .map_or_else(|| "skill".into(), |name| format!("skill: {name}")) -} - /// OpenCode loads a skill through its `skill` tool, or by reading the skill's /// `SKILL.md` directly with `read` or `bash`. pub(super) fn skill_load(tool: &str, args: &Value) -> Option { diff --git a/bt-daemon/src/translate/opencode/permission.rs b/bt-daemon/src/translate/opencode/permission.rs new file mode 100644 index 00000000..63157ba8 --- /dev/null +++ b/bt-daemon/src/translate/opencode/permission.rs @@ -0,0 +1,163 @@ +//! OpenCode permission variants own their normalized request and reply precedence. +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Default, Deserialize, Serialize)] +struct PermissionToolRecord { + #[serde(default, rename = "sessionID")] + session_id: Option, + #[serde(default, rename = "callID")] + call_id: Option, + #[serde(default)] + name: Option, + #[serde(default)] + tool: Option, + #[serde(default)] + input: Option, +} + +#[derive(Clone, Deserialize)] +#[serde(untagged)] +#[derive(Serialize)] +enum PermissionTool { + Name(String), + Record(PermissionToolRecord), +} + +#[derive(Clone, Default, Deserialize, Serialize)] +struct PermissionFields { + #[serde(default)] + id: Option, + #[serde(default, rename = "sessionID")] + session_id: Option, + #[serde(default, rename = "callID")] + call_id: Option, + #[serde(default)] + tool: Option, + #[serde(default, rename = "toolName")] + tool_name: Option, + #[serde(default, rename = "permission")] + permission: Option, + #[serde(default)] + input: Option, + #[serde(default)] + args: Option, + #[serde(default)] + title: Option, + #[serde(default, rename = "type", alias = "permissionType")] + permission_type: Option, +} + +#[derive(Deserialize)] +#[serde(untagged)] +#[derive(Serialize)] +enum PermissionPayload { + Record(Box), + Kind(String), +} + +#[derive(Default, Deserialize, Serialize)] +pub(super) struct PermissionProperties { + #[serde(default)] + permission: Option, + #[serde(default)] + info: Option, + #[serde(default, rename = "permissionID")] + permission_id: Option, + #[serde(default, rename = "requestID")] + request_id: Option, + #[serde(default)] + reply: Option, + #[serde(default)] + response: Option, + #[serde(default)] + status: Option, + #[serde(flatten)] + direct: PermissionFields, +} + +impl PermissionTool { + fn record(&self) -> Option<&PermissionToolRecord> { + match self { + Self::Record(record) => Some(record), + Self::Name(_) => None, + } + } + + fn name(&self) -> Option<&str> { + match self { + Self::Name(name) => Some(name), + Self::Record(_) => None, + } + } +} + +impl PermissionProperties { + pub(super) fn decode(payload: &Value) -> Option { + super::decode(payload.get("properties").unwrap_or(payload)) + } + pub(super) fn reply(&self) -> &str { + self.reply + .as_deref() + .or(self.response.as_deref()) + .or(self.status.as_deref()) + .unwrap_or("") + } + pub(super) fn request(&self) -> PermissionRequest { + let permission_kind = match &self.permission { + Some(PermissionPayload::Kind(kind)) => Some(kind.clone()), + _ => None, + }; + let source = match &self.permission { + Some(PermissionPayload::Record(record)) => record, + _ => self.info.as_ref().unwrap_or(&self.direct), + }; + let tool_record = source.tool.as_ref().and_then(PermissionTool::record); + PermissionRequest { + id: source + .id + .clone() + .or_else(|| self.direct.id.clone()) + .or_else(|| self.permission_id.clone()) + .or_else(|| self.request_id.clone()), + session_id: source + .session_id + .clone() + .or_else(|| self.direct.session_id.clone()) + .or_else(|| tool_record.and_then(|tool| tool.session_id.clone())), + call_id: source + .call_id + .clone() + .or_else(|| tool_record.and_then(|tool| tool.call_id.clone())), + tool: source + .tool + .as_ref() + .and_then(PermissionTool::name) + .map(str::to_owned) + .or_else(|| source.tool_name.clone()) + .or_else(|| tool_record.and_then(|tool| tool.name.clone())) + .or_else(|| tool_record.and_then(|tool| tool.tool.clone())) + // OpenCode's native permission events put the requested tool + // kind in `permission`, separate from `tool.callID`. + .or_else(|| source.permission.clone()) + .or(permission_kind), + input: source + .input + .clone() + .or_else(|| source.args.clone()) + .or_else(|| tool_record.and_then(|tool| tool.input.clone())), + title: source.title.clone(), + permission_type: source.permission_type.clone(), + } + } +} +#[derive(Clone, Default, Serialize, Deserialize)] +pub(super) struct PermissionRequest { + pub(super) id: Option, + pub(super) session_id: Option, + pub(super) call_id: Option, + pub(super) tool: Option, + pub(super) input: Option, + pub(super) title: Option, + pub(super) permission_type: Option, +} diff --git a/bt-daemon/src/translate/opencode_v2.rs b/bt-daemon/src/translate/opencode_v2.rs index 81adb29f..58776cc9 100644 --- a/bt-daemon/src/translate/opencode_v2.rs +++ b/bt-daemon/src/translate/opencode_v2.rs @@ -1,6 +1,8 @@ //! OpenCode 2 native event translation. +mod context; mod event; mod span; +mod tool_content; use self::event::*; use self::span::*; @@ -9,7 +11,7 @@ use super::{ local_username, opencode::{requested_skills, skill_load}, recent::RecentSet, - tool::{push_unique, skill_was_requested, SkillLoad, ToolApproval}, + tool::{push_unique, SkillLoad, ToolApproval}, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, }; use crate::{ids, wire::Envelope}; @@ -526,7 +528,12 @@ impl AgentTranslator for OpenCodeV2Translator { })] } NativeEvent::ToolSuccess(data) => { - let output = normalize_tool_content(data.content.unwrap_or_default()); + let output = data + .content + .unwrap_or_default() + .into_iter() + .map(ToolContent::into_span_part) + .collect(); self.finish_tool( &data.session_id, &data.message_id, @@ -796,11 +803,7 @@ impl OpenCodeV2Translator { metadata.tool_kind = Some("skill"); metadata.skill_name = Some(skill.name.as_deref()); metadata.skill_path = skill.path.as_deref(); - metadata.skill_load_trigger = skill - .name - .as_deref() - .is_some_and(|name| skill_was_requested(&s.turn_skills, name)) - .then_some("explicit"); + metadata.skill_load_trigger = skill.was_requested(&s.turn_skills).then_some("explicit"); } vec![SpanOp::Merge(SpanRow { span_id: tool.span_id, @@ -849,7 +852,7 @@ impl OpenCodeV2Translator { content: reasoning, }]); } - let input = step.context.map(normalize_context).unwrap_or_else(|| { + let input = step.context.map(Context::into_messages).unwrap_or_else(|| { let window = s .native_window .as_ref() @@ -960,7 +963,7 @@ impl OpenCodeV2Translator { ); let output = match native_messages { Some(NativeMessages::Messages(messages)) => { - let messages = normalize_context(Context { + let messages = Context { session_id: sid.to_owned(), system: Vec::new(), messages: messages @@ -970,7 +973,8 @@ impl OpenCodeV2Translator { content: message.content, }) .collect(), - }); + } + .into_messages(); if error.is_none() { s.native_window = Some(NativeWindow { model: model.clone(), @@ -1034,103 +1038,3 @@ impl OpenCodeV2Translator { })] } } -fn normalize_context(context: Context) -> Vec { - let mut messages = Vec::new(); - let system = context.system.join("\n\n"); - if !system.is_empty() { - messages.push(Message::new("system", Content::Text(system))); - } - for message in context.messages { - match message.content { - MessageContent::Text(text) => { - messages.push(Message::new(message.role, Content::Text(text))) - } - MessageContent::Other(content) => { - messages.push(Message::new(message.role, Content::Dynamic(content))) - } - MessageContent::Parts(parts) => { - let mut content = Vec::new(); - let mut calls = Vec::new(); - let mut single_text = None; - for part in parts { - match part { - ContextPart::Known(KnownContextPart::Text { text }) => { - single_text = Some(text.clone()); - content.push(ContentPart::text(text)); - } - ContextPart::Known(KnownContextPart::Media { - media_type, - data, - media, - extra, - }) => { - let source = media.as_ref().and_then(|media| media.source.as_ref()); - let mime = source - .and_then(|source| source.media_type.as_deref()) - .or(media_type.as_deref()); - let bytes = source - .and_then(|source| source.data.as_deref()) - .or(data.as_deref()); - if let Some((mime, bytes)) = mime - .zip(bytes) - .filter(|(mime, _)| mime.starts_with("image/")) - { - content.push(ContentPart::image(format!( - "data:{mime};base64,{bytes}" - ))); - } else { - content.push(ContentPart::Native(KnownContextPart::Media { - media_type, - data, - media, - extra, - })); - } - } - ContextPart::Known(KnownContextPart::ToolCall { id, name, input }) => { - calls.push(ToolCall::new(id, name, &input)) - } - ContextPart::Known(KnownContextPart::ToolResult { id, result }) => { - let value = match serde_json::from_value::>( - result.value.clone(), - ) { - Ok(parts) => Content::Parts(normalize_tool_content(parts)), - Err(_) => Content::Dynamic(result.value), - }; - messages.push(Message::tool(id, value)); - } - ContextPart::Other(value) => content.push(ContentPart::Dynamic(value)), - } - } - if message.role == "tool" && content.is_empty() && calls.is_empty() { - continue; - } - let value = if content.is_empty() { - Content::Text(String::new()) - } else if content.len() == 1 && single_text.is_some() { - Content::Text(single_text.unwrap_or_default()) - } else { - Content::Parts(content) - }; - let mut normalized = Message::new(message.role, value); - normalized.tool_calls = calls; - messages.push(normalized); - } - } - } - messages -} - -fn normalize_tool_content(parts: Vec) -> Vec { - parts - .into_iter() - .map(|part| match part { - ToolContent::Known(KnownToolContent::File { mime, uri, .. }) - if mime.starts_with("image/") => - { - ContentPart::image(uri) - } - other => ContentPart::Tool(other), - }) - .collect() -} diff --git a/bt-daemon/src/translate/opencode_v2/context.rs b/bt-daemon/src/translate/opencode_v2/context.rs new file mode 100644 index 00000000..053ea23f --- /dev/null +++ b/bt-daemon/src/translate/opencode_v2/context.rs @@ -0,0 +1,229 @@ +//! Native OpenCode context and its conversion to Braintrust messages. +use super::event::ToolContent; +use super::span::{Content, ContentPart, Message, ToolCall}; +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Deserialize, Serialize)] +pub(super) struct Context { + #[serde(rename = "sessionID")] + pub session_id: String, + #[serde(default)] + pub system: Vec, + #[serde(default)] + pub messages: Vec, +} +#[derive(Deserialize, Serialize)] +pub(super) struct ContextMessage { + pub role: String, + pub content: MessageContent, +} +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum MessageContent { + Text(String), + Parts(Vec), + Other(Value), +} +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum ContextPart { + Known(KnownContextPart), + Other(Value), +} +// Select the known schema before deserializing it. An untagged fallback +// must not turn a malformed known media or tool part into arbitrary JSON. +impl<'de> Deserialize<'de> for MessageContent { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + match value { + Value::String(text) => Ok(Self::Text(text)), + Value::Array(parts) => serde_json::from_value(Value::Array(parts)) + .map(Self::Parts) + .map_err(serde::de::Error::custom), + other => Ok(Self::Other(other)), + } + } +} +impl<'de> Deserialize<'de> for ContextPart { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + if matches!( + value.get("type").and_then(Value::as_str), + Some("text" | "media" | "tool-call" | "tool-result") + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + Ok(Self::Other(value)) + } + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type")] +pub(super) enum KnownContextPart { + #[serde(rename = "text")] + Text { text: String }, + #[serde(rename = "media")] + Media { + #[serde( + default, + rename = "mediaType", + skip_serializing_if = "Field::is_missing" + )] + media_type: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + data: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + media: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, + }, + #[serde(rename = "tool-call")] + ToolCall { + id: String, + name: String, + input: Value, + }, + #[serde(rename = "tool-result")] + ToolResult { id: String, result: ToolResult }, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct Media { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub source: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct MediaSource { + #[serde( + default, + rename = "mediaType", + skip_serializing_if = "Field::is_missing" + )] + pub media_type: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub data: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct ToolResult { + pub value: Value, +} + +impl Context { + pub(super) fn into_messages(self) -> Vec { + let mut messages = Vec::new(); + let system = self.system.join("\n\n"); + if !system.is_empty() { + messages.push(Message::new("system", Content::Text(system))); + } + for message in self.messages { + match message.content { + MessageContent::Text(text) => { + messages.push(Message::new(message.role, Content::Text(text))) + } + MessageContent::Other(content) => { + messages.push(Message::new(message.role, Content::Dynamic(content))) + } + MessageContent::Parts(parts) => { + let mut content = Vec::new(); + let mut calls = Vec::new(); + let mut single_text = None; + for part in parts { + match part { + ContextPart::Known(KnownContextPart::Text { text }) => { + single_text = Some(text.clone()); + content.push(ContentPart::text(text)); + } + ContextPart::Known(KnownContextPart::Media { + media_type, + data, + media, + extra, + }) => { + let source = media.as_ref().and_then(|media| media.source.as_ref()); + let mime = source + .and_then(|source| source.media_type.as_deref()) + .or(media_type.as_deref()); + let bytes = source + .and_then(|source| source.data.as_deref()) + .or(data.as_deref()); + if let Some((mime, bytes)) = mime + .zip(bytes) + .filter(|(mime, _)| mime.starts_with("image/")) + { + content.push(ContentPart::image(format!( + "data:{mime};base64,{bytes}" + ))); + } else { + content.push(ContentPart::Native(KnownContextPart::Media { + media_type, + data, + media, + extra, + })); + } + } + ContextPart::Known(KnownContextPart::ToolCall { id, name, input }) => { + calls.push(ToolCall::new(id, name, &input)) + } + ContextPart::Known(KnownContextPart::ToolResult { id, result }) => { + let value = match serde_json::from_value::>( + result.value.clone(), + ) { + Ok(parts) => Content::Parts( + parts + .into_iter() + .map(ToolContent::into_span_part) + .collect(), + ), + Err(_) => Content::Dynamic(result.value), + }; + messages.push(Message::tool(id, value)); + } + ContextPart::Other(value) => content.push(ContentPart::Dynamic(value)), + } + } + if message.role == "tool" && content.is_empty() && calls.is_empty() { + continue; + } + let value = if content.is_empty() { + Content::Text(String::new()) + } else if content.len() == 1 && single_text.is_some() { + Content::Text(single_text.unwrap_or_default()) + } else { + Content::Parts(content) + }; + let mut normalized = Message::new(message.role, value); + normalized.tool_calls = calls; + messages.push(normalized); + } + } + } + messages + } +} + +#[cfg(test)] +mod extension_tests { + use super::*; + use serde_json::json; + #[test] + fn media_extensions_round_trip_but_known_fields_remain_typed() { + let raw = json!([{"type":"media","media":{"source":{"mediaType":"application/pdf","data":"YWJj","future":true},"future":null},"future":[42]}]); + let parsed: MessageContent = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + assert!(serde_json::from_value::(json!([ + {"type":"media","media":{"source":{"data":42}}} + ])) + .is_err()); + let future = json!([{"type":"future","payload":{"data":42}}]); + let parsed: MessageContent = serde_json::from_value(future.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), future); + } +} diff --git a/bt-daemon/src/translate/opencode_v2/event.rs b/bt-daemon/src/translate/opencode_v2/event.rs index 953d9fab..a41165ab 100644 --- a/bt-daemon/src/translate/opencode_v2/event.rs +++ b/bt-daemon/src/translate/opencode_v2/event.rs @@ -1,7 +1,8 @@ //! Partial OpenCode 2 wire types. Unknown fields are accepted; arbitrary tool //! inputs, outputs and provider-specific content remain JSON values. +pub(super) use super::context::*; +pub(super) use super::tool_content::*; pub(super) use crate::agents::usage::OpenCodeTokens as Tokens; -use crate::json::{Extensions, Field}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -214,25 +215,6 @@ pub(super) struct NativeError { pub(super) struct ErrorResponse { pub body: String, } -#[derive(Clone, Deserialize, Serialize)] -#[serde(untagged)] -pub(super) enum ToolContent { - Known(KnownToolContent), - Other(Value), -} -#[derive(Clone, Deserialize, Serialize)] -#[serde(tag = "type")] -pub(super) enum KnownToolContent { - #[serde(rename = "text")] - Text { text: String }, - #[serde(rename = "file")] - File { - mime: String, - uri: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - name: Option, - }, -} #[derive(Deserialize)] pub(super) struct PermissionAsked { #[serde(rename = "sessionID")] @@ -308,132 +290,3 @@ pub(super) struct Interrupted { pub session_id: String, pub reason: Option, } - -#[derive(Deserialize, Serialize)] -pub(super) struct Context { - #[serde(rename = "sessionID")] - pub session_id: String, - #[serde(default)] - pub system: Vec, - #[serde(default)] - pub messages: Vec, -} -#[derive(Deserialize, Serialize)] -pub(super) struct ContextMessage { - pub role: String, - pub content: MessageContent, -} -#[derive(Serialize)] -#[serde(untagged)] -pub(super) enum MessageContent { - Text(String), - Parts(Vec), - Other(Value), -} -#[derive(Serialize)] -#[serde(untagged)] -pub(super) enum ContextPart { - Known(KnownContextPart), - Other(Value), -} -// Select the known schema before deserializing it. An untagged fallback -// must not turn a malformed known media or tool part into arbitrary JSON. -impl<'de> Deserialize<'de> for MessageContent { - fn deserialize>(deserializer: D) -> Result { - let value = Value::deserialize(deserializer)?; - match value { - Value::String(text) => Ok(Self::Text(text)), - Value::Array(parts) => serde_json::from_value(Value::Array(parts)) - .map(Self::Parts) - .map_err(serde::de::Error::custom), - other => Ok(Self::Other(other)), - } - } -} -impl<'de> Deserialize<'de> for ContextPart { - fn deserialize>(deserializer: D) -> Result { - let value = Value::deserialize(deserializer)?; - if matches!( - value.get("type").and_then(Value::as_str), - Some("text" | "media" | "tool-call" | "tool-result") - ) { - serde_json::from_value(value) - .map(Self::Known) - .map_err(serde::de::Error::custom) - } else { - Ok(Self::Other(value)) - } - } -} -#[derive(Clone, Deserialize, Serialize)] -#[serde(tag = "type")] -pub(super) enum KnownContextPart { - #[serde(rename = "text")] - Text { text: String }, - #[serde(rename = "media")] - Media { - #[serde( - default, - rename = "mediaType", - skip_serializing_if = "Field::is_missing" - )] - media_type: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - data: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - media: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extra: Extensions, - }, - #[serde(rename = "tool-call")] - ToolCall { - id: String, - name: String, - input: Value, - }, - #[serde(rename = "tool-result")] - ToolResult { id: String, result: ToolResult }, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct Media { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub source: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct MediaSource { - #[serde( - default, - rename = "mediaType", - skip_serializing_if = "Field::is_missing" - )] - pub media_type: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub data: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct ToolResult { - pub value: Value, -} - -#[cfg(test)] -mod extension_tests { - use super::*; - use serde_json::json; - #[test] - fn media_extensions_round_trip_but_known_fields_remain_typed() { - let raw = json!([{"type":"media","media":{"source":{"mediaType":"application/pdf","data":"YWJj","future":true},"future":null},"future":[42]}]); - let parsed: MessageContent = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - assert!(serde_json::from_value::(json!([ - {"type":"media","media":{"source":{"data":42}}} - ])) - .is_err()); - let future = json!([{"type":"future","payload":{"data":42}}]); - let parsed: MessageContent = serde_json::from_value(future.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), future); - } -} diff --git a/bt-daemon/src/translate/opencode_v2/span.rs b/bt-daemon/src/translate/opencode_v2/span.rs index 18a18c90..7c77c7bf 100644 --- a/bt-daemon/src/translate/opencode_v2/span.rs +++ b/bt-daemon/src/translate/opencode_v2/span.rs @@ -198,11 +198,11 @@ pub(super) struct Metrics { } impl Metrics { pub fn from_tokens(t: super::event::Tokens) -> Self { - let prompt = t.input + t.cache.read + t.cache.write; + let prompt = t.prompt_tokens(); Self { prompt_tokens: prompt, completion_tokens: t.output, - tokens: prompt + t.output + t.reasoning, + tokens: t.total_tokens(), prompt_cached_tokens: t.cache.read, prompt_cache_creation_tokens: t.cache.write, reasoning_tokens: t.reasoning, diff --git a/bt-daemon/src/translate/opencode_v2/tool_content.rs b/bt-daemon/src/translate/opencode_v2/tool_content.rs new file mode 100644 index 00000000..9c3b81c3 --- /dev/null +++ b/bt-daemon/src/translate/opencode_v2/tool_content.rs @@ -0,0 +1,34 @@ +//! Native tool result blocks own their span-content conversion. +use super::span::ContentPart; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub(super) enum ToolContent { + Known(KnownToolContent), + Other(Value), +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type")] +pub(super) enum KnownToolContent { + #[serde(rename = "text")] + Text { text: String }, + #[serde(rename = "file")] + File { + mime: String, + uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + }, +} +impl ToolContent { + pub(super) fn into_span_part(self) -> ContentPart { + match self { + Self::Known(KnownToolContent::File { mime, uri, .. }) if mime.starts_with("image/") => { + ContentPart::image(uri) + } + other => ContentPart::Tool(other), + } + } +} diff --git a/bt-daemon/src/translate/pi.rs b/bt-daemon/src/translate/pi.rs index 08e38bb6..1d04dd2f 100644 --- a/bt-daemon/src/translate/pi.rs +++ b/bt-daemon/src/translate/pi.rs @@ -1,16 +1,22 @@ //! Pi coding-agent translator. Pi forwards native extension callbacks and this //! state machine owns all span construction and recovery. +mod assistant_message; +mod compaction; +mod event; +use assistant_message::AssistantMessage; +use compaction::*; +use event::*; + use super::git::GitMetadataCache; use super::tool::{ - error_text, explicit_skill_metadata, insert_skill_metadata, skill_file_load, - with_tool_approval, without_nulls, SkillLoad, ToolApproval, + error_text, explicit_skill_metadata, skill_file_load, with_tool_approval, without_nulls, + SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; use crate::agents::request::RequestConfig; -use crate::agents::usage::PiUsage as Usage; use crate::ids; use crate::wire::Envelope; use serde::de::DeserializeOwned; @@ -48,259 +54,6 @@ impl TranslatorFactory for crate::agents::Pi { } } -// These are deliberately partial native event types. Serde ignores fields we -// do not model, while `Value` remains at the user-controlled JSON boundaries -// that we forward without interpreting (messages, tool arguments, results). -// Keeping this vocabulary local lets the raw journal remain forward-compatible -// and makes each translator reducer explicit about the fields it consumes. -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeAgentStart { - #[serde(default)] - prompt: Option, - #[serde(default)] - message: Option, - #[serde(default)] - images: Option>, -} - -/// Pi's before_agent_start images contain base64 data, separate from the prompt. -#[derive(Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -struct PromptImage { - data: String, - mime_type: String, -} - -/// `ctx.model`: the selected model, which may be a Pi 1.0 virtual model that -/// routes each request to a physical model. -#[derive(Deserialize, Serialize)] -struct SelectedModel { - provider: String, - id: String, -} - -#[derive(Deserialize, Serialize)] -struct ContextEvent { - #[serde(default)] - messages: Vec, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct MessageUpdate { - #[serde(default)] - assistant_message_event: Option, - #[serde(default, rename = "type")] - kind: Option, -} - -#[derive(Deserialize, Serialize)] -struct MessageDelta { - #[serde(default, rename = "type")] - kind: Option, -} - -#[derive(Deserialize, Serialize)] -struct ThinkingLevel { - #[serde(default)] - level: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct AssistantMessage { - #[serde(default)] - role: Option, - #[serde(default)] - provider: Option, - #[serde(default)] - api: Option, - #[serde(default)] - response_model: Option, - #[serde(default)] - routed_model: Option, - #[serde(default)] - resolved_model: Option, - #[serde(default)] - actual_model: Option, - #[serde(default)] - concrete_model: Option, - #[serde(default)] - output_model: Option, - #[serde(default)] - model: Option, - #[serde(default)] - usage: Usage, - #[serde(default)] - content: Vec, - #[serde(default)] - error_message: Option, - #[serde(default)] - stop_reason: Option, - #[serde(default)] - response_id: Option, - // Pi 1.0 records the level dispatched for this response, which a virtual - // model's router may choose independently of the selected level. - #[serde(default)] - thinking_level: Option, - #[serde(default)] - provider_thinking_level: Option, -} - -#[derive(Deserialize)] -#[serde(tag = "type")] -#[derive(Serialize)] -enum AssistantContent { - #[serde(rename = "text")] - Text { - #[serde(default)] - text: Option, - }, - #[serde(rename = "thinking")] - Thinking { - #[serde(default)] - thinking: Option, - }, - #[serde(rename = "toolCall")] - ToolCall { - #[serde(default)] - id: Option, - #[serde(default)] - name: Option, - #[serde(default)] - arguments: Option, - }, - #[serde(other)] - Other, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct ToolExecutionStart { - tool_call_id: String, - #[serde(default)] - tool_name: Option, - #[serde(default)] - args: Value, - // Pi 1.0 sets this on calls another tool made through - // `ctx.executeTool()`, such as codemode's `tools.()`. - #[serde(default)] - parent_tool_call_id: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct ToolExecutionEnd { - #[serde(default)] - tool_call_id: Option, - #[serde(default)] - tool_name: Option, - #[serde(default)] - result: Option, - #[serde(default)] - is_error: bool, - #[serde(default)] - parent_tool_call_id: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct AgentEnd { - #[serde(default)] - will_retry: bool, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct SessionCompact { - #[serde(default)] - compaction_entry: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct CompactionEntry { - #[serde(default)] - summary: Option, - #[serde(default)] - tokens_before: Option, - #[serde(default)] - timestamp: Option, -} - -#[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct Preparation { - #[serde(default)] - tokens_before: Option, - #[serde(default)] - first_kept_entry_id: Option, - #[serde(default)] - is_split_turn: Option, - #[serde(default)] - messages_to_summarize: Option>, - #[serde(default)] - turn_prefix_messages: Option>, - #[serde(default)] - target_id: Option, - #[serde(default)] - old_leaf_id: Option, - #[serde(default)] - common_ancestor_id: Option, - #[serde(default)] - user_wants_summary: Option, - #[serde(default)] - custom_instructions: Option, - #[serde(default)] - replace_instructions: Option, - #[serde(default)] - label: Option, - #[serde(default)] - entries_to_summarize: Option>, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeCompact { - #[serde(default)] - reason: Option, - #[serde(default)] - will_retry: Option, - #[serde(default)] - custom_instructions: Option, - #[serde(default)] - preparation: Option, - #[serde(default)] - branch_entries: Option>, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeTree { - #[serde(default)] - preparation: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct SessionTree { - #[serde(default)] - summary_entry: Option, -} - fn decode(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } @@ -408,35 +161,30 @@ impl AgentTranslator for PiTranslator { ops.extend(self.close_turn(envelope.ts_ms, None)); } "session_before_compact" => { - if let Some(event) = decode(event) { + if let Some(event) = decode::(event) { self.compaction = Some(( ids::span_id(&self.session_id, &format!("compaction:{}", envelope.ts_ms)), envelope.ts_ms, - compaction_input(&event), + event.input(), )); } } "session_compact" => { if let Some(typed) = decode::(event) { - self.active_compaction_message = compaction_message(&typed); + self.active_compaction_message = typed.summary_message(); } ops.extend(self.finish_special("Compaction", true, event, envelope.ts_ms)) } "session_before_tree" => { if let Some(event) = decode::(event) { - if event - .preparation - .as_ref() - .and_then(|preparation| preparation.user_wants_summary) - == Some(true) - { + if event.wants_summary() { self.branch_summary = Some(( ids::span_id( &self.session_id, &format!("branch-summary:{}", envelope.ts_ms), ), envelope.ts_ms, - branch_summary_input(&event), + event.input(), )); } } @@ -764,12 +512,12 @@ impl PiTranslator { } else { self.pending_llms.remove(0) }; - let model = response_model(&message); + let model = message.response_model(); let usage = &message.usage; let prompt = usage.input + usage.cache_read + usage.cache_write; let completion = usage.output; let total = usage.total_tokens.unwrap_or(prompt + completion); - let output = normalize_assistant(&message); + let output = message.normalized(); let failed = matches!(message.stop_reason.as_deref(), Some("error" | "aborted")); let error = failed.then(|| message.error_message.clone()).flatten(); if failed { @@ -786,10 +534,7 @@ impl PiTranslator { // Only a virtual selection differs from the physical model that answered. let selected_model = pending .selected_model - .filter(|selected| { - message.provider.as_deref() != Some(&selected.provider) - || message.model.as_deref() != Some(&selected.id) - }) + .filter(|selected| !message.matches_model(&selected.provider, &selected.id)) .map(|selected| format!("{}/{}", selected.provider, selected.id)); let mut metadata = json!(pending.request_config); if let (Value::Object(metadata), Value::Object(fields)) = ( @@ -915,7 +660,7 @@ impl PiTranslator { .unwrap_or_else(|| tracked.name.clone()); let mut skill_metadata = serde_json::Map::new(); if let Some(skill) = &skill { - insert_skill_metadata(&mut skill_metadata, skill, requested_skills); + skill.insert_metadata(&mut skill_metadata, requested_skills); } let row = SpanRow { span_id: self.tool_span_id(&call), @@ -1062,67 +807,6 @@ fn legacy_continuation(payload: &Value) -> Option { }) } -fn compaction_message(event: &SessionCompact) -> Option { - let entry = event.compaction_entry.as_ref()?; - let summary = entry.summary.clone()?; - Some(json!({ - "role": "compactionSummary", - "summary": summary, - "tokensBefore": entry.tokens_before, - "timestamp": entry.timestamp, - })) -} - -fn compaction_input(event: &BeforeCompact) -> Value { - let preparation = event.preparation.as_ref(); - json!({ - "reason": event.reason.clone(), - "willRetry": event.will_retry.clone(), - "customInstructions": event.custom_instructions.clone(), - "tokensBefore": preparation.and_then(|value| value.tokens_before), - "firstKeptEntryId": preparation.and_then(|value| value.first_kept_entry_id.clone()), - "isSplitTurn": preparation.and_then(|value| value.is_split_turn), - "messagesToSummarizeCount": preparation - .and_then(|value| value.messages_to_summarize.as_ref()) - .map(Vec::len), - "turnPrefixMessagesCount": preparation - .and_then(|value| value.turn_prefix_messages.as_ref()) - .map(Vec::len), - "branchEntryCount": event.branch_entries.as_ref().map(Vec::len), - }) -} - -fn branch_summary_input(event: &BeforeTree) -> Value { - let preparation = event.preparation.as_ref(); - json!({ - "targetId": preparation.and_then(|value| value.target_id.clone()), - "oldLeafId": preparation.and_then(|value| value.old_leaf_id.clone()), - "commonAncestorId": preparation.and_then(|value| value.common_ancestor_id.clone()), - "userWantsSummary": preparation.and_then(|value| value.user_wants_summary), - "customInstructions": preparation.and_then(|value| value.custom_instructions.clone()), - "replaceInstructions": preparation.and_then(|value| value.replace_instructions), - "label": preparation.and_then(|value| value.label.clone()), - "entriesToSummarizeCount": preparation - .and_then(|value| value.entries_to_summarize.as_ref()) - .map(Vec::len), - }) -} - -fn response_model(message: &AssistantMessage) -> Option { - [ - &message.response_model, - &message.routed_model, - &message.resolved_model, - &message.actual_model, - &message.concrete_model, - &message.output_model, - &message.model, - ] - .into_iter() - .flatten() - .next() - .cloned() -} /// The request configuration the instrumentation spec allows on LLM spans, /// read individually from the provider-native payload: sampling settings plus /// the available tool definitions and controls. Pi's API adapters name these @@ -1332,45 +1016,6 @@ fn tool_metadata(name: &str, call: &str, parent_call: Option<&str>, extra: Value } with_tool_approval(without_nulls(metadata), Some(ToolApproval::Approved)) } -fn normalize_assistant(message: &AssistantMessage) -> Value { - let mut text = String::new(); - let mut reasoning = String::new(); - let mut calls = Vec::new(); - for part in &message.content { - match part { - AssistantContent::Text { - text: Some(content), - } => text.push_str(content), - AssistantContent::Thinking { - thinking: Some(content), - } => reasoning.push_str(content), - AssistantContent::ToolCall { - id, - name, - arguments, - } => calls.push(json!({ - "id": id, - "type": "function", - "function": { - "name": name, - "arguments": serde_json::to_string( - arguments.as_ref().unwrap_or(&Value::Null), - ) - .unwrap_or_default(), - }, - })), - _ => {} - } - } - let mut out = json!({"role":"assistant","content":text}); - if !reasoning.is_empty() { - out["reasoning"] = json!([{"id":"reasoning","content":reasoning}]) - } - if !calls.is_empty() { - out["tool_calls"] = Value::Array(calls) - } - out -} fn skill_from_read(tool: &str, args: &Value) -> Option { if tool != "read" { return None; diff --git a/bt-daemon/src/translate/pi/assistant_message.rs b/bt-daemon/src/translate/pi/assistant_message.rs new file mode 100644 index 00000000..4b57516c --- /dev/null +++ b/bt-daemon/src/translate/pi/assistant_message.rs @@ -0,0 +1,136 @@ +//! Pi assistant messages own physical-model selection and span-message projection. +use crate::agents::usage::PiUsage as Usage; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct AssistantMessage { + #[serde(default)] + pub(super) role: Option, + #[serde(default)] + pub(super) provider: Option, + #[serde(default)] + pub(super) api: Option, + #[serde(default)] + response_model: Option, + #[serde(default)] + routed_model: Option, + #[serde(default)] + resolved_model: Option, + #[serde(default)] + actual_model: Option, + #[serde(default)] + concrete_model: Option, + #[serde(default)] + output_model: Option, + #[serde(default)] + model: Option, + #[serde(default)] + pub(super) usage: Usage, + #[serde(default)] + content: Vec, + #[serde(default)] + pub(super) error_message: Option, + #[serde(default)] + pub(super) stop_reason: Option, + #[serde(default)] + pub(super) response_id: Option, + // Pi 1.0 records the level dispatched for this response, which a virtual + // model's router may choose independently of the selected level. + #[serde(default)] + pub(super) thinking_level: Option, + #[serde(default)] + pub(super) provider_thinking_level: Option, +} + +#[derive(Deserialize)] +#[serde(tag = "type")] +#[derive(Serialize)] +enum AssistantContent { + #[serde(rename = "text")] + Text { + #[serde(default)] + text: Option, + }, + #[serde(rename = "thinking")] + Thinking { + #[serde(default)] + thinking: Option, + }, + #[serde(rename = "toolCall")] + ToolCall { + #[serde(default)] + id: Option, + #[serde(default)] + name: Option, + #[serde(default)] + arguments: Option, + }, + #[serde(other)] + Other, +} + +impl AssistantMessage { + /// Compare the native provider/model identity, independently of any routed + /// response-model aliases used for display metadata. + pub(super) fn matches_model(&self, provider: &str, id: &str) -> bool { + self.provider.as_deref() == Some(provider) && self.model.as_deref() == Some(id) + } + + pub(super) fn response_model(&self) -> Option { + [ + &self.response_model, + &self.routed_model, + &self.resolved_model, + &self.actual_model, + &self.concrete_model, + &self.output_model, + &self.model, + ] + .into_iter() + .flatten() + .next() + .cloned() + } + pub(super) fn normalized(&self) -> Value { + let mut text = String::new(); + let mut reasoning = String::new(); + let mut calls = Vec::new(); + for part in &self.content { + match part { + AssistantContent::Text { + text: Some(content), + } => text.push_str(content), + AssistantContent::Thinking { + thinking: Some(content), + } => reasoning.push_str(content), + AssistantContent::ToolCall { + id, + name, + arguments, + } => calls.push(json!({ + "id": id, + "type": "function", + "function": { + "name": name, + "arguments": serde_json::to_string( + arguments.as_ref().unwrap_or(&Value::Null), + ) + .unwrap_or_default(), + }, + })), + _ => {} + } + } + let mut out = json!({"role":"assistant","content":text}); + if !reasoning.is_empty() { + out["reasoning"] = json!([{"id":"reasoning","content":reasoning}]) + } + if !calls.is_empty() { + out["tool_calls"] = Value::Array(calls) + } + out + } +} diff --git a/bt-daemon/src/translate/pi/compaction.rs b/bt-daemon/src/translate/pi/compaction.rs new file mode 100644 index 00000000..51b88210 --- /dev/null +++ b/bt-daemon/src/translate/pi/compaction.rs @@ -0,0 +1,144 @@ +//! Native Pi compaction and branch-summary payloads and their span inputs. +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct SessionCompact { + #[serde(default)] + compaction_entry: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +struct CompactionEntry { + #[serde(default)] + summary: Option, + #[serde(default)] + tokens_before: Option, + #[serde(default)] + timestamp: Option, +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +struct Preparation { + #[serde(default)] + tokens_before: Option, + #[serde(default)] + first_kept_entry_id: Option, + #[serde(default)] + is_split_turn: Option, + #[serde(default)] + messages_to_summarize: Option>, + #[serde(default)] + turn_prefix_messages: Option>, + #[serde(default)] + target_id: Option, + #[serde(default)] + old_leaf_id: Option, + #[serde(default)] + common_ancestor_id: Option, + #[serde(default)] + user_wants_summary: Option, + #[serde(default)] + custom_instructions: Option, + #[serde(default)] + replace_instructions: Option, + #[serde(default)] + label: Option, + #[serde(default)] + entries_to_summarize: Option>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeCompact { + #[serde(default)] + reason: Option, + #[serde(default)] + will_retry: Option, + #[serde(default)] + custom_instructions: Option, + #[serde(default)] + preparation: Option, + #[serde(default)] + branch_entries: Option>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeTree { + #[serde(default)] + preparation: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct SessionTree { + #[serde(default)] + pub(super) summary_entry: Option, +} + +impl SessionCompact { + pub(super) fn summary_message(&self) -> Option { + let entry = self.compaction_entry.as_ref()?; + let summary = entry.summary.clone()?; + Some(json!({ + "role": "compactionSummary", + "summary": summary, + "tokensBefore": entry.tokens_before, + "timestamp": entry.timestamp, + })) + } +} +impl BeforeCompact { + pub(super) fn input(&self) -> Value { + let preparation = self.preparation.as_ref(); + json!({ + "reason": self.reason.clone(), + "willRetry": self.will_retry.clone(), + "customInstructions": self.custom_instructions.clone(), + "tokensBefore": preparation.and_then(|value| value.tokens_before), + "firstKeptEntryId": preparation.and_then(|value| value.first_kept_entry_id.clone()), + "isSplitTurn": preparation.and_then(|value| value.is_split_turn), + "messagesToSummarizeCount": preparation + .and_then(|value| value.messages_to_summarize.as_ref()) + .map(Vec::len), + "turnPrefixMessagesCount": preparation + .and_then(|value| value.turn_prefix_messages.as_ref()) + .map(Vec::len), + "branchEntryCount": self.branch_entries.as_ref().map(Vec::len), + }) + } +} +impl BeforeTree { + pub(super) fn wants_summary(&self) -> bool { + self.preparation + .as_ref() + .and_then(|preparation| preparation.user_wants_summary) + == Some(true) + } + + pub(super) fn input(&self) -> Value { + let preparation = self.preparation.as_ref(); + json!({ + "targetId": preparation.and_then(|value| value.target_id.clone()), + "oldLeafId": preparation.and_then(|value| value.old_leaf_id.clone()), + "commonAncestorId": preparation.and_then(|value| value.common_ancestor_id.clone()), + "userWantsSummary": preparation.and_then(|value| value.user_wants_summary), + "customInstructions": preparation.and_then(|value| value.custom_instructions.clone()), + "replaceInstructions": preparation.and_then(|value| value.replace_instructions), + "label": preparation.and_then(|value| value.label.clone()), + "entriesToSummarizeCount": preparation + .and_then(|value| value.entries_to_summarize.as_ref()) + .map(Vec::len), + }) + } +} diff --git a/bt-daemon/src/translate/pi/event.rs b/bt-daemon/src/translate/pi/event.rs new file mode 100644 index 00000000..302450ba --- /dev/null +++ b/bt-daemon/src/translate/pi/event.rs @@ -0,0 +1,103 @@ +//! Partial Pi callback payloads. Correlation remains in the parent reducer. +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +// These are deliberately partial native event types. Serde ignores fields we +// do not model, while `Value` remains at the user-controlled JSON boundaries +// that we forward without interpreting (messages, tool arguments, results). +// Keeping this vocabulary local lets the raw journal remain forward-compatible +// and makes each translator reducer explicit about the fields it consumes. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeAgentStart { + #[serde(default)] + pub(super) prompt: Option, + #[serde(default)] + pub(super) message: Option, + #[serde(default)] + pub(super) images: Option>, +} + +/// Pi's before_agent_start images contain base64 data, separate from the prompt. +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct PromptImage { + pub(super) data: String, + pub(super) mime_type: String, +} + +/// `ctx.model`: the selected model, which may be a Pi 1.0 virtual model that +/// routes each request to a physical model. +#[derive(Deserialize, Serialize)] +pub(super) struct SelectedModel { + pub(super) provider: String, + pub(super) id: String, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct ContextEvent { + #[serde(default)] + pub(super) messages: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct MessageUpdate { + #[serde(default)] + pub(super) assistant_message_event: Option, + #[serde(default, rename = "type")] + pub(super) kind: Option, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct MessageDelta { + #[serde(default, rename = "type")] + pub(super) kind: Option, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct ThinkingLevel { + #[serde(default)] + pub(super) level: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct ToolExecutionStart { + pub(super) tool_call_id: String, + #[serde(default)] + pub(super) tool_name: Option, + #[serde(default)] + pub(super) args: Value, + // Pi 1.0 sets this on calls another tool made through + // `ctx.executeTool()`, such as codemode's `tools.()`. + #[serde(default)] + pub(super) parent_tool_call_id: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct ToolExecutionEnd { + #[serde(default)] + pub(super) tool_call_id: Option, + #[serde(default)] + pub(super) tool_name: Option, + #[serde(default)] + pub(super) result: Option, + #[serde(default)] + pub(super) is_error: bool, + #[serde(default)] + pub(super) parent_tool_call_id: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct AgentEnd { + #[serde(default)] + pub(super) will_retry: bool, +} diff --git a/bt-daemon/src/translate/tool.rs b/bt-daemon/src/translate/tool.rs index 6c5e5a4b..5cc0f653 100644 --- a/bt-daemon/src/translate/tool.rs +++ b/bt-daemon/src/translate/tool.rs @@ -4,6 +4,9 @@ //! This module only encodes the common Braintrust representation once that //! source-specific interpretation has been made. +mod skill_load; +pub use skill_load::SkillLoad; + use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; @@ -61,32 +64,6 @@ pub fn compile_skill_regex(pattern: &str) -> Option { } } -/// A tool call that loaded a skill, as far as the source reveals it. -#[derive(Default, Serialize, Deserialize)] -pub struct SkillLoad { - pub name: Option, - pub path: Option, -} - -/// Records a skill load on a tool span. Only a load the user asked for is -/// explicit; the model choosing a skill on its own carries no trigger. -pub fn insert_skill_metadata( - metadata: &mut Map, - load: &SkillLoad, - requested: &[String], -) { - metadata.insert("tool_kind".into(), json!("skill")); - if let Some(name) = &load.name { - metadata.insert("skill_name".into(), json!(name)); - if skill_was_requested(requested, name) { - metadata.insert("skill_load_trigger".into(), json!("explicit")); - } - } - if let Some(path) = &load.path { - metadata.insert("skill_path".into(), json!(path)); - } -} - /// Appends `name` unless it is already present, keeping first-seen order. pub fn push_unique(names: &mut Vec, name: String) { if !names.contains(&name) { diff --git a/bt-daemon/src/translate/tool/skill_load.rs b/bt-daemon/src/translate/tool/skill_load.rs new file mode 100644 index 00000000..12690077 --- /dev/null +++ b/bt-daemon/src/translate/tool/skill_load.rs @@ -0,0 +1,39 @@ +//! The identity and common span representation of a skill load. +use super::skill_was_requested; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +/// A tool call that loaded a skill, as far as the source reveals it. +#[derive(Default, Serialize, Deserialize)] +pub struct SkillLoad { + pub name: Option, + pub path: Option, +} + +impl SkillLoad { + pub fn display_name(&self) -> String { + self.name + .as_ref() + .map_or_else(|| "skill".into(), |name| format!("skill: {name}")) + } + + pub fn was_requested(&self, requested: &[String]) -> bool { + self.name + .as_deref() + .is_some_and(|name| skill_was_requested(requested, name)) + } + + /// Only a load the user asked for carries an explicit trigger. + pub fn insert_metadata(&self, metadata: &mut Map, requested: &[String]) { + metadata.insert("tool_kind".into(), json!("skill")); + if let Some(name) = &self.name { + metadata.insert("skill_name".into(), json!(name)); + if self.was_requested(requested) { + metadata.insert("skill_load_trigger".into(), json!("explicit")); + } + } + if let Some(path) = &self.path { + metadata.insert("skill_path".into(), json!(path)); + } + } +} diff --git a/bt-daemon/src/wire/auth_selection.rs b/bt-daemon/src/wire/auth_selection.rs new file mode 100644 index 00000000..e2df06c5 --- /dev/null +++ b/bt-daemon/src/wire/auth_selection.rs @@ -0,0 +1,48 @@ +use super::AuthSource; +use serde::{Deserialize, Serialize}; + +/// Non-secret auth selection. An optional organization constrains credentials +/// that can address more than one organization. +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct AuthSelection { + #[serde(default, skip_serializing_if = "AuthSource::is_auto")] + pub source: AuthSource, + /// Immutable profile identifier. Preferred over the legacy display name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_name: Option, +} + +impl AuthSelection { + /// Interpret old `profile: "environment"` routes as environment auth + /// without preserving the synthetic value as a saved profile name. + pub fn effective_source(&self) -> AuthSource { + match self.source { + AuthSource::Auto if self.profile.as_deref() == Some("environment") => { + AuthSource::Environment + } + AuthSource::Auto if self.profile_id.is_some() || self.profile.is_some() => { + AuthSource::SavedProfile + } + source => source, + } + } + + pub fn canonicalized(mut self) -> anyhow::Result { + self.source = self.effective_source(); + match self.source { + AuthSource::SavedProfile if self.profile_id.is_none() && self.profile.is_none() => { + anyhow::bail!("saved-profile auth requires a profile ID or name") + } + AuthSource::Environment => { + self.profile_id = None; + self.profile = None; + } + AuthSource::Auto | AuthSource::SavedProfile => {} + } + Ok(self) + } +} diff --git a/bt-daemon/src/wire/auth_source.rs b/bt-daemon/src/wire/auth_source.rs new file mode 100644 index 00000000..d4abf0a0 --- /dev/null +++ b/bt-daemon/src/wire/auth_source.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// The non-secret credential source selected for a session route. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuthSource { + /// Resolve using the host's ordinary precedence rules. Retained for old + /// profile-less routes; newly resolved command routes are canonicalized. + #[default] + Auto, + /// Resolve a named credential from the host's saved profile store. + SavedProfile, + /// Resolve BRAINTRUST_API_KEY from the process environment at delivery + /// time. The key itself is never serialized into the route. + Environment, +} + +impl AuthSource { + pub(super) fn is_auto(&self) -> bool { + *self == Self::Auto + } +} diff --git a/bt-daemon/src/wire/backend_auth.rs b/bt-daemon/src/wire/backend_auth.rs new file mode 100644 index 00000000..8738c298 --- /dev/null +++ b/bt-daemon/src/wire/backend_auth.rs @@ -0,0 +1,19 @@ +use serde::{Deserialize, Serialize}; + +/// Backend credentials. `token` is an API key or an OAuth access token; the +/// daemon does not care which. Never serialized or persisted. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct BackendAuth { + pub token: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub app_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_name: Option, + /// Optional org id. `bt` may or may not know it; the SDK's project + /// registration works from `org_name` alone, so this is best-effort and + /// only feeds the SDK's per-session credential/batch key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_id: Option, +} diff --git a/bt-daemon/src/wire/capture_context.rs b/bt-daemon/src/wire/capture_context.rs new file mode 100644 index 00000000..317e555e --- /dev/null +++ b/bt-daemon/src/wire/capture_context.rs @@ -0,0 +1,16 @@ +use super::ProcessIdentity; +use serde::{Deserialize, Serialize}; + +/// Process evidence captured at the hook or in-process adapter boundary. +/// +/// `process_chain` is ordered from the process that connected to the daemon +/// toward the operating-system root. It intentionally excludes full command +/// lines, environment variables, and working directories. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CaptureContext { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub process_chain: Vec, + /// The process walk stopped before reaching the operating-system root. + #[serde(default)] + pub truncated: bool, +} diff --git a/bt-daemon/src/wire/envelope.rs b/bt-daemon/src/wire/envelope.rs index 89193d28..6bdfc2cb 100644 --- a/bt-daemon/src/wire/envelope.rs +++ b/bt-daemon/src/wire/envelope.rs @@ -1,36 +1,7 @@ -//! The `event.log` envelope and its session config, plus auth redaction for -//! the journal. +//! Native capture envelope and its journal-safe projection. -use braintrust_sdk_rust::SpanComponents; +use super::{CaptureContext, RedactedEnvelope, SessionConfig, SessionRoute}; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeSet, path::PathBuf}; - -/// One operating-system process observed while capturing an event. -/// -/// A PID alone is not a stable identity because operating systems reuse it. -/// `start_time_secs`, when available, distinguishes different occupants of the -/// same PID. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct ProcessIdentity { - pub pid: u32, - /// Epoch seconds reported by the operating system, or zero if unavailable. - #[serde(default)] - pub start_time_secs: u64, -} - -/// Process evidence captured at the hook or in-process adapter boundary. -/// -/// `process_chain` is ordered from the process that connected to the daemon -/// toward the operating-system root. It intentionally excludes full command -/// lines, environment variables, and working directories. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CaptureContext { - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub process_chain: Vec, - /// The process walk stopped before reaching the operating-system root. - #[serde(default)] - pub truncated: bool, -} /// One captured hook event, forwarded from a shim to the daemon. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -71,265 +42,6 @@ pub struct Envelope { pub config: Option, } -/// The non-secret credential source selected for a session route. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum AuthSource { - /// Resolve using the host's ordinary precedence rules. Retained for old - /// profile-less routes; newly resolved command routes are canonicalized. - #[default] - Auto, - /// Resolve a named credential from the host's saved profile store. - SavedProfile, - /// Resolve BRAINTRUST_API_KEY from the process environment at delivery - /// time. The key itself is never serialized into the route. - Environment, -} - -/// Non-secret auth selection. An optional organization constrains credentials -/// that can address more than one organization. -#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct AuthSelection { - #[serde(default, skip_serializing_if = "AuthSource::is_auto")] - pub source: AuthSource, - /// Immutable profile identifier. Preferred over the legacy display name. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub profile_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub profile: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_name: Option, -} - -impl AuthSource { - fn is_auto(&self) -> bool { - *self == Self::Auto - } -} - -impl AuthSelection { - /// Interpret old `profile: "environment"` routes as environment auth - /// without preserving the synthetic value as a saved profile name. - pub fn effective_source(&self) -> AuthSource { - match self.source { - AuthSource::Auto if self.profile.as_deref() == Some("environment") => { - AuthSource::Environment - } - AuthSource::Auto if self.profile_id.is_some() || self.profile.is_some() => { - AuthSource::SavedProfile - } - source => source, - } - } - - pub fn canonicalized(mut self) -> anyhow::Result { - self.source = self.effective_source(); - match self.source { - AuthSource::SavedProfile if self.profile_id.is_none() && self.profile.is_none() => { - anyhow::bail!("saved-profile auth requires a profile ID or name") - } - AuthSource::Environment => { - self.profile_id = None; - self.profile = None; - } - AuthSource::Auto | AuthSource::SavedProfile => {} - } - Ok(self) - } -} - -/// Immutable, journal-safe routing and trace settings for one agent session. -/// Credentials are deliberately absent and are resolved inside the daemon. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct SessionRoute { - #[serde(default)] - pub auth: AuthSelection, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub destination: Option, - #[serde(default)] - pub flush_mode: FlushMode, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_metadata: Option, - /// Tags applied to each root span for this session. - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub tags: BTreeSet, - /// Ordered JavaScript span transforms. Paths are resolved by explicit - /// setup, run, and import commands before entering a session route. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub span_plugins: Vec, -} - -impl SessionRoute { - pub fn with_auth(&self, auth: BackendAuth) -> SessionConfig { - SessionConfig { - auth, - destination: self.destination.clone(), - flush_mode: self.flush_mode, - additional_metadata: self.additional_metadata.clone(), - tags: self.tags.clone(), - span_plugins: self.span_plugins.clone(), - } - } - - pub fn same_route(&self, other: &Self) -> bool { - let mut left = self.clone(); - let mut right = other.clone(); - if left - .auth - .profile_id - .as_ref() - .zip(right.auth.profile_id.as_ref()) - .is_some_and(|(left, right)| left != right) - { - return false; - } - // A stable-ID route is the canonical successor to an old named route. - // Journals can legitimately contain both forms for the same session, - // so replay compares their unchanged routing intent, not the newly - // learned identifier. - left.auth.profile_id = None; - right.auth.profile_id = None; - left.auth.source = left.auth.effective_source(); - right.auth.source = right.auth.effective_source(); - serde_json::to_value(left).ok() == serde_json::to_value(right).ok() - } - - /// Delivery settings may change without moving held work to another destination. - pub(crate) fn same_destination(&self, other: &Self) -> bool { - let identity = |route: &Self| Self { - auth: route.auth.clone(), - destination: route.destination.clone(), - ..Self::default() - }; - identity(self).same_route(&identity(other)) - } - - /// Raw journal entries can be replayed through a newer plugin chain as - /// long as their Braintrust delivery route is otherwise unchanged. - pub fn same_replay_route(&self, other: &Self) -> bool { - let mut left = self.clone(); - let mut right = other.clone(); - left.span_plugins.clear(); - right.span_plugins.clear(); - left.same_route(&right) - } -} - -/// Trace settings and backend credentials resolved by the shim. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SessionConfig { - pub auth: BackendAuth, - /// Typed trace destination. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub destination: Option, - #[serde(default)] - pub flush_mode: FlushMode, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_metadata: Option, - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub tags: BTreeSet, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub span_plugins: Vec, -} - -/// Where a session's root span should be logged. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum TraceDestination { - /// Project logs selected by stable id, display name, or both. - ProjectLogs { - #[serde(default, skip_serializing_if = "Option::is_none")] - project_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - project_name: Option, - }, - /// An existing experiment. - Experiment { experiment_id: String }, - /// A child of an exported Braintrust span. - ParentSpan { components: SpanComponents }, -} - -impl SessionConfig { - /// External parent/root ids used to shape translator rows. The sink keeps - /// the full destination components for object routing and propagation. - pub fn attached_span_ids(&self) -> (Option, Option) { - if let Some(TraceDestination::ParentSpan { components }) = &self.destination { - return (components.span_id.clone(), components.root_span_id.clone()); - } - (None, None) - } - - pub fn project_name(&self) -> Option<&str> { - match &self.destination { - Some(TraceDestination::ProjectLogs { project_name, .. }) => project_name.as_deref(), - _ => None, - } - } -} - -impl std::str::FromStr for TraceDestination { - type Err = String; - - fn from_str(value: &str) -> Result { - let (kind, id) = value.split_once(':').ok_or_else(|| { - "destination must be project_logs: or experiment:" - .to_string() - })?; - if id.is_empty() { - return Err("destination id must not be empty".to_string()); - } - match kind { - "project_logs" => Ok(Self::ProjectLogs { - project_id: Some(id.to_string()), - project_name: None, - }), - "experiment" => Ok(Self::Experiment { - experiment_id: id.to_string(), - }), - _ => Err(format!( - "unsupported destination {kind:?}; expected project_logs or experiment" - )), - } - } -} - -impl TraceDestination { - pub fn project_name(&self) -> Option<&str> { - match self { - Self::ProjectLogs { project_name, .. } => project_name.as_deref(), - _ => None, - } - } -} - -/// Backend credentials. `token` is an API key or an OAuth access token; the -/// daemon does not care which. Never serialized or persisted. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct BackendAuth { - pub token: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_url: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub app_url: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_name: Option, - /// Optional org id. `bt` may or may not know it; the SDK's project - /// registration works from `org_name` alone, so this is best-effort and - /// only feeds the SDK's per-session credential/batch key. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_id: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum FlushMode { - /// Deliver in the background; flush on session end / idle. The default. - #[default] - FireAndForget, - /// Additionally block on `session.flush` at each turn boundary. - FlushOnTurnEnd, -} - impl Envelope { /// A copy safe to journal. Only the non-secret route is serializable; the /// daemon-internal resolved config is excluded by construction. @@ -348,231 +60,3 @@ impl Envelope { } } } - -/// Journal form of [`Envelope`] with the token redacted. Deserializable so a -/// replay pass can read it back (and re-supply live credentials separately). -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RedactedEnvelope { - pub source: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_version: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub plugin_version: Option, - pub session_id: String, - pub event: String, - pub ts_ms: i64, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub managed_run_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub capture: Option, - pub payload: serde_json::Value, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub route: Option, -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> Envelope { - Envelope { - source: "codex".into(), - source_version: Some("1.2.3".into()), - plugin_version: Some("0.4.0".into()), - session_id: "sess-1".into(), - event: "PostToolUse".into(), - ts_ms: 1_753_639_552_123, - managed_run_id: Some("run-1".into()), - capture: Some(CaptureContext { - process_chain: vec![ProcessIdentity { - pid: 42, - start_time_secs: 1_753_639_500, - }], - truncated: false, - }), - payload: serde_json::json!({ "session_id": "sess-1", "tool_name": "shell" }), - route: Some(SessionRoute { - auth: AuthSelection { - source: AuthSource::SavedProfile, - profile_id: None, - profile: Some("work".into()), - org_name: Some("acme".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("codex".into()), - }), - ..SessionRoute::default() - }), - config: Some(SessionConfig { - auth: BackendAuth { - token: "sk-super-secret".into(), - api_url: Some("https://api.braintrust.dev".into()), - app_url: None, - org_name: Some("acme".into()), - org_id: None, - }, - destination: None, - flush_mode: FlushMode::FireAndForget, - tags: Default::default(), - additional_metadata: None, - span_plugins: Vec::new(), - }), - } - } - - #[test] - fn envelope_round_trips() { - let e = sample(); - let s = serde_json::to_string(&e).unwrap(); - let back: Envelope = serde_json::from_str(&s).unwrap(); - assert_eq!(back.session_id, "sess-1"); - assert_eq!(back.managed_run_id.as_deref(), Some("run-1")); - assert_eq!( - back.capture.as_ref().unwrap().process_chain[0], - ProcessIdentity { - pid: 42, - start_time_secs: 1_753_639_500, - } - ); - assert_eq!(back.route.unwrap().auth.profile.as_deref(), Some("work")); - assert!(back.config.is_none()); - assert!(!s.contains("sk-super-secret")); - } - - #[test] - fn journal_form_contains_only_the_route() { - let e = sample(); - let r = e.redacted(); - let s = serde_json::to_string(&r).unwrap(); - assert!( - !s.contains("sk-super-secret"), - "token leaked into journal form: {s}" - ); - assert_eq!(r.route.unwrap().auth.profile.as_deref(), Some("work")); - assert_eq!(r.managed_run_id.as_deref(), Some("run-1")); - assert_eq!(r.capture.unwrap().process_chain[0].pid, 42); - } - - #[test] - fn capture_context_is_backward_compatible() { - let mut value = serde_json::to_value(sample()).unwrap(); - value.as_object_mut().unwrap().remove("capture"); - - let envelope: Envelope = serde_json::from_value(value).unwrap(); - - assert!(envelope.capture.is_none()); - } - - #[test] - fn route_is_journal_safe_and_builds_resolved_config() { - let route = SessionRoute { - auth: AuthSelection { - source: AuthSource::SavedProfile, - profile_id: None, - profile: Some("work".into()), - org_name: Some("acme".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("agent-traces".into()), - }), - ..SessionRoute::default() - }; - let config = route.with_auth(BackendAuth { - token: "secret".into(), - api_url: None, - app_url: None, - org_name: Some("acme".into()), - org_id: None, - }); - assert!(matches!( - config.destination, - Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) - if name == "agent-traces" - )); - assert_eq!(route.auth.profile.as_deref(), Some("work")); - - let mut envelope = sample(); - envelope.route = Some(route); - envelope.config = Some(config); - let journal = serde_json::to_string(&envelope.redacted()).unwrap(); - assert!(journal.contains("work")); - assert!(!journal.contains("secret")); - } - - #[test] - fn environment_auth_serializes_without_a_profile_or_secret() { - let selection = AuthSelection { - source: AuthSource::Environment, - profile_id: None, - profile: None, - org_name: Some("acme".into()), - }; - let json = serde_json::to_string(&selection).unwrap(); - assert_eq!(json, r#"{"source":"environment","org_name":"acme"}"#); - assert!(!json.contains("BRAINTRUST_API_KEY")); - } - - #[test] - fn legacy_environment_profile_canonicalizes_to_environment_auth() { - let selection: AuthSelection = - serde_json::from_str(r#"{"profile":"environment","org_name":"acme"}"#).unwrap(); - assert_eq!(selection.effective_source(), AuthSource::Environment); - let canonical = selection.canonicalized().unwrap(); - assert_eq!(canonical.source, AuthSource::Environment); - assert_eq!(canonical.profile, None); - assert_eq!(canonical.org_name.as_deref(), Some("acme")); - } - - #[test] - fn stable_profile_id_route_matches_its_legacy_name_route() { - let legacy = SessionRoute { - auth: AuthSelection { - source: AuthSource::Auto, - profile_id: None, - profile: Some("test-profile".into()), - org_name: Some("test-org".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("test-project".into()), - }), - ..SessionRoute::default() - }; - let mut canonical = legacy.clone(); - canonical.auth.source = AuthSource::SavedProfile; - canonical.auth.profile_id = Some("00000000-0000-4000-8000-000000000001".into()); - - assert!(legacy.same_route(&canonical)); - canonical.auth.profile = Some("other-profile".into()); - assert!(!legacy.same_route(&canonical)); - } - - #[test] - fn flush_mode_defaults_to_fire_and_forget() { - let json = serde_json::json!({ - "auth": { "token": "t" }, - }); - let cfg: SessionConfig = serde_json::from_value(json).unwrap(); - assert_eq!(cfg.flush_mode, FlushMode::FireAndForget); - } - - #[test] - fn import_destination_references_are_typed() { - let project: TraceDestination = "project_logs:proj-123".parse().unwrap(); - assert!(matches!( - project, - TraceDestination::ProjectLogs { - project_id: Some(ref id), - project_name: None - } if id == "proj-123" - )); - let experiment: TraceDestination = "experiment:exp-456".parse().unwrap(); - assert!(matches!( - experiment, - TraceDestination::Experiment { ref experiment_id } if experiment_id == "exp-456" - )); - assert!("project:ambiguous".parse::().is_err()); - } -} diff --git a/bt-daemon/src/wire/envelope_tests.rs b/bt-daemon/src/wire/envelope_tests.rs new file mode 100644 index 00000000..c75e9599 --- /dev/null +++ b/bt-daemon/src/wire/envelope_tests.rs @@ -0,0 +1,220 @@ +use super::*; + +fn sample() -> Envelope { + Envelope { + source: "codex".into(), + source_version: Some("1.2.3".into()), + plugin_version: Some("0.4.0".into()), + session_id: "sess-1".into(), + event: "PostToolUse".into(), + ts_ms: 1_753_639_552_123, + managed_run_id: Some("run-1".into()), + capture: Some(CaptureContext { + process_chain: vec![ProcessIdentity { + pid: 42, + start_time_secs: 1_753_639_500, + }], + truncated: false, + }), + payload: serde_json::json!({ "session_id": "sess-1", "tool_name": "shell" }), + route: Some(SessionRoute { + auth: AuthSelection { + source: AuthSource::SavedProfile, + profile_id: None, + profile: Some("work".into()), + org_name: Some("acme".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("codex".into()), + }), + ..SessionRoute::default() + }), + config: Some(SessionConfig { + auth: BackendAuth { + token: "sk-super-secret".into(), + api_url: Some("https://api.braintrust.dev".into()), + app_url: None, + org_name: Some("acme".into()), + org_id: None, + }, + destination: None, + flush_mode: FlushMode::FireAndForget, + tags: Default::default(), + additional_metadata: None, + span_plugins: Vec::new(), + }), + } +} + +#[test] +fn envelope_round_trips() { + let e = sample(); + let s = serde_json::to_string(&e).unwrap(); + let back: Envelope = serde_json::from_str(&s).unwrap(); + assert_eq!(back.session_id, "sess-1"); + assert_eq!(back.managed_run_id.as_deref(), Some("run-1")); + assert_eq!( + back.capture.as_ref().unwrap().process_chain[0], + ProcessIdentity { + pid: 42, + start_time_secs: 1_753_639_500, + } + ); + assert_eq!(back.route.unwrap().auth.profile.as_deref(), Some("work")); + assert!(back.config.is_none()); + assert!(!s.contains("sk-super-secret")); +} + +#[test] +fn journal_form_contains_only_the_route() { + let e = sample(); + let r = e.redacted(); + let s = serde_json::to_string(&r).unwrap(); + assert!( + !s.contains("sk-super-secret"), + "token leaked into journal form: {s}" + ); + assert_eq!(r.route.unwrap().auth.profile.as_deref(), Some("work")); + assert_eq!(r.managed_run_id.as_deref(), Some("run-1")); + assert_eq!(r.capture.unwrap().process_chain[0].pid, 42); +} + +#[test] +fn capture_context_is_backward_compatible() { + let mut value = serde_json::to_value(sample()).unwrap(); + value.as_object_mut().unwrap().remove("capture"); + + let envelope: Envelope = serde_json::from_value(value).unwrap(); + + assert!(envelope.capture.is_none()); +} + +#[test] +fn route_is_journal_safe_and_builds_resolved_config() { + let route = SessionRoute { + auth: AuthSelection { + source: AuthSource::SavedProfile, + profile_id: None, + profile: Some("work".into()), + org_name: Some("acme".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("agent-traces".into()), + }), + ..SessionRoute::default() + }; + let config = route.with_auth(BackendAuth { + token: "secret".into(), + api_url: None, + app_url: None, + org_name: Some("acme".into()), + org_id: None, + }); + assert!(matches!( + config.destination, + Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) + if name == "agent-traces" + )); + assert_eq!(route.auth.profile.as_deref(), Some("work")); + + let mut envelope = sample(); + envelope.route = Some(route); + envelope.config = Some(config); + let journal = serde_json::to_string(&envelope.redacted()).unwrap(); + assert!(journal.contains("work")); + assert!(!journal.contains("secret")); +} + +#[test] +fn environment_auth_serializes_without_a_profile_or_secret() { + let selection = AuthSelection { + source: AuthSource::Environment, + profile_id: None, + profile: None, + org_name: Some("acme".into()), + }; + let json = serde_json::to_string(&selection).unwrap(); + assert_eq!(json, r#"{"source":"environment","org_name":"acme"}"#); + assert!(!json.contains("BRAINTRUST_API_KEY")); +} + +#[test] +fn legacy_environment_profile_canonicalizes_to_environment_auth() { + let selection: AuthSelection = + serde_json::from_str(r#"{"profile":"environment","org_name":"acme"}"#).unwrap(); + assert_eq!(selection.effective_source(), AuthSource::Environment); + let canonical = selection.canonicalized().unwrap(); + assert_eq!(canonical.source, AuthSource::Environment); + assert_eq!(canonical.profile, None); + assert_eq!(canonical.org_name.as_deref(), Some("acme")); +} + +#[test] +fn stable_profile_id_route_matches_its_legacy_name_route() { + let legacy = SessionRoute { + auth: AuthSelection { + source: AuthSource::Auto, + profile_id: None, + profile: Some("test-profile".into()), + org_name: Some("test-org".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("test-project".into()), + }), + ..SessionRoute::default() + }; + let mut canonical = legacy.clone(); + canonical.auth.source = AuthSource::SavedProfile; + canonical.auth.profile_id = Some("00000000-0000-4000-8000-000000000001".into()); + + assert!(legacy.same_route(&canonical)); + canonical.auth.profile = Some("other-profile".into()); + assert!(!legacy.same_route(&canonical)); +} + +#[test] +fn flush_mode_defaults_to_fire_and_forget() { + let json = serde_json::json!({ + "auth": { "token": "t" }, + }); + let cfg: SessionConfig = serde_json::from_value(json).unwrap(); + assert_eq!(cfg.flush_mode, FlushMode::FireAndForget); +} + +#[test] +fn import_destination_references_are_typed() { + let project: TraceDestination = "project_logs:proj-123".parse().unwrap(); + assert!(matches!( + project, + TraceDestination::ProjectLogs { + project_id: Some(ref id), + project_name: None + } if id == "proj-123" + )); + let experiment: TraceDestination = "experiment:exp-456".parse().unwrap(); + assert!(matches!( + experiment, + TraceDestination::Experiment { ref experiment_id } if experiment_id == "exp-456" + )); + assert!("project:ambiguous".parse::().is_err()); +} + +#[test] +fn replay_restores_non_secret_route_configuration_without_credentials() { + let native = sample(); + let redacted = native.redacted(); + let recorded = serde_json::to_value(&redacted).unwrap(); + let replay = redacted.into_envelope(); + assert_eq!(serde_json::to_value(replay.redacted()).unwrap(), recorded); + let config = replay.config.unwrap(); + assert!(config.auth.token.is_empty()); + assert_eq!(config.auth.org_name.as_deref(), Some("acme")); + assert_eq!(config.project_name(), Some("codex")); + + let mut without_route = native.redacted(); + without_route.route = None; + assert!(without_route.into_envelope().config.is_none()); +} diff --git a/bt-daemon/src/wire/flush_mode.rs b/bt-daemon/src/wire/flush_mode.rs new file mode 100644 index 00000000..6154208c --- /dev/null +++ b/bt-daemon/src/wire/flush_mode.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FlushMode { + /// Deliver in the background; flush on session end / idle. The default. + #[default] + FireAndForget, + /// Additionally block on `session.flush` at each turn boundary. + FlushOnTurnEnd, +} diff --git a/bt-daemon/src/wire/mod.rs b/bt-daemon/src/wire/mod.rs index b6a74357..e4975645 100644 --- a/bt-daemon/src/wire/mod.rs +++ b/bt-daemon/src/wire/mod.rs @@ -1,25 +1,45 @@ //! bt-daemon wire protocol: the envelope types and JSON-RPC framing shared by //! the daemon (`serve`) and the plugin shims (`hook`). //! -//! This module is pure data + (de)serialization — no I/O, no async. The +//! Wire types own serialization and shared in-memory interpretation, without +//! I/O or async operations. The //! canonical description of the protocol lives in `docs/protocol.md`; keep //! the two in sync. +mod auth_selection; +mod auth_source; +mod backend_auth; +mod capture_context; mod envelope; +#[cfg(test)] +mod envelope_tests; +mod flush_mode; mod methods; +mod process_identity; +mod redacted_envelope; mod rpc; +mod session_config; +mod session_route; +mod trace_destination; -pub use envelope::{ - AuthSelection, AuthSource, BackendAuth, CaptureContext, Envelope, FlushMode, ProcessIdentity, - RedactedEnvelope, SessionConfig, SessionRoute, TraceDestination, -}; +pub use auth_selection::AuthSelection; +pub use auth_source::AuthSource; +pub use backend_auth::BackendAuth; +pub use capture_context::CaptureContext; +pub use envelope::Envelope; +pub use flush_mode::FlushMode; pub use methods::{ method, AuthDiagnoseParams, AuthDiagnoseResult, Capabilities, ClientInfo, EventLogResult, FlushParams, FlushResult, ImportFinishParams, ImportFinishResult, ImportResetParams, InitializeParams, InitializeResult, ManagedRunFlushParams, RecoveryInfo, SessionStatus, ShutdownResult, StatusParams, StatusResult, }; +pub use process_identity::ProcessIdentity; +pub use redacted_envelope::RedactedEnvelope; pub use rpc::{error_code, Message, Request, RequestId, Response, RpcError}; +pub use session_config::SessionConfig; +pub use session_route::SessionRoute; +pub use trace_destination::TraceDestination; /// The protocol version this build speaks. Bumped on any breaking change to /// the envelope or method contracts. See `docs/protocol.md`. diff --git a/bt-daemon/src/wire/process_identity.rs b/bt-daemon/src/wire/process_identity.rs new file mode 100644 index 00000000..96598f87 --- /dev/null +++ b/bt-daemon/src/wire/process_identity.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +/// One operating-system process observed while capturing an event. +/// +/// A PID alone is not a stable identity because operating systems reuse it. +/// `start_time_secs`, when available, distinguishes different occupants of the +/// same PID. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessIdentity { + pub pid: u32, + /// Epoch seconds reported by the operating system, or zero if unavailable. + #[serde(default)] + pub start_time_secs: u64, +} diff --git a/bt-daemon/src/wire/redacted_envelope.rs b/bt-daemon/src/wire/redacted_envelope.rs new file mode 100644 index 00000000..669147f3 --- /dev/null +++ b/bt-daemon/src/wire/redacted_envelope.rs @@ -0,0 +1,53 @@ +use super::{BackendAuth, CaptureContext, Envelope, SessionRoute}; +use serde::{Deserialize, Serialize}; + +/// Journal form of [`Envelope`] with the token redacted. Deserializable so a +/// replay pass can read it back (and re-supply live credentials separately). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedactedEnvelope { + pub source: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plugin_version: Option, + pub session_id: String, + pub event: String, + pub ts_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub managed_run_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capture: Option, + pub payload: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub route: Option, +} + +impl RedactedEnvelope { + /// Restore translator state without credentials. A replay route supplies + /// non-secret configuration; live delivery must resolve credentials again. + pub fn into_envelope(self) -> Envelope { + let route = self.route; + let config = route.as_ref().map(|route| { + route.with_auth(BackendAuth { + token: String::new(), + api_url: None, + app_url: None, + org_name: route.auth.org_name.clone(), + org_id: None, + }) + }); + Envelope { + source: self.source, + source_version: self.source_version, + plugin_version: self.plugin_version, + session_id: self.session_id, + event: self.event, + ts_ms: self.ts_ms, + managed_run_id: self.managed_run_id, + capture: self.capture, + payload: self.payload, + route, + config, + } + } +} diff --git a/bt-daemon/src/wire/session_config.rs b/bt-daemon/src/wire/session_config.rs new file mode 100644 index 00000000..9af02245 --- /dev/null +++ b/bt-daemon/src/wire/session_config.rs @@ -0,0 +1,37 @@ +use super::{BackendAuth, FlushMode, TraceDestination}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, path::PathBuf}; + +/// Trace settings and backend credentials resolved by the shim. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionConfig { + pub auth: BackendAuth, + /// Typed trace destination. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destination: Option, + #[serde(default)] + pub flush_mode: FlushMode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_metadata: Option, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub tags: BTreeSet, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub span_plugins: Vec, +} + +impl SessionConfig { + /// External parent/root ids used to shape translator rows. The sink keeps + /// the full destination components for object routing and propagation. + pub fn attached_span_ids(&self) -> (Option, Option) { + if let Some(TraceDestination::ParentSpan { components }) = &self.destination { + return (components.span_id.clone(), components.root_span_id.clone()); + } + (None, None) + } + + pub fn project_name(&self) -> Option<&str> { + self.destination + .as_ref() + .and_then(TraceDestination::project_name) + } +} diff --git a/bt-daemon/src/wire/session_route.rs b/bt-daemon/src/wire/session_route.rs new file mode 100644 index 00000000..610985a8 --- /dev/null +++ b/bt-daemon/src/wire/session_route.rs @@ -0,0 +1,119 @@ +use super::{AuthSelection, BackendAuth, FlushMode, SessionConfig, TraceDestination}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, path::PathBuf}; + +/// Immutable, journal-safe routing and trace settings for one agent session. +/// Credentials are deliberately absent and are resolved inside the daemon. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct SessionRoute { + #[serde(default)] + pub auth: AuthSelection, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destination: Option, + #[serde(default)] + pub flush_mode: FlushMode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_metadata: Option, + /// Tags applied to each root span for this session. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub tags: BTreeSet, + /// Ordered JavaScript span transforms. Paths are resolved by explicit + /// setup, run, and import commands before entering a session route. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub span_plugins: Vec, +} + +impl SessionRoute { + pub fn with_auth(&self, auth: BackendAuth) -> SessionConfig { + SessionConfig { + auth, + destination: self.destination.clone(), + flush_mode: self.flush_mode, + additional_metadata: self.additional_metadata.clone(), + tags: self.tags.clone(), + span_plugins: self.span_plugins.clone(), + } + } + + pub fn same_route(&self, other: &Self) -> bool { + let mut left = self.clone(); + let mut right = other.clone(); + if left + .auth + .profile_id + .as_ref() + .zip(right.auth.profile_id.as_ref()) + .is_some_and(|(left, right)| left != right) + { + return false; + } + // A stable-ID route is the canonical successor to an old named route. + // Journals can legitimately contain both forms for the same session, + // so replay compares their unchanged routing intent, not the newly + // learned identifier. + left.auth.profile_id = None; + right.auth.profile_id = None; + left.auth.source = left.auth.effective_source(); + right.auth.source = right.auth.effective_source(); + serde_json::to_value(left).ok() == serde_json::to_value(right).ok() + } + + /// Delivery settings may change without moving held work to another destination. + pub(crate) fn same_destination(&self, other: &Self) -> bool { + let identity = |route: &Self| Self { + auth: route.auth.clone(), + destination: route.destination.clone(), + ..Self::default() + }; + identity(self).same_route(&identity(other)) + } + + /// Raw journal entries can be replayed through a newer plugin chain as + /// long as their Braintrust delivery route is otherwise unchanged. + pub fn same_replay_route(&self, other: &Self) -> bool { + let mut left = self.clone(); + let mut right = other.clone(); + left.span_plugins.clear(); + right.span_plugins.clear(); + left.same_route(&right) + } + + /// Apply one invocation-local JSON metadata override to a non-secret route. + /// + /// The route is then carried unchanged through live hooks, managed runs, and + /// transcript import. Keeping validation here gives every public command the + /// same contract and prevents individual agent shims from parsing JSON. + pub(crate) fn apply_additional_metadata( + &mut self, + additional_metadata: Option<&str>, + ) -> anyhow::Result<()> { + let Some(metadata) = additional_metadata else { + return Ok(()); + }; + let value: serde_json::Value = serde_json::from_str(metadata) + .map_err(|e| anyhow::anyhow!("invalid --additional-metadata JSON: {e}"))?; + if !value.is_object() { + anyhow::bail!("--additional-metadata must be a JSON object"); + } + self.additional_metadata = Some(value); + Ok(()) + } + + /// Apply invocation-local root-span tags to a route. Trim whitespace and reject + /// empty tags here; the set keeps route tags unique. + pub(crate) fn apply_tags(&mut self, tags: &[String]) -> anyhow::Result<()> { + if tags.is_empty() { + return Ok(()); + } + let mut normalized = std::collections::BTreeSet::new(); + for tag in tags { + let tag = tag.trim(); + if tag.is_empty() { + anyhow::bail!("--tag must not be empty"); + } + normalized.insert(tag.to_string()); + } + self.tags = normalized; + Ok(()) + } +} diff --git a/bt-daemon/src/wire/trace_destination.rs b/bt-daemon/src/wire/trace_destination.rs new file mode 100644 index 00000000..0871db50 --- /dev/null +++ b/bt-daemon/src/wire/trace_destination.rs @@ -0,0 +1,54 @@ +use braintrust_sdk_rust::SpanComponents; +use serde::{Deserialize, Serialize}; + +/// Where a session's root span should be logged. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum TraceDestination { + /// Project logs selected by stable id, display name, or both. + ProjectLogs { + #[serde(default, skip_serializing_if = "Option::is_none")] + project_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + project_name: Option, + }, + /// An existing experiment. + Experiment { experiment_id: String }, + /// A child of an exported Braintrust span. + ParentSpan { components: SpanComponents }, +} + +impl std::str::FromStr for TraceDestination { + type Err = String; + + fn from_str(value: &str) -> Result { + let (kind, id) = value.split_once(':').ok_or_else(|| { + "destination must be project_logs: or experiment:" + .to_string() + })?; + if id.is_empty() { + return Err("destination id must not be empty".to_string()); + } + match kind { + "project_logs" => Ok(Self::ProjectLogs { + project_id: Some(id.to_string()), + project_name: None, + }), + "experiment" => Ok(Self::Experiment { + experiment_id: id.to_string(), + }), + _ => Err(format!( + "unsupported destination {kind:?}; expected project_logs or experiment" + )), + } + } +} + +impl TraceDestination { + pub fn project_name(&self) -> Option<&str> { + match self { + Self::ProjectLogs { project_name, .. } => project_name.as_deref(), + _ => None, + } + } +} diff --git a/docs/architecture/dto-ownership/README.md b/docs/architecture/dto-ownership/README.md new file mode 100644 index 00000000..7d1ec19f --- /dev/null +++ b/docs/architecture/dto-ownership/README.md @@ -0,0 +1,48 @@ +# DTO ownership review + +This review follows the concrete-schema work in PR #306. It inventories the production types at commit `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721`, traces their consumers, and distinguishes shared interpretation from data transport and runtime orchestration. The detailed tables describe that baseline, including types subsequently moved by this refactor. + +- [Agent configuration, Muse, setup, and managed runs](agent-config.md): 178 DTO and codec declarations, including nested and macro-generated types, with runtime and test exclusions. +- [Translators, transcript imports, and mirrors](translators.md): 188 DTO/result declarations and 88 explicitly excluded runtime declarations. +- [Core runtime and JavaScript/TypeScript](core-runtime.md): 235 Rust declarations, including explicit runtime exclusions, and 24 TypeScript declarations. + +These are review counts, not a count of independent public contracts: nested codecs and compatibility variants are included, while imported SDK types and reexports are not counted as new definitions. Each table records consumers, existing behavior, and an individual recommendation. Broad names such as `Message` or `Hook` do not imply that different native contracts should share a type. + +## Implemented decisions + +| Owner | Responsibility moved onto the type | Why it belongs there | +|---|---|---| +| `CursorHooks` | Registration lookup, known-command retention, and registration replacement | Setup and managed-hook cleanup no longer traverse optional maps and unknown native variants themselves. Marker recognition and process liveness stay with setup. | +| `OpenCodeConfig`, `OpenCodePlugin` | Plugin lookup, preservation-aware replacement/removal, exact-spec insertion, package matching | Setup and managed runs share collection mechanics while keeping their different version/ownership policies. Configured tuples retain their provider options. | +| `TranscriptPayload`, `Reference` | Captured-prefix validation, matching snapshots/references, native path enumeration, and Codex path precedence | Capture, polling, translation, and import no longer repeat native format selection. A modern captured absence still prevents reading newer native bytes; legacy fallback behavior remains explicit. | +| Antigravity `TranscriptRecord` | Native kind normalization, content precedence, and timestamp decoding | Import and translation share the native record's interpretation. Explicit null content keeps precedence over alternate fields. | +| `OpenCodeTokens` | Cache-inclusive prompt and total accounting | Both OpenCode protocol versions use the native counter semantics without repeating the arithmetic. Output metrics keep their existing names and projection types. | +| `SkillLoad` | Display name and common span metadata | Translators share skill naming, identity metadata, and explicit-request classification. Native discovery remains in the integration helpers. | +| Pi `AssistantMessage` | Physical response-model selection and assistant span-message projection | The reducer no longer inspects native content variants or repeats model precedence. | +| Pi compaction/branch DTOs | Input, summary message, and summary-request interpretation | Schema-specific field combinations leave the reducer; turn and continuation lifecycle stays there. | +| OpenCode `PermissionProperties` | Native permission request and reply normalization | Asked/replied handling shares precedence across native permission variants. | +| OpenCode 2 `Context`, `ToolContent` | Native context and tool-output conversion | The native owner handles media/content variants and emits the existing span representation. | +| `RedactedEnvelope` | Conversion back to the replayable runtime envelope | Recovery and translation share reconstruction without reintroducing credentials. The former journal helper was internal and is removed; public wire imports remain unchanged. | +| `SessionConfig` | Destination project-name query | Delegates to the destination's existing semantics. | +| `SessionRoute` | Additional metadata and tag edits | Route mutation owns trimming, validation and stable deduplication; filesystem and credential resolution remain outside the DTO. | +| `AuthDiagnostic` | Ready/unconfirmed construction and status predicates | Runtime and output rendering share diagnostic vocabulary and state combinations. | + +## Organization + +Shared hook/config schemas, provider usage, wire envelope types, transcript references, and Antigravity records now have directories with one primary owner per file and stable module reexports. Pi assistant messages, compaction records, and lifecycle payloads are separated; OpenCode permission, context, and tool-content families have focused modules. Primary types live beside their interpretation methods. Small private leaf records and discriminants stay with their owner when they have no independent consumers. + +This is deliberately not a rule to put every struct in its own file. A permission payload's private helper variants, or a group of single-use lifecycle records, are easier to understand together. The facade modules provide stable imports, rather than parallel schema definitions. + +## Deliberately retained as data + +Most RPC request/results, CLI argument projections, native lifecycle wrappers, export-v1 leaf records, and tool/image descriptors need no additional methods. Their jobs are validation and transport; their consumers do not share further interpretation. Existing behavior on typed IDs, token metrics, message content, outcomes, and configuration overlays is retained rather than wrapped again. + +JavaScript/TypeScript interfaces remain structural data. Turning deserialized JSON into class instances would add lifecycle requirements without useful ownership. Existing adapter/client functions already own encoding and dispatch. A typed shared JavaScript destination union is a separate contract change; this refactor does not combine it with Rust method extraction. + +Some baseline recommendations remain conditional rather than implemented requirements: a constructor at a single synthesis site, a helper replacing one field access, or a private group method that only renames a loop does not justify another API. Codex installed-file trust and invocation-local trust have different validation policies and stay separate. Likewise, sink destination resolution supplies fallbacks that correlation intentionally omits; those paths are not unified. + +Runtime actors, caches, locks, subprocess services, filesystem discovery, credential resolution, and event-ordering state remain responsible for their own operations. DTO methods do not acquire those responsibilities simply because an operation consumes a DTO. + +## Compatibility checks + +The refactor preserves serialized field names, public wire reexports, replay reconstruction, unknown extensions, missing-versus-null values, source-specific metric conventions, and existing hook ownership rules. Focused tests exercise configuration preservation, captured absence and path precedence, skill metadata, and credential-free replay conversion. The full locked all-feature Rust suite and strict all-target Clippy cover the integrated result. diff --git a/docs/architecture/dto-ownership/agent-config.md b/docs/architecture/dto-ownership/agent-config.md new file mode 100644 index 00000000..c2255bb0 --- /dev/null +++ b/docs/architecture/dto-ownership/agent-config.md @@ -0,0 +1,345 @@ +# DTO inventory: agent schemas, Muse, setup and managed runs + +Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. + +Scope: every production struct/enum/type declaration in `agents/**`, `muse/**`, `setup/**`, `managed_run/**`, `codex_hooks.rs`, `hook.rs`, `hook_executable.rs`, and `settings.rs`; macro-generated IDs and hook enums included. Test-only declarations are excluded below. DTO means native input, persisted state/config, authored output or transport shapes. Runtime services and capability marker types are separately classified, not silently omitted. Same-named agent schemas are not treated as shared contracts. + +## Highest value behavior ownership + +1. `CursorHooks`: `contains_registration`, `retain_commands`, `replace_registration`. Evidence: `setup/cursor/hooks.rs:124-129`, `186-199`, `209-250` repeatedly unwrap optional maps, distinguish known array/unknown event shapes, preserve unknown entries, and deduplicate commands. Configuration owns those mechanics; persistent marker/liveness/matcher policy stays setup. Preserve absent maps on disable, unknown arrays/entries, and existing version exactly. +2. `OpenCodeConfig`: `has_plugin`, `retain_plugins`, `replace_plugin`, `ensure_plugin` (or a minimal equivalent). `OpenCodePlugin::matches_package` recognizes the same package spec while deliberately excluding configured tuples, whose options must survive. Evidence: `setup/opencode.rs:32-81,105-114`, `managed_run/opencode.rs:72-89`. Setup owns bundled version and package policy; DTO owns optional list semantics and edits. +3. `OpenCodeTokens`: own `metrics`/prompt-inclusive-cache calculation, duplicated `translate/opencode.rs:1038-1044` and `translate/opencode_v2/span.rs:201-207`. `PiUsage` similarly own prompt/total and canonical metrics (`translate/pi.rs:769-771`). Native usage types already own parsing; consumers should not reconstruct cache accounting. Preserve signed native counters and existing optional total behavior; do not silently change overflow policy while extracting. +4. Antigravity `TranscriptRecord`: `normalized_kind`, `content`, `created_at_ms`. Current helpers `translate/antigravity.rs:669-715,815` depend only on record; importer uses kind/time/step too (`transcript_import/antigravity.rs:132-134,237-255`). Keep import-specific is_tool_result/is_denied policy in importer unless genuinely identical to reducer policy (not demonstrated). +5. `codex_hooks::Hook`: a shared `trust_identity()` for nonempty key/hash and `has_command_definition(expected_command)` would consolidate repeated structural validations in `managed_run_trust_state:255-309` and `trust_edits:327-389`. Keep full installed-file hash equality, sessionFlags/plugin source policies and error context in orchestrator; those trust policies are intentionally different. + +## Module arrangement + +Replace unrelated mega-file `agents/schema.rs` with `agents/schema/` and owner files (`hook_file`, `hook_group`, `command_hook`, `cursor_hooks`, `cursor_hook_entries`, `cursor_hook_entry`, `cursor_command_hook`, `opencode_config`, `opencode_plugin`, `plugin_manifest`, `repository`) with stable module reexports. Keep codec helper `deserialize_present` in module root or `json` rather than attach it to an unrelated DTO. `agents/usage/` can similarly separate `provider_usage`, `snake_case_usage`, `camel_case_usage`, `usage_metrics`, `token_metrics`, `opencode_tokens`, `pi_usage`; private leaf shapes stay with their owner until independently used. `muse/messages/` is worth splitting by message, content, image, and tool-call owners; single-use metadata projections can remain grouped by lifecycle domain. Do not create an impl or a public API merely to satisfy one-type-per-file. Generic `schema` modules should be compatibility facades, not the new dumping ground. + +## Per-type review + +Each row names an exact declaration. Caller descriptions below were traced to real owner modules; symbol-name grep alone is unreliable for generic names such as Hook/Session/Plugin/ContentBlock. + +### `agents/schema.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `HookFile` | Codex hooks trust + managed commands; Cursor managed runs/setup parse packaged manifests; no methods. | Own event enumeration only if a caller needs normalization; current direct iteration is clear. Split owner file, retain generic shape. | +| `HookGroup` | Nested shared hook manifest group; Codex managed run rewrites its commands. | Data-only nested group; could own replace_commands delegation if multiple rewrite callers emerge. No invented builder. | +| `CommandHook` | Nested HookGroup command schema, rewritten in managed_run/codex.rs. | Own replace_command(unix,windows) if enforcing type==command; one current caller, moderate value. | +| `OpenCodeConfig` | Setup enables/updates/disables and managed run injects optional plugins list. | Expand list edit/lookup behavior; highest value #2. | +| `OpenCodePlugin` | Setup matching and managed run equality; package() already distinguishes configured options. | Expand package matching while preserving configured tuples; no conversion to string for configured variants. | +| `CursorHooks` | Setup persistent/temporary hooks and stale process cleanup; no methods. | Expand collection behavior; highest value #1. | +| `CursorHookEntries` | Native known array or unknown future payload; only setup traverses. | Keep enum data-only; collection mutation belongs CursorHooks, preserve Other unchanged. | +| `CursorHookEntry` | Known command vs unknown definition; command() already abstracts variant. | Existing behavior sufficient; equality/retention policy belongs owner. | +| `CursorCommandHook` | Constructed by setup and managed run, capture() centralizes defaults. | Existing capture constructor sufficient; registration comparisons belong CursorHooks. | +| `PluginManifest` | Hook version probe, setup common npm version, Cursor installation ownership. | Data-only manifest projection is appropriate; package identity policy differs by caller. | +| `Repository` | PluginManifest source string vs npm object; url() deliberately returns only supported string. | Existing method sufficient; do not normalize object repository into trusted plugin source inadvertently. | + +### `agents/usage.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `ProviderUsage` | Antigravity record usage and metrics; custom boundary decode selects formats; metrics() exists. | Already owns behavior; retain. | +| `SnakeCaseUsage` | Codex/Claude counters; metrics() and is_empty() encode aliases. | Already owns behavior; split main owner file. | +| `TokenDetails` | SnakeCaseUsage nested cached/reasoning counters. | Data-only leaf; metric alias precedence belongs SnakeCaseUsage. | +| `CacheCreation` | SnakeCaseUsage nested TTL counters, roundtrip/Claude details. | Data-only leaf; keep with SnakeCaseUsage. | +| `CamelCaseUsage` | Grok translator + ProviderUsage; metrics() exists. | Existing metrics ownership sufficient; per-model aggregation remains translator policy. | +| `UsageMetrics` | Antigravity accumulated float metrics; is_empty/with_total/observe. | Already owns behavior, good model for others. | +| `TokenMetrics` | Muse and Cursor usage state; add() saturates optional counters. | Existing ownership good; split owner file. | +| `OpenCodeTokens` | OpenCode1 and2 native tokens. | Add canonical conversion/cache-inclusive prompt/total; highest value #3. | +| `OpenCodeCacheTokens` | Nested native cache read/write. | Data-only leaf with OpenCodeTokens, not independent service. | +| `PiUsage` | Pi normalized native counters, used response closure. | Add canonical metric/total methods; highest value #3. | +| `PiCost` | Nested PiUsage total price. | Data-only leaf; PiUsage decides emission. | + +### `agents/request.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `RequestConfig` | Pi caches normalized provider request config; is_empty(). | Retain current behavior; moving native request parsing here may be useful but avoid provider redaction policy coupling. | +| `Stop` | Private string/list union. | Data-only wire variant. | +| `ToolDefinition` | Function/built-in; custom known-schema dispatch. | Serialization behavior already owned; no behavioral caller beyond codec. | +| `FunctionTool` | Private function tool envelope. | Data-only leaf. | +| `FunctionType` | Closed function tag. | Data-only discriminant. | +| `FunctionDefinition` | Function name/description/schema/strict/extensions. | Data-only leaf; JSON Schema intentionally arbitrary. | +| `ToolChoice` | Mode or named function. | Data-only wire union. | +| `ChoiceMode` | auto/none/required. | Data-only discriminant. | +| `NamedChoice` | Named function wrapper. | Data-only leaf. | +| `FunctionName` | Nested function name. | Data-only leaf. | +| `ResponseFormat` | Known/future union; custom dispatch. | Codec owns behavior already. | +| `KnownResponseFormat` | text/json_object/json_schema with unknown extension retention. | Data-only variant payloads. | +| `SchemaDefinition` | Named JSON Schema descriptor. | Data-only schema envelope; preserve Field nulls. | + +### `agents/antigravity/schema.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `TranscriptRecord` | Live translator and import; fields read for kind/content/time/step. | Add record-local accessors noted #4; avoid moving importer state transitions onto DTO. | +| `ToolCalls` | One vs many native tool call; iter() shared translator/import. | Existing method sufficient. | +| `ToolCall` | Native name,args,output + opaque extensions, converted by translator/import. | Data-only: output conversion differs from invocation policy. | +| `optional_integer::Integer` | Private temporary string/number boundary codec. | Keep local, data-only, no standalone file. | + +### `agents/cursor/schema.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `TranscriptRecord` | Cursor translator + transcript importer; role()/text() already encapsulate variants. | Already good behavior ownership. | +| `Role` | User/Assistant; as_str(). | Existing method sufficient. | +| `TranscriptMessage` | Nested content payload. | Data-only leaf. | +| `TurnEndedKind` | Closed turn marker. | Data-only discriminant. | +| `MessageContent` | Text/blocks; text() joins text blocks. | Already owns normalization. | +| `ContentBlock` | Text vs tool-use marker, text() owner skips tool blocks. | Data-only leaf; no unused API. | + +### `muse/hooks.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `HookName (macro)` | Config event enumeration + decoder + translator; ALL/as_str/parse. | Already owns canonical aliases and names. | +| `MuseEvent (macro)` | Native decode, import synthesis, translation; name/context/payload/decode. | Already good aggregate behavior. | +| `Empty` | SessionStart empty body. | Data-only zero-size marker. | +| `Hook` | Common context/body envelope, synthesized by import and decoded by MuseEvent. | Data-only generic container; no generic builder needed. | +| `HookContext` | Importer + translator correlation; turn()/request() filter empty. | Existing behavior sufficient. | +| `optional_id::Id` | Local tolerant native string/ignored codec. | Keep local, data-only. | +| `SessionMetadata` | Shared across native hook context and translator root; update() preserves missing/null. | Already owns update semantics. | +| `PromptSubmitted` | User prompt/image hook body; import constructs and translator reads. | Data-only; rendering belongs message/image layer. | +| `ModelDetails` | ModelStarted flattened counters/options. | Data-only; attribution/step identity belongs reducer. | +| `ModelStarted` | Import constructs; translator starts model span. | Could own borrowed input projection if duplicated; only one output mapping currently, no new method. | +| `ModelFinished` | Import constructs; translator closes model span. | Data-only outcome+usage envelope; completion lifecycle stays reducer. | +| `ToolStarted` | Shared tool-start payload, import and translator correlate. | Potential identifier/name helper only if repeated; current reducer chooses fallback IDs, keep policy there. | +| `ToolFinished` | Finish payload nested tool/outcome, import/tool lifecycle use. | Outcome classification belongs NativeOutcome; batch reducer behavior stays translator. | +| `ToolBatchFinished` | PostToolBatch Vec. | Data-only aggregate. | +| `PermissionObserved` | Tool metadata for permission hook; translator event branch reads. | Data-only. | +| `NotificationObserved` | Notification metadata hook; translator event branch reads. | Data-only. | +| `SubagentStarted` | Child session/subagent IDs used by import and translate events. | Candidate child_id() only if same precedence multiple callers; currently caller-specific identity, retain. | +| `SubagentFinished` | Child fields/output/outcome. | Data-only; reducer closes spans. | +| `Compaction` | Trigger/outcome. | Data-only; operation correlation belongs reducer. | +| `TurnFinished` | Assistant output/terminal/outcome. | Data-only; terminal lifecycle stays reducer. | +| `SessionFinished` | Reason/outcome. | Data-only; session shutdown behavior stays reducer. | + +### `muse/messages.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `ToolInput` | Opaque tool-owned JSON wrapper used hook bodies and export synthesis. | Data-only newtype; do not add inspect-known-key methods. | +| `ToolOutput` | Opaque tool/provider output wrapper. | Data-only newtype. | +| `ModelOutput` | Text or typed messages, forwarded to output boundary. | Data-only native union; no duplicated rendering found. | +| `NativeMessage` | Messages in hook input, export output synthesis. | Could add assistant_tool_calls(calls) constructor for repeated synthesis; only one caller, not worth broad builder API. | +| `MessageRole` | Known/future role strings; From conversions. | Existing behavior sufficient. | +| `MessageContent` | Text or content blocks; retained losslessly. | Data-only; unlike Cursor, currently not repeatedly flattened to text. | +| `ContentBlock` | Known/future discriminated content; custom strict-known decoder. | Already owns codec behavior. | +| `KnownContentBlock` | Text/assistant/image payloads. | Data-only variant contents. | +| `MessagePhase` | Known/future assistant phase. | Data-only enum. | +| `ContentBlock::deserialize::Tag` | Temporary type discriminator. | Keep local, data-only. | +| `ImageSource` | Known base64/url/future; custom strict-known decoder. | Already owns codec behavior. | +| `Base64ImageSource` | Native encoded image descriptor. | Data-only leaf; no repeated extraction callers. | +| `Base64Type` | Closed base64 marker. | Data-only discriminant. | +| `UrlImageSource` | Native URL + extensions. | Data-only leaf. | +| `ImageUrl` | String or detailed URL descriptor. | Data-only union. | +| `ImageDetail` | auto/low/high/future. | Data-only discriminant. | +| `AssistantToolCall` | Import synthesizes function-call output records. | Possible constructor if repeated; currently one synthesis, keep data-only. | +| `FunctionCallType` | Closed function discriminator. | Data-only. | +| `FunctionCall` | Function name/arguments. | Data-only; args normalization belongs ToolArguments. | +| `ToolArguments` | Encoded JSON text or JSON; input() decodes/falls back. | Already owns behavior. | +| `ToolDescription` | Tool schema envelope for LLM input. | Data-only; parameter JSON Schema belongs native tool. | +| `InputSummary` | Bounded message count + extensions from hook/export. | Data-only. | + +### `muse/provider_options.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `ProviderOptions` | Hook model details + final metadata, coexisting dotted options. | Data-only lossless schema; no repeated logic over options found. | +| `ReasoningEffort` | Known/future reasoning effort strings. | Data-only discriminant. | +| `ThinkingMode` | Known/future thinking mode strings. | Data-only discriminant. | + +### `muse/outcome.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `ErrorDetail` | Hook/export errors; render(). | Already owns normalization. | +| `OperationStatus` | Known/future string statuses; From conversions. | Move failure membership into is_failure() used NativeOutcome (one caller but intrinsic status classification); useful if other consumers share exact classification. | +| `NativeOutcome` | Hook outcome across model/tool/subagent/turn/session; error_message() combines error/status/details. | Already owns common behavior. | +| `ToolOutcome` | Translator classified success/failure/unknown result. | Data-only semantic result, not raw DTO; no redundant methods. | + +### `muse/usage.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `TokenUsage` | Hook and export counters, usage reducer; delta_since()/metrics(). | Already owns common behavior; good exemplar. | +| `UsageScope` | Turn-cumulative vs per-model marker. | Data-only enum; policy stays usage reducer. | + +### `muse/ids.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `TurnId (macro)` | HookContext turn correlation; From/Deref/Display. | Already typed identity behavior, no extra methods. | +| `RequestId (macro)` | HookContext model request identity; From/Deref/Display. | Already sufficient. | +| `ToolCallId (macro)` | ToolStarted identity; From/Deref/Display. | Already sufficient. | + +### `muse/export_v1.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `Header` | Import export header schema checks/session collection. | Data-only; import orchestrator validates supported version and sessions. | +| `Version` | String/object semver; into_string(). | Already owns wire normalization. | +| `Session` | Import session synthesis and finalization. | Data-only; lifecycle state belongs importer. | +| `SessionEnd` | Session exit reason. | Data-only leaf. | +| `UnixMicros` | Export timestamp; millis(). | Already owns units conversion. | +| `ExportRecord` | Import process() unwraps envelope, fallback recorded_at. | Candidate into_event() with timestamp precedence if reused; single importer, retain data-only. | +| `NativeEnvelope` | Record inner timestamp/payload. | Data-only leaf. | +| `NativePayload` | Kind-specific known parse/custom decoder. | Already owns codec dispatch. | +| `NativePayload::deserialize::Kind` | Temporary payload kind. | Keep local, data-only. | +| `NativePayload::deserialize::Payload` | Temporary raw fields for boundary dispatch. | Keep local, no standalone file. | +| `ExportMetadata` | Run-model metadata used importer current context. | Data-only; source precedence/update decisions belong importer. | +| `RunModelRecord` | Run stream+metadata envelope. | Data-only. | +| `RunStream` | Run ID wrapper object. | Data-only leaf. | +| `RunEvent` | Discriminated native stream event. | Data-only event variants; stream lifecycle stays importer. | +| `ExportToolCall` | Tool invocation list native call args. | Could own into_hook() only if it removes repeated import mapping; single site, retain. | +| `ExportToolResult` | Tool result event list. | Data-only. | +| `TaskEvent` | Task state event with ID/origin fallback read by process_task. | Candidate task_id() centralizes task_id/idempotency precedence only if shared; current one consumer. | +| `TaskEventKind` | Scheduled/start/complete/fail/cancel/reject. | Data-only; task terminal policy stays importer. | +| `TaskOrigin` | Originating tool-call ID. | Data-only leaf. | + +### `muse/metadata.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `RootMetadata` | translate/muse.rs root metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ModelInput` | translate/muse.rs model input | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ModelStartMetadata` | translate/muse.rs model-start metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ModelEndMetadata` | translate/muse.rs model-end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ToolStartMetadata` | translate/muse_events.rs tool-start metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ToolEndMetadata` | translate/muse_events.rs tool-end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `ToolOutcomeLabel` | ToolEndMetadata success/error output label | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `SubagentMetadata` | translate/muse_events.rs child metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `CompactMetadata` | translate/muse_events.rs compaction metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `SessionEndMetadata` | translate/muse.rs session end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `UnpairedMetadata` | translate/muse.rs unmatched model completion metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `PermissionMetadata` | translate/muse_events.rs permission metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `NotificationMetadata` | translate/muse_events.rs notification metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | +| `CompletionFingerprint` | translate/muse.rs output/metrics/error/metadata dedup hash encoding | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | + +### `muse/config/hooks.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `Extensions` | Private unknown handler/group config map. | Alias stays data-only; restricted conservative extension scan needed. | +| `HookOverlay` | Setup manipulates user hooks; is_empty/contains_braintrust_hook/remove_owned/append_owned. | Already strong responsibility ownership; preserve exact foreign attributes. | +| `HookGroup` | Private handler group with matcher/extensions. | Move prune/remove_owned logic into private remove_owned() only if it meaningfully simplifies HookOverlay (moderate value). | +| `HookHandler` | Known user/enterprise or future handler; decoder/is_owned/contains_braintrust. | Already owns recognition and conservative inspection. | +| `CommandType` | Closed command tag shared strict ownership. | Data-only discriminant. | +| `UserCommand` | Owned user command with timeout/unknown attrs. | Data-only leaf; HookHandler owns variant recognition. | +| `EnterpriseCommand` | Foreign enterprise command. | Data-only leaf, never convert ownership. | +| `HookDocument` | Read-only root projection; contains_braintrust(). | Already owns inspection. | + +### `muse/config/ownership.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `OwnedHookFile` | Exact current/previous/legacy file generation and recognition. | Already owns construction/equality; no new methods. | +| `OwnedHookGroup` | Strict private group shape. | Data-only leaf. | +| `OwnedCommandHook` | Strict private command shape. | Data-only leaf. | +| `HookFileInspection` | Missing/Owned/Foreign result; is_owned/contains_braintrust. | Already owns semantic result queries. | + +### `muse/config/settings.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `MuseSettings` | Setup reads/writes; load/managed_path/hook_overlay/ensure_schema_version. | Already owns schema semantics and path resolution; writes require setup lock, keep transaction orchestration outside. | + +### `settings.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `InvocationSettings` | Managed-run env protocol; enabled(route). | Existing constructor sufficient; conversion into AgentSettings could be From impl because duplicated load paths, verify before extracting. | +| `AgentSettings` | Hook/runtime/setup settings; load_for_hook/load/load_from/tracing_enabled. | Already owns load/enablement; move matching route replacement from migrate_persisted_route_at into method only if reused; file locks/atomic IO orchestration remain external. | + +### `codex_hooks.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `ConfigRead` | activate app-server config/read response wrapper. | Data-only local protocol shape. | +| `Config` | features dictionary; activation checks hooks/codex_hooks. | Candidate hooks_enabled() if reused; only one check, retain. | +| `PluginList` | activate plugin/list response. | Candidate has_enabled(id) hides nested marketplaces traversal but single caller, low value. | +| `PluginMarketplace` | Nested plugin list. | Data-only leaf. | +| `Plugin` | Identity/installed/enabled native summary. | Data-only leaf; installation policy belongs activation. | +| `HooksList` | activate/run override native hooks/list. | Useful iter() flattening entries if reducing two loops; validation policies stay separate. | +| `HookEntry` | errors plus hook records; managed flow validates errors. | Data-only container; errors semantics differ setup/managed. | +| `Hook` | Repeated command/trust identity validation in trust_edits and managed_run_trust_state. | Add structural validation/identity methods only; keep separate source/full-file trust policies. See #5. | +| `TrustState` | Borrowed authored trusted_hash value. | Data-only output projection. | +| `request::Response` | Local RPC id/error/result wrapper in transport. | Data-only boundary codec; no reuse with unrelated wire Response. | +| `request::RpcError` | Local RPC error code/message. | Data-only transport projection. | + +### `setup/claude.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `MarketplaceEntry` | Marketplace generic callbacks inspect name/source/repo. | Could own is_published_repo(repo) if multiple callers; one generic callback, data-only okay. | +| `InstalledPlugin` | enable/disable/update/stale find ID/version/enabled. | Data-only summary; caller owns plugin identity. | +| `InstalledPlugins alias` | Vec. | Data-only alias; no wrapper solely to add find_ours(). | +| `legacy_tracing_env_keys::Settings` | Read-only diagnostic env projection. | Keep local, data-only. | + +### `setup/codex.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `MarketplaceList` | Generic marketplace find callback. | Data-only wrapper. | +| `MarketplaceEntry` | Native name/source fields. | Data-only; one generic callback. | +| `MarketplaceSource` | Native optional source string. | Data-only leaf. | +| `InstalledPlugins` | Native installed list wrapper read setup/stale. | Candidate find(id) only if broader list API needed; current private helper sufficient. | +| `InstalledPlugin` | Native plugin ID/version summary. | Data-only leaf. | + +### `setup/grok.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `InstalledPlugin` | name/source used enable/update/disable publication checks. | Move is_published(repo) onto type if removing free helper; modest value, no generalized registry. | + +### `setup/antigravity.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `update_at::PluginList` | Single plugin/list imports response. | Keep local data-only. | +| `update_at::Plugin` | Single native plugin name. | Keep local data-only. | + +### `setup/mod.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `enable_tracing_at::LegacyFields` | Legacy route metadata/tags migration projection. | Keep local data-only; migration orchestration intentionally outside modern AgentSettings. | + +### `setup/common.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `FileAccess` | Inherited/Private atomic edit permissions policy. | Data-only enum for IO helper, not native DTO. | +| `Marketplace` | Generic runtime command plan with find/is_published callbacks; reconcile/refresh methods. | Runtime behavior object, not DTO; already owns operation. | + +### `managed_run/mod.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `Terminal` | stdin/stdout terminal capability passed agent check. | Data-only value; no repeated common interpretation demonstrated. | +| `Injection` | Agent invocation args/env/lifetime guards consumed once by runner. | Runtime transfer object; no blanket builder. Methods append_env/args would mirror Vec without invariant. | +| `ManagedRunRuntime` | Host/data_dir runtime resource, start(). | Not DTO; runtime lifecycle object. | + +### `managed_run/muse.rs` + +| Type | Actual use and existing behavior | Judgment | +|---|---|---| +| `MuseManagedContext` | Serialized invocation-local route/socket/run ID/version; hook reads it. | Move load(path)/write_private(path) only if repeated secure-file lifecycle exists; currently split source/sink purposeful, data-only context file contract. | + +## Exclusions and boundary accounting + +Not DTOs: `agents::{Antigravity,Claude,Codex,Cursor,Grok,Muse,OpenCode,Pi}` are zero-size capability/registration implementations; `agents::{Agents,Registrar}` are registries; `Identity` is an immutable registry value with `matches()` already; `muse::msp::{ListSessions,MuseMspClient}` are method marker/transport service; `setup::common::SystemCommandRunner` is a subprocess service; `setup::cursor::CursorManagedHooks` is an RAII cleanup guard with install/drop. No method-only refactor indicated for these. `muse/msp.rs` uses SDK DTOs (`SessionListParams`, `SessionListResult`, other imports): external generated contracts are not local DTO declarations and should not be forked. + +Test-only declarations excluded: `hook::tests::HookCli`, `setup::common::FakeRunner`, `setup::cursor::tests::PublishedPlugin`, `setup::cursor::tests::Components`, `setup::antigravity::MissingAgyRunner`, `muse::msp::tests::TestTransport`. No DTO declarations exist in remaining hook executable helpers/setup agent files/managed-run agent files in this scope beyond types listed above. + +Review discipline: methods should own a real schema invariant, conversion, validated lookup, lossless mutation or repeated projection. Avoid builders for single construction sites, aliases wrapping scalar getters, extracting runtime correlation onto wire types, guessing schema equivalence from same field names, and moving lock/process/environment policy onto data objects. Existing fixture/integration tests are the compatibility authority for unknown-field retention, null/missing, parent/child correlation, durable replay, and hook ownership. + +## Implemented in this follow-up (agent-config ownership) + +- Split `agents/schema.rs` into a directory with eleven owner modules (`hook_file`, `hook_group`, `command_hook`, `opencode_config`, `opencode_plugin`, `cursor_hooks`, `cursor_hook_entries`, `cursor_hook_entry`, `cursor_command_hook`, `plugin_manifest`, `repository`), stable reexports, and sibling tests. This reduces unrelated DTO navigation without changing schema names or serde layout. +- Added `CursorHooks::{contains_registration,retain_commands,replace_registration}` and used them for setup registration validation, stale managed-hook cleanup, persistent-hook removal and insertion. Marker recognition, process liveness, bundled matcher selection, filesystem paths and error context remain orchestration policy. Unknown event variants and unknown entries survive, disabling never creates an absent map/event, and complete registration equality includes timeout/matcher. +- Added `OpenCodeConfig::{find_plugin,retain_plugins,replace_plugin,ensure_plugin}` and `OpenCodePlugin::matches_package`; setup and managed runs now delegate list mechanics to their owner type. Configured tuples are deliberately not owned package entries. The managed-run method still matches exact specs and leaves differently configured specs alone. +- Added regression tests for missing maps, unknown event shapes/entries, command deduplication, untouched configured plugin options and version suffix vs similarly prefixed package names. +- Other per-type recommendations above are judgments/candidates, not claims of implementation. No blanket constructors, property getters, DTO networking, process liveness logic, trust-policy merging or reducer lifecycle migration were added. Token/Antigravity changes are coordinated with other reviewers; their final implementation should be reflected in the combined inventory. diff --git a/docs/architecture/dto-ownership/core-runtime.md b/docs/architecture/dto-ownership/core-runtime.md new file mode 100644 index 00000000..49f0f0ba --- /dev/null +++ b/docs/architecture/dto-ownership/core-runtime.md @@ -0,0 +1,308 @@ +# Core/runtime DTO inventory and ownership review + +Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. + + +Scope: production Rust outside agent/setup/managed-run/translator/import/Muse modules and all production TypeScript. Test fixture types and Rust associated-type bindings are excluded. Runtime actors/handles are listed explicitly as exclusions so coverage is auditable. Each row provides observed consumers and existing impl locations; a data-only judgment is deliberate, not an omission. + +## Recommended implementation order + +1. Split wire envelope responsibilities into one primary public type per module, preserving wire::* reexports. Move journal replay reconstruction to RedactedEnvelope::into_envelope and migrate callers; remove the old journal helper after verifying its module is private and only source_journal_path is reexported. Delegate SessionConfig project_name query to TraceDestination. +2. Put SessionRoute metadata/tag mutation behind type methods; keep parsing path resolution and plugin validation I/O outside DTOs. +3. Move AuthDiagnostic ready/unconfirmed constructors and status predicate out of trace_runtime; that type currently exposes combinations the call sites manually coordinate. +4. Consider command_output per-command modules and RPC per-method modules. Most leaf request/result structs should stay data-only; no constructor/getter additions without invariants. +5. Preserve TS structural interfaces. Shared route queries/normalization belong to a focused functions module, not JS classes just to emulate Rust impl. Typed TraceDestination is a separate contract improvement; current unknown destination field causes repeated assertions in Pi/OpenCode. + +Important non-deduplication: sink::destination_components supplies project fallback while correlation::span_components preserves absence. They look similar but are not interchangeable. Preserve replay credentials/config semantics and the exported source-journal path API. + +## Rust per-declaration review + +| Declaration | Current consumers (sample) | Existing impls (sample) | Judgment and organization | +|---|---|---|---| +| `args.rs:21 struct ServeArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `server/mod.rs` | `args.rs:45` | Keep retention; environment/default retention policy belongs to parsed args already. | +| `args.rs:80 struct HookArgs` | `hook.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `args.rs:141 struct StatusArgs` | `client.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `args.rs:151 struct ImportArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `transcript_import/muse_runtime.rs` (+ more) | `args.rs:290` | Keep has_destination_override; validate_parent parse behavior remains clap schema. | +| `args.rs:235 enum ImportSource` | `lib.rs`, `trace_runtime.rs`, `trace_command.rs`, `transcript_import/mod.rs`, `transcript_import/pipeline.rs` | `args.rs:255` | Keep identity; dispatch/reader opening remains integration service. | +| `args.rs:247 enum ParentObjectType` | `lib.rs`, `transcript_import/pipeline.rs` | `args.rs:280` | Keep From into SDK SpanObjectType; no extra getter. | +| `args.rs:299 struct RunArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `managed_run/mod.rs` | `args.rs:321` | Keep validate_parent; no generic route builder until duplicate policy is established. | +| `args.rs:337 struct RunHookCommand` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `managed_run/muse.rs`, `managed_run/opencode.rs` (+ more) | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `args.rs:343 enum RunSource` | `lib.rs`, `trace_runtime.rs`, `trace_command.rs`, `managed_run/mod.rs` | `args.rs:267` | Keep identity; process startup remains integration service. | +| `attachments.rs:8 struct Attachment` | `translate/mod.rs`, `collections/upgrade.rs`, `collections/span_ops.rs`, `translate/cursor/mod.rs` | `attachments.rs:16` | Keep new: digest calculation belongs here. More generic capture recursion should remain attachment boundary adapter, not every DTO. Split attachments/attachment.rs. | +| `attachments.rs:28 struct AttachmentReference` | `sink/braintrust.rs` | `attachments.rs:40` | Keep uploaded constructor; move per-placeholder filename/content_type override into with_placeholder_details if materialize logic is reused. Split attachments/reference.rs. | +| `attachments.rs:36 enum AttachmentReferenceType` | Private/local producer and consumer in same module | Derives/data only | Data-only closed serialization marker; keep beside AttachmentReference. | +| `client.rs:22 struct HostInfo` | `hook.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `transcript_import/pipeline.rs` (+ more) | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `client.rs:30 struct RpcCallError` | `trace_runtime.rs` | `client.rs:36`, `client.rs:46` | Keep Display/Error; semantic RPC transport error, not DTO expansion target. | +| `client.rs:49 struct Conn` | `trace_runtime.rs` | `client.rs:55` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `client.rs:265 struct DaemonClient` | `transcript_import/pipeline.rs`, `src/runtime/js-daemon-client/src/index.ts`, `src/plugins/opencode/content/src/server.ts`, `src/plugins/opencode/content/src/tracing/daemon.ts`, `src/plugins/pi/content/src/index.ts` | `client.rs:272` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/events.rs:40 enum EventRecord` | `pipeline/translation.rs`, `server/ingress.rs`, `server/recovery.rs`, `server/mod.rs`, `collections/legacy.rs` (+ more) | `collections/events.rs:45`, `collections/events.rs:51`, `collections/events.rs:70`, `collections/events.rs:86` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/events.rs:58 struct EventEntry` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/events.rs:65 struct Stored` | `collections/legacy.rs`, `collections/span_ops.rs`, `collections/inspect.rs` | `collections/events.rs:70`, `collections/events.rs:86` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/events.rs:273 type Batch` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/events.rs:278 struct EventReader` | `pipeline/translation.rs`, `server/ingress.rs`, `collections/mod.rs` | `collections/events.rs:287`, `collections/events.rs:334` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/inspect.rs:11 enum Fault` | `trace_runtime.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `collections/tests.rs` | `collections/inspect.rs:19` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/inspect.rs:32 enum Table` | `pipeline/translation.rs`, `server/maintenance.rs`, `collections/upgrade.rs`, `collections/tests.rs` | `collections/inspect.rs:39` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/inspect.rs:52 struct Head` | `collections/span_ops.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/inspect.rs:66 struct Inspector` | `trace_runtime.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/maintenance.rs` (+ more) | `collections/inspect.rs:68` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/legacy.rs:212 struct Imported` | `command_output.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/legacy.rs:290 struct Checkpoint` | `dispatch.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `server/recovery.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/legacy.rs:296 enum Line` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/legacy.rs:303 struct Reader` | `transcript_import/muse.rs` | `collections/legacy.rs:309`, `transcript_import/muse.rs:66` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/session.rs:21 struct Status` | `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `command_output.rs` | `collections/session.rs:40` | Keep owner() helper; storage status snapshot is data-only otherwise. | +| `collections/span_ops.rs:21 struct BindingChanged` | `pipeline/cursor.rs`, `collections/upgrade.rs`, `collections/mod.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:29 struct StoredOp` | `pipeline/translation.rs`, `collections/upgrade.rs` | `collections/span_ops.rs:36`, `collections/span_ops.rs:46`, `collections/span_ops.rs:59` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:255 struct Translated` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `server/maintenance.rs`, `collections/session.rs`, `collections/upgrade.rs` (+ more) | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:268 struct HeldRoute` | `pipeline/cursor.rs`, `collections/mod.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:280 struct Head` | `collections/inspect.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:289 struct Subscriber` | `daemon_log.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:296 type ReplayWindow` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `collections/span_ops.rs:299 struct Channel` | `collections/store.rs` | `collections/span_ops.rs:307` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/store.rs:29 struct Inner` | Private/local producer and consumer in same module | `collections/store.rs:35`, `collections/store.rs:49` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/store.rs:69 struct SessionStorage` | `journal.rs`, `pipeline/attachment_tests.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `collections/session.rs:59`, `collections/events.rs:97`, `collections/legacy.rs:223`, `collections/span_ops.rs:328` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `collections/store.rs:231 struct Json` | `trace_runtime.rs`, `command_output.rs`, `muse/messages.rs`, `collections/events.rs`, `collections/legacy.rs` (+ more) | `collections/store.rs:233`, `collections/store.rs:241` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | +| `command_output.rs:12 enum OutputFormat` | `lib.rs`, `trace_runtime.rs`, `main.rs` | `command_output.rs:17` | Keep From; data-only choice thereafter. | +| `command_output.rs:28 struct StatusCommandOutput` | `lib.rs` | `command_output.rs:37` | Keep From>; output conversion owns running-state defaults. Split command_output/status.rs. | +| `command_output.rs:57 struct SetupCommandOutput` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:65 struct UpdateCommandOutput` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:72 struct StopCommandOutput` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:78 struct ImportSummary` | `lib.rs`, `transcript_import/muse_runtime.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:89 struct AuthDiagnostic` | `lib.rs`, `trace_runtime.rs` | Derives/data only | ADD ready/unconfirmed/failed constructors to own repeated status/source/default field combinations in trace_runtime; auth_failed predicate can live here. Split command_output/auth_diagnostic.rs. | +| `command_output.rs:106 enum DaemonStatus` | `lib.rs`, `trace_runtime.rs`, `src/runtime/js-daemon-client/src/index.ts` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:116 struct DaemonDiagnostic` | `lib.rs`, `trace_runtime.rs` | `command_output.rs:133` | Keep version_suffix/auth_failed; delegate to AuthDiagnostic::is_error if added. Split command_output/daemon_diagnostic.rs. | +| `command_output.rs:151 struct DoctorCommandOutput` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | +| `command_output.rs:168 enum TraceCommandOutput` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `setup/mod.rs` | `command_output.rs:178` | Keep render/write/emit methods (see file); already owns output formatting. Split output modules by command, not every tiny leaf. | +| `correlation.rs:22 struct ParentLink` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | +| `correlation.rs:27 struct ParentCandidate` | `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | +| `correlation.rs:33 enum Resolution` | `wire/methods.rs`, `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | +| `correlation.rs:40 struct CorrelationRegistry` | `pipeline/translation.rs`, `server/correlation_store.rs`, `server/mod.rs` | `correlation.rs:85` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `correlation.rs:45 struct State` | `pipeline/submission.rs`, `pipeline/translation.rs`, `transcript_import/mod.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `correlation.rs:61 struct ActiveTool` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `correlation.rs:68 struct ActiveParentSnapshot` | `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | +| `correlation.rs:80 struct ActiveToolSnapshot` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | +| `dispatch.rs:28 struct Counters` | `pipeline/consumer.rs` | `dispatch.rs:40` | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `dispatch.rs:35 struct Delivered` | `translate/claude.rs`, `translate/opencode_v2.rs`, `server/maintenance.rs`, `translate/opencode_v2/event.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `dispatch.rs:61 enum SessionMsg` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `dispatch.rs:71 struct SessionOptions` | `server/sessions.rs`, `server/mod.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `dispatch.rs:85 struct Session` | `lib.rs`, `span_processor.rs`, `pipeline/routing.rs`, `muse/export_v1.rs`, `translate/muse.rs` (+ more) | `dispatch.rs:99` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `journal.rs:64 struct ManagedRunKey` | `server/managed_run.rs` | Derives/data only | Data-only accepted-pipeline record; append/read/gc are repository I/O, not key methods. Could split journal/managed_run_key.rs if journal grows. | +| `json.rs:6 enum Field` | `attachments.rs`, `muse/outcome.rs`, `muse/metadata.rs`, `muse/hooks.rs`, `muse/provider_options.rs` (+ more) | `json.rs:12`, `json.rs:23`, `json.rs:28`, `json.rs:36` | Keep Missing/Null/Value plus as_ref/as_deref/is_missing; already owns optional native-field semantics. Split json/field.rs. | +| `json.rs:53 type Extensions` | `muse/provider_options.rs`, `muse/messages.rs`, `translate/grok.rs`, `agents/request.rs`, `agents/usage/camel_case_usage.rs` (+ more) | Derives/data only | Keep opaque alias + deserialize helper; a newtype only if adding real extension operations. Split json/extensions.rs. | +| `main.rs:32 struct EnvironmentAuthProvider` | Private/local producer and consumer in same module | `main.rs:37` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `main.rs:77 struct Cli` | `trace_command.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `main.rs:88 enum Command` | `subprocess.rs`, `env.rs`, `codex_hooks.rs`, `trace_runtime.rs`, `correlation.rs` (+ more) | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `main.rs:164 struct RouteArgs` | Private/local producer and consumer in same module | `main.rs:177` | Existing route construction belongs to CLI boundary. Data-only clap inputs otherwise. | +| `main.rs:193 struct RunRouteArgs` | Private/local producer and consumer in same module | `main.rs:208` | Data-only clap boundary input, no extra methods. | +| `pipeline/consumer.rs:22 enum Work` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/consumer.rs:27 type Held` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/consumer.rs:29 struct Consumer` | `dispatch.rs` | `pipeline/consumer.rs:177` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/consumer.rs:34 struct ConsumerOptions` | `dispatch.rs` | `pipeline/consumer.rs:49` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/cursor.rs:51 struct Cursor` | `hook.rs`, `dispatch.rs`, `env.rs`, `paths.rs`, `codex_hooks.rs` (+ more) | `pipeline/cursor.rs:127`, `pipeline/cursor.rs:338`, `pipeline/cursor.rs:416`, `agents/cursor.rs:14` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/cursor.rs:72 struct Progress` | `dispatch.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` | `pipeline/cursor.rs:78`, `pipeline/cursor.rs:87`, `pipeline/translation.rs:51` | Pipeline cursor/translation progress handles already have pending/completed/wait methods; runtime state not DTO. | +| `pipeline/cursor.rs:122 struct Subscription` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/cursor.rs:295 struct SharedCursor` | Private/local producer and consumer in same module | `pipeline/cursor.rs:298` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/cursor.rs:425 struct HeadCompletion` | Private/local producer and consumer in same module | `pipeline/cursor.rs:437`, `pipeline/cursor.rs:447` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/delivery.rs:7 struct Delivery` | `hook.rs`, `correlation.rs`, `pipeline/mod.rs`, `pipeline/cursor.rs`, `pipeline/routing.rs` (+ more) | `pipeline/delivery.rs:30`, `pipeline/delivery.rs:85`, `pipeline/delivery.rs:104` | Keep new/value/map/failed/into_completed. This is strong existing ownership model, not DTO-only. | +| `pipeline/delivery.rs:25 struct Unfinished` | Private/local producer and consumer in same module | Derives/data only | Data-only failed completion result preserving delivery; do not add implicit acknowledgment behavior. | +| `pipeline/input.rs:13 enum ControlKind` | `dispatch.rs`, `pipeline/translation.rs`, `server/maintenance.rs`, `server/recovery.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/input.rs:23 struct PipelineControl` | `pipeline/translation.rs`, `server/recovery.rs`, `collections/events.rs` | `collections/events.rs:51` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/input.rs:30 struct SourcePosition` | `pipeline/translation.rs`, `server/ingress.rs`, `server/sessions.rs`, `collections/events.rs` | Derives/data only | ADD bytes/len only if SourceRecord::bytes plus other identical subtraction callers justify it; avoid a forwarding method for one site. Keep pipeline/input.rs. | +| `pipeline/input.rs:35 enum SourceEvent` | `pipeline/translation.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/input.rs:40 struct SourceRecord` | `pipeline/translation.rs` | `pipeline/input.rs:45` | Keep bytes helper; stage input pair is already cohesive. No serialization/accessor boilerplate. | +| `pipeline/input.rs:52 struct Buffer` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/input.rs:58 struct SourceInput` | `pipeline/translation.rs`, `server/sessions.rs`, `server/mod.rs` | `pipeline/input.rs:60` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/live.rs:7 type SharedOp` | `pipeline/prepare.rs`, `pipeline/cursor.rs`, `pipeline/routing.rs`, `pipeline/consumer.rs`, `collections/session.rs` (+ more) | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/live.rs:11 struct Record` | `pipeline/cursor.rs`, `translate/opencode.rs`, `collections/session.rs`, `collections/events.rs`, `collections/legacy.rs` (+ more) | `pipeline/live.rs:16` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/live.rs:25 struct Queued` | `command_output.rs`, `translate/opencode_v2.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/live.rs:29 struct Route` | `journal.rs`, `pipeline/prepare.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs`, `collections/events.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/live.rs:35 struct Multiplexer` | `collections/span_ops.rs` | `pipeline/live.rs:42` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/live.rs:38 struct Receiver` | `dispatch.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `server/ingress.rs` (+ more) | `pipeline/delivery.rs:85`, `pipeline/live.rs:92`, `pipeline/live.rs:110` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/live.rs:84 struct Control` | `pipeline/cursor.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `server/recovery.rs`, `collections/events.rs` (+ more) | `pipeline/live.rs:85` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/plugins.rs:6 enum PluginOutcome` | `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/plugins.rs:13 struct Plugins` | `pipeline/routing.rs`, `setup/cursor/tests.rs` | `pipeline/plugins.rs:38`, `pipeline/plugins.rs:64` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/plugins.rs:21 struct PluginRejected` | Private/local producer and consumer in same module | `pipeline/plugins.rs:26`, `pipeline/plugins.rs:36` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/prepare.rs:27 struct Prepare` | `pipeline/translation.rs`, `pipeline/routing.rs`, `managed_run/mod.rs` | `pipeline/prepare.rs:32` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/prepare.rs:130 struct ConfiguredTranslator` | `translate/mod.rs` | `pipeline/prepare.rs:135`, `pipeline/prepare.rs:150`, `pipeline/prepare.rs:159` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/recovery.rs:10 enum Boundary` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/ingress.rs` | `pipeline/recovery.rs:19` | Keep Display; data-only discriminant. | +| `pipeline/recovery.rs:35 enum Condition` | `pipeline/cursor.rs` | Derives/data only | Existing eligibility/matching in Failure recovery owns stage context; move pure checks only with repeated caller evidence. | +| `pipeline/recovery.rs:61 struct TimeoutRetry` | Private/local producer and consumer in same module | Derives/data only | Data-only persisted retry policy. Condition owns eligibility context. | +| `pipeline/recovery.rs:69 enum RetryCondition` | `pipeline/submission.rs`, `pipeline/routing.rs` | Derives/data only | Data-only classifier result consumed by Failure creation; retain enum. | +| `pipeline/recovery.rs:83 struct RouteFailure` | `pipeline/routing.rs`, `pipeline/consumer.rs` | `pipeline/recovery.rs:90`, `pipeline/recovery.rs:95`, `pipeline/recovery.rs:105` | Keep Display/Debug/Error; route-level error carrier, no extra accessors. | +| `pipeline/recovery.rs:112 struct Failure` | `pipeline/submission.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `pipeline/submission.rs:36`, `pipeline/submission.rs:41`, `pipeline/submission.rs:49`, `pipeline/submission.rs:55` | Existing constructors/retry eligibility/status conversion in pipeline/recovery already own behavior; submission::Failure::classify already owns SDK classification. Keep separate namespaced types. | +| `pipeline/recovery.rs:317 enum RecoveryOutcome` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/recovery.rs:321 struct Recovery` | `pipeline/cursor.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/correlation_store.rs` (+ more) | `pipeline/recovery.rs:326` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/roots.rs:7 struct Roots` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `sink/braintrust.rs` | `pipeline/roots.rs:11`, `pipeline/roots.rs:21`, `pipeline/roots.rs:57` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/routing.rs:15 struct Request` | `client.rs`, `pipeline/attachment_tests.rs`, `wire/mod.rs`, `wire/rpc.rs`, `server/maintenance.rs` (+ more) | `wire/rpc.rs:50` | KEEP DATA-ONLY stage request/response pair; these are not JSON-RPC types. Keep private next to routing stage. | +| `pipeline/routing.rs:20 struct Response` | `client.rs`, `codex_hooks.rs`, `muse/msp.rs`, `wire/mod.rs`, `wire/rpc.rs` (+ more) | `wire/rpc.rs:79` | KEEP DATA-ONLY stage request/response pair; these are not JSON-RPC types. Keep private next to routing stage. | +| `pipeline/routing.rs:26 struct Forward` | `main.rs` | `pipeline/routing.rs:28` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/routing.rs:34 struct RoutingSink` | `pipeline/consumer.rs` | `pipeline/routing.rs:42`, `pipeline/routing.rs:246` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/submission.rs:5 enum Operation` | `span_processor.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/submission.rs:10 struct Input` | `pipeline/recovery.rs`, `pipeline/plugins.rs`, `pipeline/roots.rs`, `pipeline/mod.rs`, `pipeline/routing.rs` (+ more) | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/submission.rs:15 struct State` | `correlation.rs`, `pipeline/translation.rs`, `transcript_import/mod.rs` | Derives/data only | KEEP DATA-ONLY sink submission status snapshot; no new methods. | +| `pipeline/submission.rs:20 enum Outcome` | `pipeline/recovery.rs`, `pipeline/plugins.rs`, `pipeline/roots.rs`, `pipeline/mod.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/submission.rs:31 struct Failure` | `pipeline/recovery.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `pipeline/submission.rs:36`, `pipeline/submission.rs:41`, `pipeline/submission.rs:49`, `pipeline/submission.rs:55` | Existing constructors/retry eligibility/status conversion in pipeline/recovery already own behavior; submission::Failure::classify already owns SDK classification. Keep separate namespaced types. | +| `pipeline/submission.rs:88 struct Submission` | `pipeline/routing.rs` | `pipeline/submission.rs:92`, `pipeline/submission.rs:106` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:31 struct Observation` | `server/sessions.rs`, `transcript_mirror/observation.rs`, `transcript_mirror/mod.rs`, `transcript_mirror/payload.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/translation.rs:37 enum Command` | `subprocess.rs`, `env.rs`, `codex_hooks.rs`, `trace_runtime.rs`, `correlation.rs` (+ more) | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:47 struct Progress` | `dispatch.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs` | `pipeline/cursor.rs:78`, `pipeline/cursor.rs:87`, `pipeline/translation.rs:51` | Pipeline cursor/translation progress handles already have pending/completed/wait methods; runtime state not DTO. | +| `pipeline/translation.rs:58 struct RouteLifetimes` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:63 struct Translation` | `dispatch.rs`, `pipeline/recovery.rs`, `sink/braintrust.rs`, `server/ingress.rs`, `server/sessions.rs` (+ more) | `pipeline/translation.rs:87` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:74 struct TranslationOptions` | `server/sessions.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | +| `pipeline/translation.rs:188 enum State` | `correlation.rs`, `pipeline/submission.rs`, `transcript_import/mod.rs` | Derives/data only | Runtime translation state enum; EXCLUDED DTO methods target. Keep transition matching with Producer. | +| `pipeline/translation.rs:193 struct Continuation` | `translate/claude.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:205 struct Publication` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `pipeline/translation.rs:216 struct Producer` | Private/local producer and consumer in same module | `pipeline/translation.rs:237` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `plugin_diagnostics.rs:13 struct PluginDiagnostic` | `lib.rs`, `command_output.rs` | Derives/data only | ADD matches_failure and record_occurrence(now) only if record remains complex; identity and saturating occurrences belong to diagnostic. I/O stays store. Split plugin_diagnostics/diagnostic.rs optional. | +| `plugin_diagnostics.rs:27 struct DiagnosticStore` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `process.rs:56 struct ProcessSnapshot` | Private/local producer and consumer in same module | Derives/data only | Data-only one platform query result; no methods, keep private in process.rs. | +| `server/auth.rs:38 struct RouteAuthProvider` | Private/local producer and consumer in same module | `server/auth.rs:44` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `server/claude_transcripts.rs:9 struct ClaudeTranscriptObservation` | `server/mod.rs` | Derives/data only | Borderline runtime observation state. Shared observer/refill belongs to type if main+child share common representation; avoid retain payload getters. Parent owns observer refactor. | +| `server/claude_transcripts.rs:18 struct ClaudeChildObservation` | Private/local producer and consumer in same module | Derives/data only | Same observation state decision; path/through/template already concrete. Merge state shape with root observation only if lifecycle does not blur child map ownership. | +| `server/correlation_store.rs:17 struct PendingSession` | `server/maintenance.rs`, `server/recovery.rs`, `server/mod.rs` | `server/correlation_store.rs:37`, `server/correlation_store.rs:52` | Keep restore/decided/expired; already owns durable compatibility/deadline semantics. Move into server/correlation/pending_session.rs if splitting store I/O. | +| `server/correlation_store.rs:88 struct PendingEvent` | `server/ingress.rs`, `server/maintenance.rs`, `server/recovery.rs` | `server/correlation_store.rs:97` | Keep custom Deserialize old/new representation; add position() returning SourcePosition only if repeated conversion sites share semantics. Split server/correlation/pending_event.rs. | +| `server/ingress.rs:11 struct CaptureBuffer` | `server/mod.rs` | `server/ingress.rs:22` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `server/ingress.rs:17 struct EvictedRange` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | +| `server/ingress.rs:39 enum CaptureWork` | `server/maintenance.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | +| `server/ingress.rs:145 enum IngressMsg` | `server/maintenance.rs`, `server/recovery.rs`, `server/mod.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `server/mod.rs:57 struct ServeOptions` | `lib.rs`, `trace_runtime.rs`, `main.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | +| `server/mod.rs:68 enum AuthResolveReason` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/consumer.rs`, `server/maintenance.rs` (+ more) | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | +| `server/mod.rs:78 struct AuthLease` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/consumer.rs`, `server/recovery.rs` (+ more) | Derives/data only | Data-only live credentials/expiry transfer; refresh resolution and deadlines involve daemon policy, keep there unless duplicated pure is_expiring_at(now,margin). | +| `server/mod.rs:101 struct SessionAuthState` | `server/auth.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | +| `server/mod.rs:106 type StorageSlot` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `server/mod.rs:108 struct Daemon` | `subprocess.rs`, `trace_runtime.rs`, `correlation.rs`, `trace_command.rs`, `command_output.rs` (+ more) | `server/correlation_store.rs:670`, `server/ingress.rs:45`, `server/ingress.rs:337`, `server/claude_transcripts.rs:24` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `server/sessions.rs:8 struct DeliveryKey` | `server/maintenance.rs`, `server/recovery.rs`, `server/claude_transcripts.rs`, `server/auth.rs`, `server/managed_run.rs` (+ more) | `server/sessions.rs:14` | Keep new/correlation_key; no need forward field accessors. Split server/delivery_key.rs when moving sessions actor code. | +| `sink/braintrust.rs:28 struct BraintrustSinkConfig` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/attachment_tests.rs`, `pipeline/consumer.rs` (+ more) | Derives/data only | KEEP DATA-ONLY factory/options/SDK conversion carrier; client, credentials, and attachment upload lifetime are sink service responsibilities. | +| `sink/braintrust.rs:34 struct ClientCache` | Private/local producer and consumer in same module | `sink/braintrust.rs:96` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:42 struct ClientCacheState` | Private/local producer and consumer in same module | `sink/braintrust.rs:72` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:47 struct CachedClient` | Private/local producer and consumer in same module | `sink/braintrust.rs:52` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:136 struct BraintrustSinkFactory` | `lib.rs`, `pipeline/attachment_tests.rs`, `pipeline/consumer.rs`, `sink/mod.rs`, `server/mod.rs` | `sink/braintrust.rs:141`, `sink/braintrust.rs:150` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:171 struct Creds` | Private/local producer and consumer in same module | `sink/braintrust.rs:178` | KEEP DATA-ONLY factory/options/SDK conversion carrier; client, credentials, and attachment upload lifetime are sink service responsibilities. | +| `sink/braintrust.rs:190 struct AttachmentUploads` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:195 struct BraintrustSink` | Private/local producer and consumer in same module | `sink/braintrust.rs:217`, `sink/braintrust.rs:456` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/braintrust.rs:701 struct DestinationComponents` | Private/local producer and consumer in same module | Derives/data only | Data-only SDK conversion intermediate. Distinct sink/correlation fallback behavior means do not deduplicate blindly. | +| `sink/braintrust.rs:834 struct ByteCounter` | Private/local producer and consumer in same module | `sink/braintrust.rs:836` | Serializer writer implementation, not DTO; keep Write impl. | +| `sink/debug.rs:14 struct DebugSinkFactory` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `sink/mod.rs`, `server/mod.rs` | `sink/debug.rs:18` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `sink/debug.rs:37 struct DebugSink` | Private/local producer and consumer in same module | `sink/debug.rs:43` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:20 struct StopTracing` | `pipeline/routing.rs`, `pipeline/consumer.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | +| `span_processor.rs:28 struct PluginTimeout` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:44 enum Operation` | `pipeline/submission.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | +| `span_processor.rs:50 struct PluginContext` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:57 struct Engine` | `attachments.rs`, `muse/images.rs`, `setup/cursor/hooks.rs` | `span_processor.rs:87` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:70 struct CachedModule` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:76 struct FailedPlugin` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:83 struct PluginFingerprint` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `span_processor.rs:285 struct PluginFailure` | `pipeline/plugins.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | +| `span_processor.rs:293 struct ProcessResult` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | +| `subprocess/windows_daemon.rs:103 struct HandleList` | Private/local producer and consumer in same module | `subprocess/windows_daemon.rs:108`, `subprocess/windows_daemon.rs:151` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `trace_command.rs:13 struct TraceArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:22 enum TraceCommand` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:51 struct StopArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:58 struct DoctorArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:65 enum DoctorAgent` | `lib.rs`, `trace_runtime.rs` | `trace_command.rs:79` | Keep identity; enum-specific source dispatch belongs here already. | +| `trace_command.rs:95 struct EnableArgs` | `lib.rs`, `setup/mod.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:116 type SetupArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:119 struct DisableArgs` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:125 struct UpdateArgs` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | +| `trace_command.rs:131 enum SetupAgent` | `lib.rs`, `trace_runtime.rs`, `setup/mod.rs` | `trace_command.rs:152` | Keep identity; do not add forwarded enable/disable methods that couple command execution. | +| `trace_runtime.rs:26 struct RouteRequirements` | `lib.rs` | Derives/data only | Data-only host request flags. No builder/boolean accessors. | +| `trace_runtime.rs:45 struct HostRouteSelection` | `lib.rs` | `trace_runtime.rs:50` | Keep into_session_route; conversion belongs to selection. Split host_route_selection.rs if runtime service contract grows. | +| `trace_runtime.rs:156 struct TraceHostContext` | `lib.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `trace_runtime.rs:166 struct HostAuthProvider` | Private/local producer and consumer in same module | `trace_runtime.rs:171` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `transport.rs:47 type ClientStream` | `client.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `transport.rs:49 type ClientStream` | `client.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `transport.rs:52 type ServerStream` | `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `transport.rs:54 type ServerStream` | `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | +| `transport.rs:86 struct Listener` | `server/mod.rs`, `server/rpc.rs` | `transport.rs:91`, `transport.rs:111` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `transport.rs:104 struct Listener` | `server/mod.rs`, `server/rpc.rs` | `transport.rs:91`, `transport.rs:111` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `win_acl.rs:28 struct SecurityDescriptor` | `transport.rs`, `trace_runtime.rs` | `win_acl.rs:34`, `win_acl.rs:40` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `win_acl.rs:137 struct NamedDacl` | Private/local producer and consumer in same module | `win_acl.rs:142` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | +| `wire/envelope.rs:14 struct ProcessIdentity` | `correlation.rs`, `process.rs`, `wire/mod.rs`, `setup/cursor/hooks.rs` | Derives/data only | Data-only stable identity/hash key; process liveness is platform-dependent service, not DTO behavior. Split process_identity.rs. | +| `wire/envelope.rs:27 struct CaptureContext` | `correlation.rs`, `process.rs`, `wire/mod.rs` | Derives/data only | Data-only captured ancestry; matching/capture I/O belongs to correlation/process services. Split capture_context.rs. | +| `wire/envelope.rs:37 struct Envelope` | `hook.rs`, `dispatch.rs`, `client.rs`, `journal.rs`, `trace_runtime.rs` (+ more) | `wire/envelope.rs:333`, `collections/events.rs:45`, `transcript_import/muse.rs:66` | Keep redacted(); own synthetic successor creation only if semantics match. Split to envelope.rs; native payload remains opaque. | +| `wire/envelope.rs:77 enum AuthSource` | `trace_runtime.rs`, `main.rs`, `settings.rs`, `wire/mod.rs`, `setup/mod.rs` (+ more) | `wire/envelope.rs:104` | Keep is_auto serialization helper; no extra API for one match. Split auth_source.rs. | +| `wire/envelope.rs:92 struct AuthSelection` | `trace_runtime.rs`, `main.rs`, `settings.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs` (+ more) | `wire/envelope.rs:110` | Keep effective_source/canonicalized; could own source_label used by diagnostics. Split auth_selection.rs with AuthSource helper or separate auth_source.rs. | +| `wire/envelope.rs:144 struct SessionRoute` | `hook.rs`, `dispatch.rs`, `route.rs`, `journal.rs`, `lib.rs` (+ more) | `wire/envelope.rs:162` | Keep with_auth/same_route/same_destination/same_replay_route; ADD apply_metadata/apply_tags if parent consolidates route.rs normalization. No sink/storage I/O. Split session_route.rs. | +| `wire/envelope.rs:220 struct SessionConfig` | `dispatch.rs`, `trace_runtime.rs`, `correlation.rs`, `pipeline/attachment_tests.rs`, `pipeline/submission.rs` (+ more) | `wire/envelope.rs:252` | Keep attached_span_ids; DELEGATE project_name to TraceDestination::project_name. Split session_config.rs. | +| `wire/envelope.rs:238 enum TraceDestination` | `trace_runtime.rs`, `correlation.rs`, `main.rs`, `args.rs`, `settings.rs` (+ more) | `wire/envelope.rs:270`, `wire/envelope.rs:296` | Keep FromStr/project_name; ADD parent-span component/IDs query only if reused by sink + correlation. Their differing project fallback policies must remain explicit. Split trace_destination.rs. | +| `wire/envelope.rs:308 struct BackendAuth` | `journal.rs`, `trace_runtime.rs`, `correlation.rs`, `main.rs`, `pipeline/recovery.rs` (+ more) | Derives/data only | Data-only credential carrier; no I/O, cache lookup, or persistence methods. Split backend_auth.rs. | +| `wire/envelope.rs:325 enum FlushMode` | `hook.rs`, `trace_runtime.rs`, `wire/mod.rs`, `transcript_import/pipeline.rs` | Derives/data only | Data-only closed wire enum, no accessor that restates matches!. Split flush_mode.rs. | +| `wire/envelope.rs:355 struct RedactedEnvelope` | `journal.rs`, `wire/mod.rs`, `collections/events.rs`, `collections/legacy.rs` | Derives/data only | ADD into_envelope(self): own credential-free runtime reconstruction now in journal::envelope_from_redacted. Migrate internal callers; the old helper is internal-only, so it can be removed. Split redacted_envelope.rs. | +| `wire/methods.rs:19 struct InitializeParams` | `muse/msp.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:25 struct ClientInfo` | `muse/msp.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:38 struct InitializeResult` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:46 struct Capabilities` | `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:55 struct EventLogResult` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:60 struct FlushParams` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:68 struct ImportFinishParams` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:80 struct ImportFinishResult` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:91 struct ImportResetParams` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:97 struct ManagedRunFlushParams` | `client.rs`, `wire/mod.rs`, `server/managed_run.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:108 struct FlushResult` | `client.rs`, `wire/mod.rs`, `server/managed_run.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:116 struct StatusParams` | `client.rs`, `wire/mod.rs`, `server/recovery.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:123 struct StatusResult` | `client.rs`, `command_output.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | `command_output.rs:37` | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:130 struct RecoveryInfo` | `dispatch.rs`, `command_output.rs`, `pipeline/recovery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs` (+ more) | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:142 struct SessionStatus` | `command_output.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:162 struct AuthDiagnoseParams` | `trace_runtime.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:170 struct AuthDiagnoseResult` | `trace_runtime.rs`, `wire/mod.rs`, `server/auth.rs`, `server/mod.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/methods.rs:183 struct ShutdownResult` | `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | +| `wire/rpc.rs:8 enum RequestId` | `client.rs`, `muse/hooks.rs`, `muse/ids.rs`, `wire/mod.rs`, `server/maintenance.rs` (+ more) | Derives/data only | Data-only wire identifier, no extra wrapper accessors. Split rpc/request_id.rs if RPC layout is reorganized. | +| `wire/rpc.rs:23 enum Message` | `client.rs`, `wire/mod.rs`, `translate/opencode.rs`, `translate/claude.rs`, `translate/opencode_v2.rs` (+ more) | `wire/rpc.rs:29`, `translate/opencode_v2/span.rs:102` | Keep from_line/to_line; framing is type-owned already. Split rpc/message.rs with stable reexport. | +| `wire/rpc.rs:42 struct Request` | `client.rs`, `pipeline/attachment_tests.rs`, `pipeline/routing.rs`, `wire/mod.rs`, `server/maintenance.rs` (+ more) | `wire/rpc.rs:50` | Keep new constructor; optional decode_params duplicates serde and has too little benefit. Split rpc/request.rs. | +| `wire/rpc.rs:62 struct Notification` | `muse/hooks.rs`, `translate/muse_events.rs`, `server/rpc.rs`, `managed_run/claude.rs` | Derives/data only | Data-only outbound/inbound frame; no meaningful repeated interaction found. Split rpc/notification.rs. | +| `wire/rpc.rs:70 struct Response` | `client.rs`, `codex_hooks.rs`, `pipeline/routing.rs`, `muse/msp.rs`, `wire/mod.rs` (+ more) | `wire/rpc.rs:79` | Keep serialized/ok/err; already owns response invariants. Split rpc/response.rs. | +| `wire/rpc.rs:114 struct RpcError` | `codex_hooks.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | `wire/rpc.rs:121` | Keep new; retain error code constants together in rpc. Split rpc/error.rs if desired. | +| `wire/rpc.rs:145 struct JsonRpcV2` | Private/local producer and consumer in same module | `wire/rpc.rs:147`, `wire/rpc.rs:153` | Keep custom Serialize/Deserialize; no new behavior. Keep alongside RPC framing marker. | +| `attachments.rs:212 struct Marker` | Private/local producer and consumer in same module | Derives/data only | Data-only local decoding shape; keep in materialize boundary, not exported or separate file. | +| `server/claude_transcripts.rs:56 struct PollPayload` | Private/local producer and consumer in same module | Derives/data only | Data-only local synthetic encoding shape; promote reusable event constructor only if reused; no separate DTO file for one local writer. | +| `server/correlation_store.rs:104 enum StoredPendingEvent` | Private/local producer and consumer in same module | Derives/data only | Data-only private compatibility enum in PendingEvent deserializer; keep local. | + +Consumer samples are lexical cross-reference evidence, not proof of same-name identity; generic names (`State`, `Head`, `Failure`, `Request`, `Response`, `Progress`) must be interpreted with the stated module. Judgments above account for their actual stage/collection ownership. + +## TypeScript per-declaration review + +| Declaration | Usage/ownership | Recommendation | +|---|---|---| +| `src/plugins/opencode/content/src/config.ts:5 BraintrustConfig` | OpenCode loadConfig + tools + tracing + plugin input. | Keep resolved config DTO; no class. Shared route query function reduces repeated destination assertions. | +| `src/plugins/opencode/content/src/config.ts:20 PluginConfig` | OpenCode config loader and plugin setup. | Data-only authored config DTO; do not mix environment/filesystem lookup into it. | +| `src/plugins/opencode/content/src/server.ts:10 NativeEvent` | OpenCode2 server async subscribe forwarding. | Data-only partial event boundary; session/event filtering stays adapter. | +| `src/plugins/opencode/content/src/server.ts:17 Context` | OpenCode2 server SDK structural input. | Service interface, not DTO; leave structural compatibility with SDK. | +| `src/plugins/opencode/content/src/tools/bt-cli.ts:8 ProjectInfo` | BtCliToolsClient.listProjects/project tool calls. | Data-only CLI result, keep alongside tool client unless reused. | +| `src/plugins/opencode/content/src/tools/bt-cli.ts:13 ToolLogData` | OpenCode tool invocation -> BtCliToolsClient.logData JSON payload. | Data-only arbitrary user log envelope; no methods. | +| `src/plugins/opencode/content/src/tools/bt-cli.ts:26 BtCliRunner` | BtCliToolsClient dependency injection. | Function alias, not DTO; keep near client. | +| `src/plugins/opencode/content/src/tracing/daemon.ts:7 Logger` | OpenCode tracing adapter diagnostic callback. | Function alias, not DTO; keep local. | +| `src/plugins/opencode/content/src/tracing/daemon.ts:9 TracingRouteConfig` | createDaemonTracingHooks input from resolved config. | Data-only adapter projection; consider Pick if eliminating parallel shape, no class. | +| `src/plugins/pi/content/src/config.ts:7 PiConfig` | loadConfig then index.ts callbacks/UI/tracing. | Keep resolved config DTO; route/auth/project synchronization belongs to config normalization functions already. No class migration. | +| `src/plugins/pi/content/src/config.ts:18 ConfigRecord` | Pi JSON read/applyConfig boundary. | Keep unknown bag only at decoding boundary, no class. | +| `src/plugins/pi/content/src/index.ts:50 JsonObject` | Pi index native payload/type guards. | Generic boundary map alias, not DTO behavior target. | +| `src/plugins/pi/content/src/legacy-session.ts:5 LegacyContinuation` | legacyContinuationFor validation then Pi session-start payload. | Data-only compatibility result; reader owns validation, keep same file. | +| `src/plugins/pi/content/src/pi-package.ts:13 PiPackageManifest` | pi-package find/read/native manifest validation. | Data-only partial boundary view, unknown fields intentionally runtime-validated. | +| `src/plugins/pi/content/src/pi-package.ts:21 PiPackageMetadata` | runningPiPackage cache, Pi config directory, adapter source version. | Data-only normalized package info; module already one concern. | +| `src/runtime/js-daemon-client/src/index.ts:9 DaemonSessionRoute` | Shared client + Pi config + OpenCode config/tracing; repeated destination discrimination and auth projection. | Keep structural DTO; extract typed destination union and routeProjectName/routeAuth query functions to runtime route.ts after explicitly preserving boundary validation. No class methods on serialized JSON. | +| `src/runtime/js-daemon-client/src/index.ts:23 DaemonTraceSettings` | resolveDaemonTraceSettings plus both agent config loaders. | Keep DTO; shared resolver already owns invocation override semantics. Move to settings.ts with resolver for clearer ownership. | +| `src/runtime/js-daemon-client/src/index.ts:75 DaemonEnvelope` | DaemonClient.log/logPipelined and Pi/OpenCode adapters. | Keep DTO. eventParams already centralizes plugin/run stamping in client; module envelope.ts optional, no new class. | +| `src/runtime/js-daemon-client/src/index.ts:87 DaemonSessionStatus` | DaemonClient.status and Pi trace-link/status UI. | Data-only status schema; shared protocol.ts/status.ts. | +| `src/runtime/js-daemon-client/src/index.ts:96 DaemonStatus` | DaemonClient.status response and plugin UI. | Data-only aggregate; keep with session status. | +| `src/runtime/js-daemon-client/src/index.ts:102 DaemonClientOptions` | DaemonClient constructor defaults. | Data-only options; normalization already in constructor. Keep near client. | +| `src/runtime/js-daemon-client/src/index.ts:115 RpcResponse` | DaemonClient read/response dispatch. | Data-only boundary response; shared protocol.ts. Decode/validation can be free functions, no instances. | +| `src/runtime/js-daemon-client/src/index.ts:122 PendingRequest` | DaemonClient.pending map timeout/response cleanup. | Runtime completion state, not DTO; keep client-private to avoid class churn. | +| `src/runtime/js-daemon-client/src/index.ts:129 OutboxEntry` | DaemonClient.pumpOutbox/connection/retry paths. | Runtime obligation state, not DTO. Could own fail/settle only if all retry transitions move together; no partial abstraction. | + +Scan totals: 235 Rust production declarations (including explicitly excluded runtime types), 24 TypeScript declarations. No production JS declared DTO classes/interfaces beyond these TypeScript types. Generated runtime reexports and test-only aliases are not duplicate DTO definitions. + +## Suggested verification + +Full locked all-feature Rust tests and strict Clippy for module/public-import changes. Existing wire roundtrip and redaction tests guard unknown/missing fields and credentials. Replay tests guard route-preserving reconstruction. TypeScript changes, if taken, need js-daemon-client and Pi/OpenCode config suites. + +## Implemented in this stacked refactor + +- `wire/envelope.rs` is now the single Envelope owner. AuthSelection, AuthSource, BackendAuth, CaptureContext, FlushMode, ProcessIdentity, RedactedEnvelope, SessionConfig, SessionRoute, TraceDestination each have a primary type file under `wire/`, with unchanged `wire::*` public exports. Existing wire behavior tests moved intact to `wire/envelope_tests.rs`. +- `RedactedEnvelope::into_envelope` owns replay conversion, including credential-free reconstructed config. All five internal replay/maintenance/ingress callers use the method. `journal::envelope_from_redacted` was verified internal-only (`mod journal`, not reexported) and removed after migrating all callers, so no public API compatibility shim is needed. A focused test asserts complete journal projection roundtrip and absence of replay credentials/config when route absent. +- `SessionConfig::project_name` delegates to the destination's existing query. +- `SessionRoute::apply_additional_metadata` and `apply_tags` own validation and mutation shared by setup, managed runs, import, and hook capture. Their existing regression tests now call methods; filesystem/plugin validation stays outside the DTO. +- `AuthDiagnostic` moved into `command_output/auth_diagnostic.rs`. It owns ready/unconfirmed construction, diagnostic-specific auth provenance labels, and ready/error status predicates reused by runtime warnings and daemon diagnostics. Serialized strings and the distinction between requested versus daemon-confirmed profile/org remain unchanged. + +## Deliberately retained/deferred + +- RPC leaf request/result schemas, command args, snapshot rows, options, and TS interfaces stay data-only unless already owning meaningful codec/conversion behavior. No mandatory one-type-per-file churn for local encoding helpers or tightly coupled tiny enums. +- JS types remain structural; no class conversion or TS protocol change in this PR. +- Different sink/correlation project fallback policies remain separate; their SDK output ownership deserves a dedicated contract review before consolidation. +- Plugin diagnostic matching/count aggregation and deeper RPC/per-command module splits remain optional small follow-ups; current private single-service implementations do not justify increasing this PR's surface. diff --git a/docs/architecture/dto-ownership/translators.md b/docs/architecture/dto-ownership/translators.md new file mode 100644 index 00000000..891cf3bf --- /dev/null +++ b/docs/architecture/dto-ownership/translators.md @@ -0,0 +1,356 @@ +# DTO ownership inventory: translators, import, and transcript mirrors + +Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. + + +Scope: all production struct/enum/type declarations in `bt-daemon/src/translate/**`, `transcript_import/**`, and `transcript_mirror.rs`, including function-local DTOs. Reviewed against source callers, not merely derives. Test-only fixtures are excluded; runtime state declarations are explicitly accounted for below. Native schema types imported from agents/muse are owned by the other inventory scopes. This is the pre-refactor inventory; see [the review summary](README.md) for the implementation decisions. + +## Decisions and module plan + +1. Put interactions on the type that owns their policy, rather than adding mechanical getters. Highest-value changes: SkillLoad skill metadata + display name; Pi AssistantMessage response-model selection and normalization; Pi compaction input/summary projection; OpenCode PermissionProperties request normalization; OpenCode2 Context/native tool content conversion; TranscriptPayload reference selection. Existing Cursor Hook/Specialized and OpenCode2 span Message/ToolCall are good models. +2. DTOs used once solely to deserialize/serialize fields should remain data-only. A one-method wrapper around serde or a DTO getter that duplicates public field access adds no ownership. Keep provider-native models separate from span export models and actor continuation state. +3. Prefer one principal type per file with small private companions beside the owner: `pi/assistant_message.rs` + `pi/compaction.rs` + `pi/event.rs`; `opencode/permission.rs`; `opencode_v2/context.rs` for native context family and normalization; `tool/skill_load.rs`; `transcript_mirror/{reference,payload,observation,snapshot}.rs` with the I/O engine in mod.rs. Avoid 40 tiny files for OpenCode2 one-shot event payload wrappers. +4. Preserve unknown extensions, authored null/missing, native event ordering, save/restore wire JSON, capture absence vs noncaptured fallback, and replay high-water bounds. Existing fixtures and all-agent replay coverage are needed after moving code. + +Rows below list declarations individually, local consumers/nearby functions found by symbol reference (up to four examples), existing impl methods, and a concrete decision. For nested DTOs the enclosing caller is listed. Consumer line numbers reflect pre-refactor source. + + +## bt-daemon/src/transcript_import/claude.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `Subagent` :348 | subagents@364 | none | KEEP parser result data-only: one builder subagents(), one event emission loop. Hierarchy traversal belongs importer; no independent methods justified. | + +## bt-daemon/src/transcript_import/codex.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `SpawnCall` :327 | spawn_calls@336 | none | KEEP parser result data-only: one spawn_calls producer and child import consumer, no repeated policy. | + +## bt-daemon/src/transcript_import/mod.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `TranscriptLayout` :32 | resolve_transcripts@107 | `discover`, `find`, `candidates`, `single`, `locations` | KEEP existing discover/find/candidates methods: good owner of transcript filename/root search. Move `transcript_layout.rs` if splitting import mod. | +| `Refresh` :248 | refresh_with_final_partial@260, poll@473 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | + +## bt-daemon/src/transcript_import/muse.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `ReadMode` :19 | finish@543, for_each_envelope_for_session@652, for_each_snapshot_envelope_for_session@661 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | + +## bt-daemon/src/transcript_import/pipeline.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `ImportTarget` :20 | run_import@33, import_transcript@145, import_transcripts@195, new@247 | none | KEEP data-only host/socket/route launch context. Do not hide process startup behind DTO methods; clients already own it. | + +## bt-daemon/src/transcript_mirror.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `Reference` :25 | schema composition@34, read_path@50, is_empty@89 | `captured`, `read_path` | KEEP existing captured/read_path and ADD explicit complete-capture/path-bound selection only where replay semantics match. Split to transcript_mirror/reference.rs (parent owns). | +| `GrokReferences` :48 | read_path@57, is_empty@93 | `is_empty` | KEEP is_empty; no fake common iteration across heterogeneous slots, split with reference family. | +| `Observation` :64 | is_empty@95 | none | KEEP data-only; Antigravity path/bound precedence can be owned by TranscriptPayload::antigravity_source if shared, avoid filesystem I/O in DTO. | +| `Snapshot` :72 | is_empty@97 | none | KEEP data-only; content is immutable input to bounded reader. Separate snapshot.rs only if module makes lookup easier. | +| `TranscriptPayload` :80 | is_empty@112 | `decode` | ADD explicitly named Claude reference/through/native-path access methods used dispatch, server observer and readers. Preserve map-presence vs missing-entry semantics, captured absence, replay fallback. Split payload.rs (parent owns). | +| `ClaudeChildReference` :107 | is_empty@86 | none | KEEP data-only child path/offset pair; co-locate Reference family, no duplicated observer/runtime state. | + +## bt-daemon/src/translate/antigravity.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `HookPayload` :27 | ensure_root@131, pre_invocation@270, post_invocation@321, pre_tool@346 | none | ADD Antigravity `tool_approval()` by moving tool_approval_from_hook only if splitting hook schema; one call so low priority. Keep other fields data-only. | +| `Message` :44 | create@97, transcript_message@678 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `TranscriptSource` :580 | transcript_source@587 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `ToolDetails` :733 | tool_details@740 | none | KEEP projection result data-only; tool_details interprets source TranscriptRecord and belongs that schema only if truly reused, not result DTO. | + +## bt-daemon/src/translate/claude.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `HookContext` :30 | ensure_root@395, tail_main@458, observe_session_details@473, handle@1507 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `SubagentHook` :48 | parent_for@727, ensure_subagent@739, stop_subagent@968, handle@1514 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `TranscriptEnvelope` :60 | assistant_request_id@1764, parse_transcript@1793, is_real_user_record@2041 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `TimestampEnvelope` :73 | parse_timestamp_ms@2656 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `AgentOrigin` :177 | begin_compacted@288, ensure_subagent@750 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `ParsedTranscript` :1779 | emit_next_pending@1103, parse_transcript@1785 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `UsageRecord` :2162 | observe@2169 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `UsageMessage` :2166 | observe@2163 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | +| `TranscriptToolOutcome` :2254 | parse_transcript@1918, transcript_tool_outcome@2261 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | + +## bt-daemon/src/translate/codex/tool_output.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `ToolOutcome` :13 | classify@19 | `command`, `observe`, `observe_text`, `observe_command_header` | KEEP observe/command internal methods; optionally make classify an associated constructor because all work builds this result, but not high-value compared with native DTO conversions. | + +## bt-daemon/src/translate/codex.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `SessionStartHook` :54 | handle@290 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `CompactHook` :62 | handle@302, record_compaction_trigger@517 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `SubagentStartHook` :69 | handle@297, handle_subagent_start@562 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `RolloutRecord` :79 | catch_up_chunk@661, process_record@672 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `PayloadKind` :94 | process_record@733 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `WorkingDirectoryPayload` :100 | process_record@681 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `TurnContextPayload` :106 | process_record@689 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `TokenCount` :1292 | close_llm_with_tokens@1299 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `TokenCountInfo` :1296 | close_llm_with_tokens@1293 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | +| `ReadLines` :2161 | read_new_lines@2172 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | + +## bt-daemon/src/translate/cursor/hooks.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `Hook` :20 | schema composition@28 | `decode`, `generation_id`, `model`, `model_params`, `cwd`, `tool_use_id` | KEEP decode/generation_id/model/model_params/cwd/tool_use_id; strong existing ownership. Split hook.rs plus hook_common.rs, preserve central event decode. | +| `HookCommon` :90 | schema composition@23 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `DaemonFields` :101 | decode@39 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `TranscriptMirror` :109 | schema composition@25, tool_use_id@103 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `EmptyObject` :120 | tool_use_id@115 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `CursorHook` :123 | schema composition@21, decode@31, cwd@66, tool_use_id@81 | `decode` | KEEP decode; enum owns native event discrimination. Avoid one file per zero-data event. | +| `PromptHook` :188 | tool_use_id@125 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ToolPhase` :193 | tool_use_id@126, decode@147 | `duration` | KEEP duration; add terminal/error interpretation only if reducers repeat exact branching. | +| `ToolHook` :202 | tool_use_id@126, decode@215 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `PostToolHook` :213 | decode@149 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ToolResult` :221 | decode@196 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ToolFailureHook` :228 | decode@153 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ToolFailure` :236 | decode@197 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ThoughtHook` :255 | tool_use_id@127 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ResponseHook` :260 | tool_use_id@128 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `StopHook` :267 | tool_use_id@129 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `TurnUsage` :276 | duration@263 | none | ADD metrics() only if not already covered agents usage convergence; Cursor reducer currently projects totals to standard token names. Good family-level helper, no field getters. | +| `SessionEndHook` :284 | tool_use_id@130 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `SubagentStartHook` :292 | tool_use_id@131 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `SubagentStopHook` :302 | tool_use_id@132 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `Specialized` :318 | tool_use_id@82, decode@164, duration@363 | `tool_use_id`, `accepts`, `matches_input`, `result` | KEEP tool_use_id/accepts/matches_input/result; excellent owner of native differences. Split specialized.rs and related leaf payloads. | +| `ShellHook` :326 | duration@319 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `McpHook` :333 | duration@320 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `FileEditHook` :343 | duration@321 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `FileEdit` :350 | decode@170, duration@321, tool_use_id@368, accepts@381 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ReadFileHook` :356 | duration@322 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ImportBoundary` :431 | tool_use_id@135 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | +| `ImportStopHook` :439 | tool_use_id@137 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | + +## bt-daemon/src/translate/cursor/mod.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `ModelContent` :121 | value@134, encoded_len@150, push@156, model_content@551 | `text`, `encoded_len` | KEEP as data-only restoration representation; ModelStep owns traversal/history behavior. | + +## bt-daemon/src/translate/decode.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `DecodeError` :14 | schema composition@5, fmt@32, decode@43 | none | KEEP constructor/Display/Error behavior; already dedicated file. | + +## bt-daemon/src/translate/git.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `FileStamp` :13 | schema composition@21, stamp@262 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `GitFingerprint` :20 | is_empty@44, fingerprint@246 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `GitMetadata` :29 | schema composition@34, is_empty@45, metadata@113, merge_metadata@183 | `is_empty` | KEEP `is_empty`; optionally add `merge_into(metadata)` to own git key serialization currently in GitMetadataCache::enrich. Keep file/process discovery in cache. | + +## bt-daemon/src/translate/grok.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `NativeRecord` :34 | remember@286, process_update@490, process_event@927, record_ts_ms@1584 | none | ADD `timestamp_ms()` by moving record_ts_ms; encapsulates native metadata/RFC3339/epoch fallback. NativeParams/Meta remain data-only. | +| `NativeParams` :53 | schema composition@36 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | +| `NativeUpdate` :63 | schema composition@55, tool_failure_text@1641 | none | ADD `failure_text()` if touched; helper currently takes only this DTO and interprets its content/raw output. Raw tool data remains a boundary. | +| `NativeMeta` :109 | schema composition@57, turn_key@1559 | none | ADD `turn_key(sequence)` if touched, because prompt-id/prompt-index fallback belongs to identity-bearing DTO. No need to add getters for every field. | +| `PromptIndex` :125 | schema composition@113 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | +| `TurnCompletion` :226 | process_update@915, close_turn@1089, close_incomplete_turn@1143 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | +| `TranscriptRecord` :284 | remember@291, read_new_records@1502 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | +| `TranscriptBatch` :289 | read_new_records@1420 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | + +## bt-daemon/src/translate/mod.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `SpanType` :57 | local_username@93 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `OriginSnapshot` :68 | local_username@132 | none | KEEP immutable data-only, version-stamping ownership already in origins/dispatcher. Group with span row if not independently useful file. | +| `LateMergeVersion` :77 | local_username@116 | none | KEEP data-only causal watermark; ordering decisions belong delivery ledger, not generic lexicographic derive. | +| `SpanRow` :85 | schema composition@6, local_username@141, row@147, row_mut@152 | none | KEEP publicly constructible data; consider metadata mutation helper only for structurally identical cross-cutting operations. Never move sink policy/redaction into row. `span_row.rs` appropriate. | +| `SpanOp` :140 | schema composition@2, local_username@145, handle@191, drain_pending@197 | `row`, `row_mut` | KEEP row/row_mut; add into_row/is_merge only if actual repeated destructuring callers justify it (not mechanically). `span_op.rs` appropriate. | +| `SessionCtx` :161 | handle@191, drain_pending@197, checkpoint@203, finalize@211 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | + +## bt-daemon/src/translate/opencode.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `Saved` :50 | save_state@58, restore_state@65 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolInput` :121 | finalize@149 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolBeforeOutput` :131 | finalize@151 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolAfterResult` :137 | finalize@173 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolBeforePayload` :147 | finalize@193, from@194, handle@606 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolBefore` :161 | finalize@193, handle@607, tool_before@1132 | none | KEEP From, ownership already exists; co-locate ToolBeforePayload/Input/Output in tool_event.rs. | +| `ToolAfterPayload` :169 | from@202, handle@610 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolAfter` :187 | from@202, handle@611, tool_after@1172 | none | KEEP From, ownership already exists; co-locate ToolAfterPayload/Input/Result in tool_event.rs. | +| `PermissionToolRecord` :224 | from@242, record@298 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `PermissionTool` :240 | from@254, permission_record@1268 | `record`, `name` | KEEP record/name; companions remain data-only under PermissionProperties::request. Split permission.rs family. | +| `PermissionFields` :246 | from@273 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `PermissionPayload` :272 | from@280, permission_record@1261 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `PermissionProperties` :278 | permission_properties@313, permission_record@1259, permission_asked@1307, permission_replied@1315 | none | ADD `request()` by moving OpenCodeTranslator::permission_record static method; used by asked/replied and contains no translator state. Own source/info/direct/native aliases precedence in `opencode/permission.rs`. | +| `PartEvent` :320 | handle@600, part_updated@906 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `PartTime` :344 | permission_properties@328 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolPartState` :350 | permission_properties@338 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `ToolAttachment` :364 | permission_properties@358, tool_result_content@1477 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `MessageInfo` :374 | handle@603, message_updated@1019 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `MessageTime` :398 | permission_properties@386 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | +| `PermissionRequest` :574 | begin_compacted@587, permission_record@1259 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | + +## bt-daemon/src/translate/opencode_v2/event.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `NativeEnvelope` :9 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Location` :17 | schema composition@11 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `EventMetadata` :21 | schema composition@12 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `NativeEvent` :28 | schema composition@14 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Session` :80 | schema composition@68 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Created` :85 | schema composition@30 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Inbox` :93 | schema composition@34 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Enqueued` :100 | schema composition@32 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `InboxItem` :109 | schema composition@105 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Prompt` :116 | schema composition@111 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `PromptSkill` :125 | schema composition@122 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `PromptFile` :129 | schema composition@120 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Model` :134 | schema composition@147 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `StepStarted` :141 | schema composition@40 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `StepEnded` :150 | schema composition@42 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `TextEnded` :159 | schema composition@46 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolInputStarted` :168 | schema composition@50 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolCalled` :177 | schema composition@52 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolSuccess` :186 | schema composition@54 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolFailed` :195 | schema composition@56 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `NativeError` :204 | schema composition@156 | none | KEEP transport fields; if message formatting repeated, From/Display conversion is justified. Current reducer can use error.message directly without wrapper. | +| `ErrorResponse` :214 | schema composition@209 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolContent` :219 | schema composition@192 | none | ADD `into_span_part()` to own native image file to image_url conversion; reused live tool success and context tool-result normalization. Unknown native content must remain exact. | +| `KnownToolContent` :225 | schema composition@220 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `PermissionAsked` :237 | schema composition@58 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `PermissionSource` :245 | schema composition@242 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `PermissionReplied` :251 | schema composition@60 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `CompactionStarted` :259 | schema composition@62 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `CompactionEnded` :266 | schema composition@64 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `NativeCompaction` :277 | schema composition@272 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `NativeMessages` :282 | schema composition@278 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `NativeContextMessage` :288 | schema composition@283 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `CompactionFailed` :293 | schema composition@66 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ExecutionFailed` :300 | schema composition@70 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Interrupted` :306 | schema composition@72 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `Context` :313 | schema composition@38 | none | ADD `into_messages()` / From for Vec by moving normalize_context; owns system join and native content expansion. Keep session correlation in reducer. Split `context.rs` and private media children; related wrappers may stay grouped. | +| `ContextMessage` :322 | schema composition@319 | none | ADD `into_messages()` if needed by Context::into_messages; one native message may expand into tool result(s) plus assistant. Preserve order. Own normalized conversion, not actor state. | +| `MessageContent` :328 | schema composition@290 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ContextPart` :335 | schema composition@330, deserialize@353 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `KnownContextPart` :370 | schema composition@336 | none | ADD `image_url()`/media_parts only if it removes nested field fallback from Context conversion; keep no generic getters for every variant. | +| `Media` :398 | deserialize@374 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `MediaSource` :405 | deserialize@400 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | +| `ToolResult` :418 | deserialize@395 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | + +## bt-daemon/src/translate/opencode_v2/span.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `Content` :7 | new@92, tool@113, summary@119 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `ContentPart` :14 | schema composition@9, deserialize@46 | `text`, `image` | KEEP text/image constructors and exact Dynamic restoration; good ownership, split content.rs with TextPart/ImagePart/ImageUrl. | +| `TextPart` :31 | schema composition@15, text@48 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `ImagePart` :37 | schema composition@16, image@54 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `ImageUrl` :43 | deserialize@40, image@56 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `ToolCall` :61 | image@72, new@94 | `new` | KEEP new, owns JSON argument encoding and fixed kind. Split tool_call.rs with FunctionCall. | +| `FunctionCall` :68 | image@65, new@77 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `Reasoning` :85 | new@96 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `Message` :90 | new@102 | `new`, `tool`, `summary` | KEEP new/tool/summary; good examples. Split message.rs with companion output content. | +| `RootMetadata` :125 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `TurnMetadata` :137 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `RootTotals` :143 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `ToolMetadata` :148 | summary@167 | `new` | KEEP new; optional skill application method only if common interaction repeated. Group metadata siblings in metadata.rs. | +| `LlmMetadata` :183 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | +| `Metrics` :191 | new@199 | `from_tokens` | KEEP from_tokens; it owns SDK metric naming/arithmetic. Do not push sink representation into native token struct. | + +## bt-daemon/src/translate/opencode_v2.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `CompactionResult` :103 | handle@682, compact@917 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | + +## bt-daemon/src/translate/pi.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `BeforeAgentStart` :59 | start_turn@646 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `PromptImage` :71 | create@65 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `SelectedModel` :79 | decode@313, handle@372, ensure_root@570, capture_context@701 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `ContextEvent` :85 | capture_context@700 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `MessageUpdate` :93 | streaming_update@730 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `MessageDelta` :101 | create@95 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `ThinkingLevel` :107 | handle@392 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `AssistantMessage` :115 | message_end@746, response_model@1111, normalize_assistant@1335 | none | ADD `response_model()` and `normalized()` by moving existing free functions; owns seven-field model precedence and content traversal. Keep model selection policy in reducer. Move with AssistantContent to `translate/pi/assistant_message.rs`. | +| `AssistantContent` :157 | create@139, normalize_assistant@1341 | none | Keep variant payload data-only; owned/traversed by AssistantMessage::normalized. Co-locate with owner. | +| `ToolExecutionStart` :184 | tool_start@858 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `ToolExecutionEnd` :199 | tool_end@896 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `AgentEnd` :215 | handle@407 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `SessionCompact` :223 | handle@420, compaction_message@1065 | none | ADD `summary_message()` by moving compaction_message. Owns optional-entry/summary projection, called from Pi compact handler. Co-locate in `pi/compaction.rs`. | +| `CompactionEntry` :231 | create@225 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `Preparation` :243 | create@283 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `BeforeCompact` :275 | compaction_input@1076 | none | ADD `input()` by moving compaction_input; owns counts and preparation projection. Keep reducer correlation in PiTranslator. Move to `pi/compaction.rs`. | +| `BeforeTree` :291 | handle@426, branch_summary_input@1095 | none | ADD `input()` by moving branch_summary_input; owns preparation projection. Move to `pi/compaction.rs`. | +| `SessionTree` :299 | handle@449 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `LegacyContinuation` :1028 | legacy_continuation@1036 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `ResumePayload` :1038 | legacy_continuation@1049 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | +| `Resume` :1042 | legacy_continuation@1039 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | + +## bt-daemon/src/translate/shared.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `CowSpanOp` :8 | from_arc@23, from@28, as_ref@33 | `new`, `make_mut`, `downgrade`, `from_arc` | KEEP new/make_mut/downgrade/from_arc/From/AsRef/Deref; already well-owned dedicated module. | + +## bt-daemon/src/translate/state.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `SinkFields` :8 | schema composition@15, restore@36, from@42 | `of`, `restore` | KEEP of/restore: explicitly owns sink-only state serialization. Row remains private adapter, do not export. | +| `Row` :33 | schema composition@6, restore@38, from@46, serialize@55 | `restore` | KEEP From/restore private serialization adapter; already colocated with owning sink fields. | + +## bt-daemon/src/translate/tool.rs + +| Type | Callers / use | Existing methods | Decision | +|---|---|---|---| +| `ToolApproval` :15 | schema composition@20, add_tool_approval@30, tool_approval_metadata@36, with_tool_approval@182 | `as_str` | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | +| `SkillLoad` :66 | insert_skill_metadata@75, skill_file_load@120, skill_md_paths@133 | none | ADD `insert_metadata(metadata, requested)` and `display_name()` to own name/path fallback and shared skill metadata. Existing free insert_skill_metadata is called from Claude, Codex, Cursor, Pi, OpenCode; regex discovery stays separate. Move type/behavior to `translate/tool/skill_load.rs`. | + +## Runtime-state and implementation types explicitly excluded from DTO changes + +These own active lifecycle, I/O, caches, visitor state, or durable actor continuation. Serialization alone does not make them DTOs. Keep methods with state machines; splitting may improve large files, but do not convert them into passive schema models. +| File | Declarations | Reason | +|---|---|---| +| `transcript_import/antigravity.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/claude.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/codex.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/cursor.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/mod.rs` | `IncrementalRecords`, `TranscriptTail` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/muse.rs` | `RunState`, `ModelState`, `PendingTool`, `Reader`, `EventsSeed`, `EventsVisitor`, `RecordsSeed`, `RecordsVisitor` | streaming reader / visitor / incremental filesystem state | +| `transcript_import/pipeline.rs` | `ImportProcessor` | streaming reader / visitor / incremental filesystem state | +| `translate/antigravity.rs` | `Turn`, `Invocation`, `PendingTool`, `AntigravityTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/claude.rs` | `Turn`, `PendingPrompt`, `TranscriptCursor`, `Subagent`, `PendingTool`, `PendingHistory`, `MessageHistory`, `HistoryMessage`, `PendingEmission`, `ClaudeTranslator`, `LlmCall`, `TranscriptTool` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/codex.rs` | `ScopeKind`, `OpenTurn`, `TurnInputSource`, `OpenLlm`, `OpenTool`, `Scope`, `DeferredHook`, `PendingWork`, `CodexTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/cursor/mod.rs` | `History`, `Turn`, `ModelStep`, `Tool`, `TranscriptCursor`, `CursorTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/debug.rs` | `DebugTranslatorFactory`, `DebugTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/git.rs` | `RepoEntry`, `NegativeEntry`, `CacheState`, `GitMetadataCache` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/grok.rs` | `BoundedOutput`, `OpenTurn`, `OpenLlm`, `OpenTool`, `CompletedTool`, `TranscriptCursor`, `PendingWork`, `GrokTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/mod.rs` | `Registry` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/muse.rs` | `OpenOp`, `Completed`, `MuseTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/muse_events.rs` | `Events` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/muse_usage.rs` | `UsageTracker` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/opencode.rs` | `OpenCodeVersionedTranslator`, `NativeSession`, `ClosedToolSpan`, `MessageHistory`, `HistoryEntry`, `CompactionBoundary`, `OpenCodeTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/opencode_v2.rs` | `SessionState`, `ToolState`, `Step`, `Permission`, `HistoryEntry`, `NativeWindow`, `Compaction`, `OpenCodeV2Translator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/origins.rs` | `WeakOrigins` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/pi.rs` | `PendingLlm`, `ToolStart`, `PiTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/recent.rs` | `RecentSet`, `RecentMap` | translator/session/span continuation, correlation state, bounded collection or process cache | +| `translate/turn_lineage.rs` | `TurnLineage` | translator/session/span continuation, correlation state, bounded collection or process cache | + +Inventory totals: 188 DTO / transfer/result declarations reviewed individually, 88 runtime/implementation declarations reviewed and excluded. Imported/re-exported schema aliases and test-only fixtures are not double-counted. Associated `type Value`/`Target` and Result aliases are trait plumbing, not DTO definitions. From ef8e7d7588b0618eec247c1dec9ca0aa1ff52b08 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 02:04:43 +0800 Subject: [PATCH 2/2] Remove temporary DTO audit notes --- docs/architecture/dto-ownership/README.md | 48 --- .../dto-ownership/agent-config.md | 345 ----------------- .../dto-ownership/core-runtime.md | 308 --------------- .../architecture/dto-ownership/translators.md | 356 ------------------ 4 files changed, 1057 deletions(-) delete mode 100644 docs/architecture/dto-ownership/README.md delete mode 100644 docs/architecture/dto-ownership/agent-config.md delete mode 100644 docs/architecture/dto-ownership/core-runtime.md delete mode 100644 docs/architecture/dto-ownership/translators.md diff --git a/docs/architecture/dto-ownership/README.md b/docs/architecture/dto-ownership/README.md deleted file mode 100644 index 7d1ec19f..00000000 --- a/docs/architecture/dto-ownership/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# DTO ownership review - -This review follows the concrete-schema work in PR #306. It inventories the production types at commit `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721`, traces their consumers, and distinguishes shared interpretation from data transport and runtime orchestration. The detailed tables describe that baseline, including types subsequently moved by this refactor. - -- [Agent configuration, Muse, setup, and managed runs](agent-config.md): 178 DTO and codec declarations, including nested and macro-generated types, with runtime and test exclusions. -- [Translators, transcript imports, and mirrors](translators.md): 188 DTO/result declarations and 88 explicitly excluded runtime declarations. -- [Core runtime and JavaScript/TypeScript](core-runtime.md): 235 Rust declarations, including explicit runtime exclusions, and 24 TypeScript declarations. - -These are review counts, not a count of independent public contracts: nested codecs and compatibility variants are included, while imported SDK types and reexports are not counted as new definitions. Each table records consumers, existing behavior, and an individual recommendation. Broad names such as `Message` or `Hook` do not imply that different native contracts should share a type. - -## Implemented decisions - -| Owner | Responsibility moved onto the type | Why it belongs there | -|---|---|---| -| `CursorHooks` | Registration lookup, known-command retention, and registration replacement | Setup and managed-hook cleanup no longer traverse optional maps and unknown native variants themselves. Marker recognition and process liveness stay with setup. | -| `OpenCodeConfig`, `OpenCodePlugin` | Plugin lookup, preservation-aware replacement/removal, exact-spec insertion, package matching | Setup and managed runs share collection mechanics while keeping their different version/ownership policies. Configured tuples retain their provider options. | -| `TranscriptPayload`, `Reference` | Captured-prefix validation, matching snapshots/references, native path enumeration, and Codex path precedence | Capture, polling, translation, and import no longer repeat native format selection. A modern captured absence still prevents reading newer native bytes; legacy fallback behavior remains explicit. | -| Antigravity `TranscriptRecord` | Native kind normalization, content precedence, and timestamp decoding | Import and translation share the native record's interpretation. Explicit null content keeps precedence over alternate fields. | -| `OpenCodeTokens` | Cache-inclusive prompt and total accounting | Both OpenCode protocol versions use the native counter semantics without repeating the arithmetic. Output metrics keep their existing names and projection types. | -| `SkillLoad` | Display name and common span metadata | Translators share skill naming, identity metadata, and explicit-request classification. Native discovery remains in the integration helpers. | -| Pi `AssistantMessage` | Physical response-model selection and assistant span-message projection | The reducer no longer inspects native content variants or repeats model precedence. | -| Pi compaction/branch DTOs | Input, summary message, and summary-request interpretation | Schema-specific field combinations leave the reducer; turn and continuation lifecycle stays there. | -| OpenCode `PermissionProperties` | Native permission request and reply normalization | Asked/replied handling shares precedence across native permission variants. | -| OpenCode 2 `Context`, `ToolContent` | Native context and tool-output conversion | The native owner handles media/content variants and emits the existing span representation. | -| `RedactedEnvelope` | Conversion back to the replayable runtime envelope | Recovery and translation share reconstruction without reintroducing credentials. The former journal helper was internal and is removed; public wire imports remain unchanged. | -| `SessionConfig` | Destination project-name query | Delegates to the destination's existing semantics. | -| `SessionRoute` | Additional metadata and tag edits | Route mutation owns trimming, validation and stable deduplication; filesystem and credential resolution remain outside the DTO. | -| `AuthDiagnostic` | Ready/unconfirmed construction and status predicates | Runtime and output rendering share diagnostic vocabulary and state combinations. | - -## Organization - -Shared hook/config schemas, provider usage, wire envelope types, transcript references, and Antigravity records now have directories with one primary owner per file and stable module reexports. Pi assistant messages, compaction records, and lifecycle payloads are separated; OpenCode permission, context, and tool-content families have focused modules. Primary types live beside their interpretation methods. Small private leaf records and discriminants stay with their owner when they have no independent consumers. - -This is deliberately not a rule to put every struct in its own file. A permission payload's private helper variants, or a group of single-use lifecycle records, are easier to understand together. The facade modules provide stable imports, rather than parallel schema definitions. - -## Deliberately retained as data - -Most RPC request/results, CLI argument projections, native lifecycle wrappers, export-v1 leaf records, and tool/image descriptors need no additional methods. Their jobs are validation and transport; their consumers do not share further interpretation. Existing behavior on typed IDs, token metrics, message content, outcomes, and configuration overlays is retained rather than wrapped again. - -JavaScript/TypeScript interfaces remain structural data. Turning deserialized JSON into class instances would add lifecycle requirements without useful ownership. Existing adapter/client functions already own encoding and dispatch. A typed shared JavaScript destination union is a separate contract change; this refactor does not combine it with Rust method extraction. - -Some baseline recommendations remain conditional rather than implemented requirements: a constructor at a single synthesis site, a helper replacing one field access, or a private group method that only renames a loop does not justify another API. Codex installed-file trust and invocation-local trust have different validation policies and stay separate. Likewise, sink destination resolution supplies fallbacks that correlation intentionally omits; those paths are not unified. - -Runtime actors, caches, locks, subprocess services, filesystem discovery, credential resolution, and event-ordering state remain responsible for their own operations. DTO methods do not acquire those responsibilities simply because an operation consumes a DTO. - -## Compatibility checks - -The refactor preserves serialized field names, public wire reexports, replay reconstruction, unknown extensions, missing-versus-null values, source-specific metric conventions, and existing hook ownership rules. Focused tests exercise configuration preservation, captured absence and path precedence, skill metadata, and credential-free replay conversion. The full locked all-feature Rust suite and strict all-target Clippy cover the integrated result. diff --git a/docs/architecture/dto-ownership/agent-config.md b/docs/architecture/dto-ownership/agent-config.md deleted file mode 100644 index c2255bb0..00000000 --- a/docs/architecture/dto-ownership/agent-config.md +++ /dev/null @@ -1,345 +0,0 @@ -# DTO inventory: agent schemas, Muse, setup and managed runs - -Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. - -Scope: every production struct/enum/type declaration in `agents/**`, `muse/**`, `setup/**`, `managed_run/**`, `codex_hooks.rs`, `hook.rs`, `hook_executable.rs`, and `settings.rs`; macro-generated IDs and hook enums included. Test-only declarations are excluded below. DTO means native input, persisted state/config, authored output or transport shapes. Runtime services and capability marker types are separately classified, not silently omitted. Same-named agent schemas are not treated as shared contracts. - -## Highest value behavior ownership - -1. `CursorHooks`: `contains_registration`, `retain_commands`, `replace_registration`. Evidence: `setup/cursor/hooks.rs:124-129`, `186-199`, `209-250` repeatedly unwrap optional maps, distinguish known array/unknown event shapes, preserve unknown entries, and deduplicate commands. Configuration owns those mechanics; persistent marker/liveness/matcher policy stays setup. Preserve absent maps on disable, unknown arrays/entries, and existing version exactly. -2. `OpenCodeConfig`: `has_plugin`, `retain_plugins`, `replace_plugin`, `ensure_plugin` (or a minimal equivalent). `OpenCodePlugin::matches_package` recognizes the same package spec while deliberately excluding configured tuples, whose options must survive. Evidence: `setup/opencode.rs:32-81,105-114`, `managed_run/opencode.rs:72-89`. Setup owns bundled version and package policy; DTO owns optional list semantics and edits. -3. `OpenCodeTokens`: own `metrics`/prompt-inclusive-cache calculation, duplicated `translate/opencode.rs:1038-1044` and `translate/opencode_v2/span.rs:201-207`. `PiUsage` similarly own prompt/total and canonical metrics (`translate/pi.rs:769-771`). Native usage types already own parsing; consumers should not reconstruct cache accounting. Preserve signed native counters and existing optional total behavior; do not silently change overflow policy while extracting. -4. Antigravity `TranscriptRecord`: `normalized_kind`, `content`, `created_at_ms`. Current helpers `translate/antigravity.rs:669-715,815` depend only on record; importer uses kind/time/step too (`transcript_import/antigravity.rs:132-134,237-255`). Keep import-specific is_tool_result/is_denied policy in importer unless genuinely identical to reducer policy (not demonstrated). -5. `codex_hooks::Hook`: a shared `trust_identity()` for nonempty key/hash and `has_command_definition(expected_command)` would consolidate repeated structural validations in `managed_run_trust_state:255-309` and `trust_edits:327-389`. Keep full installed-file hash equality, sessionFlags/plugin source policies and error context in orchestrator; those trust policies are intentionally different. - -## Module arrangement - -Replace unrelated mega-file `agents/schema.rs` with `agents/schema/` and owner files (`hook_file`, `hook_group`, `command_hook`, `cursor_hooks`, `cursor_hook_entries`, `cursor_hook_entry`, `cursor_command_hook`, `opencode_config`, `opencode_plugin`, `plugin_manifest`, `repository`) with stable module reexports. Keep codec helper `deserialize_present` in module root or `json` rather than attach it to an unrelated DTO. `agents/usage/` can similarly separate `provider_usage`, `snake_case_usage`, `camel_case_usage`, `usage_metrics`, `token_metrics`, `opencode_tokens`, `pi_usage`; private leaf shapes stay with their owner until independently used. `muse/messages/` is worth splitting by message, content, image, and tool-call owners; single-use metadata projections can remain grouped by lifecycle domain. Do not create an impl or a public API merely to satisfy one-type-per-file. Generic `schema` modules should be compatibility facades, not the new dumping ground. - -## Per-type review - -Each row names an exact declaration. Caller descriptions below were traced to real owner modules; symbol-name grep alone is unreliable for generic names such as Hook/Session/Plugin/ContentBlock. - -### `agents/schema.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `HookFile` | Codex hooks trust + managed commands; Cursor managed runs/setup parse packaged manifests; no methods. | Own event enumeration only if a caller needs normalization; current direct iteration is clear. Split owner file, retain generic shape. | -| `HookGroup` | Nested shared hook manifest group; Codex managed run rewrites its commands. | Data-only nested group; could own replace_commands delegation if multiple rewrite callers emerge. No invented builder. | -| `CommandHook` | Nested HookGroup command schema, rewritten in managed_run/codex.rs. | Own replace_command(unix,windows) if enforcing type==command; one current caller, moderate value. | -| `OpenCodeConfig` | Setup enables/updates/disables and managed run injects optional plugins list. | Expand list edit/lookup behavior; highest value #2. | -| `OpenCodePlugin` | Setup matching and managed run equality; package() already distinguishes configured options. | Expand package matching while preserving configured tuples; no conversion to string for configured variants. | -| `CursorHooks` | Setup persistent/temporary hooks and stale process cleanup; no methods. | Expand collection behavior; highest value #1. | -| `CursorHookEntries` | Native known array or unknown future payload; only setup traverses. | Keep enum data-only; collection mutation belongs CursorHooks, preserve Other unchanged. | -| `CursorHookEntry` | Known command vs unknown definition; command() already abstracts variant. | Existing behavior sufficient; equality/retention policy belongs owner. | -| `CursorCommandHook` | Constructed by setup and managed run, capture() centralizes defaults. | Existing capture constructor sufficient; registration comparisons belong CursorHooks. | -| `PluginManifest` | Hook version probe, setup common npm version, Cursor installation ownership. | Data-only manifest projection is appropriate; package identity policy differs by caller. | -| `Repository` | PluginManifest source string vs npm object; url() deliberately returns only supported string. | Existing method sufficient; do not normalize object repository into trusted plugin source inadvertently. | - -### `agents/usage.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `ProviderUsage` | Antigravity record usage and metrics; custom boundary decode selects formats; metrics() exists. | Already owns behavior; retain. | -| `SnakeCaseUsage` | Codex/Claude counters; metrics() and is_empty() encode aliases. | Already owns behavior; split main owner file. | -| `TokenDetails` | SnakeCaseUsage nested cached/reasoning counters. | Data-only leaf; metric alias precedence belongs SnakeCaseUsage. | -| `CacheCreation` | SnakeCaseUsage nested TTL counters, roundtrip/Claude details. | Data-only leaf; keep with SnakeCaseUsage. | -| `CamelCaseUsage` | Grok translator + ProviderUsage; metrics() exists. | Existing metrics ownership sufficient; per-model aggregation remains translator policy. | -| `UsageMetrics` | Antigravity accumulated float metrics; is_empty/with_total/observe. | Already owns behavior, good model for others. | -| `TokenMetrics` | Muse and Cursor usage state; add() saturates optional counters. | Existing ownership good; split owner file. | -| `OpenCodeTokens` | OpenCode1 and2 native tokens. | Add canonical conversion/cache-inclusive prompt/total; highest value #3. | -| `OpenCodeCacheTokens` | Nested native cache read/write. | Data-only leaf with OpenCodeTokens, not independent service. | -| `PiUsage` | Pi normalized native counters, used response closure. | Add canonical metric/total methods; highest value #3. | -| `PiCost` | Nested PiUsage total price. | Data-only leaf; PiUsage decides emission. | - -### `agents/request.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `RequestConfig` | Pi caches normalized provider request config; is_empty(). | Retain current behavior; moving native request parsing here may be useful but avoid provider redaction policy coupling. | -| `Stop` | Private string/list union. | Data-only wire variant. | -| `ToolDefinition` | Function/built-in; custom known-schema dispatch. | Serialization behavior already owned; no behavioral caller beyond codec. | -| `FunctionTool` | Private function tool envelope. | Data-only leaf. | -| `FunctionType` | Closed function tag. | Data-only discriminant. | -| `FunctionDefinition` | Function name/description/schema/strict/extensions. | Data-only leaf; JSON Schema intentionally arbitrary. | -| `ToolChoice` | Mode or named function. | Data-only wire union. | -| `ChoiceMode` | auto/none/required. | Data-only discriminant. | -| `NamedChoice` | Named function wrapper. | Data-only leaf. | -| `FunctionName` | Nested function name. | Data-only leaf. | -| `ResponseFormat` | Known/future union; custom dispatch. | Codec owns behavior already. | -| `KnownResponseFormat` | text/json_object/json_schema with unknown extension retention. | Data-only variant payloads. | -| `SchemaDefinition` | Named JSON Schema descriptor. | Data-only schema envelope; preserve Field nulls. | - -### `agents/antigravity/schema.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `TranscriptRecord` | Live translator and import; fields read for kind/content/time/step. | Add record-local accessors noted #4; avoid moving importer state transitions onto DTO. | -| `ToolCalls` | One vs many native tool call; iter() shared translator/import. | Existing method sufficient. | -| `ToolCall` | Native name,args,output + opaque extensions, converted by translator/import. | Data-only: output conversion differs from invocation policy. | -| `optional_integer::Integer` | Private temporary string/number boundary codec. | Keep local, data-only, no standalone file. | - -### `agents/cursor/schema.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `TranscriptRecord` | Cursor translator + transcript importer; role()/text() already encapsulate variants. | Already good behavior ownership. | -| `Role` | User/Assistant; as_str(). | Existing method sufficient. | -| `TranscriptMessage` | Nested content payload. | Data-only leaf. | -| `TurnEndedKind` | Closed turn marker. | Data-only discriminant. | -| `MessageContent` | Text/blocks; text() joins text blocks. | Already owns normalization. | -| `ContentBlock` | Text vs tool-use marker, text() owner skips tool blocks. | Data-only leaf; no unused API. | - -### `muse/hooks.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `HookName (macro)` | Config event enumeration + decoder + translator; ALL/as_str/parse. | Already owns canonical aliases and names. | -| `MuseEvent (macro)` | Native decode, import synthesis, translation; name/context/payload/decode. | Already good aggregate behavior. | -| `Empty` | SessionStart empty body. | Data-only zero-size marker. | -| `Hook` | Common context/body envelope, synthesized by import and decoded by MuseEvent. | Data-only generic container; no generic builder needed. | -| `HookContext` | Importer + translator correlation; turn()/request() filter empty. | Existing behavior sufficient. | -| `optional_id::Id` | Local tolerant native string/ignored codec. | Keep local, data-only. | -| `SessionMetadata` | Shared across native hook context and translator root; update() preserves missing/null. | Already owns update semantics. | -| `PromptSubmitted` | User prompt/image hook body; import constructs and translator reads. | Data-only; rendering belongs message/image layer. | -| `ModelDetails` | ModelStarted flattened counters/options. | Data-only; attribution/step identity belongs reducer. | -| `ModelStarted` | Import constructs; translator starts model span. | Could own borrowed input projection if duplicated; only one output mapping currently, no new method. | -| `ModelFinished` | Import constructs; translator closes model span. | Data-only outcome+usage envelope; completion lifecycle stays reducer. | -| `ToolStarted` | Shared tool-start payload, import and translator correlate. | Potential identifier/name helper only if repeated; current reducer chooses fallback IDs, keep policy there. | -| `ToolFinished` | Finish payload nested tool/outcome, import/tool lifecycle use. | Outcome classification belongs NativeOutcome; batch reducer behavior stays translator. | -| `ToolBatchFinished` | PostToolBatch Vec. | Data-only aggregate. | -| `PermissionObserved` | Tool metadata for permission hook; translator event branch reads. | Data-only. | -| `NotificationObserved` | Notification metadata hook; translator event branch reads. | Data-only. | -| `SubagentStarted` | Child session/subagent IDs used by import and translate events. | Candidate child_id() only if same precedence multiple callers; currently caller-specific identity, retain. | -| `SubagentFinished` | Child fields/output/outcome. | Data-only; reducer closes spans. | -| `Compaction` | Trigger/outcome. | Data-only; operation correlation belongs reducer. | -| `TurnFinished` | Assistant output/terminal/outcome. | Data-only; terminal lifecycle stays reducer. | -| `SessionFinished` | Reason/outcome. | Data-only; session shutdown behavior stays reducer. | - -### `muse/messages.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `ToolInput` | Opaque tool-owned JSON wrapper used hook bodies and export synthesis. | Data-only newtype; do not add inspect-known-key methods. | -| `ToolOutput` | Opaque tool/provider output wrapper. | Data-only newtype. | -| `ModelOutput` | Text or typed messages, forwarded to output boundary. | Data-only native union; no duplicated rendering found. | -| `NativeMessage` | Messages in hook input, export output synthesis. | Could add assistant_tool_calls(calls) constructor for repeated synthesis; only one caller, not worth broad builder API. | -| `MessageRole` | Known/future role strings; From conversions. | Existing behavior sufficient. | -| `MessageContent` | Text or content blocks; retained losslessly. | Data-only; unlike Cursor, currently not repeatedly flattened to text. | -| `ContentBlock` | Known/future discriminated content; custom strict-known decoder. | Already owns codec behavior. | -| `KnownContentBlock` | Text/assistant/image payloads. | Data-only variant contents. | -| `MessagePhase` | Known/future assistant phase. | Data-only enum. | -| `ContentBlock::deserialize::Tag` | Temporary type discriminator. | Keep local, data-only. | -| `ImageSource` | Known base64/url/future; custom strict-known decoder. | Already owns codec behavior. | -| `Base64ImageSource` | Native encoded image descriptor. | Data-only leaf; no repeated extraction callers. | -| `Base64Type` | Closed base64 marker. | Data-only discriminant. | -| `UrlImageSource` | Native URL + extensions. | Data-only leaf. | -| `ImageUrl` | String or detailed URL descriptor. | Data-only union. | -| `ImageDetail` | auto/low/high/future. | Data-only discriminant. | -| `AssistantToolCall` | Import synthesizes function-call output records. | Possible constructor if repeated; currently one synthesis, keep data-only. | -| `FunctionCallType` | Closed function discriminator. | Data-only. | -| `FunctionCall` | Function name/arguments. | Data-only; args normalization belongs ToolArguments. | -| `ToolArguments` | Encoded JSON text or JSON; input() decodes/falls back. | Already owns behavior. | -| `ToolDescription` | Tool schema envelope for LLM input. | Data-only; parameter JSON Schema belongs native tool. | -| `InputSummary` | Bounded message count + extensions from hook/export. | Data-only. | - -### `muse/provider_options.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `ProviderOptions` | Hook model details + final metadata, coexisting dotted options. | Data-only lossless schema; no repeated logic over options found. | -| `ReasoningEffort` | Known/future reasoning effort strings. | Data-only discriminant. | -| `ThinkingMode` | Known/future thinking mode strings. | Data-only discriminant. | - -### `muse/outcome.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `ErrorDetail` | Hook/export errors; render(). | Already owns normalization. | -| `OperationStatus` | Known/future string statuses; From conversions. | Move failure membership into is_failure() used NativeOutcome (one caller but intrinsic status classification); useful if other consumers share exact classification. | -| `NativeOutcome` | Hook outcome across model/tool/subagent/turn/session; error_message() combines error/status/details. | Already owns common behavior. | -| `ToolOutcome` | Translator classified success/failure/unknown result. | Data-only semantic result, not raw DTO; no redundant methods. | - -### `muse/usage.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `TokenUsage` | Hook and export counters, usage reducer; delta_since()/metrics(). | Already owns common behavior; good exemplar. | -| `UsageScope` | Turn-cumulative vs per-model marker. | Data-only enum; policy stays usage reducer. | - -### `muse/ids.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `TurnId (macro)` | HookContext turn correlation; From/Deref/Display. | Already typed identity behavior, no extra methods. | -| `RequestId (macro)` | HookContext model request identity; From/Deref/Display. | Already sufficient. | -| `ToolCallId (macro)` | ToolStarted identity; From/Deref/Display. | Already sufficient. | - -### `muse/export_v1.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `Header` | Import export header schema checks/session collection. | Data-only; import orchestrator validates supported version and sessions. | -| `Version` | String/object semver; into_string(). | Already owns wire normalization. | -| `Session` | Import session synthesis and finalization. | Data-only; lifecycle state belongs importer. | -| `SessionEnd` | Session exit reason. | Data-only leaf. | -| `UnixMicros` | Export timestamp; millis(). | Already owns units conversion. | -| `ExportRecord` | Import process() unwraps envelope, fallback recorded_at. | Candidate into_event() with timestamp precedence if reused; single importer, retain data-only. | -| `NativeEnvelope` | Record inner timestamp/payload. | Data-only leaf. | -| `NativePayload` | Kind-specific known parse/custom decoder. | Already owns codec dispatch. | -| `NativePayload::deserialize::Kind` | Temporary payload kind. | Keep local, data-only. | -| `NativePayload::deserialize::Payload` | Temporary raw fields for boundary dispatch. | Keep local, no standalone file. | -| `ExportMetadata` | Run-model metadata used importer current context. | Data-only; source precedence/update decisions belong importer. | -| `RunModelRecord` | Run stream+metadata envelope. | Data-only. | -| `RunStream` | Run ID wrapper object. | Data-only leaf. | -| `RunEvent` | Discriminated native stream event. | Data-only event variants; stream lifecycle stays importer. | -| `ExportToolCall` | Tool invocation list native call args. | Could own into_hook() only if it removes repeated import mapping; single site, retain. | -| `ExportToolResult` | Tool result event list. | Data-only. | -| `TaskEvent` | Task state event with ID/origin fallback read by process_task. | Candidate task_id() centralizes task_id/idempotency precedence only if shared; current one consumer. | -| `TaskEventKind` | Scheduled/start/complete/fail/cancel/reject. | Data-only; task terminal policy stays importer. | -| `TaskOrigin` | Originating tool-call ID. | Data-only leaf. | - -### `muse/metadata.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `RootMetadata` | translate/muse.rs root metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ModelInput` | translate/muse.rs model input | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ModelStartMetadata` | translate/muse.rs model-start metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ModelEndMetadata` | translate/muse.rs model-end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ToolStartMetadata` | translate/muse_events.rs tool-start metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ToolEndMetadata` | translate/muse_events.rs tool-end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `ToolOutcomeLabel` | ToolEndMetadata success/error output label | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `SubagentMetadata` | translate/muse_events.rs child metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `CompactMetadata` | translate/muse_events.rs compaction metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `SessionEndMetadata` | translate/muse.rs session end metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `UnpairedMetadata` | translate/muse.rs unmatched model completion metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `PermissionMetadata` | translate/muse_events.rs permission metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `NotificationMetadata` | translate/muse_events.rs notification metadata | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | -| `CompletionFingerprint` | translate/muse.rs output/metrics/error/metadata dedup hash encoding | Retain data-only authored output projection; one construction site, serialization is its responsibility. Keep related lifecycle projections grouped, not independent builders. | - -### `muse/config/hooks.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `Extensions` | Private unknown handler/group config map. | Alias stays data-only; restricted conservative extension scan needed. | -| `HookOverlay` | Setup manipulates user hooks; is_empty/contains_braintrust_hook/remove_owned/append_owned. | Already strong responsibility ownership; preserve exact foreign attributes. | -| `HookGroup` | Private handler group with matcher/extensions. | Move prune/remove_owned logic into private remove_owned() only if it meaningfully simplifies HookOverlay (moderate value). | -| `HookHandler` | Known user/enterprise or future handler; decoder/is_owned/contains_braintrust. | Already owns recognition and conservative inspection. | -| `CommandType` | Closed command tag shared strict ownership. | Data-only discriminant. | -| `UserCommand` | Owned user command with timeout/unknown attrs. | Data-only leaf; HookHandler owns variant recognition. | -| `EnterpriseCommand` | Foreign enterprise command. | Data-only leaf, never convert ownership. | -| `HookDocument` | Read-only root projection; contains_braintrust(). | Already owns inspection. | - -### `muse/config/ownership.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `OwnedHookFile` | Exact current/previous/legacy file generation and recognition. | Already owns construction/equality; no new methods. | -| `OwnedHookGroup` | Strict private group shape. | Data-only leaf. | -| `OwnedCommandHook` | Strict private command shape. | Data-only leaf. | -| `HookFileInspection` | Missing/Owned/Foreign result; is_owned/contains_braintrust. | Already owns semantic result queries. | - -### `muse/config/settings.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `MuseSettings` | Setup reads/writes; load/managed_path/hook_overlay/ensure_schema_version. | Already owns schema semantics and path resolution; writes require setup lock, keep transaction orchestration outside. | - -### `settings.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `InvocationSettings` | Managed-run env protocol; enabled(route). | Existing constructor sufficient; conversion into AgentSettings could be From impl because duplicated load paths, verify before extracting. | -| `AgentSettings` | Hook/runtime/setup settings; load_for_hook/load/load_from/tracing_enabled. | Already owns load/enablement; move matching route replacement from migrate_persisted_route_at into method only if reused; file locks/atomic IO orchestration remain external. | - -### `codex_hooks.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `ConfigRead` | activate app-server config/read response wrapper. | Data-only local protocol shape. | -| `Config` | features dictionary; activation checks hooks/codex_hooks. | Candidate hooks_enabled() if reused; only one check, retain. | -| `PluginList` | activate plugin/list response. | Candidate has_enabled(id) hides nested marketplaces traversal but single caller, low value. | -| `PluginMarketplace` | Nested plugin list. | Data-only leaf. | -| `Plugin` | Identity/installed/enabled native summary. | Data-only leaf; installation policy belongs activation. | -| `HooksList` | activate/run override native hooks/list. | Useful iter() flattening entries if reducing two loops; validation policies stay separate. | -| `HookEntry` | errors plus hook records; managed flow validates errors. | Data-only container; errors semantics differ setup/managed. | -| `Hook` | Repeated command/trust identity validation in trust_edits and managed_run_trust_state. | Add structural validation/identity methods only; keep separate source/full-file trust policies. See #5. | -| `TrustState` | Borrowed authored trusted_hash value. | Data-only output projection. | -| `request::Response` | Local RPC id/error/result wrapper in transport. | Data-only boundary codec; no reuse with unrelated wire Response. | -| `request::RpcError` | Local RPC error code/message. | Data-only transport projection. | - -### `setup/claude.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `MarketplaceEntry` | Marketplace generic callbacks inspect name/source/repo. | Could own is_published_repo(repo) if multiple callers; one generic callback, data-only okay. | -| `InstalledPlugin` | enable/disable/update/stale find ID/version/enabled. | Data-only summary; caller owns plugin identity. | -| `InstalledPlugins alias` | Vec. | Data-only alias; no wrapper solely to add find_ours(). | -| `legacy_tracing_env_keys::Settings` | Read-only diagnostic env projection. | Keep local, data-only. | - -### `setup/codex.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `MarketplaceList` | Generic marketplace find callback. | Data-only wrapper. | -| `MarketplaceEntry` | Native name/source fields. | Data-only; one generic callback. | -| `MarketplaceSource` | Native optional source string. | Data-only leaf. | -| `InstalledPlugins` | Native installed list wrapper read setup/stale. | Candidate find(id) only if broader list API needed; current private helper sufficient. | -| `InstalledPlugin` | Native plugin ID/version summary. | Data-only leaf. | - -### `setup/grok.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `InstalledPlugin` | name/source used enable/update/disable publication checks. | Move is_published(repo) onto type if removing free helper; modest value, no generalized registry. | - -### `setup/antigravity.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `update_at::PluginList` | Single plugin/list imports response. | Keep local data-only. | -| `update_at::Plugin` | Single native plugin name. | Keep local data-only. | - -### `setup/mod.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `enable_tracing_at::LegacyFields` | Legacy route metadata/tags migration projection. | Keep local data-only; migration orchestration intentionally outside modern AgentSettings. | - -### `setup/common.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `FileAccess` | Inherited/Private atomic edit permissions policy. | Data-only enum for IO helper, not native DTO. | -| `Marketplace` | Generic runtime command plan with find/is_published callbacks; reconcile/refresh methods. | Runtime behavior object, not DTO; already owns operation. | - -### `managed_run/mod.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `Terminal` | stdin/stdout terminal capability passed agent check. | Data-only value; no repeated common interpretation demonstrated. | -| `Injection` | Agent invocation args/env/lifetime guards consumed once by runner. | Runtime transfer object; no blanket builder. Methods append_env/args would mirror Vec without invariant. | -| `ManagedRunRuntime` | Host/data_dir runtime resource, start(). | Not DTO; runtime lifecycle object. | - -### `managed_run/muse.rs` - -| Type | Actual use and existing behavior | Judgment | -|---|---|---| -| `MuseManagedContext` | Serialized invocation-local route/socket/run ID/version; hook reads it. | Move load(path)/write_private(path) only if repeated secure-file lifecycle exists; currently split source/sink purposeful, data-only context file contract. | - -## Exclusions and boundary accounting - -Not DTOs: `agents::{Antigravity,Claude,Codex,Cursor,Grok,Muse,OpenCode,Pi}` are zero-size capability/registration implementations; `agents::{Agents,Registrar}` are registries; `Identity` is an immutable registry value with `matches()` already; `muse::msp::{ListSessions,MuseMspClient}` are method marker/transport service; `setup::common::SystemCommandRunner` is a subprocess service; `setup::cursor::CursorManagedHooks` is an RAII cleanup guard with install/drop. No method-only refactor indicated for these. `muse/msp.rs` uses SDK DTOs (`SessionListParams`, `SessionListResult`, other imports): external generated contracts are not local DTO declarations and should not be forked. - -Test-only declarations excluded: `hook::tests::HookCli`, `setup::common::FakeRunner`, `setup::cursor::tests::PublishedPlugin`, `setup::cursor::tests::Components`, `setup::antigravity::MissingAgyRunner`, `muse::msp::tests::TestTransport`. No DTO declarations exist in remaining hook executable helpers/setup agent files/managed-run agent files in this scope beyond types listed above. - -Review discipline: methods should own a real schema invariant, conversion, validated lookup, lossless mutation or repeated projection. Avoid builders for single construction sites, aliases wrapping scalar getters, extracting runtime correlation onto wire types, guessing schema equivalence from same field names, and moving lock/process/environment policy onto data objects. Existing fixture/integration tests are the compatibility authority for unknown-field retention, null/missing, parent/child correlation, durable replay, and hook ownership. - -## Implemented in this follow-up (agent-config ownership) - -- Split `agents/schema.rs` into a directory with eleven owner modules (`hook_file`, `hook_group`, `command_hook`, `opencode_config`, `opencode_plugin`, `cursor_hooks`, `cursor_hook_entries`, `cursor_hook_entry`, `cursor_command_hook`, `plugin_manifest`, `repository`), stable reexports, and sibling tests. This reduces unrelated DTO navigation without changing schema names or serde layout. -- Added `CursorHooks::{contains_registration,retain_commands,replace_registration}` and used them for setup registration validation, stale managed-hook cleanup, persistent-hook removal and insertion. Marker recognition, process liveness, bundled matcher selection, filesystem paths and error context remain orchestration policy. Unknown event variants and unknown entries survive, disabling never creates an absent map/event, and complete registration equality includes timeout/matcher. -- Added `OpenCodeConfig::{find_plugin,retain_plugins,replace_plugin,ensure_plugin}` and `OpenCodePlugin::matches_package`; setup and managed runs now delegate list mechanics to their owner type. Configured tuples are deliberately not owned package entries. The managed-run method still matches exact specs and leaves differently configured specs alone. -- Added regression tests for missing maps, unknown event shapes/entries, command deduplication, untouched configured plugin options and version suffix vs similarly prefixed package names. -- Other per-type recommendations above are judgments/candidates, not claims of implementation. No blanket constructors, property getters, DTO networking, process liveness logic, trust-policy merging or reducer lifecycle migration were added. Token/Antigravity changes are coordinated with other reviewers; their final implementation should be reflected in the combined inventory. diff --git a/docs/architecture/dto-ownership/core-runtime.md b/docs/architecture/dto-ownership/core-runtime.md deleted file mode 100644 index 49f0f0ba..00000000 --- a/docs/architecture/dto-ownership/core-runtime.md +++ /dev/null @@ -1,308 +0,0 @@ -# Core/runtime DTO inventory and ownership review - -Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. - - -Scope: production Rust outside agent/setup/managed-run/translator/import/Muse modules and all production TypeScript. Test fixture types and Rust associated-type bindings are excluded. Runtime actors/handles are listed explicitly as exclusions so coverage is auditable. Each row provides observed consumers and existing impl locations; a data-only judgment is deliberate, not an omission. - -## Recommended implementation order - -1. Split wire envelope responsibilities into one primary public type per module, preserving wire::* reexports. Move journal replay reconstruction to RedactedEnvelope::into_envelope and migrate callers; remove the old journal helper after verifying its module is private and only source_journal_path is reexported. Delegate SessionConfig project_name query to TraceDestination. -2. Put SessionRoute metadata/tag mutation behind type methods; keep parsing path resolution and plugin validation I/O outside DTOs. -3. Move AuthDiagnostic ready/unconfirmed constructors and status predicate out of trace_runtime; that type currently exposes combinations the call sites manually coordinate. -4. Consider command_output per-command modules and RPC per-method modules. Most leaf request/result structs should stay data-only; no constructor/getter additions without invariants. -5. Preserve TS structural interfaces. Shared route queries/normalization belong to a focused functions module, not JS classes just to emulate Rust impl. Typed TraceDestination is a separate contract improvement; current unknown destination field causes repeated assertions in Pi/OpenCode. - -Important non-deduplication: sink::destination_components supplies project fallback while correlation::span_components preserves absence. They look similar but are not interchangeable. Preserve replay credentials/config semantics and the exported source-journal path API. - -## Rust per-declaration review - -| Declaration | Current consumers (sample) | Existing impls (sample) | Judgment and organization | -|---|---|---|---| -| `args.rs:21 struct ServeArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `server/mod.rs` | `args.rs:45` | Keep retention; environment/default retention policy belongs to parsed args already. | -| `args.rs:80 struct HookArgs` | `hook.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `args.rs:141 struct StatusArgs` | `client.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `args.rs:151 struct ImportArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `transcript_import/muse_runtime.rs` (+ more) | `args.rs:290` | Keep has_destination_override; validate_parent parse behavior remains clap schema. | -| `args.rs:235 enum ImportSource` | `lib.rs`, `trace_runtime.rs`, `trace_command.rs`, `transcript_import/mod.rs`, `transcript_import/pipeline.rs` | `args.rs:255` | Keep identity; dispatch/reader opening remains integration service. | -| `args.rs:247 enum ParentObjectType` | `lib.rs`, `transcript_import/pipeline.rs` | `args.rs:280` | Keep From into SDK SpanObjectType; no extra getter. | -| `args.rs:299 struct RunArgs` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `managed_run/mod.rs` | `args.rs:321` | Keep validate_parent; no generic route builder until duplicate policy is established. | -| `args.rs:337 struct RunHookCommand` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `managed_run/muse.rs`, `managed_run/opencode.rs` (+ more) | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `args.rs:343 enum RunSource` | `lib.rs`, `trace_runtime.rs`, `trace_command.rs`, `managed_run/mod.rs` | `args.rs:267` | Keep identity; process startup remains integration service. | -| `attachments.rs:8 struct Attachment` | `translate/mod.rs`, `collections/upgrade.rs`, `collections/span_ops.rs`, `translate/cursor/mod.rs` | `attachments.rs:16` | Keep new: digest calculation belongs here. More generic capture recursion should remain attachment boundary adapter, not every DTO. Split attachments/attachment.rs. | -| `attachments.rs:28 struct AttachmentReference` | `sink/braintrust.rs` | `attachments.rs:40` | Keep uploaded constructor; move per-placeholder filename/content_type override into with_placeholder_details if materialize logic is reused. Split attachments/reference.rs. | -| `attachments.rs:36 enum AttachmentReferenceType` | Private/local producer and consumer in same module | Derives/data only | Data-only closed serialization marker; keep beside AttachmentReference. | -| `client.rs:22 struct HostInfo` | `hook.rs`, `lib.rs`, `trace_runtime.rs`, `main.rs`, `transcript_import/pipeline.rs` (+ more) | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `client.rs:30 struct RpcCallError` | `trace_runtime.rs` | `client.rs:36`, `client.rs:46` | Keep Display/Error; semantic RPC transport error, not DTO expansion target. | -| `client.rs:49 struct Conn` | `trace_runtime.rs` | `client.rs:55` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `client.rs:265 struct DaemonClient` | `transcript_import/pipeline.rs`, `src/runtime/js-daemon-client/src/index.ts`, `src/plugins/opencode/content/src/server.ts`, `src/plugins/opencode/content/src/tracing/daemon.ts`, `src/plugins/pi/content/src/index.ts` | `client.rs:272` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/events.rs:40 enum EventRecord` | `pipeline/translation.rs`, `server/ingress.rs`, `server/recovery.rs`, `server/mod.rs`, `collections/legacy.rs` (+ more) | `collections/events.rs:45`, `collections/events.rs:51`, `collections/events.rs:70`, `collections/events.rs:86` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/events.rs:58 struct EventEntry` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/events.rs:65 struct Stored` | `collections/legacy.rs`, `collections/span_ops.rs`, `collections/inspect.rs` | `collections/events.rs:70`, `collections/events.rs:86` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/events.rs:273 type Batch` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/events.rs:278 struct EventReader` | `pipeline/translation.rs`, `server/ingress.rs`, `collections/mod.rs` | `collections/events.rs:287`, `collections/events.rs:334` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/inspect.rs:11 enum Fault` | `trace_runtime.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `collections/tests.rs` | `collections/inspect.rs:19` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/inspect.rs:32 enum Table` | `pipeline/translation.rs`, `server/maintenance.rs`, `collections/upgrade.rs`, `collections/tests.rs` | `collections/inspect.rs:39` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/inspect.rs:52 struct Head` | `collections/span_ops.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/inspect.rs:66 struct Inspector` | `trace_runtime.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/maintenance.rs` (+ more) | `collections/inspect.rs:68` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/legacy.rs:212 struct Imported` | `command_output.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/legacy.rs:290 struct Checkpoint` | `dispatch.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `server/recovery.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/legacy.rs:296 enum Line` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/legacy.rs:303 struct Reader` | `transcript_import/muse.rs` | `collections/legacy.rs:309`, `transcript_import/muse.rs:66` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/session.rs:21 struct Status` | `trace_runtime.rs`, `main.rs`, `trace_command.rs`, `command_output.rs` | `collections/session.rs:40` | Keep owner() helper; storage status snapshot is data-only otherwise. | -| `collections/span_ops.rs:21 struct BindingChanged` | `pipeline/cursor.rs`, `collections/upgrade.rs`, `collections/mod.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:29 struct StoredOp` | `pipeline/translation.rs`, `collections/upgrade.rs` | `collections/span_ops.rs:36`, `collections/span_ops.rs:46`, `collections/span_ops.rs:59` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:255 struct Translated` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `server/maintenance.rs`, `collections/session.rs`, `collections/upgrade.rs` (+ more) | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:268 struct HeldRoute` | `pipeline/cursor.rs`, `collections/mod.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:280 struct Head` | `collections/inspect.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:289 struct Subscriber` | `daemon_log.rs` | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:296 type ReplayWindow` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `collections/span_ops.rs:299 struct Channel` | `collections/store.rs` | `collections/span_ops.rs:307` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/store.rs:29 struct Inner` | Private/local producer and consumer in same module | `collections/store.rs:35`, `collections/store.rs:49` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/store.rs:69 struct SessionStorage` | `journal.rs`, `pipeline/attachment_tests.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `collections/session.rs:59`, `collections/events.rs:97`, `collections/legacy.rs:223`, `collections/span_ops.rs:328` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `collections/store.rs:231 struct Json` | `trace_runtime.rs`, `command_output.rs`, `muse/messages.rs`, `collections/events.rs`, `collections/legacy.rs` (+ more) | `collections/store.rs:233`, `collections/store.rs:241` | KEEP DATA-ONLY storage/stream transfer or serialization adapter; existing TryFrom/Stream/Deserialize impls own codecs. Keep near collection owner; no SQL methods on row structs. | -| `command_output.rs:12 enum OutputFormat` | `lib.rs`, `trace_runtime.rs`, `main.rs` | `command_output.rs:17` | Keep From; data-only choice thereafter. | -| `command_output.rs:28 struct StatusCommandOutput` | `lib.rs` | `command_output.rs:37` | Keep From>; output conversion owns running-state defaults. Split command_output/status.rs. | -| `command_output.rs:57 struct SetupCommandOutput` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:65 struct UpdateCommandOutput` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:72 struct StopCommandOutput` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:78 struct ImportSummary` | `lib.rs`, `transcript_import/muse_runtime.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:89 struct AuthDiagnostic` | `lib.rs`, `trace_runtime.rs` | Derives/data only | ADD ready/unconfirmed/failed constructors to own repeated status/source/default field combinations in trace_runtime; auth_failed predicate can live here. Split command_output/auth_diagnostic.rs. | -| `command_output.rs:106 enum DaemonStatus` | `lib.rs`, `trace_runtime.rs`, `src/runtime/js-daemon-client/src/index.ts` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:116 struct DaemonDiagnostic` | `lib.rs`, `trace_runtime.rs` | `command_output.rs:133` | Keep version_suffix/auth_failed; delegate to AuthDiagnostic::is_error if added. Split command_output/daemon_diagnostic.rs. | -| `command_output.rs:151 struct DoctorCommandOutput` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: final user-facing output leaf consumed by TraceCommandOutput rendering. Group under corresponding command output module. | -| `command_output.rs:168 enum TraceCommandOutput` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `setup/mod.rs` | `command_output.rs:178` | Keep render/write/emit methods (see file); already owns output formatting. Split output modules by command, not every tiny leaf. | -| `correlation.rs:22 struct ParentLink` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | -| `correlation.rs:27 struct ParentCandidate` | `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | -| `correlation.rs:33 enum Resolution` | `wire/methods.rs`, `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | -| `correlation.rs:40 struct CorrelationRegistry` | `pipeline/translation.rs`, `server/correlation_store.rs`, `server/mod.rs` | `correlation.rs:85` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `correlation.rs:45 struct State` | `pipeline/submission.rs`, `pipeline/translation.rs`, `transcript_import/mod.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `correlation.rs:61 struct ActiveTool` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `correlation.rs:68 struct ActiveParentSnapshot` | `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | -| `correlation.rs:80 struct ActiveToolSnapshot` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY correlation result/persisted snapshot; matching/registration and snapshot restoration involve registry state. Split persisted snapshot DTOs into correlation/snapshot.rs if reducing file. | -| `dispatch.rs:28 struct Counters` | `pipeline/consumer.rs` | `dispatch.rs:40` | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `dispatch.rs:35 struct Delivered` | `translate/claude.rs`, `translate/opencode_v2.rs`, `server/maintenance.rs`, `translate/opencode_v2/event.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `dispatch.rs:61 enum SessionMsg` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `dispatch.rs:71 struct SessionOptions` | `server/sessions.rs`, `server/mod.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `dispatch.rs:85 struct Session` | `lib.rs`, `span_processor.rs`, `pipeline/routing.rs`, `muse/export_v1.rs`, `translate/muse.rs` (+ more) | `dispatch.rs:99` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `journal.rs:64 struct ManagedRunKey` | `server/managed_run.rs` | Derives/data only | Data-only accepted-pipeline record; append/read/gc are repository I/O, not key methods. Could split journal/managed_run_key.rs if journal grows. | -| `json.rs:6 enum Field` | `attachments.rs`, `muse/outcome.rs`, `muse/metadata.rs`, `muse/hooks.rs`, `muse/provider_options.rs` (+ more) | `json.rs:12`, `json.rs:23`, `json.rs:28`, `json.rs:36` | Keep Missing/Null/Value plus as_ref/as_deref/is_missing; already owns optional native-field semantics. Split json/field.rs. | -| `json.rs:53 type Extensions` | `muse/provider_options.rs`, `muse/messages.rs`, `translate/grok.rs`, `agents/request.rs`, `agents/usage/camel_case_usage.rs` (+ more) | Derives/data only | Keep opaque alias + deserialize helper; a newtype only if adding real extension operations. Split json/extensions.rs. | -| `main.rs:32 struct EnvironmentAuthProvider` | Private/local producer and consumer in same module | `main.rs:37` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `main.rs:77 struct Cli` | `trace_command.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `main.rs:88 enum Command` | `subprocess.rs`, `env.rs`, `codex_hooks.rs`, `trace_runtime.rs`, `correlation.rs` (+ more) | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `main.rs:164 struct RouteArgs` | Private/local producer and consumer in same module | `main.rs:177` | Existing route construction belongs to CLI boundary. Data-only clap inputs otherwise. | -| `main.rs:193 struct RunRouteArgs` | Private/local producer and consumer in same module | `main.rs:208` | Data-only clap boundary input, no extra methods. | -| `pipeline/consumer.rs:22 enum Work` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/consumer.rs:27 type Held` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/consumer.rs:29 struct Consumer` | `dispatch.rs` | `pipeline/consumer.rs:177` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/consumer.rs:34 struct ConsumerOptions` | `dispatch.rs` | `pipeline/consumer.rs:49` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/cursor.rs:51 struct Cursor` | `hook.rs`, `dispatch.rs`, `env.rs`, `paths.rs`, `codex_hooks.rs` (+ more) | `pipeline/cursor.rs:127`, `pipeline/cursor.rs:338`, `pipeline/cursor.rs:416`, `agents/cursor.rs:14` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/cursor.rs:72 struct Progress` | `dispatch.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` | `pipeline/cursor.rs:78`, `pipeline/cursor.rs:87`, `pipeline/translation.rs:51` | Pipeline cursor/translation progress handles already have pending/completed/wait methods; runtime state not DTO. | -| `pipeline/cursor.rs:122 struct Subscription` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/cursor.rs:295 struct SharedCursor` | Private/local producer and consumer in same module | `pipeline/cursor.rs:298` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/cursor.rs:425 struct HeadCompletion` | Private/local producer and consumer in same module | `pipeline/cursor.rs:437`, `pipeline/cursor.rs:447` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/delivery.rs:7 struct Delivery` | `hook.rs`, `correlation.rs`, `pipeline/mod.rs`, `pipeline/cursor.rs`, `pipeline/routing.rs` (+ more) | `pipeline/delivery.rs:30`, `pipeline/delivery.rs:85`, `pipeline/delivery.rs:104` | Keep new/value/map/failed/into_completed. This is strong existing ownership model, not DTO-only. | -| `pipeline/delivery.rs:25 struct Unfinished` | Private/local producer and consumer in same module | Derives/data only | Data-only failed completion result preserving delivery; do not add implicit acknowledgment behavior. | -| `pipeline/input.rs:13 enum ControlKind` | `dispatch.rs`, `pipeline/translation.rs`, `server/maintenance.rs`, `server/recovery.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/input.rs:23 struct PipelineControl` | `pipeline/translation.rs`, `server/recovery.rs`, `collections/events.rs` | `collections/events.rs:51` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/input.rs:30 struct SourcePosition` | `pipeline/translation.rs`, `server/ingress.rs`, `server/sessions.rs`, `collections/events.rs` | Derives/data only | ADD bytes/len only if SourceRecord::bytes plus other identical subtraction callers justify it; avoid a forwarding method for one site. Keep pipeline/input.rs. | -| `pipeline/input.rs:35 enum SourceEvent` | `pipeline/translation.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/input.rs:40 struct SourceRecord` | `pipeline/translation.rs` | `pipeline/input.rs:45` | Keep bytes helper; stage input pair is already cohesive. No serialization/accessor boilerplate. | -| `pipeline/input.rs:52 struct Buffer` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/input.rs:58 struct SourceInput` | `pipeline/translation.rs`, `server/sessions.rs`, `server/mod.rs` | `pipeline/input.rs:60` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/live.rs:7 type SharedOp` | `pipeline/prepare.rs`, `pipeline/cursor.rs`, `pipeline/routing.rs`, `pipeline/consumer.rs`, `collections/session.rs` (+ more) | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/live.rs:11 struct Record` | `pipeline/cursor.rs`, `translate/opencode.rs`, `collections/session.rs`, `collections/events.rs`, `collections/legacy.rs` (+ more) | `pipeline/live.rs:16` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/live.rs:25 struct Queued` | `command_output.rs`, `translate/opencode_v2.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/live.rs:29 struct Route` | `journal.rs`, `pipeline/prepare.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs`, `collections/events.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/live.rs:35 struct Multiplexer` | `collections/span_ops.rs` | `pipeline/live.rs:42` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/live.rs:38 struct Receiver` | `dispatch.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `server/ingress.rs` (+ more) | `pipeline/delivery.rs:85`, `pipeline/live.rs:92`, `pipeline/live.rs:110` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/live.rs:84 struct Control` | `pipeline/cursor.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `server/recovery.rs`, `collections/events.rs` (+ more) | `pipeline/live.rs:85` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/plugins.rs:6 enum PluginOutcome` | `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/plugins.rs:13 struct Plugins` | `pipeline/routing.rs`, `setup/cursor/tests.rs` | `pipeline/plugins.rs:38`, `pipeline/plugins.rs:64` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/plugins.rs:21 struct PluginRejected` | Private/local producer and consumer in same module | `pipeline/plugins.rs:26`, `pipeline/plugins.rs:36` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/prepare.rs:27 struct Prepare` | `pipeline/translation.rs`, `pipeline/routing.rs`, `managed_run/mod.rs` | `pipeline/prepare.rs:32` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/prepare.rs:130 struct ConfiguredTranslator` | `translate/mod.rs` | `pipeline/prepare.rs:135`, `pipeline/prepare.rs:150`, `pipeline/prepare.rs:159` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/recovery.rs:10 enum Boundary` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/ingress.rs` | `pipeline/recovery.rs:19` | Keep Display; data-only discriminant. | -| `pipeline/recovery.rs:35 enum Condition` | `pipeline/cursor.rs` | Derives/data only | Existing eligibility/matching in Failure recovery owns stage context; move pure checks only with repeated caller evidence. | -| `pipeline/recovery.rs:61 struct TimeoutRetry` | Private/local producer and consumer in same module | Derives/data only | Data-only persisted retry policy. Condition owns eligibility context. | -| `pipeline/recovery.rs:69 enum RetryCondition` | `pipeline/submission.rs`, `pipeline/routing.rs` | Derives/data only | Data-only classifier result consumed by Failure creation; retain enum. | -| `pipeline/recovery.rs:83 struct RouteFailure` | `pipeline/routing.rs`, `pipeline/consumer.rs` | `pipeline/recovery.rs:90`, `pipeline/recovery.rs:95`, `pipeline/recovery.rs:105` | Keep Display/Debug/Error; route-level error carrier, no extra accessors. | -| `pipeline/recovery.rs:112 struct Failure` | `pipeline/submission.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `pipeline/submission.rs:36`, `pipeline/submission.rs:41`, `pipeline/submission.rs:49`, `pipeline/submission.rs:55` | Existing constructors/retry eligibility/status conversion in pipeline/recovery already own behavior; submission::Failure::classify already owns SDK classification. Keep separate namespaced types. | -| `pipeline/recovery.rs:317 enum RecoveryOutcome` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/correlation_store.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/recovery.rs:321 struct Recovery` | `pipeline/cursor.rs`, `pipeline/input.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs`, `server/correlation_store.rs` (+ more) | `pipeline/recovery.rs:326` | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/roots.rs:7 struct Roots` | `pipeline/cursor.rs`, `pipeline/translation.rs`, `sink/braintrust.rs` | `pipeline/roots.rs:11`, `pipeline/roots.rs:21`, `pipeline/roots.rs:57` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/routing.rs:15 struct Request` | `client.rs`, `pipeline/attachment_tests.rs`, `wire/mod.rs`, `wire/rpc.rs`, `server/maintenance.rs` (+ more) | `wire/rpc.rs:50` | KEEP DATA-ONLY stage request/response pair; these are not JSON-RPC types. Keep private next to routing stage. | -| `pipeline/routing.rs:20 struct Response` | `client.rs`, `codex_hooks.rs`, `muse/msp.rs`, `wire/mod.rs`, `wire/rpc.rs` (+ more) | `wire/rpc.rs:79` | KEEP DATA-ONLY stage request/response pair; these are not JSON-RPC types. Keep private next to routing stage. | -| `pipeline/routing.rs:26 struct Forward` | `main.rs` | `pipeline/routing.rs:28` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/routing.rs:34 struct RoutingSink` | `pipeline/consumer.rs` | `pipeline/routing.rs:42`, `pipeline/routing.rs:246` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/submission.rs:5 enum Operation` | `span_processor.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/submission.rs:10 struct Input` | `pipeline/recovery.rs`, `pipeline/plugins.rs`, `pipeline/roots.rs`, `pipeline/mod.rs`, `pipeline/routing.rs` (+ more) | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/submission.rs:15 struct State` | `correlation.rs`, `pipeline/translation.rs`, `transcript_import/mod.rs` | Derives/data only | KEEP DATA-ONLY sink submission status snapshot; no new methods. | -| `pipeline/submission.rs:20 enum Outcome` | `pipeline/recovery.rs`, `pipeline/plugins.rs`, `pipeline/roots.rs`, `pipeline/mod.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/submission.rs:31 struct Failure` | `pipeline/recovery.rs`, `pipeline/delivery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs`, `pipeline/consumer.rs` (+ more) | `pipeline/submission.rs:36`, `pipeline/submission.rs:41`, `pipeline/submission.rs:49`, `pipeline/submission.rs:55` | Existing constructors/retry eligibility/status conversion in pipeline/recovery already own behavior; submission::Failure::classify already owns SDK classification. Keep separate namespaced types. | -| `pipeline/submission.rs:88 struct Submission` | `pipeline/routing.rs` | `pipeline/submission.rs:92`, `pipeline/submission.rs:106` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:31 struct Observation` | `server/sessions.rs`, `transcript_mirror/observation.rs`, `transcript_mirror/mod.rs`, `transcript_mirror/payload.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/translation.rs:37 enum Command` | `subprocess.rs`, `env.rs`, `codex_hooks.rs`, `trace_runtime.rs`, `correlation.rs` (+ more) | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:47 struct Progress` | `dispatch.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs` | `pipeline/cursor.rs:78`, `pipeline/cursor.rs:87`, `pipeline/translation.rs:51` | Pipeline cursor/translation progress handles already have pending/completed/wait methods; runtime state not DTO. | -| `pipeline/translation.rs:58 struct RouteLifetimes` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:63 struct Translation` | `dispatch.rs`, `pipeline/recovery.rs`, `sink/braintrust.rs`, `server/ingress.rs`, `server/sessions.rs` (+ more) | `pipeline/translation.rs:87` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:74 struct TranslationOptions` | `server/sessions.rs` | Derives/data only | KEEP DATA-ONLY stage command/options/outcome; direct stage-local transfer. Runtime processing/ack policy stays stage or Delivery. Keep in stage module unless reused outside. | -| `pipeline/translation.rs:188 enum State` | `correlation.rs`, `pipeline/submission.rs`, `transcript_import/mod.rs` | Derives/data only | Runtime translation state enum; EXCLUDED DTO methods target. Keep transition matching with Producer. | -| `pipeline/translation.rs:193 struct Continuation` | `translate/claude.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:205 struct Publication` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `pipeline/translation.rs:216 struct Producer` | Private/local producer and consumer in same module | `pipeline/translation.rs:237` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `plugin_diagnostics.rs:13 struct PluginDiagnostic` | `lib.rs`, `command_output.rs` | Derives/data only | ADD matches_failure and record_occurrence(now) only if record remains complex; identity and saturating occurrences belong to diagnostic. I/O stays store. Split plugin_diagnostics/diagnostic.rs optional. | -| `plugin_diagnostics.rs:27 struct DiagnosticStore` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `process.rs:56 struct ProcessSnapshot` | Private/local producer and consumer in same module | Derives/data only | Data-only one platform query result; no methods, keep private in process.rs. | -| `server/auth.rs:38 struct RouteAuthProvider` | Private/local producer and consumer in same module | `server/auth.rs:44` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `server/claude_transcripts.rs:9 struct ClaudeTranscriptObservation` | `server/mod.rs` | Derives/data only | Borderline runtime observation state. Shared observer/refill belongs to type if main+child share common representation; avoid retain payload getters. Parent owns observer refactor. | -| `server/claude_transcripts.rs:18 struct ClaudeChildObservation` | Private/local producer and consumer in same module | Derives/data only | Same observation state decision; path/through/template already concrete. Merge state shape with root observation only if lifecycle does not blur child map ownership. | -| `server/correlation_store.rs:17 struct PendingSession` | `server/maintenance.rs`, `server/recovery.rs`, `server/mod.rs` | `server/correlation_store.rs:37`, `server/correlation_store.rs:52` | Keep restore/decided/expired; already owns durable compatibility/deadline semantics. Move into server/correlation/pending_session.rs if splitting store I/O. | -| `server/correlation_store.rs:88 struct PendingEvent` | `server/ingress.rs`, `server/maintenance.rs`, `server/recovery.rs` | `server/correlation_store.rs:97` | Keep custom Deserialize old/new representation; add position() returning SourcePosition only if repeated conversion sites share semantics. Split server/correlation/pending_event.rs. | -| `server/ingress.rs:11 struct CaptureBuffer` | `server/mod.rs` | `server/ingress.rs:22` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `server/ingress.rs:17 struct EvictedRange` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | -| `server/ingress.rs:39 enum CaptureWork` | `server/maintenance.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | -| `server/ingress.rs:145 enum IngressMsg` | `server/maintenance.rs`, `server/recovery.rs`, `server/mod.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `server/mod.rs:57 struct ServeOptions` | `lib.rs`, `trace_runtime.rs`, `main.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | -| `server/mod.rs:68 enum AuthResolveReason` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/consumer.rs`, `server/maintenance.rs` (+ more) | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | -| `server/mod.rs:78 struct AuthLease` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/consumer.rs`, `server/recovery.rs` (+ more) | Derives/data only | Data-only live credentials/expiry transfer; refresh resolution and deadlines involve daemon policy, keep there unless duplicated pure is_expiring_at(now,margin). | -| `server/mod.rs:101 struct SessionAuthState` | `server/auth.rs` | Derives/data only | KEEP DATA-ONLY server command/options/result or private runtime state; no duplicated intrinsic operation found beyond owning subsystem. | -| `server/mod.rs:106 type StorageSlot` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `server/mod.rs:108 struct Daemon` | `subprocess.rs`, `trace_runtime.rs`, `correlation.rs`, `trace_command.rs`, `command_output.rs` (+ more) | `server/correlation_store.rs:670`, `server/ingress.rs:45`, `server/ingress.rs:337`, `server/claude_transcripts.rs:24` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `server/sessions.rs:8 struct DeliveryKey` | `server/maintenance.rs`, `server/recovery.rs`, `server/claude_transcripts.rs`, `server/auth.rs`, `server/managed_run.rs` (+ more) | `server/sessions.rs:14` | Keep new/correlation_key; no need forward field accessors. Split server/delivery_key.rs when moving sessions actor code. | -| `sink/braintrust.rs:28 struct BraintrustSinkConfig` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `pipeline/attachment_tests.rs`, `pipeline/consumer.rs` (+ more) | Derives/data only | KEEP DATA-ONLY factory/options/SDK conversion carrier; client, credentials, and attachment upload lifetime are sink service responsibilities. | -| `sink/braintrust.rs:34 struct ClientCache` | Private/local producer and consumer in same module | `sink/braintrust.rs:96` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:42 struct ClientCacheState` | Private/local producer and consumer in same module | `sink/braintrust.rs:72` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:47 struct CachedClient` | Private/local producer and consumer in same module | `sink/braintrust.rs:52` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:136 struct BraintrustSinkFactory` | `lib.rs`, `pipeline/attachment_tests.rs`, `pipeline/consumer.rs`, `sink/mod.rs`, `server/mod.rs` | `sink/braintrust.rs:141`, `sink/braintrust.rs:150` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:171 struct Creds` | Private/local producer and consumer in same module | `sink/braintrust.rs:178` | KEEP DATA-ONLY factory/options/SDK conversion carrier; client, credentials, and attachment upload lifetime are sink service responsibilities. | -| `sink/braintrust.rs:190 struct AttachmentUploads` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:195 struct BraintrustSink` | Private/local producer and consumer in same module | `sink/braintrust.rs:217`, `sink/braintrust.rs:456` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/braintrust.rs:701 struct DestinationComponents` | Private/local producer and consumer in same module | Derives/data only | Data-only SDK conversion intermediate. Distinct sink/correlation fallback behavior means do not deduplicate blindly. | -| `sink/braintrust.rs:834 struct ByteCounter` | Private/local producer and consumer in same module | `sink/braintrust.rs:836` | Serializer writer implementation, not DTO; keep Write impl. | -| `sink/debug.rs:14 struct DebugSinkFactory` | `lib.rs`, `trace_runtime.rs`, `main.rs`, `sink/mod.rs`, `server/mod.rs` | `sink/debug.rs:18` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `sink/debug.rs:37 struct DebugSink` | Private/local producer and consumer in same module | `sink/debug.rs:43` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:20 struct StopTracing` | `pipeline/routing.rs`, `pipeline/consumer.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | -| `span_processor.rs:28 struct PluginTimeout` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:44 enum Operation` | `pipeline/submission.rs`, `pipeline/routing.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | -| `span_processor.rs:50 struct PluginContext` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:57 struct Engine` | `attachments.rs`, `muse/images.rs`, `setup/cursor/hooks.rs` | `span_processor.rs:87` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:70 struct CachedModule` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:76 struct FailedPlugin` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:83 struct PluginFingerprint` | Private/local producer and consumer in same module | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `span_processor.rs:285 struct PluginFailure` | `pipeline/plugins.rs` | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | -| `span_processor.rs:293 struct ProcessResult` | Private/local producer and consumer in same module | Derives/data only | KEEP DATA-ONLY plugin result/error or private engine command; plugin execution and caching belong to Engine. | -| `subprocess/windows_daemon.rs:103 struct HandleList` | Private/local producer and consumer in same module | `subprocess/windows_daemon.rs:108`, `subprocess/windows_daemon.rs:151` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `trace_command.rs:13 struct TraceArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:22 enum TraceCommand` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:51 struct StopArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:58 struct DoctorArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:65 enum DoctorAgent` | `lib.rs`, `trace_runtime.rs` | `trace_command.rs:79` | Keep identity; enum-specific source dispatch belongs here already. | -| `trace_command.rs:95 struct EnableArgs` | `lib.rs`, `setup/mod.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:116 type SetupArgs` | `lib.rs`, `trace_runtime.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:119 struct DisableArgs` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:125 struct UpdateArgs` | `lib.rs` | Derives/data only | KEEP DATA-ONLY: clap parsing/dispatch boundary input. Keep flags/validation declarative and avoid one-field getters; split by command only when improving navigation. | -| `trace_command.rs:131 enum SetupAgent` | `lib.rs`, `trace_runtime.rs`, `setup/mod.rs` | `trace_command.rs:152` | Keep identity; do not add forwarded enable/disable methods that couple command execution. | -| `trace_runtime.rs:26 struct RouteRequirements` | `lib.rs` | Derives/data only | Data-only host request flags. No builder/boolean accessors. | -| `trace_runtime.rs:45 struct HostRouteSelection` | `lib.rs` | `trace_runtime.rs:50` | Keep into_session_route; conversion belongs to selection. Split host_route_selection.rs if runtime service contract grows. | -| `trace_runtime.rs:156 struct TraceHostContext` | `lib.rs` | Derives/data only | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `trace_runtime.rs:166 struct HostAuthProvider` | Private/local producer and consumer in same module | `trace_runtime.rs:171` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `transport.rs:47 type ClientStream` | `client.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `transport.rs:49 type ClientStream` | `client.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `transport.rs:52 type ServerStream` | `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `transport.rs:54 type ServerStream` | `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY or subsystem-local value; current callers transfer fields without repeated semantic interaction. Preserve existing behavior; no speculative impl. | -| `transport.rs:86 struct Listener` | `server/mod.rs`, `server/rpc.rs` | `transport.rs:91`, `transport.rs:111` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `transport.rs:104 struct Listener` | `server/mod.rs`, `server/rpc.rs` | `transport.rs:91`, `transport.rs:111` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `win_acl.rs:28 struct SecurityDescriptor` | `transport.rs`, `trace_runtime.rs` | `win_acl.rs:34`, `win_acl.rs:40` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `win_acl.rs:137 struct NamedDacl` | Private/local producer and consumer in same module | `win_acl.rs:142` | EXCLUDED runtime actor/handle/private implementation state. Keep lifecycle/locking methods with subsystem; no DTO extraction just to satisfy file count. | -| `wire/envelope.rs:14 struct ProcessIdentity` | `correlation.rs`, `process.rs`, `wire/mod.rs`, `setup/cursor/hooks.rs` | Derives/data only | Data-only stable identity/hash key; process liveness is platform-dependent service, not DTO behavior. Split process_identity.rs. | -| `wire/envelope.rs:27 struct CaptureContext` | `correlation.rs`, `process.rs`, `wire/mod.rs` | Derives/data only | Data-only captured ancestry; matching/capture I/O belongs to correlation/process services. Split capture_context.rs. | -| `wire/envelope.rs:37 struct Envelope` | `hook.rs`, `dispatch.rs`, `client.rs`, `journal.rs`, `trace_runtime.rs` (+ more) | `wire/envelope.rs:333`, `collections/events.rs:45`, `transcript_import/muse.rs:66` | Keep redacted(); own synthetic successor creation only if semantics match. Split to envelope.rs; native payload remains opaque. | -| `wire/envelope.rs:77 enum AuthSource` | `trace_runtime.rs`, `main.rs`, `settings.rs`, `wire/mod.rs`, `setup/mod.rs` (+ more) | `wire/envelope.rs:104` | Keep is_auto serialization helper; no extra API for one match. Split auth_source.rs. | -| `wire/envelope.rs:92 struct AuthSelection` | `trace_runtime.rs`, `main.rs`, `settings.rs`, `pipeline/cursor.rs`, `pipeline/consumer.rs` (+ more) | `wire/envelope.rs:110` | Keep effective_source/canonicalized; could own source_label used by diagnostics. Split auth_selection.rs with AuthSource helper or separate auth_source.rs. | -| `wire/envelope.rs:144 struct SessionRoute` | `hook.rs`, `dispatch.rs`, `route.rs`, `journal.rs`, `lib.rs` (+ more) | `wire/envelope.rs:162` | Keep with_auth/same_route/same_destination/same_replay_route; ADD apply_metadata/apply_tags if parent consolidates route.rs normalization. No sink/storage I/O. Split session_route.rs. | -| `wire/envelope.rs:220 struct SessionConfig` | `dispatch.rs`, `trace_runtime.rs`, `correlation.rs`, `pipeline/attachment_tests.rs`, `pipeline/submission.rs` (+ more) | `wire/envelope.rs:252` | Keep attached_span_ids; DELEGATE project_name to TraceDestination::project_name. Split session_config.rs. | -| `wire/envelope.rs:238 enum TraceDestination` | `trace_runtime.rs`, `correlation.rs`, `main.rs`, `args.rs`, `settings.rs` (+ more) | `wire/envelope.rs:270`, `wire/envelope.rs:296` | Keep FromStr/project_name; ADD parent-span component/IDs query only if reused by sink + correlation. Their differing project fallback policies must remain explicit. Split trace_destination.rs. | -| `wire/envelope.rs:308 struct BackendAuth` | `journal.rs`, `trace_runtime.rs`, `correlation.rs`, `main.rs`, `pipeline/recovery.rs` (+ more) | Derives/data only | Data-only credential carrier; no I/O, cache lookup, or persistence methods. Split backend_auth.rs. | -| `wire/envelope.rs:325 enum FlushMode` | `hook.rs`, `trace_runtime.rs`, `wire/mod.rs`, `transcript_import/pipeline.rs` | Derives/data only | Data-only closed wire enum, no accessor that restates matches!. Split flush_mode.rs. | -| `wire/envelope.rs:355 struct RedactedEnvelope` | `journal.rs`, `wire/mod.rs`, `collections/events.rs`, `collections/legacy.rs` | Derives/data only | ADD into_envelope(self): own credential-free runtime reconstruction now in journal::envelope_from_redacted. Migrate internal callers; the old helper is internal-only, so it can be removed. Split redacted_envelope.rs. | -| `wire/methods.rs:19 struct InitializeParams` | `muse/msp.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:25 struct ClientInfo` | `muse/msp.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:38 struct InitializeResult` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:46 struct Capabilities` | `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:55 struct EventLogResult` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:60 struct FlushParams` | `client.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:68 struct ImportFinishParams` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:80 struct ImportFinishResult` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:91 struct ImportResetParams` | `wire/mod.rs`, `server/rpc.rs`, `transcript_import/pipeline.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:97 struct ManagedRunFlushParams` | `client.rs`, `wire/mod.rs`, `server/managed_run.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:108 struct FlushResult` | `client.rs`, `wire/mod.rs`, `server/managed_run.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:116 struct StatusParams` | `client.rs`, `wire/mod.rs`, `server/recovery.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:123 struct StatusResult` | `client.rs`, `command_output.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | `command_output.rs:37` | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:130 struct RecoveryInfo` | `dispatch.rs`, `command_output.rs`, `pipeline/recovery.rs`, `pipeline/cursor.rs`, `pipeline/translation.rs` (+ more) | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:142 struct SessionStatus` | `command_output.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:162 struct AuthDiagnoseParams` | `trace_runtime.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:170 struct AuthDiagnoseResult` | `trace_runtime.rs`, `wire/mod.rs`, `server/auth.rs`, `server/mod.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/methods.rs:183 struct ShutdownResult` | `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | Derives/data only | KEEP DATA-ONLY: request/result schema with direct construction/dispatch; no repeated intrinsic interaction beyond field transfer. Group by RPC operation under wire/methods/.rs, with shared session_status/recovery_info types separate. | -| `wire/rpc.rs:8 enum RequestId` | `client.rs`, `muse/hooks.rs`, `muse/ids.rs`, `wire/mod.rs`, `server/maintenance.rs` (+ more) | Derives/data only | Data-only wire identifier, no extra wrapper accessors. Split rpc/request_id.rs if RPC layout is reorganized. | -| `wire/rpc.rs:23 enum Message` | `client.rs`, `wire/mod.rs`, `translate/opencode.rs`, `translate/claude.rs`, `translate/opencode_v2.rs` (+ more) | `wire/rpc.rs:29`, `translate/opencode_v2/span.rs:102` | Keep from_line/to_line; framing is type-owned already. Split rpc/message.rs with stable reexport. | -| `wire/rpc.rs:42 struct Request` | `client.rs`, `pipeline/attachment_tests.rs`, `pipeline/routing.rs`, `wire/mod.rs`, `server/maintenance.rs` (+ more) | `wire/rpc.rs:50` | Keep new constructor; optional decode_params duplicates serde and has too little benefit. Split rpc/request.rs. | -| `wire/rpc.rs:62 struct Notification` | `muse/hooks.rs`, `translate/muse_events.rs`, `server/rpc.rs`, `managed_run/claude.rs` | Derives/data only | Data-only outbound/inbound frame; no meaningful repeated interaction found. Split rpc/notification.rs. | -| `wire/rpc.rs:70 struct Response` | `client.rs`, `codex_hooks.rs`, `pipeline/routing.rs`, `muse/msp.rs`, `wire/mod.rs` (+ more) | `wire/rpc.rs:79` | Keep serialized/ok/err; already owns response invariants. Split rpc/response.rs. | -| `wire/rpc.rs:114 struct RpcError` | `codex_hooks.rs`, `wire/mod.rs`, `server/mod.rs`, `server/rpc.rs` | `wire/rpc.rs:121` | Keep new; retain error code constants together in rpc. Split rpc/error.rs if desired. | -| `wire/rpc.rs:145 struct JsonRpcV2` | Private/local producer and consumer in same module | `wire/rpc.rs:147`, `wire/rpc.rs:153` | Keep custom Serialize/Deserialize; no new behavior. Keep alongside RPC framing marker. | -| `attachments.rs:212 struct Marker` | Private/local producer and consumer in same module | Derives/data only | Data-only local decoding shape; keep in materialize boundary, not exported or separate file. | -| `server/claude_transcripts.rs:56 struct PollPayload` | Private/local producer and consumer in same module | Derives/data only | Data-only local synthetic encoding shape; promote reusable event constructor only if reused; no separate DTO file for one local writer. | -| `server/correlation_store.rs:104 enum StoredPendingEvent` | Private/local producer and consumer in same module | Derives/data only | Data-only private compatibility enum in PendingEvent deserializer; keep local. | - -Consumer samples are lexical cross-reference evidence, not proof of same-name identity; generic names (`State`, `Head`, `Failure`, `Request`, `Response`, `Progress`) must be interpreted with the stated module. Judgments above account for their actual stage/collection ownership. - -## TypeScript per-declaration review - -| Declaration | Usage/ownership | Recommendation | -|---|---|---| -| `src/plugins/opencode/content/src/config.ts:5 BraintrustConfig` | OpenCode loadConfig + tools + tracing + plugin input. | Keep resolved config DTO; no class. Shared route query function reduces repeated destination assertions. | -| `src/plugins/opencode/content/src/config.ts:20 PluginConfig` | OpenCode config loader and plugin setup. | Data-only authored config DTO; do not mix environment/filesystem lookup into it. | -| `src/plugins/opencode/content/src/server.ts:10 NativeEvent` | OpenCode2 server async subscribe forwarding. | Data-only partial event boundary; session/event filtering stays adapter. | -| `src/plugins/opencode/content/src/server.ts:17 Context` | OpenCode2 server SDK structural input. | Service interface, not DTO; leave structural compatibility with SDK. | -| `src/plugins/opencode/content/src/tools/bt-cli.ts:8 ProjectInfo` | BtCliToolsClient.listProjects/project tool calls. | Data-only CLI result, keep alongside tool client unless reused. | -| `src/plugins/opencode/content/src/tools/bt-cli.ts:13 ToolLogData` | OpenCode tool invocation -> BtCliToolsClient.logData JSON payload. | Data-only arbitrary user log envelope; no methods. | -| `src/plugins/opencode/content/src/tools/bt-cli.ts:26 BtCliRunner` | BtCliToolsClient dependency injection. | Function alias, not DTO; keep near client. | -| `src/plugins/opencode/content/src/tracing/daemon.ts:7 Logger` | OpenCode tracing adapter diagnostic callback. | Function alias, not DTO; keep local. | -| `src/plugins/opencode/content/src/tracing/daemon.ts:9 TracingRouteConfig` | createDaemonTracingHooks input from resolved config. | Data-only adapter projection; consider Pick if eliminating parallel shape, no class. | -| `src/plugins/pi/content/src/config.ts:7 PiConfig` | loadConfig then index.ts callbacks/UI/tracing. | Keep resolved config DTO; route/auth/project synchronization belongs to config normalization functions already. No class migration. | -| `src/plugins/pi/content/src/config.ts:18 ConfigRecord` | Pi JSON read/applyConfig boundary. | Keep unknown bag only at decoding boundary, no class. | -| `src/plugins/pi/content/src/index.ts:50 JsonObject` | Pi index native payload/type guards. | Generic boundary map alias, not DTO behavior target. | -| `src/plugins/pi/content/src/legacy-session.ts:5 LegacyContinuation` | legacyContinuationFor validation then Pi session-start payload. | Data-only compatibility result; reader owns validation, keep same file. | -| `src/plugins/pi/content/src/pi-package.ts:13 PiPackageManifest` | pi-package find/read/native manifest validation. | Data-only partial boundary view, unknown fields intentionally runtime-validated. | -| `src/plugins/pi/content/src/pi-package.ts:21 PiPackageMetadata` | runningPiPackage cache, Pi config directory, adapter source version. | Data-only normalized package info; module already one concern. | -| `src/runtime/js-daemon-client/src/index.ts:9 DaemonSessionRoute` | Shared client + Pi config + OpenCode config/tracing; repeated destination discrimination and auth projection. | Keep structural DTO; extract typed destination union and routeProjectName/routeAuth query functions to runtime route.ts after explicitly preserving boundary validation. No class methods on serialized JSON. | -| `src/runtime/js-daemon-client/src/index.ts:23 DaemonTraceSettings` | resolveDaemonTraceSettings plus both agent config loaders. | Keep DTO; shared resolver already owns invocation override semantics. Move to settings.ts with resolver for clearer ownership. | -| `src/runtime/js-daemon-client/src/index.ts:75 DaemonEnvelope` | DaemonClient.log/logPipelined and Pi/OpenCode adapters. | Keep DTO. eventParams already centralizes plugin/run stamping in client; module envelope.ts optional, no new class. | -| `src/runtime/js-daemon-client/src/index.ts:87 DaemonSessionStatus` | DaemonClient.status and Pi trace-link/status UI. | Data-only status schema; shared protocol.ts/status.ts. | -| `src/runtime/js-daemon-client/src/index.ts:96 DaemonStatus` | DaemonClient.status response and plugin UI. | Data-only aggregate; keep with session status. | -| `src/runtime/js-daemon-client/src/index.ts:102 DaemonClientOptions` | DaemonClient constructor defaults. | Data-only options; normalization already in constructor. Keep near client. | -| `src/runtime/js-daemon-client/src/index.ts:115 RpcResponse` | DaemonClient read/response dispatch. | Data-only boundary response; shared protocol.ts. Decode/validation can be free functions, no instances. | -| `src/runtime/js-daemon-client/src/index.ts:122 PendingRequest` | DaemonClient.pending map timeout/response cleanup. | Runtime completion state, not DTO; keep client-private to avoid class churn. | -| `src/runtime/js-daemon-client/src/index.ts:129 OutboxEntry` | DaemonClient.pumpOutbox/connection/retry paths. | Runtime obligation state, not DTO. Could own fail/settle only if all retry transitions move together; no partial abstraction. | - -Scan totals: 235 Rust production declarations (including explicitly excluded runtime types), 24 TypeScript declarations. No production JS declared DTO classes/interfaces beyond these TypeScript types. Generated runtime reexports and test-only aliases are not duplicate DTO definitions. - -## Suggested verification - -Full locked all-feature Rust tests and strict Clippy for module/public-import changes. Existing wire roundtrip and redaction tests guard unknown/missing fields and credentials. Replay tests guard route-preserving reconstruction. TypeScript changes, if taken, need js-daemon-client and Pi/OpenCode config suites. - -## Implemented in this stacked refactor - -- `wire/envelope.rs` is now the single Envelope owner. AuthSelection, AuthSource, BackendAuth, CaptureContext, FlushMode, ProcessIdentity, RedactedEnvelope, SessionConfig, SessionRoute, TraceDestination each have a primary type file under `wire/`, with unchanged `wire::*` public exports. Existing wire behavior tests moved intact to `wire/envelope_tests.rs`. -- `RedactedEnvelope::into_envelope` owns replay conversion, including credential-free reconstructed config. All five internal replay/maintenance/ingress callers use the method. `journal::envelope_from_redacted` was verified internal-only (`mod journal`, not reexported) and removed after migrating all callers, so no public API compatibility shim is needed. A focused test asserts complete journal projection roundtrip and absence of replay credentials/config when route absent. -- `SessionConfig::project_name` delegates to the destination's existing query. -- `SessionRoute::apply_additional_metadata` and `apply_tags` own validation and mutation shared by setup, managed runs, import, and hook capture. Their existing regression tests now call methods; filesystem/plugin validation stays outside the DTO. -- `AuthDiagnostic` moved into `command_output/auth_diagnostic.rs`. It owns ready/unconfirmed construction, diagnostic-specific auth provenance labels, and ready/error status predicates reused by runtime warnings and daemon diagnostics. Serialized strings and the distinction between requested versus daemon-confirmed profile/org remain unchanged. - -## Deliberately retained/deferred - -- RPC leaf request/result schemas, command args, snapshot rows, options, and TS interfaces stay data-only unless already owning meaningful codec/conversion behavior. No mandatory one-type-per-file churn for local encoding helpers or tightly coupled tiny enums. -- JS types remain structural; no class conversion or TS protocol change in this PR. -- Different sink/correlation project fallback policies remain separate; their SDK output ownership deserves a dedicated contract review before consolidation. -- Plugin diagnostic matching/count aggregation and deeper RPC/per-command module splits remain optional small follow-ups; current private single-service implementations do not justify increasing this PR's surface. diff --git a/docs/architecture/dto-ownership/translators.md b/docs/architecture/dto-ownership/translators.md deleted file mode 100644 index 891cf3bf..00000000 --- a/docs/architecture/dto-ownership/translators.md +++ /dev/null @@ -1,356 +0,0 @@ -# DTO ownership inventory: translators, import, and transcript mirrors - -Reviewed against `1b4a4e611f1a9bc73c796361c9d82cdbf52bb721` before this refactor. Paths, line numbers, and existing-method columns describe that baseline. See [the review summary](README.md) for changes made from these findings. - - -Scope: all production struct/enum/type declarations in `bt-daemon/src/translate/**`, `transcript_import/**`, and `transcript_mirror.rs`, including function-local DTOs. Reviewed against source callers, not merely derives. Test-only fixtures are excluded; runtime state declarations are explicitly accounted for below. Native schema types imported from agents/muse are owned by the other inventory scopes. This is the pre-refactor inventory; see [the review summary](README.md) for the implementation decisions. - -## Decisions and module plan - -1. Put interactions on the type that owns their policy, rather than adding mechanical getters. Highest-value changes: SkillLoad skill metadata + display name; Pi AssistantMessage response-model selection and normalization; Pi compaction input/summary projection; OpenCode PermissionProperties request normalization; OpenCode2 Context/native tool content conversion; TranscriptPayload reference selection. Existing Cursor Hook/Specialized and OpenCode2 span Message/ToolCall are good models. -2. DTOs used once solely to deserialize/serialize fields should remain data-only. A one-method wrapper around serde or a DTO getter that duplicates public field access adds no ownership. Keep provider-native models separate from span export models and actor continuation state. -3. Prefer one principal type per file with small private companions beside the owner: `pi/assistant_message.rs` + `pi/compaction.rs` + `pi/event.rs`; `opencode/permission.rs`; `opencode_v2/context.rs` for native context family and normalization; `tool/skill_load.rs`; `transcript_mirror/{reference,payload,observation,snapshot}.rs` with the I/O engine in mod.rs. Avoid 40 tiny files for OpenCode2 one-shot event payload wrappers. -4. Preserve unknown extensions, authored null/missing, native event ordering, save/restore wire JSON, capture absence vs noncaptured fallback, and replay high-water bounds. Existing fixtures and all-agent replay coverage are needed after moving code. - -Rows below list declarations individually, local consumers/nearby functions found by symbol reference (up to four examples), existing impl methods, and a concrete decision. For nested DTOs the enclosing caller is listed. Consumer line numbers reflect pre-refactor source. - - -## bt-daemon/src/transcript_import/claude.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `Subagent` :348 | subagents@364 | none | KEEP parser result data-only: one builder subagents(), one event emission loop. Hierarchy traversal belongs importer; no independent methods justified. | - -## bt-daemon/src/transcript_import/codex.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `SpawnCall` :327 | spawn_calls@336 | none | KEEP parser result data-only: one spawn_calls producer and child import consumer, no repeated policy. | - -## bt-daemon/src/transcript_import/mod.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `TranscriptLayout` :32 | resolve_transcripts@107 | `discover`, `find`, `candidates`, `single`, `locations` | KEEP existing discover/find/candidates methods: good owner of transcript filename/root search. Move `transcript_layout.rs` if splitting import mod. | -| `Refresh` :248 | refresh_with_final_partial@260, poll@473 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | - -## bt-daemon/src/transcript_import/muse.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `ReadMode` :19 | finish@543, for_each_envelope_for_session@652, for_each_snapshot_envelope_for_session@661 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | - -## bt-daemon/src/transcript_import/pipeline.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `ImportTarget` :20 | run_import@33, import_transcript@145, import_transcripts@195, new@247 | none | KEEP data-only host/socket/route launch context. Do not hide process startup behind DTO methods; clients already own it. | - -## bt-daemon/src/transcript_mirror.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `Reference` :25 | schema composition@34, read_path@50, is_empty@89 | `captured`, `read_path` | KEEP existing captured/read_path and ADD explicit complete-capture/path-bound selection only where replay semantics match. Split to transcript_mirror/reference.rs (parent owns). | -| `GrokReferences` :48 | read_path@57, is_empty@93 | `is_empty` | KEEP is_empty; no fake common iteration across heterogeneous slots, split with reference family. | -| `Observation` :64 | is_empty@95 | none | KEEP data-only; Antigravity path/bound precedence can be owned by TranscriptPayload::antigravity_source if shared, avoid filesystem I/O in DTO. | -| `Snapshot` :72 | is_empty@97 | none | KEEP data-only; content is immutable input to bounded reader. Separate snapshot.rs only if module makes lookup easier. | -| `TranscriptPayload` :80 | is_empty@112 | `decode` | ADD explicitly named Claude reference/through/native-path access methods used dispatch, server observer and readers. Preserve map-presence vs missing-entry semantics, captured absence, replay fallback. Split payload.rs (parent owns). | -| `ClaudeChildReference` :107 | is_empty@86 | none | KEEP data-only child path/offset pair; co-locate Reference family, no duplicated observer/runtime state. | - -## bt-daemon/src/translate/antigravity.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `HookPayload` :27 | ensure_root@131, pre_invocation@270, post_invocation@321, pre_tool@346 | none | ADD Antigravity `tool_approval()` by moving tool_approval_from_hook only if splitting hook schema; one call so low priority. Keep other fields data-only. | -| `Message` :44 | create@97, transcript_message@678 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `TranscriptSource` :580 | transcript_source@587 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `ToolDetails` :733 | tool_details@740 | none | KEEP projection result data-only; tool_details interprets source TranscriptRecord and belongs that schema only if truly reused, not result DTO. | - -## bt-daemon/src/translate/claude.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `HookContext` :30 | ensure_root@395, tail_main@458, observe_session_details@473, handle@1507 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `SubagentHook` :48 | parent_for@727, ensure_subagent@739, stop_subagent@968, handle@1514 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `TranscriptEnvelope` :60 | assistant_request_id@1764, parse_transcript@1793, is_real_user_record@2041 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `TimestampEnvelope` :73 | parse_timestamp_ms@2656 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `AgentOrigin` :177 | begin_compacted@288, ensure_subagent@750 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `ParsedTranscript` :1779 | emit_next_pending@1103, parse_transcript@1785 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `UsageRecord` :2162 | observe@2169 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `UsageMessage` :2166 | observe@2163 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | -| `TranscriptToolOutcome` :2254 | parse_transcript@1918, transcript_tool_outcome@2261 | none | KEEP data-only partial routing/parse result; reducer/parser owns correlation; put native envelopes in claude/hook.rs or transcript.rs if splitting, preserve isolated timestamp decode. | - -## bt-daemon/src/translate/codex/tool_output.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `ToolOutcome` :13 | classify@19 | `command`, `observe`, `observe_text`, `observe_command_header` | KEEP observe/command internal methods; optionally make classify an associated constructor because all work builds this result, but not high-value compared with native DTO conversions. | - -## bt-daemon/src/translate/codex.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `SessionStartHook` :54 | handle@290 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `CompactHook` :62 | handle@302, record_compaction_trigger@517 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `SubagentStartHook` :69 | handle@297, handle_subagent_start@562 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `RolloutRecord` :79 | catch_up_chunk@661, process_record@672 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `PayloadKind` :94 | process_record@733 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `WorkingDirectoryPayload` :100 | process_record@681 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `TurnContextPayload` :106 | process_record@689 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `TokenCount` :1292 | close_llm_with_tokens@1299 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `TokenCountInfo` :1296 | close_llm_with_tokens@1293 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | -| `ReadLines` :2161 | read_new_lines@2172 | none | KEEP data-only partial routing/parse result; one decode path handles it. Group hook fields in codex/hook.rs and rollout fields in codex/rollout.rs, no trivial accessors. | - -## bt-daemon/src/translate/cursor/hooks.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `Hook` :20 | schema composition@28 | `decode`, `generation_id`, `model`, `model_params`, `cwd`, `tool_use_id` | KEEP decode/generation_id/model/model_params/cwd/tool_use_id; strong existing ownership. Split hook.rs plus hook_common.rs, preserve central event decode. | -| `HookCommon` :90 | schema composition@23 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `DaemonFields` :101 | decode@39 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `TranscriptMirror` :109 | schema composition@25, tool_use_id@103 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `EmptyObject` :120 | tool_use_id@115 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `CursorHook` :123 | schema composition@21, decode@31, cwd@66, tool_use_id@81 | `decode` | KEEP decode; enum owns native event discrimination. Avoid one file per zero-data event. | -| `PromptHook` :188 | tool_use_id@125 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ToolPhase` :193 | tool_use_id@126, decode@147 | `duration` | KEEP duration; add terminal/error interpretation only if reducers repeat exact branching. | -| `ToolHook` :202 | tool_use_id@126, decode@215 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `PostToolHook` :213 | decode@149 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ToolResult` :221 | decode@196 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ToolFailureHook` :228 | decode@153 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ToolFailure` :236 | decode@197 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ThoughtHook` :255 | tool_use_id@127 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ResponseHook` :260 | tool_use_id@128 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `StopHook` :267 | tool_use_id@129 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `TurnUsage` :276 | duration@263 | none | ADD metrics() only if not already covered agents usage convergence; Cursor reducer currently projects totals to standard token names. Good family-level helper, no field getters. | -| `SessionEndHook` :284 | tool_use_id@130 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `SubagentStartHook` :292 | tool_use_id@131 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `SubagentStopHook` :302 | tool_use_id@132 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `Specialized` :318 | tool_use_id@82, decode@164, duration@363 | `tool_use_id`, `accepts`, `matches_input`, `result` | KEEP tool_use_id/accepts/matches_input/result; excellent owner of native differences. Split specialized.rs and related leaf payloads. | -| `ShellHook` :326 | duration@319 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `McpHook` :333 | duration@320 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `FileEditHook` :343 | duration@321 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `FileEdit` :350 | decode@170, duration@321, tool_use_id@368, accepts@381 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ReadFileHook` :356 | duration@322 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ImportBoundary` :431 | tool_use_id@135 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | -| `ImportStopHook` :439 | tool_use_id@137 | none | KEEP data-only native leaf payload: Hook/CursorHook/ToolPhase/Specialized already own common interactions. Group with its principal owner. | - -## bt-daemon/src/translate/cursor/mod.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `ModelContent` :121 | value@134, encoded_len@150, push@156, model_content@551 | `text`, `encoded_len` | KEEP as data-only restoration representation; ModelStep owns traversal/history behavior. | - -## bt-daemon/src/translate/decode.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `DecodeError` :14 | schema composition@5, fmt@32, decode@43 | none | KEEP constructor/Display/Error behavior; already dedicated file. | - -## bt-daemon/src/translate/git.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `FileStamp` :13 | schema composition@21, stamp@262 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `GitFingerprint` :20 | is_empty@44, fingerprint@246 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `GitMetadata` :29 | schema composition@34, is_empty@45, metadata@113, merge_metadata@183 | `is_empty` | KEEP `is_empty`; optionally add `merge_into(metadata)` to own git key serialization currently in GitMetadataCache::enrich. Keep file/process discovery in cache. | - -## bt-daemon/src/translate/grok.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `NativeRecord` :34 | remember@286, process_update@490, process_event@927, record_ts_ms@1584 | none | ADD `timestamp_ms()` by moving record_ts_ms; encapsulates native metadata/RFC3339/epoch fallback. NativeParams/Meta remain data-only. | -| `NativeParams` :53 | schema composition@36 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | -| `NativeUpdate` :63 | schema composition@55, tool_failure_text@1641 | none | ADD `failure_text()` if touched; helper currently takes only this DTO and interprets its content/raw output. Raw tool data remains a boundary. | -| `NativeMeta` :109 | schema composition@57, turn_key@1559 | none | ADD `turn_key(sequence)` if touched, because prompt-id/prompt-index fallback belongs to identity-bearing DTO. No need to add getters for every field. | -| `PromptIndex` :125 | schema composition@113 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | -| `TurnCompletion` :226 | process_update@915, close_turn@1089, close_incomplete_turn@1143 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | -| `TranscriptRecord` :284 | remember@291, read_new_records@1502 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | -| `TranscriptBatch` :289 | read_new_records@1420 | none | KEEP data-only native nested payload or bounded-read result; parent NativeRecord/Update or transcript I/O owns interpretation. Group in grok/native.rs or reader.rs. | - -## bt-daemon/src/translate/mod.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `SpanType` :57 | local_username@93 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `OriginSnapshot` :68 | local_username@132 | none | KEEP immutable data-only, version-stamping ownership already in origins/dispatcher. Group with span row if not independently useful file. | -| `LateMergeVersion` :77 | local_username@116 | none | KEEP data-only causal watermark; ordering decisions belong delivery ledger, not generic lexicographic derive. | -| `SpanRow` :85 | schema composition@6, local_username@141, row@147, row_mut@152 | none | KEEP publicly constructible data; consider metadata mutation helper only for structurally identical cross-cutting operations. Never move sink policy/redaction into row. `span_row.rs` appropriate. | -| `SpanOp` :140 | schema composition@2, local_username@145, handle@191, drain_pending@197 | `row`, `row_mut` | KEEP row/row_mut; add into_row/is_merge only if actual repeated destructuring callers justify it (not mechanically). `span_op.rs` appropriate. | -| `SessionCtx` :161 | handle@191, drain_pending@197, checkpoint@203, finalize@211 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | - -## bt-daemon/src/translate/opencode.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `Saved` :50 | save_state@58, restore_state@65 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolInput` :121 | finalize@149 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolBeforeOutput` :131 | finalize@151 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolAfterResult` :137 | finalize@173 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolBeforePayload` :147 | finalize@193, from@194, handle@606 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolBefore` :161 | finalize@193, handle@607, tool_before@1132 | none | KEEP From, ownership already exists; co-locate ToolBeforePayload/Input/Output in tool_event.rs. | -| `ToolAfterPayload` :169 | from@202, handle@610 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolAfter` :187 | from@202, handle@611, tool_after@1172 | none | KEEP From, ownership already exists; co-locate ToolAfterPayload/Input/Result in tool_event.rs. | -| `PermissionToolRecord` :224 | from@242, record@298 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `PermissionTool` :240 | from@254, permission_record@1268 | `record`, `name` | KEEP record/name; companions remain data-only under PermissionProperties::request. Split permission.rs family. | -| `PermissionFields` :246 | from@273 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `PermissionPayload` :272 | from@280, permission_record@1261 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `PermissionProperties` :278 | permission_properties@313, permission_record@1259, permission_asked@1307, permission_replied@1315 | none | ADD `request()` by moving OpenCodeTranslator::permission_record static method; used by asked/replied and contains no translator state. Own source/info/direct/native aliases precedence in `opencode/permission.rs`. | -| `PartEvent` :320 | handle@600, part_updated@906 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `PartTime` :344 | permission_properties@328 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolPartState` :350 | permission_properties@338 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `ToolAttachment` :364 | permission_properties@358, tool_result_content@1477 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `MessageInfo` :374 | handle@603, message_updated@1019 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `MessageTime` :398 | permission_properties@386 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | -| `PermissionRequest` :574 | begin_compacted@587, permission_record@1259 | none | KEEP data-only native envelope/leaf; ToolBefore/After conversions and PermissionProperties own normalization. Group with event, permission, or message family. | - -## bt-daemon/src/translate/opencode_v2/event.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `NativeEnvelope` :9 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Location` :17 | schema composition@11 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `EventMetadata` :21 | schema composition@12 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `NativeEvent` :28 | schema composition@14 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Session` :80 | schema composition@68 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Created` :85 | schema composition@30 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Inbox` :93 | schema composition@34 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Enqueued` :100 | schema composition@32 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `InboxItem` :109 | schema composition@105 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Prompt` :116 | schema composition@111 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `PromptSkill` :125 | schema composition@122 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `PromptFile` :129 | schema composition@120 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Model` :134 | schema composition@147 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `StepStarted` :141 | schema composition@40 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `StepEnded` :150 | schema composition@42 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `TextEnded` :159 | schema composition@46 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolInputStarted` :168 | schema composition@50 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolCalled` :177 | schema composition@52 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolSuccess` :186 | schema composition@54 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolFailed` :195 | schema composition@56 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `NativeError` :204 | schema composition@156 | none | KEEP transport fields; if message formatting repeated, From/Display conversion is justified. Current reducer can use error.message directly without wrapper. | -| `ErrorResponse` :214 | schema composition@209 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolContent` :219 | schema composition@192 | none | ADD `into_span_part()` to own native image file to image_url conversion; reused live tool success and context tool-result normalization. Unknown native content must remain exact. | -| `KnownToolContent` :225 | schema composition@220 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `PermissionAsked` :237 | schema composition@58 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `PermissionSource` :245 | schema composition@242 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `PermissionReplied` :251 | schema composition@60 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `CompactionStarted` :259 | schema composition@62 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `CompactionEnded` :266 | schema composition@64 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `NativeCompaction` :277 | schema composition@272 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `NativeMessages` :282 | schema composition@278 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `NativeContextMessage` :288 | schema composition@283 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `CompactionFailed` :293 | schema composition@66 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ExecutionFailed` :300 | schema composition@70 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Interrupted` :306 | schema composition@72 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `Context` :313 | schema composition@38 | none | ADD `into_messages()` / From for Vec by moving normalize_context; owns system join and native content expansion. Keep session correlation in reducer. Split `context.rs` and private media children; related wrappers may stay grouped. | -| `ContextMessage` :322 | schema composition@319 | none | ADD `into_messages()` if needed by Context::into_messages; one native message may expand into tool result(s) plus assistant. Preserve order. Own normalized conversion, not actor state. | -| `MessageContent` :328 | schema composition@290 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ContextPart` :335 | schema composition@330, deserialize@353 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `KnownContextPart` :370 | schema composition@336 | none | ADD `image_url()`/media_parts only if it removes nested field fallback from Context conversion; keep no generic getters for every variant. | -| `Media` :398 | deserialize@374 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `MediaSource` :405 | deserialize@400 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | -| `ToolResult` :418 | deserialize@395 | none | KEEP data-only native event/leaf shape: one event-dispatch arm or parent DTO consumes fields; move with event family, no independent method justified. | - -## bt-daemon/src/translate/opencode_v2/span.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `Content` :7 | new@92, tool@113, summary@119 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `ContentPart` :14 | schema composition@9, deserialize@46 | `text`, `image` | KEEP text/image constructors and exact Dynamic restoration; good ownership, split content.rs with TextPart/ImagePart/ImageUrl. | -| `TextPart` :31 | schema composition@15, text@48 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `ImagePart` :37 | schema composition@16, image@54 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `ImageUrl` :43 | deserialize@40, image@56 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `ToolCall` :61 | image@72, new@94 | `new` | KEEP new, owns JSON argument encoding and fixed kind. Split tool_call.rs with FunctionCall. | -| `FunctionCall` :68 | image@65, new@77 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `Reasoning` :85 | new@96 | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `Message` :90 | new@102 | `new`, `tool`, `summary` | KEEP new/tool/summary; good examples. Split message.rs with companion output content. | -| `RootMetadata` :125 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `TurnMetadata` :137 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `RootTotals` :143 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `ToolMetadata` :148 | summary@167 | `new` | KEEP new; optional skill application method only if common interaction repeated. Group metadata siblings in metadata.rs. | -| `LlmMetadata` :183 | field of enclosing DTO; consumed by parent decoder/reducer | none | KEEP data-only serialization companion; constructor or conversion belongs principal Message/ContentPart/ToolCall/Metrics owner. Group with that type or metadata family. | -| `Metrics` :191 | new@199 | `from_tokens` | KEEP from_tokens; it owns SDK metric naming/arithmetic. Do not push sink representation into native token struct. | - -## bt-daemon/src/translate/opencode_v2.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `CompactionResult` :103 | handle@682, compact@917 | none | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | - -## bt-daemon/src/translate/pi.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `BeforeAgentStart` :59 | start_turn@646 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `PromptImage` :71 | create@65 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `SelectedModel` :79 | decode@313, handle@372, ensure_root@570, capture_context@701 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `ContextEvent` :85 | capture_context@700 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `MessageUpdate` :93 | streaming_update@730 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `MessageDelta` :101 | create@95 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `ThinkingLevel` :107 | handle@392 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `AssistantMessage` :115 | message_end@746, response_model@1111, normalize_assistant@1335 | none | ADD `response_model()` and `normalized()` by moving existing free functions; owns seven-field model precedence and content traversal. Keep model selection policy in reducer. Move with AssistantContent to `translate/pi/assistant_message.rs`. | -| `AssistantContent` :157 | create@139, normalize_assistant@1341 | none | Keep variant payload data-only; owned/traversed by AssistantMessage::normalized. Co-locate with owner. | -| `ToolExecutionStart` :184 | tool_start@858 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `ToolExecutionEnd` :199 | tool_end@896 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `AgentEnd` :215 | handle@407 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `SessionCompact` :223 | handle@420, compaction_message@1065 | none | ADD `summary_message()` by moving compaction_message. Owns optional-entry/summary projection, called from Pi compact handler. Co-locate in `pi/compaction.rs`. | -| `CompactionEntry` :231 | create@225 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `Preparation` :243 | create@283 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `BeforeCompact` :275 | compaction_input@1076 | none | ADD `input()` by moving compaction_input; owns counts and preparation projection. Keep reducer correlation in PiTranslator. Move to `pi/compaction.rs`. | -| `BeforeTree` :291 | handle@426, branch_summary_input@1095 | none | ADD `input()` by moving branch_summary_input; owns preparation projection. Move to `pi/compaction.rs`. | -| `SessionTree` :299 | handle@449 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `LegacyContinuation` :1028 | legacy_continuation@1036 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `ResumePayload` :1038 | legacy_continuation@1049 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | -| `Resume` :1042 | legacy_continuation@1039 | none | KEEP data-only partial native event or private resume wire companion: decoded in one Pi event handler; move event leaves to pi/event.rs, not getters for each field. | - -## bt-daemon/src/translate/shared.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `CowSpanOp` :8 | from_arc@23, from@28, as_ref@33 | `new`, `make_mut`, `downgrade`, `from_arc` | KEEP new/make_mut/downgrade/from_arc/From/AsRef/Deref; already well-owned dedicated module. | - -## bt-daemon/src/translate/state.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `SinkFields` :8 | schema composition@15, restore@36, from@42 | `of`, `restore` | KEEP of/restore: explicitly owns sink-only state serialization. Row remains private adapter, do not export. | -| `Row` :33 | schema composition@6, restore@38, from@46, serialize@55 | `restore` | KEEP From/restore private serialization adapter; already colocated with owning sink fields. | - -## bt-daemon/src/translate/tool.rs - -| Type | Callers / use | Existing methods | Decision | -|---|---|---|---| -| `ToolApproval` :15 | schema composition@20, add_tool_approval@30, tool_approval_metadata@36, with_tool_approval@182 | `as_str` | KEEP data-only; one composition/dispatch consumer; retain related-family locality and avoid invented methods. | -| `SkillLoad` :66 | insert_skill_metadata@75, skill_file_load@120, skill_md_paths@133 | none | ADD `insert_metadata(metadata, requested)` and `display_name()` to own name/path fallback and shared skill metadata. Existing free insert_skill_metadata is called from Claude, Codex, Cursor, Pi, OpenCode; regex discovery stays separate. Move type/behavior to `translate/tool/skill_load.rs`. | - -## Runtime-state and implementation types explicitly excluded from DTO changes - -These own active lifecycle, I/O, caches, visitor state, or durable actor continuation. Serialization alone does not make them DTOs. Keep methods with state machines; splitting may improve large files, but do not convert them into passive schema models. -| File | Declarations | Reason | -|---|---|---| -| `transcript_import/antigravity.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/claude.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/codex.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/cursor.rs` | `Tail` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/mod.rs` | `IncrementalRecords`, `TranscriptTail` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/muse.rs` | `RunState`, `ModelState`, `PendingTool`, `Reader`, `EventsSeed`, `EventsVisitor`, `RecordsSeed`, `RecordsVisitor` | streaming reader / visitor / incremental filesystem state | -| `transcript_import/pipeline.rs` | `ImportProcessor` | streaming reader / visitor / incremental filesystem state | -| `translate/antigravity.rs` | `Turn`, `Invocation`, `PendingTool`, `AntigravityTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/claude.rs` | `Turn`, `PendingPrompt`, `TranscriptCursor`, `Subagent`, `PendingTool`, `PendingHistory`, `MessageHistory`, `HistoryMessage`, `PendingEmission`, `ClaudeTranslator`, `LlmCall`, `TranscriptTool` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/codex.rs` | `ScopeKind`, `OpenTurn`, `TurnInputSource`, `OpenLlm`, `OpenTool`, `Scope`, `DeferredHook`, `PendingWork`, `CodexTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/cursor/mod.rs` | `History`, `Turn`, `ModelStep`, `Tool`, `TranscriptCursor`, `CursorTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/debug.rs` | `DebugTranslatorFactory`, `DebugTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/git.rs` | `RepoEntry`, `NegativeEntry`, `CacheState`, `GitMetadataCache` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/grok.rs` | `BoundedOutput`, `OpenTurn`, `OpenLlm`, `OpenTool`, `CompletedTool`, `TranscriptCursor`, `PendingWork`, `GrokTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/mod.rs` | `Registry` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/muse.rs` | `OpenOp`, `Completed`, `MuseTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/muse_events.rs` | `Events` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/muse_usage.rs` | `UsageTracker` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/opencode.rs` | `OpenCodeVersionedTranslator`, `NativeSession`, `ClosedToolSpan`, `MessageHistory`, `HistoryEntry`, `CompactionBoundary`, `OpenCodeTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/opencode_v2.rs` | `SessionState`, `ToolState`, `Step`, `Permission`, `HistoryEntry`, `NativeWindow`, `Compaction`, `OpenCodeV2Translator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/origins.rs` | `WeakOrigins` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/pi.rs` | `PendingLlm`, `ToolStart`, `PiTranslator` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/recent.rs` | `RecentSet`, `RecentMap` | translator/session/span continuation, correlation state, bounded collection or process cache | -| `translate/turn_lineage.rs` | `TurnLineage` | translator/session/span continuation, correlation state, bounded collection or process cache | - -Inventory totals: 188 DTO / transfer/result declarations reviewed individually, 88 runtime/implementation declarations reviewed and excluded. Imported/re-exported schema aliases and test-only fixtures are not double-counted. Associated `type Value`/`Target` and Result aliases are trait plumbing, not DTO definitions.