crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
//! Handlers for agent monitoring and lock endpoints.
//!
//! Implements:
//! - `GET /api/v1/agents` — list all agents with latest heartbeat and status
//! - `GET /api/v1/agents/:id` — single agent detail with heartbeat history, locks, kickoff status
//! - `GET /api/v1/agents/:id/status` — kickoff status for a specific agent
//! - `GET /api/v1/locks` — all current locks
//! - `GET /api/v1/locks/stale` — stale locks with age

use std::path::{Path, PathBuf};

use axum::{
    extract::{Path as AxumPath, State},
    http::StatusCode,
    response::Json,
};
use chrono::{Duration, Utc};
use serde::Serialize;
use serde_json::{json, Value};

use crate::server::{
    state::AppState,
    types::{AgentDetail, AgentStatus, AgentSummary, ApiError, LockEntry},
};
use crate::sync::SyncManager;

// ---------------------------------------------------------------------------
// Staleness thresholds
// ---------------------------------------------------------------------------

/// Heartbeat age below which an agent is considered "active".
const ACTIVE_THRESHOLD_SECS: i64 = 5 * 60;
/// Heartbeat age above which an agent is considered "stale" (between this and
/// `ACTIVE_THRESHOLD` is "idle").
const IDLE_THRESHOLD_SECS: i64 = 30 * 60;

// ---------------------------------------------------------------------------
// Helper types
// ---------------------------------------------------------------------------

/// Response for `GET /api/v1/agents/:id/status`.
#[derive(Debug, Serialize)]
pub struct AgentStatusResponse {
    pub agent_id: String,
    /// Content of `.kickoff-status` file, or a derived string when not present.
    pub kickoff_status: String,
    /// Absolute path of the agent's git worktree, if discoverable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree_path: Option<String>,
    /// Whether the agent's tmux session is currently running.
    pub tmux_session_active: bool,
}

// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------

/// Classify an agent's status from its heartbeat age in seconds.
const fn classify_status(age_secs: i64) -> AgentStatus {
    if age_secs < ACTIVE_THRESHOLD_SECS {
        AgentStatus::Active
    } else if age_secs < IDLE_THRESHOLD_SECS {
        AgentStatus::Idle
    } else {
        AgentStatus::Stale
    }
}

/// Scan `.worktrees/` for a directory whose name matches the given `agent_id`.
///
/// Matching rules (tried in order):
/// 1. Exact slug match.
/// 2. Word-boundary match: the `agent_id` contains the slug (or vice versa)
///    at a word boundary (preceded/followed by start/end or `-`/`_`/`.`).
///
/// The word-boundary constraint prevents false positives like agent "a"
/// matching worktree "abc" or short common substrings matching unrelated
/// worktrees.
fn find_worktree_for_agent(root: &Path, agent_id: &str) -> Option<PathBuf> {
    let worktrees_dir = root.join(".worktrees");
    if !worktrees_dir.is_dir() {
        return None;
    }
    std::fs::read_dir(&worktrees_dir)
        .ok()?
        .filter_map(std::result::Result::ok)
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .find(|e| {
            let slug = e.file_name().to_string_lossy().to_string();
            agent_id == slug
                || contains_at_word_boundary(agent_id, &slug)
                || contains_at_word_boundary(&slug, agent_id)
        })
        .map(|e| e.path())
}

/// Returns true if `haystack` contains `needle` at a word boundary.
///
/// A word boundary means the character immediately before and after the
/// match is either absent (start/end of string) or a separator (`-`, `_`, `.`).
const fn is_boundary(c: u8) -> bool {
    matches!(c, b'-' | b'_' | b'.')
}

fn contains_at_word_boundary(haystack: &str, needle: &str) -> bool {
    if needle.is_empty() || needle.len() > haystack.len() {
        return false;
    }
    let h = haystack.as_bytes();
    let n = needle.as_bytes();
    for start in 0..=(h.len() - n.len()) {
        if &h[start..start + n.len()] == n {
            let left_ok = start == 0 || is_boundary(h[start - 1]);
            let right_ok = start + n.len() == h.len() || is_boundary(h[start + n.len()]);
            if left_ok && right_ok {
                return true;
            }
        }
    }
    false
}

/// Read the current git branch from a linked worktree directory.
///
/// In a git linked worktree the `.git` entry is a *file* (not a directory)
/// containing `gitdir: <path>`.  We resolve that path and read the `HEAD`
/// file from it.
fn read_worktree_branch(worktree: &Path) -> Option<String> {
    let git_entry = worktree.join(".git");
    let head_content = if git_entry.is_file() {
        // Linked worktree: .git is a file with "gitdir: <path>"
        let git_file = std::fs::read_to_string(&git_entry).ok()?;
        let gitdir = git_file.strip_prefix("gitdir: ")?.trim();
        let head_path = PathBuf::from(gitdir).join("HEAD");
        std::fs::read_to_string(&head_path).ok()?
    } else if git_entry.is_dir() {
        // Bare-style: .git/HEAD
        std::fs::read_to_string(git_entry.join("HEAD")).ok()?
    } else {
        return None;
    };

    // HEAD contains either "ref: refs/heads/<branch>" or a detached SHA.
    head_content
        .strip_prefix("ref: refs/heads/")
        .map(|b| b.trim().to_string())
}

/// Return `true` if the named tmux session is currently running.
///
/// Uses `tokio::process::Command` to avoid blocking the async runtime.
async fn tmux_session_exists(name: &str) -> bool {
    tokio::process::Command::new("tmux")
        .args(["has-session", "-t", name])
        .output()
        .await
        .is_ok_and(|o| o.status.success())
}

/// Derive the expected tmux session name for a worktree slug.
///
/// Mirrors the logic in `commands::kickoff::tmux_session_name`.
fn agent_tmux_session(agent_id: &str) -> String {
    // Strip common prefixes used in agent IDs / branch names
    let slug = agent_id
        .strip_prefix("feature/")
        .or_else(|| agent_id.strip_prefix("feat-"))
        .unwrap_or(agent_id);
    // Split on "--": agent IDs are "<parent>--<slug>"; we want the last part
    let wt_slug = slug.rsplit("--").next().unwrap_or(slug);
    let raw = format!("feat-{wt_slug}");
    let sanitized: String = raw
        .chars()
        .map(|c| if c == '.' || c == ':' { '-' } else { c })
        .collect();
    if sanitized.len() > 50 {
        sanitized[..50].to_string()
    } else {
        sanitized
    }
}

use crate::server::errors::internal_error;

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

/// `GET /api/v1/agents` — list all known agents with latest heartbeat and status.
///
/// # Errors
///
/// Returns an error if the sync manager or heartbeat/lock reads fail.
pub async fn list_agents(
    State(state): State<AppState>,
) -> Result<Json<Value>, (StatusCode, Json<ApiError>)> {
    let sync = SyncManager::new(&state.crosslink_dir)
        .map_err(|e| internal_error("Failed to initialise SyncManager", e))?;

    let heartbeats = sync
        .read_heartbeats_auto()
        .map_err(|e| internal_error("Failed to read heartbeats", e))?;

    let locks_file = sync
        .read_locks_auto()
        .unwrap_or_else(|_| crate::locks::LocksFile::empty());

    let now = Utc::now();
    let root = state
        .crosslink_dir
        .parent()
        .map_or_else(|| state.crosslink_dir.clone(), std::path::Path::to_path_buf);

    let agents: Vec<AgentSummary> = heartbeats
        .into_iter()
        .map(|hb| {
            let age_secs = now
                .signed_duration_since(hb.last_heartbeat)
                .max(Duration::zero())
                .num_seconds();
            let status = classify_status(age_secs);
            let agent_locks = locks_file.agent_locks(&hb.agent_id);
            let worktree = find_worktree_for_agent(&root, &hb.agent_id);
            let branch = worktree.as_deref().and_then(read_worktree_branch);
            let worktree_path = worktree.map(|p| p.to_string_lossy().into_owned());
            AgentSummary {
                agent_id: hb.agent_id,
                machine_id: hb.machine_id,
                description: None,
                status,
                last_heartbeat: hb.last_heartbeat,
                active_issue_id: hb.active_issue_id,
                branch,
                worktree_path,
                locks: agent_locks,
            }
        })
        .collect();

    let total = agents.len();
    Ok(Json(json!({
        "items": agents,
        "total": total
    })))
}

/// `GET /api/v1/agents/:id` — detailed view of a single agent.
///
/// # Errors
///
/// Returns an error if the sync manager or heartbeat/lock reads fail.
pub async fn get_agent(
    State(state): State<AppState>,
    AxumPath(agent_id): AxumPath<String>,
) -> Result<Json<AgentDetail>, (StatusCode, Json<ApiError>)> {
    let sync = SyncManager::new(&state.crosslink_dir)
        .map_err(|e| internal_error("Failed to initialise SyncManager", e))?;

    let heartbeats = sync
        .read_heartbeats_auto()
        .map_err(|e| internal_error("Failed to read heartbeats", e))?;

    let hb = heartbeats.into_iter().find(|h| h.agent_id == agent_id);

    let locks_file = sync
        .read_locks_auto()
        .unwrap_or_else(|_| crate::locks::LocksFile::empty());

    let now = Utc::now();
    let (status, agent_locks) = hb.as_ref().map_or_else(
        || (AgentStatus::Unknown, locks_file.agent_locks(&agent_id)),
        |h| {
            let age_secs = now
                .signed_duration_since(h.last_heartbeat)
                .max(Duration::zero())
                .num_seconds();
            (
                classify_status(age_secs),
                locks_file.agent_locks(&h.agent_id),
            )
        },
    );

    let root = state
        .crosslink_dir
        .parent()
        .map_or_else(|| state.crosslink_dir.clone(), std::path::Path::to_path_buf);

    let worktree = find_worktree_for_agent(&root, &agent_id);
    let branch = worktree.as_deref().and_then(read_worktree_branch);
    let worktree_path = worktree.as_ref().map(|p| p.to_string_lossy().into_owned());

    let kickoff_status = worktree.as_ref().and_then(|wt| {
        let path = wt.join(".kickoff-status");
        std::fs::read_to_string(path)
            .ok()
            .map(|s| s.trim().to_string())
    });

    let heartbeat_history = hb
        .as_ref()
        .map(|h| vec![h.last_heartbeat])
        .unwrap_or_default();

    let summary = AgentSummary {
        agent_id: hb
            .as_ref()
            .map_or_else(|| agent_id.clone(), |h| h.agent_id.clone()),
        machine_id: hb
            .as_ref()
            .map(|h| h.machine_id.clone())
            .unwrap_or_default(),
        description: None,
        status,
        last_heartbeat: hb.as_ref().map_or_else(Utc::now, |h| h.last_heartbeat),
        active_issue_id: hb.as_ref().and_then(|h| h.active_issue_id),
        branch,
        worktree_path,
        locks: agent_locks,
    };

    Ok(Json(AgentDetail {
        summary,
        heartbeat_history,
        kickoff_status,
    }))
}

/// `GET /api/v1/agents/:id/status` — kickoff status for a specific agent.
///
/// Reads the `.kickoff-status` file from the agent's worktree (if present)
/// and reports whether the agent's tmux session is still running.
///
/// # Errors
///
/// Returns an error if the agent status cannot be determined.
pub async fn get_agent_status(
    State(state): State<AppState>,
    AxumPath(agent_id): AxumPath<String>,
) -> Result<Json<AgentStatusResponse>, (StatusCode, Json<ApiError>)> {
    let root = state
        .crosslink_dir
        .parent()
        .map_or_else(|| state.crosslink_dir.clone(), std::path::Path::to_path_buf);

    let worktree = find_worktree_for_agent(&root, &agent_id);

    let kickoff_status = worktree.as_ref().map_or_else(
        || "unknown".to_string(),
        |wt| {
            let path = wt.join(".kickoff-status");
            if path.exists() {
                std::fs::read_to_string(&path)
                    .unwrap_or_default()
                    .trim()
                    .to_string()
            } else {
                "running".to_string()
            }
        },
    );

    let session_name = agent_tmux_session(&agent_id);
    let tmux_session_active = tmux_session_exists(&session_name).await;

    Ok(Json(AgentStatusResponse {
        agent_id,
        kickoff_status,
        worktree_path: worktree.map(|p| p.to_string_lossy().into_owned()),
        tmux_session_active,
    }))
}

/// `GET /api/v1/locks` — all active locks with derived metadata.
///
/// # Errors
///
/// Returns an error if the sync manager or lock reads fail.
pub async fn list_locks(
    State(state): State<AppState>,
) -> Result<Json<Value>, (StatusCode, Json<ApiError>)> {
    let sync = SyncManager::new(&state.crosslink_dir)
        .map_err(|e| internal_error("Failed to initialise SyncManager", e))?;

    let locks_file = sync
        .read_locks_auto()
        .map_err(|e| internal_error("Failed to read locks", e))?;

    let now = Utc::now();
    let stale_timeout =
        Duration::minutes(locks_file.settings.stale_lock_timeout_minutes.cast_signed());

    let entries: Vec<LockEntry> = locks_file
        .locks
        .iter()
        .map(|(issue_id, lock)| {
            let age = now
                .signed_duration_since(lock.claimed_at)
                .max(Duration::zero());
            let is_stale = age >= stale_timeout;
            LockEntry {
                issue_id: *issue_id,
                agent_id: lock.agent_id.clone(),
                branch: lock.branch.clone(),
                claimed_at: lock.claimed_at,
                signed_by: lock.signed_by.clone(),
                age_seconds: age.num_seconds(),
                is_stale,
            }
        })
        .collect();

    let total = entries.len();
    Ok(Json(json!({
        "items": entries,
        "total": total
    })))
}

/// `GET /api/v1/locks/stale` — locks whose holding agent has gone stale.
///
/// Uses `SyncManager::find_stale_locks_with_age` which accounts for the
/// agent's heartbeat freshness, not just lock claimed-at time.
///
/// # Errors
///
/// Returns an error if the sync manager or stale lock detection fails.
pub async fn list_stale_locks(
    State(state): State<AppState>,
) -> Result<Json<Value>, (StatusCode, Json<ApiError>)> {
    let sync = SyncManager::new(&state.crosslink_dir)
        .map_err(|e| internal_error("Failed to initialise SyncManager", e))?;

    let stale_locks = sync
        .find_stale_locks_with_age()
        .map_err(|e| internal_error("Failed to read stale locks", e))?;

    // Re-read the full locks file to get branch/claimed_at/signed_by.
    let locks_file = sync
        .read_locks_auto()
        .unwrap_or_else(|_| crate::locks::LocksFile::empty());

    let now = Utc::now();
    let entries: Vec<LockEntry> = stale_locks
        .into_iter()
        .filter_map(|(issue_id, _agent_id_from_stale, _age_minutes)| {
            let lock = locks_file.get_lock(issue_id)?;
            let age_secs = now
                .signed_duration_since(lock.claimed_at)
                .max(Duration::zero())
                .num_seconds();
            Some(LockEntry {
                issue_id,
                agent_id: lock.agent_id.clone(),
                branch: lock.branch.clone(),
                claimed_at: lock.claimed_at,
                signed_by: lock.signed_by.clone(),
                age_seconds: age_secs,
                is_stale: true,
            })
        })
        .collect();

    let total = entries.len();
    Ok(Json(json!({
        "items": entries,
        "total": total
    })))
}

// ---------------------------------------------------------------------------
// Lock change notification
// ---------------------------------------------------------------------------

/// Request body for `POST /api/v1/locks/notify`.
#[derive(serde::Deserialize)]
pub struct LockNotifyRequest {
    pub issue_id: i64,
    pub action: String,
    pub agent_id: String,
}

/// `POST /api/v1/locks/notify` — broadcast a lock change event over WebSocket.
///
/// Agents call this after claiming or releasing a lock so that all connected
/// WebSocket clients are notified in real time.
///
/// # Errors
///
/// Returns an error if the lock action is invalid.
pub async fn notify_lock_changed(
    State(state): State<AppState>,
    Json(body): Json<LockNotifyRequest>,
) -> Result<Json<Value>, (StatusCode, Json<ApiError>)> {
    let action = match body.action.as_str() {
        "claimed" => crate::server::types::LockAction::Claimed,
        "released" => crate::server::types::LockAction::Released,
        other => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(ApiError {
                    error: format!(
                        "Invalid lock action '{other}'. Must be 'claimed' or 'released'"
                    ),
                    detail: None,
                }),
            ));
        }
    };

    // INTENTIONAL: broadcast failure is harmless when no WebSocket subscribers are connected
    let _ = state.ws_tx.send(crate::server::ws::WsEvent::LockChanged(
        crate::server::types::WsLockChangedEvent {
            event_type: crate::server::types::WsEventType::LockChanged,
            issue_id: body.issue_id,
            action,
            agent_id: body.agent_id,
        },
    ));

    Ok(Json(json!({ "ok": true })))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_classify_status_active() {
        assert_eq!(classify_status(0), AgentStatus::Active);
        assert_eq!(classify_status(60), AgentStatus::Active);
        assert_eq!(
            classify_status(ACTIVE_THRESHOLD_SECS - 1),
            AgentStatus::Active
        );
    }

    #[test]
    fn test_classify_status_idle() {
        assert_eq!(classify_status(ACTIVE_THRESHOLD_SECS), AgentStatus::Idle);
        assert_eq!(classify_status(IDLE_THRESHOLD_SECS - 1), AgentStatus::Idle);
    }

    #[test]
    fn test_classify_status_stale() {
        assert_eq!(classify_status(IDLE_THRESHOLD_SECS), AgentStatus::Stale);
        assert_eq!(
            classify_status(IDLE_THRESHOLD_SECS + 3600),
            AgentStatus::Stale
        );
    }

    #[test]
    fn test_agent_tmux_session_basic() {
        let name = agent_tmux_session("add-auth-feature");
        assert_eq!(name, "feat-add-auth-feature");
    }

    #[test]
    fn test_agent_tmux_session_strips_feature_prefix() {
        let name = agent_tmux_session("feature/add-auth");
        assert_eq!(name, "feat-add-auth");
    }

    #[test]
    fn test_agent_tmux_session_sanitizes_dots() {
        let name = agent_tmux_session("fix.auth.bug");
        assert_eq!(name, "feat-fix-auth-bug");
    }

    #[test]
    fn test_agent_tmux_session_truncates() {
        let long = "a".repeat(100);
        let name = agent_tmux_session(&long);
        assert!(name.len() <= 50);
    }

    #[test]
    fn test_find_worktree_exact_match() {
        let dir = tempfile::tempdir().unwrap();
        let worktrees = dir.path().join(".worktrees");
        std::fs::create_dir_all(worktrees.join("my-agent")).unwrap();

        let result = find_worktree_for_agent(dir.path(), "my-agent");
        assert!(result.is_some());
        assert!(result.unwrap().ends_with("my-agent"));
    }

    #[test]
    fn test_find_worktree_no_match() {
        let dir = tempfile::tempdir().unwrap();
        let worktrees = dir.path().join(".worktrees");
        std::fs::create_dir_all(worktrees.join("other-agent")).unwrap();

        let result = find_worktree_for_agent(dir.path(), "nonexistent-xyz");
        assert!(result.is_none());
    }

    #[test]
    fn test_find_worktree_no_worktrees_dir() {
        let dir = tempfile::tempdir().unwrap();
        let result = find_worktree_for_agent(dir.path(), "my-agent");
        assert!(result.is_none());
    }

    #[test]
    fn test_read_worktree_branch_from_file() {
        let dir = tempfile::tempdir().unwrap();
        // Simulate a linked worktree: .git is a file pointing to a real gitdir
        let gitdir = dir.path().join("gitdir");
        std::fs::create_dir_all(&gitdir).unwrap();
        std::fs::write(gitdir.join("HEAD"), "ref: refs/heads/feature/my-branch\n").unwrap();
        std::fs::write(
            dir.path().join(".git"),
            format!("gitdir: {}\n", gitdir.display()),
        )
        .unwrap();

        let branch = read_worktree_branch(dir.path());
        assert_eq!(branch, Some("feature/my-branch".to_string()));
    }

    #[test]
    fn test_read_worktree_branch_detached() {
        let dir = tempfile::tempdir().unwrap();
        let gitdir = dir.path().join("gitdir");
        std::fs::create_dir_all(&gitdir).unwrap();
        // Detached HEAD — just a SHA, no "ref: refs/heads/" prefix
        std::fs::write(
            gitdir.join("HEAD"),
            "abc123def456abc123def456abc123def456abc1\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join(".git"),
            format!("gitdir: {}\n", gitdir.display()),
        )
        .unwrap();

        // Detached HEAD has no branch name — should return None
        let branch = read_worktree_branch(dir.path());
        assert!(branch.is_none());
    }

    #[test]
    fn test_read_worktree_branch_bare_git_dir() {
        let dir = tempfile::tempdir().unwrap();
        let git_dir = dir.path().join(".git");
        std::fs::create_dir_all(&git_dir).unwrap();
        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").unwrap();

        let branch = read_worktree_branch(dir.path());
        assert_eq!(branch, Some("main".to_string()));
    }

    #[test]
    fn test_read_worktree_branch_no_git() {
        let dir = tempfile::tempdir().unwrap();
        let branch = read_worktree_branch(dir.path());
        assert!(branch.is_none());
    }

    #[test]
    fn test_agent_tmux_session_double_dash_split() {
        let name = agent_tmux_session("parent--child-slug");
        assert_eq!(name, "feat-child-slug");
    }

    #[test]
    fn test_agent_tmux_session_feat_prefix() {
        let name = agent_tmux_session("feat-my-task");
        assert_eq!(name, "feat-my-task");
    }

    #[test]
    fn test_agent_tmux_session_colons_sanitized() {
        let name = agent_tmux_session("fix:auth:bug");
        assert_eq!(name, "feat-fix-auth-bug");
    }

    #[test]
    fn test_find_worktree_partial_match_agent_contains_slug() {
        let dir = tempfile::tempdir().unwrap();
        let worktrees = dir.path().join(".worktrees");
        std::fs::create_dir_all(worktrees.join("short")).unwrap();

        // agent_id "long-short-name" contains slug "short"
        let result = find_worktree_for_agent(dir.path(), "long-short-name");
        assert!(result.is_some());
    }

    #[test]
    fn test_find_worktree_partial_match_slug_contains_agent() {
        let dir = tempfile::tempdir().unwrap();
        let worktrees = dir.path().join(".worktrees");
        std::fs::create_dir_all(worktrees.join("my-agent-extended")).unwrap();

        // slug "my-agent-extended" contains agent_id "my-agent"
        let result = find_worktree_for_agent(dir.path(), "my-agent");
        assert!(result.is_some());
    }

    #[test]
    fn test_classify_status_boundary_values() {
        // Exactly at active threshold -> idle
        assert_eq!(classify_status(ACTIVE_THRESHOLD_SECS), AgentStatus::Idle);
        // One below active threshold -> active
        assert_eq!(
            classify_status(ACTIVE_THRESHOLD_SECS - 1),
            AgentStatus::Active
        );
        // Exactly at idle threshold -> stale
        assert_eq!(classify_status(IDLE_THRESHOLD_SECS), AgentStatus::Stale);
        // One below idle threshold -> idle
        assert_eq!(classify_status(IDLE_THRESHOLD_SECS - 1), AgentStatus::Idle);
        // Negative age (clock skew) -> active
        assert_eq!(classify_status(-10), AgentStatus::Active);
    }

    // -----------------------------------------------------------------------
    // Handler integration tests
    // -----------------------------------------------------------------------

    use crate::db::Database;
    use crate::server::{routes::build_router, state::AppState};
    use axum::{
        body::Body,
        http::{Method, Request, StatusCode},
    };
    use tower::util::ServiceExt;

    fn test_app() -> (axum::Router, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir)
    }

    /// Create a test app with a heartbeat file seeded in the hub cache.
    fn test_app_with_heartbeat(agent_id: &str) -> (axum::Router, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        // Seed a heartbeat file in the hub cache
        let heartbeats_dir = crosslink_dir.join(".hub-cache").join("heartbeats");
        std::fs::create_dir_all(&heartbeats_dir).unwrap();
        let hb = serde_json::json!({
            "agent_id": agent_id,
            "last_heartbeat": chrono::Utc::now().to_rfc3339(),
            "active_issue_id": null,
            "machine_id": "test-machine"
        });
        std::fs::write(
            heartbeats_dir.join(format!("{agent_id}.json")),
            serde_json::to_string(&hb).unwrap(),
        )
        .unwrap();

        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir)
    }

    async fn body_json(resp: axum::response::Response) -> serde_json::Value {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice(&bytes).unwrap()
    }

    #[tokio::test]
    async fn test_list_agents_empty() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"], 0);
        assert!(body["items"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_list_agents_with_heartbeat() {
        let (app, _dir) = test_app_with_heartbeat("test-agent-1");
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"], 1);
        let items = body["items"].as_array().unwrap();
        assert_eq!(items[0]["agent_id"], "test-agent-1");
        assert_eq!(items[0]["machine_id"], "test-machine");
        assert_eq!(items[0]["status"], "active");
    }

    #[tokio::test]
    async fn test_get_agent_no_heartbeat_returns_unknown() {
        // Use the heartbeat test app so sync is initialized, but query a different agent
        let (app, _dir) = test_app_with_heartbeat("existing-agent");
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/no-heartbeat-agent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // Agent with no heartbeat returns OK with Unknown status when sync
        // is available. In test environments where the hub cache may not be
        // fully initialized, a 500 from SyncManager init is also valid.
        let status = resp.status();
        assert!(
            status == StatusCode::OK || status == StatusCode::INTERNAL_SERVER_ERROR,
            "Expected 200 or 500, got {status}"
        );
        if status == StatusCode::OK {
            let body = body_json(resp).await;
            assert_eq!(body["status"], "unknown");
            assert_eq!(body["agent_id"], "no-heartbeat-agent");
        }
    }

    #[tokio::test]
    async fn test_get_agent_found() {
        let (app, _dir) = test_app_with_heartbeat("my-agent");
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/my-agent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        // AgentDetail uses #[serde(flatten)] on summary, so fields are top-level
        assert_eq!(body["agent_id"], "my-agent");
        assert_eq!(body["status"], "active");
        assert!(body["heartbeat_history"].as_array().unwrap().len() == 1);
    }

    #[tokio::test]
    async fn test_get_agent_status_unknown() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/unknown-agent/status")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["agent_id"], "unknown-agent");
        assert_eq!(body["kickoff_status"], "unknown");
        assert_eq!(body["tmux_session_active"], false);
    }

    #[tokio::test]
    async fn test_list_locks_empty() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/locks")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"], 0);
        assert!(body["items"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_list_stale_locks_empty() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/locks/stale")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"], 0);
        assert!(body["items"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_notify_lock_changed_claimed() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/locks/notify")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "issue_id": 1,
                            "action": "claimed",
                            "agent_id": "agent-1"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["ok"], true);
    }

    #[tokio::test]
    async fn test_notify_lock_changed_released() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/locks/notify")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "issue_id": 42,
                            "action": "released",
                            "agent_id": "agent-2"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["ok"], true);
    }

    #[tokio::test]
    async fn test_notify_lock_changed_invalid_action() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/locks/notify")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "issue_id": 1,
                            "action": "stolen",
                            "agent_id": "agent-1"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = body_json(resp).await;
        assert!(body["error"]
            .as_str()
            .unwrap()
            .contains("Invalid lock action"));
    }

    #[tokio::test]
    async fn test_get_agent_status_with_worktree_no_kickoff_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        // Create a worktree directory matching the agent name
        let worktrees_dir = dir.path().join(".worktrees").join("my-wt-agent");
        std::fs::create_dir_all(&worktrees_dir).unwrap();

        let state = AppState::new(db, crosslink_dir);
        let app = build_router(state, None);

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/my-wt-agent/status")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["agent_id"], "my-wt-agent");
        // No .kickoff-status file → defaults to "running"
        assert_eq!(body["kickoff_status"], "running");
    }

    #[tokio::test]
    async fn test_get_agent_status_with_worktree_and_kickoff_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        // Create a worktree directory matching the agent name
        let worktrees_dir = dir.path().join(".worktrees").join("my-wt-agent2");
        std::fs::create_dir_all(&worktrees_dir).unwrap();
        // Write a .kickoff-status file
        std::fs::write(worktrees_dir.join(".kickoff-status"), "completed\n").unwrap();

        let state = AppState::new(db, crosslink_dir);
        let app = build_router(state, None);

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/my-wt-agent2/status")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["agent_id"], "my-wt-agent2");
        assert_eq!(body["kickoff_status"], "completed");
        assert!(body["worktree_path"].as_str().is_some());
    }

    #[test]
    fn test_internal_error_helper() {
        let (status, json) = crate::server::errors::internal_error("ctx", "boom");
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(json.error, "ctx");
        assert_eq!(json.detail.as_deref(), Some("boom"));
    }

    #[test]
    fn test_not_found_helper() {
        let (status, json) = crate::server::errors::not_found("missing");
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(json.error, "not found");
        assert_eq!(json.detail.as_deref(), Some("missing"));
    }

    /// Test app with a seeded heartbeat AND a worktree directory that contains
    /// a .kickoff-status file, so `get_agent` returns `kickoff_status`.
    fn test_app_with_heartbeat_and_kickoff(
        agent_id: &str,
        kickoff_status: &str,
    ) -> (axum::Router, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        // Seed a heartbeat file in the hub cache.
        let heartbeats_dir = crosslink_dir.join(".hub-cache").join("heartbeats");
        std::fs::create_dir_all(&heartbeats_dir).unwrap();
        let hb = serde_json::json!({
            "agent_id": agent_id,
            "last_heartbeat": chrono::Utc::now().to_rfc3339(),
            "active_issue_id": null,
            "machine_id": "test-machine"
        });
        std::fs::write(
            heartbeats_dir.join(format!("{agent_id}.json")),
            serde_json::to_string(&hb).unwrap(),
        )
        .unwrap();

        // Create a matching worktree with a .kickoff-status file.
        let worktrees_dir = dir.path().join(".worktrees").join(agent_id);
        std::fs::create_dir_all(&worktrees_dir).unwrap();
        std::fs::write(
            worktrees_dir.join(".kickoff-status"),
            format!("{kickoff_status}\n"),
        )
        .unwrap();

        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir)
    }

    #[tokio::test]
    async fn test_get_agent_with_kickoff_status() {
        let (app, _dir) = test_app_with_heartbeat_and_kickoff("kickoff-agent", "completed");
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/agents/kickoff-agent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["agent_id"], "kickoff-agent");
        // kickoff_status should be populated from the .kickoff-status file
        assert_eq!(body["kickoff_status"], "completed");
    }

    /// Seed a locks.json file in the hub cache with one active lock.
    fn test_app_with_lock(agent_id: &str, issue_id: i64) -> (axum::Router, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        let hub_cache = crosslink_dir.join(".hub-cache");
        std::fs::create_dir_all(&hub_cache).unwrap();

        let locks_json = serde_json::json!({
            "version": 1,
            "locks": {
                issue_id.to_string(): {
                    "agent_id": agent_id,
                    "branch": "feature/test",
                    "claimed_at": chrono::Utc::now().to_rfc3339(),
                    "signed_by": ""
                }
            },
            "settings": {
                "stale_lock_timeout_minutes": 30
            }
        });
        std::fs::write(
            hub_cache.join("locks.json"),
            serde_json::to_string(&locks_json).unwrap(),
        )
        .unwrap();

        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir)
    }

    #[tokio::test]
    async fn test_list_locks_with_one_lock() {
        let (app, _dir) = test_app_with_lock("lock-agent", 42);
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/locks")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"], 1);
        let items = body["items"].as_array().unwrap();
        assert_eq!(items[0]["issue_id"], 42);
        assert_eq!(items[0]["agent_id"], "lock-agent");
        assert_eq!(items[0]["branch"], "feature/test");
        assert_eq!(items[0]["is_stale"], false);
    }

    /// Build a test app where the hub cache has a lock and a stale heartbeat so
    /// that `list_stale_locks` returns at least one entry (exercises lines 407-417).
    fn test_app_with_stale_lock(
        agent_id: &str,
        issue_id: i64,
    ) -> (axum::Router, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).expect("test db");
        let crosslink_dir = dir.path().join(".crosslink");
        let hub_cache = crosslink_dir.join(".hub-cache");
        std::fs::create_dir_all(hub_cache.join("heartbeats")).unwrap();

        // A heartbeat that is 120 minutes old → agent is stale (threshold is 30 min)
        let old_time = chrono::Utc::now() - chrono::Duration::minutes(120);
        let hb = serde_json::json!({
            "agent_id": agent_id,
            "last_heartbeat": old_time.to_rfc3339(),
            "active_issue_id": issue_id,
            "machine_id": "test-machine"
        });
        std::fs::write(
            hub_cache
                .join("heartbeats")
                .join(format!("{agent_id}.json")),
            serde_json::to_string(&hb).unwrap(),
        )
        .unwrap();

        // A lock entry claimed at the same old time
        let locks_json = serde_json::json!({
            "version": 1,
            "locks": {
                issue_id.to_string(): {
                    "agent_id": agent_id,
                    "branch": "feature/stale-test",
                    "claimed_at": old_time.to_rfc3339(),
                    "signed_by": ""
                }
            },
            "settings": {
                "stale_lock_timeout_minutes": 30
            }
        });
        std::fs::write(
            hub_cache.join("locks.json"),
            serde_json::to_string(&locks_json).unwrap(),
        )
        .unwrap();

        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir)
    }

    #[tokio::test]
    async fn test_list_stale_locks_with_stale_entry() {
        let (app, _dir) = test_app_with_stale_lock("stale-agent", 77);
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/locks/stale")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        // There should be at least one stale lock entry
        let total = body["total"].as_u64().unwrap_or(0);
        assert!(total >= 1, "expected at least one stale lock, got {total}");
        let items = body["items"].as_array().unwrap();
        let entry = &items[0];
        assert_eq!(entry["issue_id"], 77);
        assert_eq!(entry["agent_id"], "stale-agent");
        assert_eq!(entry["branch"], "feature/stale-test");
        assert_eq!(entry["is_stale"], true);
        // age_seconds should be positive
        assert!(entry["age_seconds"].as_i64().unwrap_or(0) > 0);
    }

    #[test]
    fn test_internal_error_helper_detail_none_via_display() {
        // Verify internal_error formats any Display type correctly
        let (status, json) =
            crate::server::errors::internal_error("db error", std::io::Error::other("disk full"));
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(json.error, "db error");
        assert!(json.detail.as_deref().unwrap().contains("disk full"));
    }

    #[test]
    fn test_not_found_helper_with_owned_string() {
        // Verify not_found accepts an owned String (exercises the Into<String> bound)
        let msg = format!("agent '{}' not found", "worker-1");
        let (status, json) = crate::server::errors::not_found(msg);
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(json.error, "not found");
        assert!(json.detail.as_deref().unwrap().contains("worker-1"));
    }
}