workmux 0.1.215

An opinionated workflow tool that orchestrates git worktrees and tmux
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Shared JSON hook utilities for agent status tracking setup.
//!
//! Agents like Claude Code, Codex, and Gemini all use the same pattern:
//! hooks are stored as JSON objects under a "hooks" key, with workmux
//! commands in the "command" fields. This module provides shared helpers.

use anyhow::{Context, Result};
use serde_json::Value;

/// Check if a parsed JSON value contains any workmux status hooks.
pub fn has_workmux_hooks(settings: &Value) -> bool {
    let Some(hooks) = settings.get("hooks").and_then(|v| v.as_object()) else {
        return false;
    };
    for (_event, groups) in hooks {
        let Some(groups_arr) = groups.as_array() else {
            continue;
        };
        for group in groups_arr {
            let Some(hook_list) = group.get("hooks").and_then(|v| v.as_array()) else {
                continue;
            };
            for hook in hook_list {
                if let Some(cmd) = hook.get("command").and_then(|v| v.as_str())
                    && cmd.contains("workmux set-window-status")
                {
                    return true;
                }
            }
        }
    }
    false
}

/// Remove workmux hook commands from `settings` in place.
///
/// Removes individual hook entries whose command contains
/// `workmux set-window-status`, then cleans up empty groups
/// and events. Returns true if anything was removed.
pub fn remove_workmux_hooks(settings: &mut Value) -> bool {
    let Some(hooks) = settings.get_mut("hooks").and_then(|v| v.as_object_mut()) else {
        return false;
    };

    let mut modified = false;
    let mut events_to_remove: Vec<String> = Vec::new();

    for (event, groups) in hooks.iter_mut() {
        let Some(groups_arr) = groups.as_array_mut() else {
            continue;
        };

        // For each group, remove only workmux hooks from its inner hooks array
        for group in groups_arr.iter_mut() {
            if let Some(hooks_list) = group.get_mut("hooks").and_then(|h| h.as_array_mut()) {
                let len_before = hooks_list.len();
                hooks_list.retain(|e| {
                    !e.get("command")
                        .and_then(|c| c.as_str())
                        .is_some_and(|c| c.contains("workmux set-window-status"))
                });
                if hooks_list.len() < len_before {
                    modified = true;
                }
            }
        }

        // Remove groups that now have empty hooks arrays
        groups_arr.retain(|group| {
            group
                .get("hooks")
                .and_then(|h| h.as_array())
                .is_some_and(|h| !h.is_empty())
        });

        if groups_arr.is_empty() {
            events_to_remove.push(event.clone());
        }
    }

    for event in &events_to_remove {
        hooks.remove(event);
    }

    modified
}

/// Remove workmux-status plugin entries from enabledPlugins.
pub fn remove_workmux_plugins(settings: &mut Value) -> bool {
    let Some(plugins) = settings
        .get_mut("enabledPlugins")
        .and_then(|v| v.as_object_mut())
    else {
        return false;
    };
    let keys: Vec<String> = plugins
        .keys()
        .filter(|k| k.starts_with("workmux-status@"))
        .cloned()
        .collect();
    let modified = !keys.is_empty();
    for key in &keys {
        plugins.remove(key);
    }
    modified
}

/// Remove empty wrapper objects from the JSON tree.
/// E.g., if "hooks" is now an empty object, remove the "hooks" key.
pub fn remove_empty_hooks_wrapper(settings: &mut Value) -> bool {
    let root = settings.as_object_mut().map(|o| {
        let mut modified = false;
        if let Some(hooks) = o.get("hooks")
            && hooks.as_object().is_some_and(|m| m.is_empty())
        {
            o.remove("hooks");
            modified = true;
        }
        if let Some(plugins) = o.get("enabledPlugins")
            && plugins.as_object().is_some_and(|m| m.is_empty())
        {
            o.remove("enabledPlugins");
            modified = true;
        }
        modified
    });
    root.unwrap_or(false)
}

/// Merge hook groups into a config root, deduplicating by value equality.
///
/// `config_root` is the parsed JSON settings file (must be an object).
/// `hooks_to_add` is the hooks map from the embedded config file
/// (e.g. `{"Stop": [{"hooks": [...]}]}`).
///
/// Ensures a "hooks" key exists in config_root, then for each event in
/// hooks_to_add: if the event already exists in config, merges groups
/// avoiding duplicates by serde_json::Value equality; otherwise inserts
/// the new groups. Skips incoming hook_groups that are not arrays.
/// Errors if an existing hooks.<event> value is not an array.
pub fn merge_hook_groups(config_root: &mut Value, hooks_to_add: &Value) -> Result<()> {
    let config_obj = config_root
        .as_object_mut()
        .context("config root is not an object")?;

    if !config_obj.contains_key("hooks") {
        config_obj.insert("hooks".to_string(), Value::Object(serde_json::Map::new()));
    }

    let existing_hooks = config_obj
        .get_mut("hooks")
        .and_then(|v| v.as_object_mut())
        .context("hooks value is not an object")?;

    let hooks_map = hooks_to_add
        .as_object()
        .context("hooks to add is not an object")?;

    for (event, hook_groups) in hooks_map {
        let Some(new_groups) = hook_groups.as_array() else {
            continue;
        };

        if let Some(existing_groups) = existing_hooks.get_mut(event) {
            let arr = existing_groups
                .as_array_mut()
                .with_context(|| format!("hooks.{event} is not an array"))?;
            for group in new_groups {
                if !arr.contains(group) {
                    arr.push(group.clone());
                }
            }
        } else {
            existing_hooks.insert(event.clone(), hook_groups.clone());
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_has_workmux_hooks_empty() {
        let settings = json!({});
        assert!(!has_workmux_hooks(&settings));
    }

    #[test]
    fn test_has_workmux_hooks_present() {
        let settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{
                        "type": "command",
                        "command": "workmux set-window-status done"
                    }]
                }]
            }
        });
        assert!(has_workmux_hooks(&settings));
    }

    #[test]
    fn test_has_workmux_hooks_other_hooks_only() {
        let settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{
                        "type": "command",
                        "command": "afplay /System/Library/Sounds/Glass.aiff"
                    }]
                }]
            }
        });
        assert!(!has_workmux_hooks(&settings));
    }

    #[test]
    fn test_remove_workmux_hooks_mixed() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{ "type": "command", "command": "workmux set-window-status done" }]
                }, {
                    "hooks": [{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }]
                }]
            },
            "enabledPlugins": {
                "workmux-status@workmux": true,
                "other-plugin@1.0": true
            }
        });

        assert!(remove_workmux_hooks(&mut settings));
        assert!(remove_workmux_plugins(&mut settings));
        remove_empty_hooks_wrapper(&mut settings);

        // Workmux hook group removed, non-workmux group preserved
        let stop = settings["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 1);
        assert!(
            stop[0]["hooks"][0]["command"]
                .as_str()
                .unwrap()
                .contains("Glass")
        );

        // Workmux plugin removed, other plugin preserved
        assert!(
            settings["enabledPlugins"]
                .as_object()
                .unwrap()
                .contains_key("other-plugin@1.0")
        );
        assert!(
            !settings["enabledPlugins"]
                .as_object()
                .unwrap()
                .contains_key("workmux-status@workmux")
        );
    }

    #[test]
    fn test_remove_workmux_hooks_only_workmux() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{ "type": "command", "command": "workmux set-window-status done" }]
                }]
            }
        });

        assert!(remove_workmux_hooks(&mut settings));
        remove_empty_hooks_wrapper(&mut settings);
        // Empty hooks object should be removed
        assert!(settings.get("hooks").is_none());
    }

    #[test]
    fn test_remove_workmux_hooks_mixed_in_same_group() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [
                        { "type": "command", "command": "workmux set-window-status done" },
                        { "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" },
                        { "type": "command", "command": "echo user-hook" }
                    ]
                }]
            }
        });

        assert!(remove_workmux_hooks(&mut settings));

        // The group should still exist with non-workmux hooks preserved
        let stop = settings["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 1);
        let hooks = stop[0]["hooks"].as_array().unwrap();
        assert_eq!(hooks.len(), 2);
        assert!(hooks[0]["command"].as_str().unwrap().contains("Glass"));
        assert!(hooks[1]["command"].as_str().unwrap().contains("echo"));
    }

    #[test]
    fn test_remove_workmux_hooks_idempotent() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{ "type": "command", "command": "workmux set-window-status done" }]
                }]
            }
        });
        assert!(remove_workmux_hooks(&mut settings));
        // Second call should return false (nothing to remove)
        assert!(!remove_workmux_hooks(&mut settings));
    }

    #[test]
    fn test_remove_workmux_hooks_empty_settings() {
        let mut settings = json!({});
        assert!(!remove_workmux_hooks(&mut settings));
    }

    #[test]
    fn test_remove_workmux_plugins_empty() {
        let mut settings = json!({});
        assert!(!remove_workmux_plugins(&mut settings));
    }

    #[test]
    fn test_remove_workmux_plugins_only_workmux() {
        let mut settings = json!({
            "enabledPlugins": {
                "workmux-status@workmux": true
            }
        });
        assert!(remove_workmux_plugins(&mut settings));
        assert!(settings["enabledPlugins"].as_object().unwrap().is_empty());
    }

    #[test]
    fn test_remove_workmux_plugins_idempotent() {
        let mut settings = json!({
            "enabledPlugins": {
                "workmux-status@workmux": true
            }
        });
        assert!(remove_workmux_plugins(&mut settings));
        assert!(!remove_workmux_plugins(&mut settings));
    }

    #[test]
    fn test_remove_empty_hooks_wrapper_none() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{"hooks": [{"command": "echo hi"}]}]
            }
        });
        assert!(!remove_empty_hooks_wrapper(&mut settings));
    }

    #[test]
    fn test_remove_empty_hooks_wrapper_empty_hooks() {
        let mut settings = json!({ "hooks": {} });
        assert!(remove_empty_hooks_wrapper(&mut settings));
        assert!(settings.get("hooks").is_none());
    }

    #[test]
    fn test_remove_empty_hooks_wrapper_empty_plugins() {
        let mut settings = json!({ "enabledPlugins": {} });
        assert!(remove_empty_hooks_wrapper(&mut settings));
        assert!(settings.get("enabledPlugins").is_none());
    }

    #[test]
    fn test_merge_hook_groups_into_empty() {
        let mut config = json!({ "hooks": {} });
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}]
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        let hooks = config["hooks"].as_object().unwrap();
        assert_eq!(hooks.len(), 1);
        assert_eq!(
            config["hooks"]["Stop"][0]["hooks"][0]["command"],
            "workmux set-window-status done"
        );
    }

    #[test]
    fn test_merge_hook_groups_into_empty_root_creates_hooks() {
        let mut config = json!({});
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}]
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        let hooks = config["hooks"].as_object().unwrap();
        assert_eq!(hooks.len(), 1);
    }

    #[test]
    fn test_merge_hook_groups_deduplicates() {
        let mut config = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{"type": "command", "command": "workmux set-window-status done"}]
                }]
            }
        });
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}]
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        let stop = config["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 1);
    }

    #[test]
    fn test_merge_hook_groups_preserves_existing() {
        let mut config = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{"type": "command", "command": "python3 my-hook.py"}]
                }]
            }
        });
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}]
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        let stop = config["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 2);
    }

    #[test]
    fn test_merge_hook_groups_adds_new_event() {
        let mut config = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [{"type": "command", "command": "python3 my-hook.py"}]
                }]
            }
        });
        let hooks_to_add = json!({
            "UserPromptSubmit": [{
                "hooks": [{"type": "command", "command": "workmux set-window-status working"}]
            }]
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        assert!(
            config["hooks"]
                .as_object()
                .unwrap()
                .contains_key("UserPromptSubmit")
        );
        assert!(config["hooks"].as_object().unwrap().contains_key("Stop"));
    }

    #[test]
    fn test_merge_hook_groups_skips_non_array() {
        let mut config = json!({ "hooks": {} });
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}],
            "InvalidEvent": "not an array"
        });
        merge_hook_groups(&mut config, &hooks_to_add).unwrap();
        // InvalidEvent should be silently skipped, Stop should be merged
        assert!(config["hooks"].as_object().unwrap().contains_key("Stop"));
        assert!(
            !config["hooks"]
                .as_object()
                .unwrap()
                .contains_key("InvalidEvent")
        );
    }

    #[test]
    fn test_merge_hook_groups_errors_on_non_array_existing() {
        let mut config = json!({
            "hooks": {
                "Stop": "not an array"
            }
        });
        let hooks_to_add = json!({
            "Stop": [{"hooks": [{"type": "command", "command": "workmux set-window-status done"}]}]
        });
        let result = merge_hook_groups(&mut config, &hooks_to_add);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("hooks.Stop is not an array")
        );
    }

    #[test]
    fn test_merge_hook_groups_errors_on_non_object_root() {
        let mut config = json!("not an object");
        let hooks_to_add = json!({});
        let result = merge_hook_groups(&mut config, &hooks_to_add);
        assert!(result.is_err());
    }
}