haiai 0.2.2

Rust SDK for HAI.AI agent benchmarking, designed as a JACS-delegating wrapper
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
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::{HaiError, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    pub jacs_agent_name: String,
    pub jacs_agent_version: String,
    pub jacs_key_dir: PathBuf,
    pub jacs_id: Option<String>,
    pub jacs_private_key_path: Option<PathBuf>,
    pub source_path: PathBuf,
    /// Cached @hai.ai email address for this agent.
    pub agent_email: Option<String>,
}

/// Load `jacs.config.json`.
///
/// Discovery order:
/// 1. explicit `path`
/// 2. `JACS_CONFIG_PATH`
/// 3. `./jacs.config.json`
pub fn load_config(path: Option<&Path>) -> Result<AgentConfig> {
    let source_path = resolve_config_path(path);
    if !source_path.is_file() {
        return Err(HaiError::ConfigNotFound {
            path: source_path.display().to_string(),
        });
    }

    let raw = fs::read_to_string(&source_path).map_err(|e| HaiError::ConfigInvalid {
        message: format!("failed to read {}: {e}", source_path.display()),
    })?;
    let data: Value = serde_json::from_str(&raw)?;

    let config_dir = source_path.parent().unwrap_or_else(|| Path::new("."));

    let jacs_agent_name = get_string(&data, &["jacsAgentName", "agent_name"]).ok_or_else(|| {
        HaiError::ConfigInvalid {
            message: "jacsAgentName (or agent_name) is required but missing".to_string(),
        }
    })?;
    let jacs_agent_version = get_string(&data, &["jacsAgentVersion", "agent_version"])
        .unwrap_or_else(|| "1.0.0".to_string());

    let key_dir_raw =
        get_string(&data, &["jacsKeyDir", "key_dir"]).unwrap_or_else(|| ".".to_string());
    let jacs_key_dir = if Path::new(&key_dir_raw).is_absolute() {
        PathBuf::from(key_dir_raw)
    } else {
        config_dir.join(key_dir_raw)
    };

    let jacs_id = get_string(&data, &["jacsId", "jacs_id"]);
    if jacs_id.is_none() {
        return Err(HaiError::ConfigInvalid {
            message: "jacsId (or jacs_id) is required but missing".to_string(),
        });
    }

    let private_key_raw = get_string(&data, &["jacsPrivateKeyPath", "private_key_path"]);
    let jacs_private_key_path = private_key_raw.map(|p| {
        if Path::new(&p).is_absolute() {
            PathBuf::from(p)
        } else {
            config_dir.join(p)
        }
    });

    let agent_email = get_string(&data, &["agent_email", "agentEmail"]);

    Ok(AgentConfig {
        jacs_agent_name,
        jacs_agent_version,
        jacs_key_dir,
        jacs_id,
        jacs_private_key_path,
        source_path,
        agent_email,
    })
}

pub fn resolve_private_key_candidates(config: &AgentConfig) -> Vec<PathBuf> {
    let mut candidates = Vec::new();
    if let Some(explicit) = &config.jacs_private_key_path {
        candidates.push(explicit.clone());
    }

    candidates.push(config.jacs_key_dir.join("agent_private_key.pem"));
    candidates.push(
        config
            .jacs_key_dir
            .join(format!("{}.private.pem", config.jacs_agent_name)),
    );
    candidates.push(config.jacs_key_dir.join("private_key.pem"));

    candidates
}

fn resolve_config_path(path: Option<&Path>) -> PathBuf {
    if let Some(path) = path {
        return path.to_path_buf();
    }

    if let Ok(path) = env::var("JACS_CONFIG_PATH") {
        if !path.is_empty() {
            return PathBuf::from(path);
        }
    }

    PathBuf::from("./jacs.config.json")
}

/// Validate a routed backend label for DocumentService-backed operations.
///
/// Accepts: `fs`, `rusqlite`, `sqlite` (alias for `rusqlite`).
/// Returns the canonical label on success, or an error with valid options on failure.
pub fn resolve_storage_backend_label(label: &str) -> Result<String> {
    match label {
        "fs" => Ok("fs".to_string()),
        "rusqlite" | "sqlite" => Ok("rusqlite".to_string()),
        other => Err(HaiError::ConfigInvalid {
            message: format!(
                "Unsupported storage backend '{}'. Valid routed labels: fs, rusqlite, sqlite",
                other
            ),
        }),
    }
}

/// Resolve which storage backend to use with priority:
/// 1. Explicit parameter (CLI `--storage` flag)
/// 2. `JACS_STORAGE` env var
/// 3. `default_storage` field in `jacs.config.json`
/// 4. `"fs"` default
pub fn resolve_storage_backend(
    explicit: Option<&str>,
    config_path: Option<&Path>,
) -> Result<String> {
    // Priority 1: explicit parameter
    if let Some(label) = explicit {
        return resolve_storage_backend_label(label);
    }

    // Priority 2: JACS_STORAGE env var
    if let Ok(label) = env::var("JACS_STORAGE") {
        if !label.is_empty() {
            return resolve_storage_backend_label(&label);
        }
    }

    // Priority 3: default_storage in config
    let config_path_resolved = resolve_config_path(config_path);
    if config_path_resolved.is_file() {
        if let Ok(raw) = fs::read_to_string(&config_path_resolved) {
            if let Ok(data) = serde_json::from_str::<Value>(&raw) {
                if let Some(label) = get_string(&data, &["default_storage", "defaultStorage"]) {
                    return resolve_storage_backend_label(&label);
                }
            }
        }
    }

    // Priority 4: default to fs
    Ok("fs".to_string())
}

/// A storage configuration summary safe for logging/display.
///
/// Never includes passwords, connection strings, or credentials.
/// Complies with PRD Section 4.4.6: "Never log backend configuration details."
#[derive(Debug, Clone, Serialize)]
pub struct StorageConfigSummary {
    pub backend: String,
    pub source: &'static str,
}

impl std::fmt::Display for StorageConfigSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "backend={} (from {})", self.backend, self.source)
    }
}

/// Return a redacted summary of the resolved storage configuration.
///
/// This is safe for logging, CLI output, and error messages.
/// It reports the backend label and its resolution source, but never
/// exposes connection strings, passwords, or file system paths.
pub fn redacted_display(explicit: Option<&str>, config_path: Option<&Path>) -> StorageConfigSummary {
    // Priority 1: explicit parameter
    if let Some(label) = explicit {
        return StorageConfigSummary {
            backend: label.to_string(),
            source: "--storage flag",
        };
    }

    // Priority 2: JACS_STORAGE env var
    if let Ok(label) = env::var("JACS_STORAGE") {
        if !label.is_empty() {
            return StorageConfigSummary {
                backend: label,
                source: "JACS_STORAGE env var",
            };
        }
    }

    // Priority 3: config file
    let config_path_resolved = resolve_config_path(config_path);
    if config_path_resolved.is_file() {
        if let Ok(raw) = fs::read_to_string(&config_path_resolved) {
            if let Ok(data) = serde_json::from_str::<Value>(&raw) {
                if let Some(label) = get_string(&data, &["default_storage", "defaultStorage"]) {
                    return StorageConfigSummary {
                        backend: label,
                        source: "config file",
                    };
                }
            }
        }
    }

    // Priority 4: default
    StorageConfigSummary {
        backend: "fs".to_string(),
        source: "default",
    }
}

fn get_string(data: &Value, keys: &[&str]) -> Option<String> {
    for key in keys {
        if let Some(value) = data.get(key).and_then(Value::as_str) {
            return Some(value.to_string());
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;

    #[test]
    fn resolves_relative_paths_from_config_location() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("nested").join("jacs.config.json");
        fs::create_dir_all(config_path.parent().expect("parent")).expect("mkdir");

        fs::write(
            &config_path,
            r#"{
  "jacsAgentName": "agent",
  "jacsAgentVersion": "1.0.0",
  "jacsKeyDir": "./keys",
  "jacsPrivateKeyPath": "./custom/private.pem",
  "jacsId": "agent-1"
}"#,
        )
        .expect("write config");

        let cfg = load_config(Some(&config_path)).expect("load");
        assert!(cfg.jacs_key_dir.ends_with("nested/keys"));
        assert!(cfg
            .jacs_private_key_path
            .expect("private key path")
            .ends_with("nested/custom/private.pem"));
    }

    // ── Issue #8: required config fields ─────────────────────────────────

    #[test]
    fn load_config_errors_when_jacs_agent_name_missing() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"jacsId": "agent-1", "jacsAgentVersion": "2.0.0"}"#,
        )
        .expect("write config");

        let result = load_config(Some(&config_path));
        assert!(result.is_err(), "missing jacs_agent_name should be an error");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("jacsAgentName") || err.contains("agent_name"),
            "error should mention the missing field: {err}"
        );
    }

    #[test]
    fn load_config_errors_when_jacs_id_missing() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"jacsAgentName": "my-agent", "jacsAgentVersion": "2.0.0"}"#,
        )
        .expect("write config");

        let result = load_config(Some(&config_path));
        assert!(result.is_err(), "missing jacs_id should be an error");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("jacsId") || err.contains("jacs_id"),
            "error should mention the missing field: {err}"
        );
    }

    #[test]
    fn load_config_defaults_version_and_key_dir() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"jacsAgentName": "my-agent", "jacsId": "agent-1"}"#,
        )
        .expect("write config");

        let cfg = load_config(Some(&config_path)).expect("should succeed with defaults for version and key_dir");
        assert_eq!(cfg.jacs_agent_version, "1.0.0");
        assert_eq!(cfg.jacs_agent_name, "my-agent");
        assert_eq!(cfg.jacs_id, Some("agent-1".to_string()));
    }

    #[test]
    fn redacted_display_explicit_flag() {
        let summary = redacted_display(Some("rusqlite"), None);
        assert_eq!(summary.backend, "rusqlite");
        assert_eq!(summary.source, "--storage flag");
        // Display trait should never expose connection details
        let rendered = format!("{}", summary);
        assert!(rendered.contains("rusqlite"));
        assert!(rendered.contains("--storage flag"));
    }

    #[test]
    fn redacted_display_default_fallback() {
        // When nothing is configured, should return fs/default.
        // Note: this test may pick up JACS_STORAGE from the environment.
        // We temporarily clear it for a clean test.
        let orig = env::var("JACS_STORAGE").ok();
        env::remove_var("JACS_STORAGE");

        let summary = redacted_display(None, Some(Path::new("/nonexistent/path.json")));
        assert_eq!(summary.backend, "fs");
        assert_eq!(summary.source, "default");

        if let Some(val) = orig {
            env::set_var("JACS_STORAGE", val);
        }
    }

    #[test]
    fn redacted_display_from_config_file() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"default_storage": "sqlite", "jacsAgentName": "test"}"#,
        )
        .expect("write config");

        let orig = env::var("JACS_STORAGE").ok();
        env::remove_var("JACS_STORAGE");

        let summary = redacted_display(None, Some(&config_path));
        assert_eq!(summary.backend, "sqlite");
        assert_eq!(summary.source, "config file");

        if let Some(val) = orig {
            env::set_var("JACS_STORAGE", val);
        }
    }

    #[test]
    fn load_config_reads_agent_email() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"jacsAgentName": "bot", "jacsId": "a-1", "agent_email": "bot@hai.ai"}"#,
        )
        .expect("write config");

        let cfg = load_config(Some(&config_path)).expect("load");
        assert_eq!(cfg.agent_email, Some("bot@hai.ai".to_string()));
    }

    #[test]
    fn load_config_agent_email_absent_is_none() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("jacs.config.json");
        fs::write(
            &config_path,
            r#"{"jacsAgentName": "bot", "jacsId": "a-1"}"#,
        )
        .expect("write config");

        let cfg = load_config(Some(&config_path)).expect("load");
        assert_eq!(cfg.agent_email, None);
    }
}