Skip to main content

codewhale_command_contract/
config_policy.rs

1//! Policy/status observations only. Hosts own persistence, runtime services and I/O.
2//! These values do not grant authority to edit configuration or operate a session.
3use crate::types::{CommandApprovalMode, CommandCurrency, CommandMode};
4use codewhale_protocol::cloud_facts::CloudFactsState;
5use std::path::PathBuf;
6use std::time::Duration;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum CommandPermissionAction {
10    Allow,
11    Ask,
12    Deny,
13}
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum CommandPermissionsFileState {
16    Missing,
17    Empty,
18    Present,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct PermissionRule {
23    pub action: CommandPermissionAction,
24    pub tool: String,
25    pub command: Option<String>,
26    pub command_exact: bool,
27    pub path: Option<String>,
28    pub workspace: Option<String>,
29    pub applies_here: bool,
30    /// Opaque host-generated token, kept with the rule it confirms.
31    pub removal_token: String,
32}
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct PermissionsView {
35    pub path: PathBuf,
36    pub file_state: CommandPermissionsFileState,
37    pub rules: Vec<PermissionRule>,
38    pub approval_mode: CommandApprovalMode,
39    pub audit_path: Option<PathBuf>,
40}
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct RemovedPermissionRule {
43    pub action: CommandPermissionAction,
44    pub tool: String,
45}
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct BlockedPermissionAction {
48    pub receipt_id: Option<String>,
49    pub tool_name: String,
50    pub rule: String,
51    pub reason: String,
52    pub action_summary: String,
53    pub approvable: bool,
54    pub approved: bool,
55}
56
57pub trait CommandPermissionsContext {
58    fn snapshot(&self) -> Result<PermissionsView, String>;
59    /// The host must lock, re-read and verify this token before atomic removal.
60    /// Index is zero-based; failure must not mutate the file.
61    fn remove_rule(
62        &mut self,
63        index: usize,
64        expected_token: &str,
65    ) -> Result<RemovedPermissionRule, String>;
66    fn blocked_actions(&self) -> Vec<BlockedPermissionAction> {
67        Vec::new()
68    }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum StatusSafety {
73    ReadOnly {
74        enforced: bool,
75    },
76    WorkspaceWrite {
77        enforced: bool,
78        network_access: bool,
79    },
80    FullAccess {
81        no_new_privs: Option<bool>,
82    },
83    External,
84}
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct StatusFleetDrift {
87    pub name: String,
88    pub ids: Vec<String>,
89}
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum StatusSnapshotScope {
92    /// Snapshot-eligible content exceeds the configured workspace size cap.
93    WorkspaceTooLarge,
94    /// The entry ceiling is independent from the configurable size cap.
95    TooManyFiles,
96    /// Home/root locations remain refused regardless of the size setting.
97    UnsafeLocation,
98    /// Missing history was restarted; earlier restore points are gone.
99    HistoryRepaired,
100    /// A real git/disk failure; the notice limit field carries the error.
101    Failing,
102}
103#[derive(Debug, Clone, PartialEq, Eq)]
104/// Retained semantic observation shared by status and transient host notices.
105pub struct StatusSnapshotNotice {
106    pub workspace: String,
107    pub scope: StatusSnapshotScope,
108    pub limit: String,
109}
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum StatusContextSource {
112    Configured,
113    UserDeclared,
114    ConfiguredModel,
115    ProviderReported,
116    StaticKimiCodeSafeFloor,
117    Catalog,
118    NameSuffixHint,
119    Fallback,
120}
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum StatusWindowOverride {
123    Provider(String),
124    ActiveProvider,
125}
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum StatusCatalogFreshness {
128    Bundled,
129    Live,
130    Stale,
131    Failed,
132}
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct StatusCatalog {
135    pub freshness: StatusCatalogFreshness,
136    pub offering_count: usize,
137    pub fetched_at: Option<u64>,
138    pub last_error: Option<String>,
139}
140/// Same semantic inputs as the existing session metrics strip; no renderer dependency.
141#[derive(Debug, Clone, Copy, Default, PartialEq)]
142pub struct StatusMetrics {
143    pub turns: u64,
144    pub steps: u64,
145    pub llm_time: Duration,
146    pub tool_time: Duration,
147    pub ttft_avg: Option<Duration>,
148    pub tokens_per_second: Option<f64>,
149    pub cache_hit_percent: Option<u8>,
150    pub input_tokens: u64,
151}
152impl StatusMetrics {
153    #[must_use]
154    pub fn is_empty(&self) -> bool {
155        self.turns == 0 && self.steps == 0 && self.input_tokens == 0
156    }
157}
158#[derive(Debug, Clone, Default, PartialEq, Eq)]
159pub struct StatusToolOutputs {
160    pub raw_large_count: usize,
161    pub raw_large_chars: usize,
162    pub receipt_count: usize,
163    pub artifact_count: usize,
164    pub artifact_bytes: u64,
165}
166
167#[derive(Debug, Clone, PartialEq)]
168pub struct ConfigStatusView {
169    pub version: String,
170    pub provider: String,
171    pub model: String,
172    pub reasoning: String,
173    pub workspace: PathBuf,
174    pub home: Option<PathBuf>,
175    pub project_docs: Vec<String>,
176    pub mode: CommandMode,
177    pub approval_mode: CommandApprovalMode,
178    pub trusted: bool,
179    pub allow_shell: bool,
180    pub safety: StatusSafety,
181    pub mcp_configured_count: usize,
182    /// The raw missing pin, which may differ from the display model label.
183    pub model_pin_drift: Option<String>,
184    pub fleet_drift: Option<StatusFleetDrift>,
185    pub snapshot_notice: Option<StatusSnapshotNotice>,
186    pub context_used: usize,
187    pub context_window: u32,
188    pub context_source: StatusContextSource,
189    pub window_override: Option<StatusWindowOverride>,
190    pub catalog: StatusCatalog,
191    pub cloud_facts: CloudFactsState,
192    pub observed_at: u64,
193    pub session_id: Option<String>,
194    pub history_count: usize,
195    pub message_count: usize,
196    pub input_tokens: u32,
197    pub output_tokens: u32,
198    pub total_tokens: u32,
199    pub cache_hit_tokens: u32,
200    pub cache_miss_tokens: u32,
201    pub cost: f64,
202    pub currency: CommandCurrency,
203    pub cost_label: Option<String>,
204    pub metrics: StatusMetrics,
205    pub ascii_safe: bool,
206    pub tool_outputs: StatusToolOutputs,
207}
208
209/// Read-only observations; optional failures are represented by absent fields.
210/// No config/session mutation, provider refresh or rendered-report callback.
211pub trait CommandConfigStatusContext {
212    fn snapshot(&self) -> ConfigStatusView;
213}
214
215/// The size-cap remedy is shared by the status report and host toast.
216pub const SNAPSHOTS_CAP_CONFIG_KEY: &str = "[snapshots] max_workspace_gb";
217impl StatusSnapshotNotice {
218    pub fn render(&self, template: &str) -> String {
219        codewhale_protocol::display::interpolate(
220            template,
221            &[
222                ("{workspace}", &self.workspace),
223                ("{limit}", &self.limit),
224                ("{config_key}", SNAPSHOTS_CAP_CONFIG_KEY),
225            ],
226        )
227    }
228}