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
413
414
415
416
417
use anyhow::{Context, Result};
use minijinja::Environment;
use std::path::Path;

/// Render agent template files into a JSON string for the `--agents` CLI flag.
///
/// Looks for `templates/agents/messaging.md.tmpl` and `templates/agents/expert-discovery.md.tmpl`
/// under `core_path`. Returns `Ok(None)` if no agent templates exist.
pub fn render_agents_json(
    core_path: &Path,
    expert_id: u32,
    expert_name: &str,
    worktree_path: Option<&str>,
    manifest_path: &str,
    status_dir: &str,
) -> Result<Option<String>> {
    let agents_dir = core_path.join("templates").join("agents");

    let messaging_path = agents_dir.join("messaging.md.tmpl");
    let discovery_path = agents_dir.join("expert-discovery.md.tmpl");

    if !messaging_path.exists() && !discovery_path.exists() {
        return Ok(None);
    }

    let mut json = serde_json::Map::new();

    if messaging_path.exists() {
        let template_content = std::fs::read_to_string(&messaging_path)
            .context("Failed to read messaging agent template")?;
        let rendered = render_messaging_template(&template_content, expert_id, expert_name)?;

        let description = "Send messages to other experts through the MACOT messaging system. \
                            Use this agent when you need to coordinate, ask questions, \
                            or delegate tasks to other experts.";

        json.insert(
            "messaging".to_string(),
            serde_json::json!({
                "description": description,
                "prompt": rendered
            }),
        );
    }

    if discovery_path.exists() {
        let template_content = std::fs::read_to_string(&discovery_path)
            .context("Failed to read expert-discovery agent template")?;
        let rendered = render_discovery_template(
            &template_content,
            expert_id,
            expert_name,
            worktree_path,
            manifest_path,
            status_dir,
        )?;

        let description = "Query information about other experts in your worktree: \
                            their IDs, names, roles, and current status (idle/busy).";

        json.insert(
            "expert-discovery".to_string(),
            serde_json::json!({
                "description": description,
                "prompt": rendered
            }),
        );
    }

    if json.is_empty() {
        return Ok(None);
    }

    Ok(Some(
        serde_json::to_string(&serde_json::Value::Object(json))
            .context("Failed to serialize agents JSON")?,
    ))
}

fn render_discovery_template(
    template_content: &str,
    expert_id: u32,
    expert_name: &str,
    worktree_path: Option<&str>,
    manifest_path: &str,
    status_dir: &str,
) -> Result<String> {
    let mut env = Environment::new();
    env.add_template("discovery", template_content)
        .context("Failed to add expert-discovery template")?;

    let template = env
        .get_template("discovery")
        .context("Failed to get expert-discovery template")?;

    let wt_display = worktree_path.unwrap_or("null");

    let rendered = template
        .render(minijinja::context! {
            expert_id => expert_id,
            expert_name => expert_name,
            worktree_path => wt_display,
            manifest_path => manifest_path,
            status_dir => status_dir,
        })
        .context("Failed to render expert-discovery template")?;

    Ok(rendered)
}

fn render_messaging_template(
    template_content: &str,
    expert_id: u32,
    expert_name: &str,
) -> Result<String> {
    let mut env = Environment::new();
    env.add_template("messaging", template_content)
        .context("Failed to add messaging template")?;

    let template = env
        .get_template("messaging")
        .context("Failed to get messaging template")?;

    let rendered = template
        .render(minijinja::context! {
            expert_id => expert_id,
            expert_name => expert_name,
        })
        .context("Failed to render messaging template")?;

    Ok(rendered)
}

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

    #[test]
    fn render_agents_json_returns_none_when_no_template() {
        let tmp = TempDir::new().unwrap();
        let result = render_agents_json(
            tmp.path(),
            0,
            "test",
            None,
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap();
        assert!(
            result.is_none(),
            "render_agents_json: should return None when no agent templates exist"
        );
    }

    #[test]
    fn render_agents_json_returns_valid_json_with_template() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("messaging.md.tmpl"),
            "Send a message from expert {{ expert_id }}.",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            2,
            "Alyosha",
            None,
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap();
        assert!(
            result.is_some(),
            "render_agents_json: should return Some when template exists"
        );

        let json: serde_json::Value = serde_json::from_str(result.as_ref().unwrap()).unwrap();
        assert!(
            json.get("messaging").is_some(),
            "render_agents_json: JSON should have 'messaging' key"
        );
        assert!(
            json["messaging"]["description"].is_string(),
            "render_agents_json: messaging should have 'description' string"
        );
        assert!(
            json["messaging"]["prompt"].is_string(),
            "render_agents_json: messaging should have 'prompt' string"
        );
    }

    #[test]
    fn render_agents_json_renders_expert_id() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("messaging.md.tmpl"),
            "from_expert_id: {{ expert_id }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            5,
            "TestExpert",
            None,
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap()
        .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        let prompt = json["messaging"]["prompt"].as_str().unwrap();

        assert!(
            prompt.contains("from_expert_id: 5"),
            "render_agents_json: should render expert_id in template, got: {}",
            prompt
        );
        assert!(
            !prompt.contains("{{ expert_id }}"),
            "render_agents_json: should not contain unrendered template variable"
        );
    }

    #[test]
    fn render_agents_json_includes_discovery_agent() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("expert-discovery.md.tmpl"),
            "Manifest: {{ manifest_path }}, Status: {{ status_dir }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            0,
            "Alyosha",
            None,
            "/tmp/.macot/experts_manifest.json",
            "/tmp/.macot/status",
        )
        .unwrap();
        assert!(
            result.is_some(),
            "render_agents_json: should return Some when discovery template exists"
        );

        let json: serde_json::Value = serde_json::from_str(result.as_ref().unwrap()).unwrap();
        assert!(
            json.get("expert-discovery").is_some(),
            "render_agents_json: JSON should have 'expert-discovery' key"
        );
        assert!(
            json["expert-discovery"]["description"].is_string(),
            "render_agents_json: expert-discovery should have 'description' string"
        );
        assert!(
            json["expert-discovery"]["prompt"].is_string(),
            "render_agents_json: expert-discovery should have 'prompt' string"
        );
    }

    #[test]
    fn render_agents_json_discovery_absent_without_template() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("messaging.md.tmpl"),
            "msg from {{ expert_id }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            0,
            "test",
            None,
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap()
        .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();

        assert!(
            json.get("messaging").is_some(),
            "render_agents_json: should have messaging when only messaging template exists"
        );
        assert!(
            json.get("expert-discovery").is_none(),
            "render_agents_json: should not have expert-discovery when no discovery template"
        );
    }

    #[test]
    fn render_agents_json_discovery_renders_manifest_path() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("expert-discovery.md.tmpl"),
            "path={{ manifest_path }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            0,
            "test",
            None,
            "/custom/path/manifest.json",
            "/tmp/status",
        )
        .unwrap()
        .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        let prompt = json["expert-discovery"]["prompt"].as_str().unwrap();

        assert!(
            prompt.contains("/custom/path/manifest.json"),
            "render_agents_json: discovery prompt should contain rendered manifest_path, got: {}",
            prompt
        );
    }

    #[test]
    fn render_agents_json_discovery_renders_status_dir() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("expert-discovery.md.tmpl"),
            "dir={{ status_dir }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            0,
            "test",
            None,
            "/tmp/manifest.json",
            "/custom/status/dir",
        )
        .unwrap()
        .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        let prompt = json["expert-discovery"]["prompt"].as_str().unwrap();

        assert!(
            prompt.contains("/custom/status/dir"),
            "render_agents_json: discovery prompt should contain rendered status_dir, got: {}",
            prompt
        );
    }

    #[test]
    fn render_agents_json_discovery_renders_worktree_path() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join("templates").join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("expert-discovery.md.tmpl"),
            "wt={{ worktree_path }}",
        )
        .unwrap();

        let result = render_agents_json(
            tmp.path(),
            0,
            "test",
            Some("/wt/feature-auth"),
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap()
        .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        let prompt = json["expert-discovery"]["prompt"].as_str().unwrap();

        assert!(
            prompt.contains("/wt/feature-auth"),
            "render_agents_json: discovery prompt should contain worktree_path, got: {}",
            prompt
        );

        // Test null worktree_path
        let result_null = render_agents_json(
            tmp.path(),
            0,
            "test",
            None,
            "/tmp/manifest.json",
            "/tmp/status",
        )
        .unwrap()
        .unwrap();
        let json_null: serde_json::Value = serde_json::from_str(&result_null).unwrap();
        let prompt_null = json_null["expert-discovery"]["prompt"].as_str().unwrap();

        assert!(
            prompt_null.contains("null"),
            "render_agents_json: discovery prompt should render 'null' for None worktree_path, got: {}",
            prompt_null
        );
    }
}