ljos 0.35.7

Memory, a work tracker and a shell-command gate for coding agents (Claude Code, Codex, Grok Build, agy, opencode) over MCP and hooks.
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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! The subagent a tool call runs for, so its ballot binds its own session
//! rather than its parent's. Claude Code hands a hook the subagent's
//! `agent_id` and the call's `tool_use_id`, but gives the command it runs
//! no variable that names the agent. The hook leaves the call under the
//! runtime directory, and the `ljos` the command runs, or the MCP server
//! the call reaches, takes it back once. A shell call stays behind as
//! taken until it expires, so the same line run again inside the call
//! binds the session its first run bound and is refused as cast.
//!
//! A shell call is kept with the hook's ancestors, and only a process that
//! runs under the nearest of them still alive takes it: the harness that
//! ran the hook runs the command too. The files are not signed. Anything
//! running as the same user can still write one naming a live ancestor of
//! a later `ljos`; the check stops a record left by hand, or by a process
//! in another tree, from naming a session.

use crate::proc_tree::Proc;
use serde_json::Value;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

/// How long a shell call the hook saw waits to be taken: the longest a
/// Claude Code shell command runs.
const CALL_TTL_MS: u64 = 600_000;

/// How long an MCP hook call waits to be taken by `ljos-mcp`.
const MCP_CALL_TTL_MS: u64 = 30_000;

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Call {
    session: String,
    agent: String,
    argv: Vec<String>,
    at: u64,
    /// The hook's ancestors, nearest first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    tree: Vec<Proc>,
}

fn root() -> PathBuf {
    crate::runtime_dir().join("agent-calls")
}

/// A name safe as one path component. `.` is left out, so it can join a
/// call to its index.
pub(crate) fn token(raw: &str) -> String {
    raw.trim()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') {
                c
            } else {
                '_'
            }
        })
        .collect()
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}

fn shell_dir(root: &Path, session: &str) -> PathBuf {
    root.join("shell").join(token(session))
}

fn mcp_path(root: &Path, call: &str) -> PathBuf {
    root.join("mcp").join(format!("{call}.json"))
}

fn put(path: &Path, call: &Call) {
    let Some(dir) = path.parent() else {
        return;
    };
    let Ok(text) = serde_json::to_string(call) else {
        return;
    };
    if std::fs::create_dir_all(dir).is_err() {
        return;
    }
    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
    if std::fs::write(&tmp, text).is_ok() && std::fs::rename(&tmp, path).is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
}

fn read(path: &Path) -> Option<Call> {
    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
}

/// The extension a call takes once a process took it. It stays until
/// [`CALL_TTL_MS`], so the same line run again inside the call binds what
/// the first run bound rather than nothing.
const TAKEN: &str = "taken";

/// The calls under `dir` still waiting, each with its file. A call past
/// [`CALL_TTL_MS`] is dropped.
fn waiting(dir: &Path, now: u64) -> Vec<(PathBuf, Call)> {
    listed(dir, now, "json", CALL_TTL_MS)
}

/// The MCP calls under `dir` still waiting, within [`MCP_CALL_TTL_MS`].
fn waiting_mcp(dir: &Path, now: u64) -> Vec<(PathBuf, Call)> {
    listed(dir, now, "json", MCP_CALL_TTL_MS)
}

/// The calls under `dir` already taken, within [`CALL_TTL_MS`].
fn spent(dir: &Path, now: u64) -> Vec<(PathBuf, Call)> {
    listed(dir, now, TAKEN, CALL_TTL_MS)
}

fn listed(dir: &Path, now: u64, ext: &str, ttl: u64) -> Vec<(PathBuf, Call)> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for path in entries.flatten().map(|e| e.path()) {
        if path.extension().is_none_or(|e| e != ext) {
            continue;
        }
        let Some(call) = read(&path) else {
            continue;
        };
        if now.saturating_sub(call.at) > ttl {
            let _ = std::fs::remove_file(&path);
            continue;
        }
        out.push((path, call));
    }
    out
}

fn text(v: &Value, keys: &[&str]) -> Option<String> {
    keys.iter()
        .find_map(|k| v[*k].as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

/// `mcp__SERVER__NAME`, split on the last `__` so `SERVER` may contain
/// `__`. `None` when the name is not that shape.
#[must_use]
pub fn mcp_prefixed_tool(tool: &str) -> Option<(&str, &str)> {
    let rest = tool.strip_prefix("mcp__")?;
    let (server, name) = rest.rsplit_once("__")?;
    if server.is_empty() || name.is_empty() {
        None
    } else {
        Some((server, name))
    }
}

/// Whether `tool` is one of the seat's MCP tools, `mcp__SERVER__ljos_NAME`,
/// and `SERVER` is a key whose command is the seat's own MCP server.
/// The name shape alone is not enough. An unknown or unreadable config
/// is not a match.
#[must_use]
pub fn is_seat_mcp_tool(tool: &str) -> bool {
    is_confirmed_seat_call(tool, None, None)
}

/// `tool` is `ljos_*` on a server key the seat's MCP config names.
/// `field` is a payload server (`server`, `mcp_server_name`). When both
/// the name and the field name a server, they have to be the same key.
pub(crate) fn is_confirmed_seat_call(
    tool: &str,
    field: Option<&str>,
    command: Option<&str>,
) -> bool {
    // The Cursor payload names the server binary in `command`. When that
    // field is present it has to be the seat server. A key in a config
    // file cannot promote a foreign binary.
    if let Some(command) = command.map(str::trim).filter(|text| !text.is_empty()) {
        if !crate::cloud::payload_command_is_seat(command) {
            return false;
        }
    }
    match crate::cloud::seat_mcp_keys() {
        crate::cloud::SeatMcpKeys::Known(keys) => seat_call_matches(tool, field, &keys),
        crate::cloud::SeatMcpKeys::Unknown | crate::cloud::SeatMcpKeys::Ambiguous => false,
    }
}

pub(crate) fn seat_call_matches(tool: &str, field: Option<&str>, keys: &BTreeSet<String>) -> bool {
    if let Some((embedded, short)) = mcp_prefixed_tool(tool) {
        if !short.starts_with("ljos_") {
            return false;
        }
        if field.is_some_and(|name| name != embedded) {
            return false;
        }
        return keys.contains(embedded);
    }
    if !tool.starts_with("ljos_") {
        return false;
    }
    field.is_some_and(|name| keys.contains(name))
}

/// `mcp__SERVER__ljos_NAME`. The server key is not checked: a subagent
/// vote binds to the agent on this call even when `SERVER` is not one
/// the seat configured.
fn seat_shaped_mcp_tool(tool: &str) -> bool {
    mcp_prefixed_tool(tool).is_some_and(|(_, name)| name.starts_with("ljos_"))
}

fn is_any_seat_mcp_tool(tool: &str) -> bool {
    let tool = tool.trim();
    seat_shaped_mcp_tool(tool)
        || tool.starts_with("ljos_")
        || tool
            .strip_prefix("MCP:")
            .is_some_and(|rest| rest.starts_with("ljos_"))
}

/// An MCP tool call. Shell-only checks, such as a missing working
/// directory, do not apply to it.
pub fn payload_names_mcp_tool(input: &str) -> bool {
    let Ok(v) = serde_json::from_str::<Value>(input.trim()) else {
        return false;
    };
    text(&v, &["tool_name", "toolName"])
        .is_some_and(|name| name.starts_with("mcp__") || name.starts_with("MCP:"))
}

/// Leave what a hook payload says about its tool call. On `PreToolUse`,
/// each `ljos` line of a shell call is kept for the process that runs it,
/// and a subagent's `mcp__SERVER__ljos_NAME` call is kept for the server
/// whether or not `SERVER` is a configured key. On `PostToolUse` what the
/// call did not take is dropped. The payload's agent is this hook
/// process's own. Returns whether the call is a `PreToolUse` on a
/// confirmed seat server: the server judges that call, so the hook has
/// nothing more to say.
pub fn note_hook_call(input: &str, event: &str) -> bool {
    let Ok(v) = serde_json::from_str::<Value>(input.trim()) else {
        return false;
    };
    let agent = text(&v, &["agent_id", "agentId"]).map(|a| crate::ballot_sig::field(&a));
    crate::ballot_sig::hook_agent(agent.clone());
    let tool = text(&v, &["tool_name", "toolName"]).unwrap_or_default();
    let field = ["mcp_server_name", "mcpServerName", "server_name", "server"]
        .iter()
        .find_map(|key| v[*key].as_str())
        .map(str::trim)
        .filter(|name| !name.is_empty());
    let command = text(&v, &["command"]);
    let shaped = event == "PreToolUse" && seat_shaped_mcp_tool(&tool);
    let seat_tool = shaped && is_confirmed_seat_call(&tool, field, command.as_deref());
    let any_mcp_tool = matches!(event, "PreToolUse" | "preToolUse" | "beforeMCPExecution")
        && is_any_seat_mcp_tool(&tool);
    let session = crate::hook_call_as(input, Some(event))
        .session
        .map(|s| crate::ballot_sig::field(&s));
    let call = text(&v, &["tool_use_id", "toolUseId"])
        .map(|c| token(&c))
        .filter(|c| !c.is_empty());
    if any_mcp_tool {
        if let Some(ref s) = session {
            if let Some(id) = crate::usable_session_id(s) {
                let root = root();
                let tree = crate::proc_tree::ancestors();
                let found = Call {
                    session: id.to_string(),
                    agent: agent.clone().unwrap_or_default(),
                    argv: Vec::new(),
                    at: now_ms(),
                    tree,
                };
                if let Some(ref c) = call {
                    put(&mcp_path(&root, c), &found);
                } else if !crate::subagent_id(id) && agent.is_none() {
                    put(
                        &root.join("mcp").join(format!("latest-{}.json", now_ms())),
                        &found,
                    );
                }
            }
        }
    }
    if matches!(event, "PreToolUse" | "preToolUse" | "beforeShellExecution") {
        if let Some(ref s) = session {
            if crate::usable_session_id(s).is_some_and(|id| !crate::subagent_id(id)) {
                let input_obj = if v["tool_input"].is_object() {
                    &v["tool_input"]
                } else {
                    &v["toolInput"]
                };
                let line = input_obj["command"]
                    .as_str()
                    .or_else(|| v["command"].as_str())
                    .unwrap_or("");
                crate::note_tmux_spawn(line, v["cwd"].as_str(), s);
            }
        }
    }
    let (Some(session), Some(call)) = (session, call) else {
        return seat_tool;
    };
    let root = root();
    match event {
        "PreToolUse" if shaped => {}
        "PreToolUse" => {
            let input = if v["tool_input"].is_object() {
                &v["tool_input"]
            } else {
                &v["toolInput"]
            };
            let Some(line) = input["command"].as_str() else {
                return false;
            };
            let at = now_ms();
            let dir = shell_dir(&root, &session);
            let tree = crate::proc_tree::ancestors();
            for (i, argv) in crate::ljos_invocations(line).into_iter().enumerate() {
                let found = Call {
                    session: session.clone(),
                    agent: agent.clone().unwrap_or_default(),
                    argv,
                    at,
                    tree: tree.clone(),
                };
                put(&dir.join(format!("{call}.{i}.json")), &found);
            }
        }
        "PostToolUse" | "PostToolUseFailure" => forget(&root, &session, &call),
        _ => {}
    }
    seat_tool
}

fn forget(root: &Path, session: &str, call: &str) {
    let _ = std::fs::remove_file(mcp_path(root, call));
    let Ok(entries) = std::fs::read_dir(shell_dir(root, session)) else {
        return;
    };
    let prefix = format!("{call}.");
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if name.starts_with(&prefix) && !name.ends_with(&format!(".{TAKEN}")) {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Whether the line a hook saw runs as `argv`. A word the shell expands
/// (a variable, a substitution, a glob, a tilde) stands for any one word.
fn argv_matches(written: &[String], argv: &[String]) -> bool {
    written.len() == argv.len()
        && written
            .iter()
            .zip(argv)
            .all(|(w, a)| w == a || w.contains(['$', '`', '*', '?', '[', '~']))
}

/// The process that ran the hook for `call` and runs this line too: the
/// nearest of the hook's ancestors still alive, when it is one of `mine`.
/// A record that names none is no call.
fn harness_of<'a>(call: &'a Call, mine: &[Proc]) -> Option<&'a Proc> {
    let nearest = call.tree.iter().find(|p| crate::proc_tree::alive(p))?;
    mine.iter().any(|m| m.same(nearest)).then_some(nearest)
}

/// The call a hook saw run this process's `ljos` line, as this process
/// took it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Taken {
    pub session: String,
    pub agent: String,
    /// The harness that ran the hook and runs this process.
    pub harness: Proc,
}

static THIS_CALL: std::sync::OnceLock<Option<Taken>> = std::sync::OnceLock::new();

/// The call this process runs, taken once per process. `session` is the
/// one its environment names: that session's calls are read first, then
/// every session's, since a line whose environment names another session
/// than its hook saw still runs under that hook's harness.
fn this_call(session: Option<&str>) -> Option<Taken> {
    THIS_CALL
        .get_or_init(|| {
            let mine = crate::proc_tree::ancestors();
            claim_in(&root(), session, &this_line()?, now_ms(), &mine)
        })
        .clone()
}

/// The harness of the call this process took, once it has looked for one.
#[must_use]
pub fn taken_harness() -> Option<Proc> {
    THIS_CALL.get()?.as_ref().map(|t| t.harness.clone())
}

/// The agent of the `ljos` line this process runs, when a hook saw it
/// under `session`. The newest call whose line is this argv is taken, so
/// no other process takes it too and a parent's call is never answered
/// by an older one its subagent left. An empty agent is the parent's.
#[must_use]
pub fn claim_command(session: &str) -> Option<String> {
    this_call(Some(session))
        .filter(|t| t.session == session)
        .map(|t| t.agent)
}

/// The session and agent of the `ljos` line this process runs, when this
/// process names no session of its own: a seat whose runner stamps no id
/// in the shell. The hook saw the line under its session, so every
/// session's calls are read, and the newest whose line is this argv is
/// taken once. An empty agent is the parent's.
#[must_use]
pub fn claim_unsessioned_command() -> Option<(String, String)> {
    this_call(None).map(|t| (t.session, t.agent))
}

/// Whether this process is the `ljos` command line, rather than the MCP
/// server or a test.
#[must_use]
pub fn runs_as_ljos() -> bool {
    this_line().is_some()
}

/// This process's argv after the program, when the program is `ljos`: the
/// hook keeps only lines that run it, so the MCP server takes none.
fn this_line() -> Option<Vec<String>> {
    let mut args = std::env::args_os();
    let program = PathBuf::from(args.next()?);
    (program.file_name()? == "ljos")
        .then(|| args.map(|a| a.to_string_lossy().into_owned()).collect())
}

fn claim_in(
    root: &Path,
    session: Option<&str>,
    argv: &[String],
    now: u64,
    mine: &[Proc],
) -> Option<Taken> {
    let fits = |c: &Call| argv_matches(&c.argv, argv) && harness_of(c, mine).is_some();
    let own =
        session.and_then(|s| claim_from(&[shell_dir(root, s)], now, |c| c.session == s && fits(c)));
    let call = own.or_else(|| {
        let dirs: Vec<PathBuf> = std::fs::read_dir(root.join("shell"))
            .ok()?
            .flatten()
            .map(|d| d.path())
            .collect();
        claim_from(&dirs, now, fits)
    })?;
    let harness = harness_of(&call, mine)?.clone();
    Some(Taken {
        session: call.session,
        agent: call.agent,
        harness,
    })
}

/// The newest waiting call under `dirs` that `fits`, taken. With none, the
/// newest that fits and was already taken: this line ran before inside
/// the same call, and binds what it bound then.
fn claim_from(dirs: &[PathBuf], now: u64, fits: impl Fn(&Call) -> bool) -> Option<Call> {
    let among = |list: fn(&Path, u64) -> Vec<(PathBuf, Call)>| -> Vec<(PathBuf, Call)> {
        let mut found: Vec<_> = dirs
            .iter()
            .flat_map(|d| list(d, now))
            .filter(|(_, c)| fits(c))
            .collect();
        found.sort_by(|a, b| b.1.at.cmp(&a.1.at).then_with(|| b.0.cmp(&a.0)));
        found
    };
    take_newest(among(waiting)).or_else(|| among(spent).into_iter().next().map(|(_, c)| c))
}

/// The first of `found` this process takes, so no other process takes it
/// too. Its file is left as taken for [`spent`].
fn take_newest(found: Vec<(PathBuf, Call)>) -> Option<Call> {
    found.into_iter().find_map(|(path, c)| {
        std::fs::rename(&path, path.with_extension(TAKEN))
            .is_ok()
            .then_some(c)
    })
}

/// The session and subagent of a Claude Code MCP call, by the tool use id
/// its `_meta` carries, when its hook saw a subagent make it. Taken once.
#[must_use]
pub fn claim_mcp_call(call: &str) -> Option<(String, String)> {
    claim_mcp_in(&root(), call, now_ms())
}

fn claim_mcp_in(root: &Path, call: &str, now: u64) -> Option<(String, String)> {
    let call = token(call);
    if call.is_empty() {
        return None;
    }
    let path = mcp_path(root, &call);
    let found = waiting_mcp(&root.join("mcp"), now)
        .into_iter()
        .find(|(p, _)| *p == path)?
        .1;
    std::fs::remove_file(&path).ok()?;
    Some((found.session, found.agent))
}

/// The session of a recent MCP hook call when `_meta` carried no id or
/// `toolUseId`, taken once when only one conversation's hook call is
/// waiting in the last [`MCP_CALL_TTL_MS`].
#[must_use]
pub fn claim_recent_mcp_session() -> Option<String> {
    recent_mcp_session(true)
}

/// [`claim_recent_mcp_session`] without taking the record, for a caller
/// that only wants to know whether the record names it.
#[must_use]
pub fn peek_recent_mcp_session() -> Option<String> {
    recent_mcp_session(false)
}

fn recent_mcp_session(consume: bool) -> Option<String> {
    let dir = root().join("mcp");
    let now = now_ms();
    let mut found: Vec<_> = waiting_mcp(&dir, now)
        .into_iter()
        .filter(|(p, c)| {
            p.file_name()
                .is_some_and(|n| n.to_string_lossy().starts_with("latest-"))
                && c.agent.is_empty()
                && !crate::subagent_id(&c.session)
        })
        .collect();
    let first_session = found.first()?.1.session.clone();
    if found.iter().any(|(_, c)| c.session != first_session) {
        return None;
    }
    found.sort_by(|a, b| b.1.at.cmp(&a.1.at).then_with(|| b.0.cmp(&a.0)));
    if !consume {
        return Some(first_session);
    }
    found
        .into_iter()
        .find_map(|(path, c)| std::fs::remove_file(&path).ok().map(|()| c.session))
}

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

    fn claim_command_in(
        root: &Path,
        session: &str,
        argv: &[String],
        now: u64,
        mine: &[Proc],
    ) -> Option<String> {
        claim_in(root, Some(session), argv, now, mine)
            .filter(|t| t.session == session)
            .map(|t| t.agent)
    }

    fn claim_any_in(
        root: &Path,
        argv: &[String],
        now: u64,
        mine: &[Proc],
    ) -> Option<(String, String)> {
        claim_in(root, None, argv, now, mine).map(|t| (t.session, t.agent))
    }

    fn words(line: &str) -> Vec<String> {
        line.split_whitespace().map(str::to_string).collect()
    }

    /// A call as a hook running in this process's place would leave it.
    fn call(session: &str, agent: &str, argv: &str, at: u64) -> Call {
        Call {
            session: session.into(),
            agent: agent.into(),
            argv: words(argv),
            at,
            tree: crate::proc_tree::ancestors(),
        }
    }

    #[test]
    fn a_line_matches_its_argv_and_an_expanded_word_matches_any() {
        let argv = words("vote demo-a --for ship --used none");
        assert!(argv_matches(&argv, &argv));
        assert!(argv_matches(
            &words("vote $ISSUE --for ship --used none"),
            &argv
        ));
        assert!(!argv_matches(
            &words("vote demo-a --for hold --used none"),
            &argv
        ));
        assert!(!argv_matches(&words("vote demo-a --for ship"), &argv));
    }

    #[test]
    fn the_newest_matching_call_is_taken_once_and_a_stale_one_is_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let shell = shell_dir(dir.path(), "sess-1");
        let line = "vote demo-a --for ship --used none";
        put(
            &shell.join("toolu_old.0.json"),
            &call("sess-1", "agent-b", line, 1_000),
        );
        put(
            &shell.join("toolu_new.0.json"),
            &call("sess-1", "", line, 2_000),
        );
        put(
            &shell.join("toolu_sub.0.json"),
            &call("sess-1", "agent-a", line, 1_500),
        );
        put(
            &shell.join("toolu_other.0.json"),
            &call("sess-1", "agent-c", "recall demo-a", 2_500),
        );
        let argv = words(line);
        let now = 3_000;
        let mine = crate::proc_tree::ancestors();
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, now, &mine).as_deref(),
            Some("")
        );
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, now, &mine).as_deref(),
            Some("agent-a")
        );
        assert_eq!(
            claim_command_in(dir.path(), "sess-2", &argv, now, &mine),
            None,
            "another session's call names no agent of this one"
        );
        let late = 2_000 + CALL_TTL_MS + 1;
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, late, &mine),
            None
        );
        assert!(!shell.join("toolu_old.0.json").exists());
        assert!(!shell.join("toolu_new.0.taken").exists());
    }

    #[test]
    fn a_process_with_no_session_takes_the_newest_call_of_any_session() {
        let dir = tempfile::tempdir().unwrap();
        let line = "vote demo-a --for ship --used none --as reviewer";
        put(
            &shell_dir(dir.path(), "sess-1").join("toolu_a.0.json"),
            &call("sess-1", "agent-a", line, 1_000),
        );
        put(
            &shell_dir(dir.path(), "sess-2").join("toolu_b.0.json"),
            &call("sess-2", "agent-b", line, 2_000),
        );
        put(
            &shell_dir(dir.path(), "sess-2").join("toolu_c.0.json"),
            &call("sess-2", "", "recall demo-a", 3_000),
        );
        let argv = words(line);
        let now = 4_000;
        let mine = crate::proc_tree::ancestors();
        assert_eq!(
            claim_any_in(dir.path(), &argv, now, &mine),
            Some(("sess-2".into(), "agent-b".into()))
        );
        assert_eq!(
            claim_any_in(dir.path(), &argv, now, &mine),
            Some(("sess-1".into(), "agent-a".into()))
        );
        assert_eq!(
            claim_any_in(dir.path(), &argv, 2_000 + CALL_TTL_MS + 1, &mine),
            None
        );
        assert_eq!(
            claim_any_in(
                dir.path(),
                &words("recall demo-a"),
                3_000 + CALL_TTL_MS + 1,
                &mine
            ),
            None
        );
        let empty = tempfile::tempdir().unwrap();
        assert_eq!(claim_any_in(empty.path(), &argv, now, &mine), None);
    }

    #[test]
    fn a_line_run_again_binds_what_its_first_run_took() {
        let dir = tempfile::tempdir().unwrap();
        let shell = shell_dir(dir.path(), "sess-1");
        let line = "vote demo-a --for ship --used none --as reviewer";
        let argv = words(line);
        let mine = crate::proc_tree::ancestors();
        put(
            &shell.join("toolu_a.0.json"),
            &call("sess-1", "agent-a", line, 1_000),
        );
        let first = Some(("sess-1".to_string(), "agent-a".to_string()));
        assert_eq!(claim_any_in(dir.path(), &argv, 2_000, &mine), first);
        forget(dir.path(), "sess-1", "toolu_a");
        assert!(shell.join("toolu_a.0.taken").exists());
        assert_eq!(claim_any_in(dir.path(), &argv, 2_500, &mine), first);
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, 2_500, &mine).as_deref(),
            Some("agent-a")
        );
        put(
            &shell.join("toolu_b.0.json"),
            &call("sess-1", "", line, 1_500),
        );
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, 2_500, &mine).as_deref(),
            Some(""),
            "a call still waiting comes before one already taken"
        );
        let mut elsewhere = call("sess-1", "agent-x", line, 1_800);
        elsewhere.tree.clear();
        put(&shell.join("toolu_x.0.taken"), &elsewhere);
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, 2_500, &mine).as_deref(),
            Some(""),
            "a taken call names no session unless its hook ran above this one"
        );
    }

    #[test]
    fn a_line_whose_environment_names_another_session_still_finds_its_harness() {
        let dir = tempfile::tempdir().unwrap();
        let line = "vote demo-a --for ship --used none --as reviewer";
        let argv = words(line);
        let mine = crate::proc_tree::ancestors();
        put(
            &shell_dir(dir.path(), "sess-hook").join("toolu_h.0.json"),
            &call("sess-hook", "", line, 1_000),
        );
        let taken = claim_in(dir.path(), Some("sess-env"), &argv, 2_000, &mine).unwrap();
        assert_eq!(taken.session, "sess-hook");
        assert!(taken.harness.same(&mine[0]));
        assert_eq!(
            claim_command_in(dir.path(), "sess-env", &argv, 2_000, &mine),
            None,
            "the hook's session names no agent of the environment's"
        );
    }

    #[test]
    fn a_call_whose_hook_ran_in_another_tree_is_not_taken() {
        let dir = tempfile::tempdir().unwrap();
        let line = "vote demo-a --for ship --used none --as reviewer";
        let argv = words(line);
        let mine = crate::proc_tree::ancestors();
        let mut sibling = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .unwrap();
        let reused = crate::proc_tree::Proc {
            start: mine[0].start + 1,
            ..mine[0].clone()
        };
        let forged = [
            ("toolu_bare", Vec::new()),
            (
                "toolu_sibling",
                vec![crate::proc_tree::of(sibling.id()).unwrap()],
            ),
            ("toolu_gone", vec![reused]),
        ];
        for (id, tree) in forged {
            let mut c = call("sess-1", "agent-forged", line, 1_000);
            c.tree = tree;
            put(
                &shell_dir(dir.path(), "sess-1").join(format!("{id}.0.json")),
                &c,
            );
        }
        assert_eq!(claim_any_in(dir.path(), &argv, 2_000, &mine), None);
        assert_eq!(
            claim_command_in(dir.path(), "sess-1", &argv, 2_000, &mine),
            None
        );
        sibling.kill().unwrap();
        sibling.wait().unwrap();
        put(
            &shell_dir(dir.path(), "sess-1").join("toolu_real.0.json"),
            &call("sess-1", "agent-a", line, 1_500),
        );
        assert_eq!(
            claim_any_in(dir.path(), &argv, 2_000, &mine),
            Some(("sess-1".into(), "agent-a".into()))
        );
    }

    #[test]
    fn an_mcp_call_names_its_subagent_once() {
        let dir = tempfile::tempdir().unwrap();
        put(
            &mcp_path(dir.path(), "toolu_a"),
            &call("sess-1", "agent-a", "", 1_000),
        );
        assert_eq!(
            claim_mcp_in(dir.path(), "toolu_a", 2_000),
            Some(("sess-1".into(), "agent-a".into()))
        );
        assert_eq!(claim_mcp_in(dir.path(), "toolu_a", 2_000), None);
        assert_eq!(claim_mcp_in(dir.path(), "toolu_b", 2_000), None);
        put(
            &mcp_path(dir.path(), "toolu_c"),
            &call("sess-1", "agent-c", "", 1_000),
        );
        assert_eq!(claim_mcp_in(dir.path(), "../toolu_c", 2_000), None);
        assert_eq!(
            claim_mcp_in(dir.path(), "toolu_c", 1_000 + MCP_CALL_TTL_MS + 1),
            None
        );
    }

    #[test]
    fn a_seat_shaped_name_needs_the_configured_server() {
        let keys = BTreeSet::from(["ljos".to_string(), "my__seat".to_string()]);
        assert!(seat_call_matches("mcp__ljos__ljos_vote", None, &keys));
        assert!(seat_call_matches("mcp__my__seat__ljos_vote", None, &keys));
        assert!(seat_call_matches(
            "mcp__ljos__ljos_vote",
            Some("ljos"),
            &keys
        ));
        assert!(seat_call_matches("ljos_note", Some("ljos"), &keys));
        assert!(!seat_call_matches(
            "mcp__plugin_ljos_ljos__ljos_vote",
            None,
            &keys
        ));
        assert!(!seat_call_matches("mcp__github__ljos_note", None, &keys));
        assert!(!seat_call_matches("mcp__Ljos__ljos_vote", None, &keys));
        assert!(!seat_call_matches(
            "mcp__ljos__ljos_vote",
            Some("github"),
            &keys
        ));
        assert!(!seat_call_matches("mcp:ljos:ljos_vote", None, &keys));
        assert!(!seat_call_matches("ljos_vote", None, &keys));
        assert!(!seat_call_matches(
            "mcp__github__add_issue_comment",
            None,
            &keys
        ));
        assert!(!seat_call_matches("Bash", None, &keys));
        assert!(!seat_call_matches(
            "mcp__ljos__ljos_vote",
            None,
            &BTreeSet::new()
        ));
    }
}