innate 0.1.14

Innate — self-growing procedural knowledge layer for AI agents
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use super::{ui::gray, *};

pub(super) struct Agent {
    pub(super) id: &'static str,
    pub(super) label: String, // display name with "(detected)" suffix if found
    pub(super) detected: bool,
    pub(super) config: PathBuf,
}

pub(super) fn detect_agents(global: bool) -> Vec<Agent> {
    let home = home_dir();

    // Claude Code: global = ~/.claude.json (User MCPs), project = .claude/settings.json
    let claude_global = home.join(".claude.json");
    let claude_project = PathBuf::from(".claude").join("settings.json");
    let claude_config = if global {
        claude_global.clone()
    } else {
        claude_project
    };
    let claude_detected =
        claude_global.exists() || home.join(".claude").exists() || which_binary("claude").is_some();

    // Codex CLI: always global
    let codex_config = home.join(".codex").join("config.toml");
    let codex_detected = codex_config.exists() || which_binary("codex").is_some();

    // opencode: always global
    let opencode_config = home.join(".config").join("opencode").join("opencode.jsonc");
    let opencode_detected = opencode_config.exists() || which_binary("opencode").is_some();

    vec![
        Agent {
            id: "claude",
            label: if claude_detected {
                format!("Claude Code {}", gray("(detected)"))
            } else {
                "Claude Code".to_string()
            },
            detected: claude_detected,
            config: claude_config,
        },
        Agent {
            id: "codex",
            label: if codex_detected {
                format!("Codex CLI {}", gray("(detected)"))
            } else {
                "Codex CLI".to_string()
            },
            detected: codex_detected,
            config: codex_config,
        },
        Agent {
            id: "opencode",
            label: if opencode_detected {
                format!("opencode {}", gray("(detected)"))
            } else {
                "opencode".to_string()
            },
            detected: opencode_detected,
            config: opencode_config,
        },
    ]
}

pub(super) fn binary_name() -> &'static str {
    if cfg!(windows) {
        "innate.exe"
    } else {
        "innate"
    }
}

pub(super) fn path_sep() -> char {
    if cfg!(windows) {
        ';'
    } else {
        ':'
    }
}

pub(super) fn which_binary(name: &str) -> Option<PathBuf> {
    let exe = if cfg!(windows) && !name.ends_with(".exe") {
        format!("{name}.exe")
    } else {
        name.to_string()
    };
    std::env::var("PATH").ok().and_then(|path| {
        path.split(path_sep()).find_map(|dir| {
            let p = PathBuf::from(dir).join(&exe);
            if p.exists() {
                Some(p)
            } else {
                None
            }
        })
    })
}

// ── Config writers ────────────────────────────────────────────────────────────

#[derive(Debug)]
pub(super) enum ConfigStatus {
    Updated(PathBuf),
    Unchanged(PathBuf),
    Skipped(String),
    Error(String),
}

pub(super) fn configure_claude(agent: &Agent, binary: &Path, auto_allow: bool) -> ConfigStatus {
    let path = &agent.config;
    let mut settings: Value = match read_json_object(path) {
        Ok(v) => v,
        Err(e) => return ConfigStatus::Error(e),
    };

    let binary_str = binary.to_string_lossy().to_string();

    // Check current state
    let existing_cmd = settings
        .pointer("/mcpServers/innate/command")
        .and_then(Value::as_str)
        .unwrap_or("");
    let already_allowed = !auto_allow
        || settings
            .pointer("/permissions/allow")
            .and_then(Value::as_array)
            .map(|arr| arr.iter().any(|v| v.as_str() == Some("mcp__innate__*")))
            .unwrap_or(false);

    if existing_cmd == binary_str && already_allowed {
        return ConfigStatus::Unchanged(path.clone());
    }

    // Set mcpServers.innate (root is an object — guaranteed by read_json_object)
    let root = settings.as_object_mut().unwrap();
    let Some(mcp_servers) = root
        .entry("mcpServers")
        .or_insert(json!({}))
        .as_object_mut()
    else {
        return ConfigStatus::Error(format!(
            "{}: \"mcpServers\" is not an object",
            path.display()
        ));
    };
    mcp_servers.insert(
        "innate".to_string(),
        json!({
            "type": "stdio",
            "command": binary_str,
            "args": ["mcp"]
        }),
    );

    // Set permissions.allow
    if auto_allow {
        let Some(permissions) = root
            .entry("permissions")
            .or_insert(json!({}))
            .as_object_mut()
        else {
            return ConfigStatus::Error(format!(
                "{}: \"permissions\" is not an object",
                path.display()
            ));
        };
        let Some(arr) = permissions
            .entry("allow")
            .or_insert(json!([]))
            .as_array_mut()
        else {
            return ConfigStatus::Error(format!(
                "{}: \"permissions.allow\" is not an array",
                path.display()
            ));
        };
        let pat = "mcp__innate__*";
        if !arr.iter().any(|v| v.as_str() == Some(pat)) {
            arr.push(json!(pat));
        }
    }

    match write_json(path, &settings) {
        Ok(()) => ConfigStatus::Updated(path.clone()),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}

pub(super) fn configure_codex(agent: &Agent, binary: &Path, auto_allow: bool) -> ConfigStatus {
    let path = &agent.config;
    if !path.parent().map(|p| p.exists()).unwrap_or(false) {
        return ConfigStatus::Skipped("~/.codex/ not found — install Codex CLI first".to_string());
    }

    let existing = std::fs::read_to_string(path).unwrap_or_default();
    let binary_str = binary.to_string_lossy();

    // Check if already configured
    let already = existing.contains("[mcp_servers.innate]");
    if already {
        // Check if command matches
        if existing.contains(&format!("command = \"{binary_str}\"")) {
            return ConfigStatus::Unchanged(path.clone());
        }
    }

    let mut addition =
        format!("\n[mcp_servers.innate]\ncommand = \"{binary_str}\"\nargs = [\"mcp\"]\n");

    if auto_allow {
        for tool in INNATE_TOOLS {
            addition.push_str(&format!(
                "\n[mcp_servers.innate.tools.{tool}]\napproval_mode = \"auto\"\n"
            ));
        }
    }

    let new_content = if already {
        // Replace existing innate section (simplified: just append updated block at end)
        // Strip old innate block and append fresh one
        let stripped = strip_toml_section(&existing, "mcp_servers.innate");
        stripped + &addition
    } else {
        existing + &addition
    };

    match std::fs::write(path, new_content) {
        Ok(()) => ConfigStatus::Updated(path.clone()),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}

pub(super) fn configure_opencode(agent: &Agent, binary: &Path, _auto_allow: bool) -> ConfigStatus {
    let path = &agent.config;
    if !path.exists() {
        return ConfigStatus::Skipped("opencode.jsonc not found".into());
    }

    let txt = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) => return ConfigStatus::Error(e.to_string()),
    };

    let stripped = strip_jsonc_comments(&txt);
    let mut config: Value = match serde_json::from_str(&stripped) {
        Ok(v) => v,
        Err(e) => return ConfigStatus::Error(format!("parse error: {e}")),
    };

    let binary_str = binary.to_string_lossy().to_string();

    // Check if already configured
    if let Some(existing_cmd) = config.pointer("/mcp/innate/command") {
        let already = existing_cmd
            .as_array()
            .and_then(|a| a.first())
            .and_then(Value::as_str)
            == Some(&binary_str);
        if already {
            return ConfigStatus::Unchanged(path.clone());
        }
    }

    let Some(root) = config.as_object_mut() else {
        return ConfigStatus::Error(format!("{}: root is not a JSON object", path.display()));
    };
    let Some(mcp) = root.entry("mcp").or_insert(json!({})).as_object_mut() else {
        return ConfigStatus::Error(format!("{}: \"mcp\" is not an object", path.display()));
    };
    mcp.insert(
        "innate".to_string(),
        json!({
            "type": "local",
            "command": [binary_str, "mcp"],
            "enabled": true
        }),
    );

    match write_json(path, &config) {
        Ok(()) => ConfigStatus::Updated(path.clone()),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}
pub(super) fn remove_claude_config(config_path: &Path) -> ConfigStatus {
    if !config_path.exists() {
        return ConfigStatus::Skipped("not found".into());
    }
    let mut settings: Value = match read_json(config_path) {
        Some(v) => v,
        None => return ConfigStatus::Skipped("could not parse".into()),
    };
    let mut changed = false;

    if let Some(mcp) = settings.pointer_mut("/mcpServers") {
        if let Some(obj) = mcp.as_object_mut() {
            if obj.remove("innate").is_some() {
                changed = true;
            }
        }
    }
    if let Some(allow) = settings.pointer_mut("/permissions/allow") {
        if let Some(arr) = allow.as_array_mut() {
            let before = arr.len();
            arr.retain(|v| {
                !v.as_str()
                    .map(|s| s.starts_with("mcp__innate__"))
                    .unwrap_or(false)
            });
            if arr.len() != before {
                changed = true;
            }
        }
    }

    if !changed {
        return ConfigStatus::Unchanged(config_path.to_path_buf());
    }
    match write_json(config_path, &settings) {
        Ok(()) => ConfigStatus::Updated(config_path.to_path_buf()),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}

pub(super) fn remove_codex_config() -> ConfigStatus {
    let path = home_dir().join(".codex").join("config.toml");
    if !path.exists() {
        return ConfigStatus::Skipped("~/.codex/config.toml not found".into());
    }
    let content = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) => return ConfigStatus::Error(e.to_string()),
    };
    if !content.contains("[mcp_servers.innate]") {
        return ConfigStatus::Unchanged(path);
    }
    let stripped = strip_toml_section(&content, "mcp_servers.innate");
    match std::fs::write(&path, stripped) {
        Ok(()) => ConfigStatus::Updated(path),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}

pub(super) fn remove_opencode_config() -> ConfigStatus {
    let path = home_dir()
        .join(".config")
        .join("opencode")
        .join("opencode.jsonc");
    if !path.exists() {
        return ConfigStatus::Skipped("opencode.jsonc not found".into());
    }
    let txt = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) => return ConfigStatus::Error(e.to_string()),
    };
    let stripped = strip_jsonc_comments(&txt);
    let mut config: Value = match serde_json::from_str(&stripped) {
        Ok(v) => v,
        Err(e) => return ConfigStatus::Error(format!("parse error: {e}")),
    };
    let removed = config
        .pointer_mut("/mcp")
        .and_then(Value::as_object_mut)
        .and_then(|obj| obj.remove("innate"))
        .is_some();
    if !removed {
        return ConfigStatus::Unchanged(path);
    }
    match write_json(&path, &config) {
        Ok(()) => ConfigStatus::Updated(path),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}

/// Append a Stop hook entry to the Claude Code settings at `config_path`.
/// Uses the provided `binary` path so no Python interpreter is required.
pub(super) fn configure_claude_stop_hook(config_path: &Path, binary: &Path) -> ConfigStatus {
    configure_claude_hook(config_path, binary, "Stop", "hook stop")
}

/// Append a UserPromptSubmit hook that recalls relevant knowledge for every prompt.
/// This is the high-frequency, relevance-gated recall trigger (see `innate hook prompt`).
pub(super) fn configure_claude_prompt_hook(config_path: &Path, binary: &Path) -> ConfigStatus {
    configure_claude_hook(config_path, binary, "UserPromptSubmit", "hook prompt")
}

/// Append a SubagentStop hook so Task-tool subagents also feed session events to the daemon.
/// Reuses the same `hook stop` handler — the subagent stop payload carries the same transcript
/// reference, plus `agent_id`/`agent_type` for attribution.
pub(super) fn configure_claude_subagent_stop_hook(
    config_path: &Path,
    binary: &Path,
) -> ConfigStatus {
    configure_claude_hook(config_path, binary, "SubagentStop", "hook stop")
}

/// Append a SessionStart hook that warms up context with high-relevance project knowledge.
pub(super) fn configure_claude_session_start_hook(
    config_path: &Path,
    binary: &Path,
) -> ConfigStatus {
    configure_claude_hook(config_path, binary, "SessionStart", "hook session-start")
}

/// Generic Claude Code hook installer: append `<binary> <subcommand>` to `hooks.<event>`.
/// Idempotent — skips if the exact command is already present. No Python interpreter required.
fn configure_claude_hook(
    config_path: &Path,
    binary: &Path,
    event: &str,
    subcommand: &str,
) -> ConfigStatus {
    let mut settings: Value = match read_json_object(config_path) {
        Ok(v) => v,
        Err(e) => return ConfigStatus::Error(e),
    };

    // Quote the binary path in case it contains spaces.
    let binary_str = binary.to_string_lossy();
    let cmd = if binary_str.contains(' ') {
        format!("\"{binary_str}\" {subcommand}")
    } else {
        format!("{binary_str} {subcommand}")
    };

    // Idempotence check — skip if the command is already present.
    let already = settings
        .pointer(&format!("/hooks/{event}"))
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter().any(|h| {
                h.pointer("/hooks")
                    .and_then(Value::as_array)
                    .map(|cmds| {
                        cmds.iter()
                            .any(|c| c.get("command").and_then(Value::as_str) == Some(&cmd))
                    })
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false);

    if already {
        return ConfigStatus::Unchanged(config_path.to_path_buf());
    }

    // Root is an object — guaranteed by read_json_object.
    let Some(hooks_map) = settings
        .as_object_mut()
        .unwrap()
        .entry("hooks")
        .or_insert(json!({}))
        .as_object_mut()
    else {
        return ConfigStatus::Error(format!(
            "{}: \"hooks\" is not an object",
            config_path.display()
        ));
    };

    let Some(event_arr) = hooks_map.entry(event).or_insert(json!([])).as_array_mut() else {
        return ConfigStatus::Error(format!(
            "{}: \"hooks.{event}\" is not an array",
            config_path.display()
        ));
    };

    event_arr.push(json!({
        "hooks": [{"type": "command", "command": cmd}]
    }));

    match write_json(config_path, &settings) {
        Ok(()) => ConfigStatus::Updated(config_path.to_path_buf()),
        Err(e) => ConfigStatus::Error(e.to_string()),
    }
}