macot 0.1.11

Multi Agent Control Tower - CLI for orchestrating Claude CLI instances
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
use anyhow::{Context, Result};
use serde_json::json;
use std::path::{Path, PathBuf};

/// Write content to an expert-specific file, creating parent directories as needed.
fn write_expert_file(path: &Path, content: &str) -> Result<PathBuf> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }
    std::fs::write(path, content)
        .with_context(|| format!("Failed to write file: {}", path.display()))?;
    Ok(path.to_path_buf())
}

#[allow(dead_code)]
pub fn instruction_file_path(queue_path: &Path, expert_id: u32) -> PathBuf {
    queue_path
        .join("system_prompt")
        .join(format!("expert{expert_id}.md"))
}

pub fn write_instruction_file(queue_path: &Path, expert_id: u32, content: &str) -> Result<PathBuf> {
    write_expert_file(&instruction_file_path(queue_path, expert_id), content)
}

pub fn agents_file_path(queue_path: &Path, expert_id: u32) -> PathBuf {
    queue_path
        .join("system_prompt")
        .join(format!("expert{expert_id}_agents.json"))
}

pub fn write_agents_file(queue_path: &Path, expert_id: u32, json: &str) -> Result<PathBuf> {
    write_expert_file(&agents_file_path(queue_path, expert_id), json)
}

pub fn settings_file_path(queue_path: &Path, expert_id: u32) -> PathBuf {
    queue_path
        .join("system_prompt")
        .join(format!("expert{expert_id}_settings.json"))
}

pub fn write_settings_file(queue_path: &Path, expert_id: u32, json: &str) -> Result<PathBuf> {
    write_expert_file(&settings_file_path(queue_path, expert_id), json)
}

pub fn generate_hooks_settings(status_file_path: &str) -> String {
    let dq_path = shell_double_quote(status_file_path);
    let processing_cmd = bash_c_wrap(&format!("printf \"%s\" \"processing\" >| \"{}\"", dq_path));
    let pending_cmd = bash_c_wrap(&format!("printf \"%s\" \"pending\" >| \"{}\"", dq_path));
    let pre_tool_use_inner = concat!(
        "INPUT=$(cat); ",
        "TARGET=$(echo \"$INPUT\" | jq -r '(.tool_input.file_path // .tool_input.command // \"\")'); ",
        "if echo \"$TARGET\" | grep -q 'messages/queue/'; then ",
        "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",",
        "\"permissionDecision\":\"deny\",",
        "\"permissionDecisionReason\":\"ERROR: Writing directly to messages/queue/ is forbidden. ",
        "Write to messages/outbox/ instead.\"}}'; ",
        "fi"
    );
    let pre_tool_use_command = bash_c_wrap(pre_tool_use_inner);
    json!({
        "hooks": {
            "UserPromptSubmit": [{
                "hooks": [{
                    "type": "command",
                    "command": processing_cmd,
                }]
            }],
            "Stop": [{
                "hooks": [{
                    "type": "command",
                    "command": pending_cmd,
                }]
            }],
            "PreToolUse": [{
                "matcher": "Write|Edit|Bash",
                "hooks": [{
                    "type": "command",
                    "command": pre_tool_use_command,
                }]
            }]
        }
    })
    .to_string()
}

fn shell_single_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn shell_double_quote(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('$', "\\$")
        .replace('`', "\\`")
}

fn bash_c_wrap(command: &str) -> String {
    format!("bash -c {}", shell_single_quote(command))
}

#[allow(dead_code)]
pub fn cleanup_instruction_file(queue_path: &Path, expert_id: u32) -> Result<()> {
    let path = instruction_file_path(queue_path, expert_id);
    if path.exists() {
        std::fs::remove_file(&path)
            .with_context(|| format!("Failed to remove instruction file: {}", path.display()))?;
    }
    Ok(())
}

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

    #[test]
    fn instruction_file_path_returns_expected_path() {
        let path = instruction_file_path(Path::new("/tmp/queue"), 0);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert0.md"),
            "instruction_file_path: should return queue_path/system_prompt/expertN.md"
        );
    }

    #[test]
    fn instruction_file_path_different_expert_ids() {
        let path = instruction_file_path(Path::new("/tmp/queue"), 3);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert3.md"),
            "instruction_file_path: should include expert id in filename"
        );
    }

    #[test]
    fn write_instruction_file_creates_dir_and_file() {
        let tmp = TempDir::new().unwrap();
        let content = "# Test Instruction\n\nSome content.";

        let path = write_instruction_file(tmp.path(), 0, content).unwrap();

        assert!(
            path.exists(),
            "write_instruction_file: should create the file"
        );
        let read_back = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            read_back, content,
            "write_instruction_file: file content should match"
        );
    }

    #[test]
    fn write_instruction_file_overwrites_existing() {
        let tmp = TempDir::new().unwrap();

        write_instruction_file(tmp.path(), 1, "first").unwrap();
        let path = write_instruction_file(tmp.path(), 1, "second").unwrap();

        let read_back = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            read_back, "second",
            "write_instruction_file: should overwrite existing file"
        );
    }

    #[test]
    fn cleanup_instruction_file_removes_existing() {
        let tmp = TempDir::new().unwrap();
        let path = write_instruction_file(tmp.path(), 2, "content").unwrap();
        assert!(path.exists());

        cleanup_instruction_file(tmp.path(), 2).unwrap();

        assert!(
            !path.exists(),
            "cleanup_instruction_file: should remove the file"
        );
    }

    #[test]
    fn cleanup_instruction_file_noop_when_missing() {
        let tmp = TempDir::new().unwrap();
        let result = cleanup_instruction_file(tmp.path(), 99);
        assert!(
            result.is_ok(),
            "cleanup_instruction_file: should succeed when file doesn't exist"
        );
    }

    #[test]
    fn agents_file_path_returns_expected_path() {
        let path = agents_file_path(Path::new("/tmp/queue"), 0);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert0_agents.json"),
            "agents_file_path: should return queue_path/system_prompt/expertN_agents.json"
        );
    }

    #[test]
    fn agents_file_path_different_expert_ids() {
        let path = agents_file_path(Path::new("/tmp/queue"), 5);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert5_agents.json"),
            "agents_file_path: should include expert id in filename"
        );
    }

    #[test]
    fn write_agents_file_creates_dir_and_file() {
        let tmp = TempDir::new().unwrap();
        let json = r#"{"messaging":{"description":"test","prompt":"hello"}}"#;

        let path = write_agents_file(tmp.path(), 0, json).unwrap();

        assert!(path.exists(), "write_agents_file: should create the file");
        let read_back = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            read_back, json,
            "write_agents_file: file content should match"
        );
    }

    #[test]
    fn write_agents_file_overwrites_existing() {
        let tmp = TempDir::new().unwrap();

        write_agents_file(tmp.path(), 1, "first").unwrap();
        let path = write_agents_file(tmp.path(), 1, "second").unwrap();

        let read_back = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            read_back, "second",
            "write_agents_file: should overwrite existing file"
        );
    }

    #[test]
    fn settings_file_path_returns_expected_path() {
        let path = settings_file_path(Path::new("/tmp/queue"), 0);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert0_settings.json"),
            "settings_file_path: should return queue_path/system_prompt/expertN_settings.json"
        );
    }

    #[test]
    fn settings_file_path_different_expert_ids() {
        let path = settings_file_path(Path::new("/tmp/queue"), 7);
        assert_eq!(
            path,
            PathBuf::from("/tmp/queue/system_prompt/expert7_settings.json"),
            "settings_file_path: should include expert id in filename"
        );
    }

    #[test]
    fn write_settings_file_creates_dir_and_file() {
        let tmp = TempDir::new().unwrap();
        let json = r#"{"hooks":{}}"#;

        let path = write_settings_file(tmp.path(), 0, json).unwrap();

        assert!(path.exists(), "write_settings_file: should create the file");
        let read_back = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            read_back, json,
            "write_settings_file: file content should match"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_user_prompt_submit() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("UserPromptSubmit"),
            "generate_hooks_settings: should contain UserPromptSubmit hook"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_stop_hook() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("Stop"),
            "generate_hooks_settings: should contain Stop hook"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_status_path() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("/tmp/status/expert0"),
            "generate_hooks_settings: should contain the status file path"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_processing_command() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("processing"),
            "generate_hooks_settings: UserPromptSubmit hook should write 'processing'"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_pending_command() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("pending"),
            "generate_hooks_settings: Stop hook should write 'pending'"
        );
    }

    #[test]
    fn generate_hooks_settings_is_valid_json() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        let parsed: serde_json::Value = serde_json::from_str(&json)
            .expect("generate_hooks_settings: output should be valid JSON");
        assert!(
            parsed.get("hooks").is_some(),
            "generate_hooks_settings: should have a 'hooks' top-level key"
        );
    }

    #[test]
    fn generate_hooks_settings_contains_pre_tool_use_hook() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        assert!(
            json.contains("PreToolUse"),
            "generate_hooks_settings: should contain PreToolUse hook"
        );
    }

    #[test]
    fn generate_hooks_settings_pre_tool_use_has_write_edit_bash_matcher() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        let pre_tool_use = &parsed["hooks"]["PreToolUse"];
        assert!(
            !pre_tool_use.is_null(),
            "generate_hooks_settings: PreToolUse hook should exist"
        );
        let matcher = pre_tool_use[0]["matcher"].as_str().unwrap_or("");
        assert!(
            matcher.contains("Write") && matcher.contains("Edit") && matcher.contains("Bash"),
            "generate_hooks_settings: PreToolUse matcher should include Write, Edit, and Bash"
        );
    }

    #[test]
    fn generate_hooks_settings_pre_tool_use_blocks_queue_writes() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        let command = parsed["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap_or("");
        assert!(
            command.contains("messages/queue/"),
            "generate_hooks_settings: PreToolUse command should check for messages/queue/ path"
        );
        assert!(
            command.contains("deny"),
            "generate_hooks_settings: PreToolUse command should deny writes to queue"
        );
    }

    #[test]
    fn generate_hooks_settings_pre_tool_use_suggests_outbox() {
        let json = generate_hooks_settings("/tmp/status/expert0");
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        let command = parsed["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap_or("");
        assert!(
            command.contains("outbox"),
            "generate_hooks_settings: PreToolUse deny reason should suggest outbox"
        );
    }

    #[test]
    fn generate_hooks_settings_escapes_single_quote_in_status_path() {
        let json = generate_hooks_settings("/tmp/status/it's/me");
        let parsed: serde_json::Value = serde_json::from_str(&json)
            .expect("generate_hooks_settings: output should be valid JSON");

        let processing_cmd = parsed["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"]
            .as_str()
            .expect("generate_hooks_settings: command should be string");
        let stop_cmd = parsed["hooks"]["Stop"][0]["hooks"][0]["command"]
            .as_str()
            .expect("generate_hooks_settings: command should be string");

        assert_eq!(
            processing_cmd, "bash -c 'printf \"%s\" \"processing\" >| \"/tmp/status/it'\\''s/me\"'",
            "generate_hooks_settings: processing command should be wrapped with bash -c"
        );
        assert_eq!(
            stop_cmd, "bash -c 'printf \"%s\" \"pending\" >| \"/tmp/status/it'\\''s/me\"'",
            "generate_hooks_settings: stop command should be wrapped with bash -c"
        );
    }
}