nexo-driver-loop 0.1.9

Goal orchestrator + LlmDecider + Unix socket bridge for the nexo-rs driver subsystem. Phase 67.4.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Driver runtime configuration. The full YAML at
//! `config/driver/claude.yaml` deserialises into [`DriverConfig`].
//!
//! Env-var substitution (`${VAR}` and `${VAR:-default}`) happens
//! *before* yaml parsing — same convention as `crates/config`.

use std::path::{Path, PathBuf};
use std::time::Duration;

use nexo_config::types::llm::AutoCompactionConfig;
use nexo_driver_types::{ExtractMemoriesConfig, SmCompactConfig};
use serde::Deserialize;

use crate::error::DriverError;

#[derive(Clone, Debug, Deserialize)]
pub struct DriverConfig {
    /// Top-level Claude CLI config (binary, default args, timeouts).
    /// Flattened from the YAML root for ergonomic access.
    #[serde(flatten)]
    pub claude: nexo_driver_claude::ClaudeConfig,
    #[serde(with = "humantime_serde", default = "default_setup_timeout")]
    pub setup_timeout: Duration,
    pub binding_store: BindingStoreConfig,
    pub permission: PermissionConfig,
    pub workspace: WorkspaceConfig,
    pub driver: DriverBinConfig,
    #[serde(default)]
    pub acceptance: AcceptanceConfig,
    /// Replay-policy + LlmDecider deny-shortcut tuning.
    #[serde(default)]
    pub replay_policy: ReplayPolicyConfig,
    /// Opportunistic /compact injection.
    #[serde(default)]
    pub compact_policy: CompactPolicyConfig,
}

#[derive(Clone, Debug, Deserialize)]
pub struct CompactPolicyConfig {
    #[serde(default = "default_compact_enabled")]
    pub enabled: bool,
    /// Model context window in tokens. `0` disables the policy.
    #[serde(default)]
    pub context_window: u64,
    #[serde(default = "default_compact_threshold")]
    pub threshold: f64,
    #[serde(default = "default_compact_min_gap")]
    pub min_turns_between_compacts: u32,
    /// Auto-compaction triggers (token pressure + age).
    #[serde(default)]
    pub auto: Option<AutoCompactionConfig>,
    /// Session-memory compact persistence config.
    #[serde(default)]
    pub sm_compact: Option<SmCompactConfig>,
    /// Post-turn memory extraction config.
    #[serde(default)]
    pub extract_memories: Option<ExtractMemoriesConfig>,
}

impl Default for CompactPolicyConfig {
    fn default() -> Self {
        Self {
            enabled: default_compact_enabled(),
            context_window: 0,
            threshold: default_compact_threshold(),
            min_turns_between_compacts: default_compact_min_gap(),
            auto: None,
            sm_compact: None,
            extract_memories: None,
        }
    }
}

fn default_compact_enabled() -> bool {
    true
}
fn default_compact_threshold() -> f64 {
    0.7
}
fn default_compact_min_gap() -> u32 {
    5
}

#[derive(Clone, Debug, Deserialize)]
pub struct ReplayPolicyConfig {
    #[serde(default = "default_max_fresh_session_retries")]
    pub max_fresh_session_retries: u32,
    #[serde(default)]
    pub deny_shortcut: DenyShortcutConfig,
}

impl Default for ReplayPolicyConfig {
    fn default() -> Self {
        Self {
            max_fresh_session_retries: default_max_fresh_session_retries(),
            deny_shortcut: DenyShortcutConfig::default(),
        }
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct DenyShortcutConfig {
    #[serde(default = "default_deny_shortcut_enabled")]
    pub enabled: bool,
    #[serde(default = "default_deny_shortcut_threshold")]
    pub threshold: f32,
    #[serde(default = "default_deny_shortcut_min_hits")]
    pub min_hits: usize,
}

impl Default for DenyShortcutConfig {
    fn default() -> Self {
        Self {
            enabled: default_deny_shortcut_enabled(),
            threshold: default_deny_shortcut_threshold(),
            min_hits: default_deny_shortcut_min_hits(),
        }
    }
}

fn default_max_fresh_session_retries() -> u32 {
    1
}
fn default_deny_shortcut_enabled() -> bool {
    true
}
fn default_deny_shortcut_threshold() -> f32 {
    0.6
}
fn default_deny_shortcut_min_hits() -> usize {
    3
}

#[derive(Clone, Debug, Deserialize)]
pub struct BindingStoreConfig {
    pub kind: BindingStoreKind,
    #[serde(default)]
    pub path: Option<PathBuf>,
    #[serde(default, with = "humantime_serde::option")]
    pub idle_ttl: Option<Duration>,
    #[serde(default, with = "humantime_serde::option")]
    pub max_age: Option<Duration>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BindingStoreKind {
    Sqlite,
    Memory,
}

#[derive(Clone, Debug, Deserialize)]
pub struct PermissionConfig {
    pub socket: PathBuf,
    #[serde(with = "humantime_serde", default = "default_decision_timeout")]
    pub decision_timeout: Duration,
    #[serde(default = "default_session_cache_max")]
    pub session_cache_max: usize,
    pub decider: DeciderConfig,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DeciderConfig {
    Llm {
        provider: String,
        #[serde(default)]
        model: Option<String>,
        #[serde(default = "default_decider_max_tokens")]
        max_tokens: u32,
        #[serde(default)]
        system_prompt_path: Option<PathBuf>,
        /// Semantic memory of past decisions.
        #[serde(default)]
        memory: Option<DeciderMemoryConfig>,
    },
    AllowAll,
    DenyAll {
        reason: String,
    },
}

#[derive(Clone, Debug, Deserialize)]
pub struct DeciderMemoryConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub path: Option<PathBuf>,
    pub embedding_provider: EmbeddingProviderConfig,
    #[serde(default = "default_recall_k")]
    pub recall_k: usize,
    #[serde(default)]
    pub namespace: NamespaceConfig,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NamespaceConfig {
    #[default]
    PerGoal,
    Global,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EmbeddingProviderConfig {
    Http {
        base_url: String,
        model: String,
        #[serde(default)]
        api_key_env: Option<String>,
    },
}

fn default_recall_k() -> usize {
    5
}

#[derive(Clone, Debug, Deserialize)]
pub struct WorkspaceConfig {
    pub root: PathBuf,
    #[serde(default)]
    pub cleanup_on_done: bool,
    #[serde(default)]
    pub git: WorkspaceGitConfig,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorkspaceGitConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub source_repo: Option<PathBuf>,
    #[serde(default = "default_base_ref")]
    pub base_ref: String,
}

fn default_base_ref() -> String {
    "HEAD".into()
}

#[derive(Clone, Debug, Deserialize)]
pub struct DriverBinConfig {
    pub bin_path: PathBuf,
    #[serde(default = "default_emit_nats_events")]
    pub emit_nats_events: bool,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct AcceptanceConfig {
    #[serde(default, with = "humantime_serde::option")]
    pub default_shell_timeout: Option<Duration>,
    /// Bytes of stdout+stderr attached as evidence on each
    /// `AcceptanceFailure`. Default 4 KiB.
    #[serde(default)]
    pub evidence_byte_limit: Option<usize>,
}

fn default_setup_timeout() -> Duration {
    Duration::from_secs(30)
}
fn default_decision_timeout() -> Duration {
    Duration::from_secs(30)
}
fn default_session_cache_max() -> usize {
    1024
}
fn default_decider_max_tokens() -> u32 {
    256
}
fn default_emit_nats_events() -> bool {
    true
}

impl DriverConfig {
    pub fn from_yaml_str(yaml: &str) -> Result<Self, DriverError> {
        let substituted = substitute_env_vars(yaml);
        serde_yaml::from_str(&substituted).map_err(|e| DriverError::Yaml(e.to_string()))
    }

    pub fn from_yaml_file(path: &Path) -> Result<Self, DriverError> {
        let raw = std::fs::read_to_string(path)?;
        Self::from_yaml_str(&raw)
    }
}

/// Substitute `${VAR}` and `${VAR:-default}` against process env.
/// Patterns we don't recognise are left intact.
fn substitute_env_vars(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    // `last_copy` marks the start of the next ASCII-safe slice we
    // owe to the output. Copying via `push_str(&input[..])` keeps
    // multi-byte UTF-8 (em-dashes, accents, …) intact — the
    // earlier byte-by-byte `as char` cast split codepoints into
    // bytes, and bytes like 0x80–0x9F are C1 control characters
    // that YAML rejects with "control characters are not allowed".
    let mut last_copy = 0;
    while i < bytes.len() {
        if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' {
            if let Some(end) = find_close_brace(bytes, i + 2) {
                let inner = &input[i + 2..end];
                let (name, fallback) = match inner.find(":-") {
                    Some(pos) => (&inner[..pos], Some(&inner[pos + 2..])),
                    None => (inner, None),
                };
                if is_var_name(name) {
                    out.push_str(&input[last_copy..i]);
                    let value = std::env::var(name).ok();
                    let resolved = value.as_deref().or(fallback).unwrap_or("");
                    out.push_str(resolved);
                    i = end + 1;
                    last_copy = i;
                    continue;
                }
            }
        }
        i += 1;
    }
    out.push_str(&input[last_copy..]);
    out
}

fn find_close_brace(bytes: &[u8], from: usize) -> Option<usize> {
    bytes[from..]
        .iter()
        .position(|&b| b == b'}')
        .map(|p| from + p)
}

fn is_var_name(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

#[cfg(test)]
mod tests {
    use super::*;

    const MIN_YAML: &str = r#"
binary: claude
binding_store:
  kind: memory
permission:
  socket: /tmp/driver.sock
  decider:
    kind: allow_all
workspace:
  root: /tmp/claude-runs
driver:
  bin_path: /usr/local/bin/nexo-driver-permission-mcp
"#;

    #[test]
    fn parses_minimum_yaml_with_defaults() {
        let cfg = DriverConfig::from_yaml_str(MIN_YAML).unwrap();
        assert_eq!(cfg.binding_store.kind, BindingStoreKind::Memory);
        assert!(matches!(cfg.permission.decider, DeciderConfig::AllowAll));
        assert_eq!(cfg.setup_timeout, Duration::from_secs(30));
        assert_eq!(cfg.permission.decision_timeout, Duration::from_secs(30));
        assert!(cfg.driver.emit_nats_events);
        assert!(!cfg.workspace.cleanup_on_done);
    }

    #[test]
    fn env_substitution_basic() {
        std::env::set_var("NEXO_DRIVER_TEST_PATH", "/run/x.sock");
        let yaml = r#"
binary: claude
binding_store:
  kind: memory
permission:
  socket: ${NEXO_DRIVER_TEST_PATH}
  decider: { kind: allow_all }
workspace:
  root: /tmp/claude-runs
driver:
  bin_path: /usr/local/bin/nexo-driver-permission-mcp
"#;
        let cfg = DriverConfig::from_yaml_str(yaml).unwrap();
        assert_eq!(cfg.permission.socket, PathBuf::from("/run/x.sock"));
        std::env::remove_var("NEXO_DRIVER_TEST_PATH");
    }

    #[test]
    fn env_substitution_with_default_fallback() {
        std::env::remove_var("NEXO_DRIVER_TEST_UNSET");
        let yaml = r#"
binary: claude
binding_store:
  kind: memory
permission:
  socket: ${NEXO_DRIVER_TEST_UNSET:-/fallback.sock}
  decider: { kind: allow_all }
workspace:
  root: /tmp/claude-runs
driver:
  bin_path: /usr/local/bin/nexo-driver-permission-mcp
"#;
        let cfg = DriverConfig::from_yaml_str(yaml).unwrap();
        assert_eq!(cfg.permission.socket, PathBuf::from("/fallback.sock"));
    }

    #[test]
    fn unknown_var_pattern_left_intact() {
        // `$NOT_BRACED` is not our pattern — we only handle `${...}`.
        let yaml = "$NOT_BRACED stays\n";
        let out = substitute_env_vars(yaml);
        assert_eq!(out, "$NOT_BRACED stays\n");
    }
}