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
47pub trait CommandPermissionsContext {
48    fn snapshot(&self) -> Result<PermissionsView, String>;
49    /// The host must lock, re-read and verify this token before atomic removal.
50    /// Index is zero-based; failure must not mutate the file.
51    fn remove_rule(
52        &mut self,
53        index: usize,
54        expected_token: &str,
55    ) -> Result<RemovedPermissionRule, String>;
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum StatusSafety {
60    ReadOnly {
61        enforced: bool,
62    },
63    WorkspaceWrite {
64        enforced: bool,
65        network_access: bool,
66    },
67    FullAccess {
68        no_new_privs: Option<bool>,
69    },
70    External,
71}
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct StatusFleetDrift {
74    pub name: String,
75    pub ids: Vec<String>,
76}
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum StatusSnapshotScope {
79    /// Snapshot-eligible content exceeds the configured workspace size cap.
80    WorkspaceTooLarge,
81    /// The entry ceiling is independent from the configurable size cap.
82    TooManyFiles,
83    /// Home/root locations remain refused regardless of the size setting.
84    UnsafeLocation,
85    /// Missing history was restarted; earlier restore points are gone.
86    HistoryRepaired,
87    /// A real git/disk failure; the notice limit field carries the error.
88    Failing,
89}
90#[derive(Debug, Clone, PartialEq, Eq)]
91/// Retained semantic observation shared by status and transient host notices.
92pub struct StatusSnapshotNotice {
93    pub workspace: String,
94    pub scope: StatusSnapshotScope,
95    pub limit: String,
96}
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum StatusContextSource {
99    Configured,
100    UserDeclared,
101    ConfiguredModel,
102    ProviderReported,
103    StaticKimiCodeSafeFloor,
104    Catalog,
105    NameSuffixHint,
106    Fallback,
107}
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum StatusWindowOverride {
110    Provider(String),
111    ActiveProvider,
112}
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum StatusCatalogFreshness {
115    Bundled,
116    Live,
117    Stale,
118    Failed,
119}
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct StatusCatalog {
122    pub freshness: StatusCatalogFreshness,
123    pub offering_count: usize,
124    pub fetched_at: Option<u64>,
125    pub last_error: Option<String>,
126}
127/// Same semantic inputs as the existing session metrics strip; no renderer dependency.
128#[derive(Debug, Clone, Copy, Default, PartialEq)]
129pub struct StatusMetrics {
130    pub turns: u64,
131    pub steps: u64,
132    pub llm_time: Duration,
133    pub tool_time: Duration,
134    pub ttft_avg: Option<Duration>,
135    pub tokens_per_second: Option<f64>,
136    pub cache_hit_percent: Option<u8>,
137    pub input_tokens: u64,
138}
139impl StatusMetrics {
140    #[must_use]
141    pub fn is_empty(&self) -> bool {
142        self.turns == 0 && self.steps == 0 && self.input_tokens == 0
143    }
144}
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146pub struct StatusToolOutputs {
147    pub raw_large_count: usize,
148    pub raw_large_chars: usize,
149    pub receipt_count: usize,
150    pub artifact_count: usize,
151    pub artifact_bytes: u64,
152}
153
154#[derive(Debug, Clone, PartialEq)]
155pub struct ConfigStatusView {
156    pub version: String,
157    pub provider: String,
158    pub model: String,
159    pub reasoning: String,
160    pub workspace: PathBuf,
161    pub home: Option<PathBuf>,
162    pub project_docs: Vec<String>,
163    pub mode: CommandMode,
164    pub approval_mode: CommandApprovalMode,
165    pub trusted: bool,
166    pub allow_shell: bool,
167    pub safety: StatusSafety,
168    pub mcp_configured_count: usize,
169    /// The raw missing pin, which may differ from the display model label.
170    pub model_pin_drift: Option<String>,
171    pub fleet_drift: Option<StatusFleetDrift>,
172    pub snapshot_notice: Option<StatusSnapshotNotice>,
173    pub context_used: usize,
174    pub context_window: u32,
175    pub context_source: StatusContextSource,
176    pub window_override: Option<StatusWindowOverride>,
177    pub catalog: StatusCatalog,
178    pub cloud_facts: CloudFactsState,
179    pub observed_at: u64,
180    pub session_id: Option<String>,
181    pub history_count: usize,
182    pub message_count: usize,
183    pub input_tokens: u32,
184    pub output_tokens: u32,
185    pub total_tokens: u32,
186    pub cache_hit_tokens: u32,
187    pub cache_miss_tokens: u32,
188    pub cost: f64,
189    pub currency: CommandCurrency,
190    pub metrics: StatusMetrics,
191    pub ascii_safe: bool,
192    pub tool_outputs: StatusToolOutputs,
193}
194
195/// Read-only observations; optional failures are represented by absent fields.
196/// No config/session mutation, provider refresh or rendered-report callback.
197pub trait CommandConfigStatusContext {
198    fn snapshot(&self) -> ConfigStatusView;
199}
200
201/// The size-cap remedy is shared by the status report and host toast.
202pub const SNAPSHOTS_CAP_CONFIG_KEY: &str = "[snapshots] max_workspace_gb";
203impl StatusSnapshotNotice {
204    pub fn render(&self, template: &str) -> String {
205        codewhale_protocol::display::interpolate(
206            template,
207            &[
208                ("{workspace}", &self.workspace),
209                ("{limit}", &self.limit),
210                ("{config_key}", SNAPSHOTS_CAP_CONFIG_KEY),
211            ],
212        )
213    }
214}