omk 0.5.0

A Rust runtime for Kimi CLI. Turns prompts into proof-backed engineering runs with gates, worktrees, and replay.
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
477
478
479
480
481
482
483
use omk::runtime::events::{EventKind, EventWriter, RunId};
use omk::runtime::wire_worker::hook_executor::{
    discover_hook_subscriptions, HookExecutor, HookResult,
};
use omk::wire::protocol::HookRequest;
use std::path::PathBuf;
use tempfile::TempDir;
use tokio::time::Duration;

fn make_script(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
    let path = dir.join(name);
    std::fs::write(&path, content).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
    }
    path
}

#[tokio::test]
async fn test_discover_hooks_from_config_toml() {
    let tmp = TempDir::new().unwrap();
    let kimi = tmp.path().join(".kimi");
    let hooks_dir = kimi.join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(&hooks_dir, "safety-check.sh", "#!/bin/bash\nexit 0\n");
    make_script(&hooks_dir, "notify.sh", "#!/bin/bash\nexit 0\n");

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/safety-check.sh"
matcher = "WriteFile"
timeout = 10

[[hooks]]
event = "SubagentStart"
command = ".kimi/hooks/notify.sh"
timeout = 5
"#;
    std::fs::write(kimi.join("config.toml"), config).unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert_eq!(subs.len(), 2);

    let pre_tool = subs.iter().find(|s| s.event == "PreToolUse").unwrap();
    assert_eq!(pre_tool.id, "pre_tool_use-writefile");
    assert_eq!(pre_tool.matcher.as_deref(), Some("WriteFile"));
    assert_eq!(pre_tool.timeout, Some(10));

    let subagent = subs.iter().find(|s| s.event == "SubagentStart").unwrap();
    assert_eq!(subagent.id, "subagent_start");
    assert_eq!(subagent.matcher, None);
    assert_eq!(subagent.timeout, Some(5));
}

#[tokio::test]
async fn test_discover_hooks_fallback_to_defaults() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    // Only install one default hook — only that one should be discovered.
    make_script(&hooks_dir, "safety-check.sh", "#!/bin/bash\nexit 0\n");

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert_eq!(subs.len(), 1);
    assert_eq!(subs[0].event, "PreToolUse");
    assert_eq!(subs[0].id, "pre_tool_use-writefile|strreplacefile");
    assert_eq!(
        subs[0].matcher,
        Some("WriteFile|StrReplaceFile".to_string())
    );
    assert_eq!(subs[0].timeout, Some(10));
}

#[tokio::test]
#[cfg(unix)]
async fn test_discover_hooks_skips_non_executable() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    // Write script but do NOT chmod +x
    let path = hooks_dir.join("safety-check.sh");
    std::fs::write(&path, "#!/bin/bash\nexit 0\n").unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert!(subs.is_empty());
}

#[tokio::test]
async fn test_discover_hooks_malformed_config_ignores_hooks() {
    let tmp = TempDir::new().unwrap();
    let kimi = tmp.path().join(".kimi");
    let hooks_dir = kimi.join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(&hooks_dir, "safety-check.sh", "#!/bin/bash\nexit 0\n");

    // Invalid TOML
    std::fs::write(kimi.join("config.toml"), "[[hooks\nevent = bad").unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    // Malformed config logs a warning and returns empty subscriptions
    assert!(subs.is_empty());
}

#[tokio::test]
async fn test_discover_hooks_empty_hooks_list() {
    let tmp = TempDir::new().unwrap();
    let kimi = tmp.path().join(".kimi");
    std::fs::create_dir_all(kimi.join("hooks")).unwrap();

    std::fs::write(kimi.join("config.toml"), "hooks = []\n").unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert!(subs.is_empty());
}

#[tokio::test]
async fn test_discover_hooks_timeout_clamped_to_300() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(&hooks_dir, "safety-check.sh", "#!/bin/bash\nexit 0\n");

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/safety-check.sh"
timeout = 500
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert_eq!(subs[0].timeout, Some(300));
}

#[tokio::test]
async fn test_discover_hooks_zero_timeout_clamped_to_1() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(&hooks_dir, "safety-check.sh", "#!/bin/bash\nexit 0\n");

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/safety-check.sh"
timeout = 0
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let subs = discover_hook_subscriptions(Some(tmp.path())).await;
    assert_eq!(subs[0].timeout, Some(1));
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_allow_on_exit_zero() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(
        &hooks_dir,
        "safety-check.sh",
        "#!/bin/bash\necho 'safe'\nexit 0\n",
    );

    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "pre_tool_use".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({"file": "/tmp/test"}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert_eq!(result.reason, "safe");
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_block_on_exit_one() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(
        &hooks_dir,
        "safety-check.sh",
        "#!/bin/bash\necho 'blocked'\nexit 1\n",
    );

    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Block);
    assert_eq!(result.reason, "blocked");
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_block_on_nonzero_exit() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(
        &hooks_dir,
        "safety-check.sh",
        "#!/bin/bash\necho 'error' >&2\nexit 42\n",
    );

    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Block);
    assert!(result.reason.contains("42"));
    assert!(result.reason.contains("error"));
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_timeout() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    // Script that sleeps longer than the subscription timeout.
    make_script(&hooks_dir, "slow.sh", "#!/bin/bash\nsleep 10\nexit 0\n");

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/slow.sh"
timeout = 1
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({}),
    };

    let start = std::time::Instant::now();
    let result = executor.run(&request).await.unwrap();
    let elapsed = start.elapsed();

    assert_eq!(result.action, omk::wire::protocol::HookAction::Block);
    assert!(result.reason.contains("timed out"));
    assert!(
        elapsed < Duration::from_secs(5),
        "hook should have timed out quickly"
    );
}

#[tokio::test]
async fn test_hook_executor_default_allow_when_no_match() {
    let tmp = TempDir::new().unwrap();
    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "UnknownEvent".to_string(),
        target: "something".to_string(),
        input_data: serde_json::json!({}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert!(result.reason.contains("No matching hook"));
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_subscription_id_fast_path() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(
        &hooks_dir,
        "safety-check.sh",
        "#!/bin/bash\necho 'fast'\nexit 0\n",
    );

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/safety-check.sh"
matcher = "WriteFile|StrReplaceFile"
timeout = 10
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let executor = HookExecutor::new(tmp.path());
    // Use subscription_id to match directly, bypassing regex matcher
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "pre_tool_use-writefile|strreplacefile".to_string(),
        event: "PreToolUse".to_string(),
        target: "ReadFile".to_string(), // target does NOT match the regex
        input_data: serde_json::json!({}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert_eq!(result.reason, "fast");
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_regex_matcher_matching() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(
        &hooks_dir,
        "safety-check.sh",
        "#!/bin/bash\necho 'regex-match'\nexit 0\n",
    );

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/safety-check.sh"
matcher = "Write.*"
timeout = 10
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let executor = HookExecutor::new(tmp.path());

    // Positive match
    let req_match = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({}),
    };
    let result = executor.run(&req_match).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert_eq!(result.reason, "regex-match");

    // Negative match — should default allow
    let req_no_match = HookRequest {
        id: "hook_2".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "ReadFile".to_string(),
        input_data: serde_json::json!({}),
    };
    let result = executor.run(&req_no_match).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert!(result.reason.contains("No matching hook"));
}

#[tokio::test]
#[cfg(unix)]
async fn test_hook_executor_stdin_input_delivery() {
    let tmp = TempDir::new().unwrap();
    let hooks_dir = tmp.path().join(".kimi").join("hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();

    make_script(&hooks_dir, "echo-stdin.sh", "#!/bin/bash\ncat\nexit 0\n");

    let config = r#"
[[hooks]]
event = "PreToolUse"
command = ".kimi/hooks/echo-stdin.sh"
timeout = 10
"#;
    std::fs::write(tmp.path().join(".kimi").join("config.toml"), config).unwrap();

    let executor = HookExecutor::new(tmp.path());
    let request = HookRequest {
        id: "hook_1".to_string(),
        subscription_id: "".to_string(),
        event: "PreToolUse".to_string(),
        target: "WriteFile".to_string(),
        input_data: serde_json::json!({"key": "value"}),
    };

    let result = executor.run(&request).await.unwrap();
    assert_eq!(result.action, omk::wire::protocol::HookAction::Allow);
    assert!(result.reason.contains("key"));
    assert!(result.reason.contains("value"));
}

#[test]
fn test_hook_result_response_value() {
    let result = HookResult {
        action: omk::wire::protocol::HookAction::Allow,
        reason: "all good".to_string(),
    };
    let value = result.to_response_value("req-42");
    assert_eq!(value["request_id"], "req-42");
    assert_eq!(value["action"], "allow");
    assert_eq!(value["reason"], "all good");

    let block = HookResult {
        action: omk::wire::protocol::HookAction::Block,
        reason: "nope".to_string(),
    };
    let value = block.to_response_value("req-43");
    assert_eq!(value["action"], "block");
    assert_eq!(value["reason"], "nope");
}

#[tokio::test]
async fn test_hook_event_writer_serialization() {
    let tmp = TempDir::new().unwrap();
    let events_path = tmp.path().join("events.jsonl");
    let writer = EventWriter::new(&events_path);
    let run_id = RunId("run-hook".to_string());

    let triggered = omk::runtime::events::Event::new(run_id.clone(), EventKind::HookTriggered)
        .with_actor("worker-1")
        .with_payload(serde_json::json!({
            "event": "PreToolUse",
            "target": "WriteFile",
            "hook_count": 1,
        }))
        .unwrap();
    writer.append(&triggered).await.unwrap();

    let resolved = omk::runtime::events::Event::new(run_id.clone(), EventKind::HookResolved)
        .with_actor("worker-1")
        .with_payload(serde_json::json!({
            "event": "PreToolUse",
            "target": "WriteFile",
            "action": "allow",
            "reason": "safe",
            "duration_ms": 12,
        }))
        .unwrap();
    writer.append(&resolved).await.unwrap();

    let content = tokio::fs::read_to_string(&events_path).await.unwrap();
    let lines: Vec<&str> = content.lines().collect();
    assert_eq!(lines.len(), 2);

    let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(first["kind"], "hook_triggered");
    assert_eq!(first["actor"], "worker-1");
    assert_eq!(first["payload"]["event"], "PreToolUse");

    let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
    assert_eq!(second["kind"], "hook_resolved");
    assert_eq!(second["payload"]["action"], "allow");
    assert_eq!(second["payload"]["duration_ms"], 12);
}