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
//! Handlers for session management endpoints.
//!
//! Implements:
//! - `GET /api/v1/sessions/current` — get the active session for the calling agent
//! - `POST /api/v1/sessions/start` — start a new session
//! - `POST /api/v1/sessions/end` — end the current session
//! - `POST /api/v1/sessions/work/:id` — set the active issue for the current session

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};

use crate::server::{
    errors::{bad_request, internal_error, not_found},
    state::AppState,
    types::{
        ApiError, EndSessionRequest, OkResponse, SessionResponse, StartSessionRequest,
        WorkOnIssueRequest,
    },
};

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

/// `GET /api/v1/sessions/current` — return the active (not yet ended) session.
///
/// Accepts an optional `?agent_id=` query param to scope to a specific agent.
///
/// # Errors
///
/// Returns an error if no active session is found or the database query fails.
pub async fn get_current_session(
    State(state): State<AppState>,
    axum::extract::Query(params): axum::extract::Query<
        std::collections::HashMap<String, String, std::hash::RandomState>,
    >,
) -> Result<Json<SessionResponse>, (StatusCode, Json<ApiError>)> {
    let agent_id = params.get("agent_id").map(std::string::String::as_str);
    let db = state.db().await;

    let session = db
        .get_current_session_for_agent(agent_id)
        .map_err(|e| internal_error("Failed to query current session", e))?
        .ok_or_else(|| not_found("No active session found"))?;

    drop(db);
    Ok(Json(SessionResponse { session }))
}

/// `POST /api/v1/sessions/start` — start a new session.
///
/// Body: `{"agent_id": "<optional>"}`.
///
/// Returns the newly created session.
///
/// # Errors
///
/// Returns an error if creating or fetching the new session fails.
pub async fn start_session(
    State(state): State<AppState>,
    Json(body): Json<StartSessionRequest>,
) -> Result<Json<SessionResponse>, (StatusCode, Json<ApiError>)> {
    let db = state.db().await;

    let agent_id_ref = body.agent_id.as_deref();
    let session_id = db
        .start_session_with_agent(agent_id_ref)
        .map_err(|e| internal_error("Failed to start session", e))?;

    // Fetch the newly-created session to return it.
    let session = db
        .get_current_session_for_agent(agent_id_ref)
        .map_err(|e| internal_error("Failed to fetch new session", e))?
        .ok_or_else(|| {
            internal_error("Session created but not found", format!("id={session_id}"))
        })?;

    drop(db);
    Ok(Json(SessionResponse { session }))
}

/// `POST /api/v1/sessions/end` — end the current active session.
///
/// Body: `{"notes": "<optional handoff notes>"}`.
///
/// To end a session scoped to a specific agent, pass `?agent_id=` as a query param.
///
/// # Errors
///
/// Returns an error if no active session is found or ending it fails.
pub async fn end_session(
    State(state): State<AppState>,
    axum::extract::Query(params): axum::extract::Query<
        std::collections::HashMap<String, String, std::hash::RandomState>,
    >,
    Json(body): Json<EndSessionRequest>,
) -> Result<Json<OkResponse>, (StatusCode, Json<ApiError>)> {
    let agent_id = params.get("agent_id").map(std::string::String::as_str);
    let db = state.db().await;

    // Find the current active session so we know its ID.
    let session = db
        .get_current_session_for_agent(agent_id)
        .map_err(|e| internal_error("Failed to query current session", e))?
        .ok_or_else(|| not_found("No active session to end"))?;

    let ended = db
        .end_session(session.id, body.notes.as_deref())
        .map_err(|e| internal_error("Failed to end session", e))?;

    drop(db);
    if !ended {
        return Err(bad_request(format!(
            "Session {} could not be ended (already ended?)",
            session.id
        )));
    }

    Ok(Json(OkResponse { ok: true }))
}

/// `POST /api/v1/sessions/work/:id` — set the active issue for the current session.
///
/// `:id` is the crosslink issue ID to mark as the current work item.
/// Accepts an optional `?agent_id=` query param to scope to a specific agent's session.
///
/// # Errors
///
/// Returns an error if the issue is not found, no active session exists, or the update fails.
pub async fn work_on_issue(
    State(state): State<AppState>,
    Path(issue_id): Path<i64>,
    axum::extract::Query(params): axum::extract::Query<WorkOnIssueRequest>,
) -> Result<Json<OkResponse>, (StatusCode, Json<ApiError>)> {
    let agent_id = params.agent_id.as_deref();
    let db = state.db().await;

    // Verify the issue exists before updating the session.
    let issue_exists = db
        .get_issue(issue_id)
        .map_err(|e| internal_error("Failed to look up issue", e))?
        .is_some();

    if !issue_exists {
        return Err(not_found(format!("Issue {issue_id} not found")));
    }

    // Find the current session.
    let session = db
        .get_current_session_for_agent(agent_id)
        .map_err(|e| internal_error("Failed to query current session", e))?
        .ok_or_else(|| not_found("No active session — call POST /sessions/start first"))?;

    let updated = db
        .set_session_issue(session.id, issue_id)
        .map_err(|e| internal_error("Failed to update session issue", e))?;

    drop(db);
    if !updated {
        return Err(internal_error("set_session_issue returned false", ""));
    }

    Ok(Json(OkResponse { ok: true }))
}

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

#[cfg(test)]
mod tests {
    use axum::{
        body::Body,
        http::{Method, Request, StatusCode},
        Router,
    };
    use serde_json::{json, Value};
    use tower::util::ServiceExt;

    use crate::db::Database;
    use crate::server::{routes::build_router, state::AppState};

    fn test_app() -> (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 state = AppState::new(db, dir.path().join(".crosslink"));
        (build_router(state, None), dir)
    }

    async fn body_json(resp: axum::response::Response) -> 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_get_current_session_no_session() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/sessions/current")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_start_session_returns_session() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert!(body.get("id").is_some());
        assert!(body.get("started_at").is_some());
        assert!(body.get("ended_at").unwrap().is_null());
    }

    #[tokio::test]
    async fn test_start_session_with_agent_id() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({"agent_id": "my-agent"}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["agent_id"], "my-agent");
    }

    #[tokio::test]
    async fn test_end_session_no_active_session() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/end")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_work_on_issue_no_session() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/work/1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // No active session → 404
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_get_current_session_after_start() {
        let (app, _dir) = test_app();
        // Start a session
        let start_resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({"agent_id": "test-agent"}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(start_resp.status(), StatusCode::OK);

        // Now fetch the current session
        let get_resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/sessions/current?agent_id=test-agent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(get_resp.status(), StatusCode::OK);
        let body = body_json(get_resp).await;
        assert_eq!(body["agent_id"], "test-agent");
        assert!(body["ended_at"].is_null());
    }

    #[tokio::test]
    async fn test_end_session_success() {
        let (app, _dir) = test_app();
        // Start a session first
        app.clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        json!({"agent_id": "end-test-agent"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // End it
        let end_resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/end?agent_id=end-test-agent")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({"notes": "done"}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(end_resp.status(), StatusCode::OK);
        let body = body_json(end_resp).await;
        assert_eq!(body["ok"], true);
    }

    /// Helper that returns (Router, `TempDir`) with an active session and a created issue.
    fn test_app_with_session_and_issue() -> (Router, tempfile::TempDir, i64) {
        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();
        // Start a session and create an issue directly via db
        db.start_session().unwrap();
        let issue_id = db.create_issue("work item", None, "medium").unwrap();
        let state = AppState::new(db, crosslink_dir);
        (build_router(state, None), dir, issue_id)
    }

    #[tokio::test]
    async fn test_work_on_issue_success() {
        let (app, _dir, issue_id) = test_app_with_session_and_issue();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri(format!("/api/v1/sessions/work/{issue_id}"))
                    .body(Body::empty())
                    .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_work_on_issue_not_found() {
        let (app, _dir, _) = test_app_with_session_and_issue();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/work/9999")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        let body = body_json(resp).await;
        assert!(body["detail"].as_str().unwrap().contains("9999"));
    }

    #[test]
    fn test_helper_functions() {
        let (status, json) = crate::server::errors::internal_error("ctx", "err");
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(json.error, "ctx");

        let (status, json) = crate::server::errors::not_found("gone");
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(json.detail.as_deref(), Some("gone"));

        let (status, json) = crate::server::errors::bad_request("invalid");
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json.detail.as_deref(), Some("invalid"));
    }

    #[tokio::test]
    async fn test_get_current_session_with_agent_id_scoping() {
        // Start two sessions for different agents, verify current session
        // returns the right one when scoped by agent_id.
        let (app, _dir) = test_app();

        // Start session for agent-alpha
        app.clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"agent_id": "agent-alpha"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Start session for agent-beta
        app.clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"agent_id": "agent-beta"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Fetch current session for agent-beta
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/sessions/current?agent_id=agent-beta")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        // SessionResponse wraps the session object
        assert_eq!(body["agent_id"], "agent-beta");
    }

    #[tokio::test]
    async fn test_end_session_with_notes() {
        // Start a session and end it with notes.
        let (app, _dir) = test_app();

        app.clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/start")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"agent_id": "note-agent"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        let end_resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/api/v1/sessions/end?agent_id=note-agent")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"notes": "finished implementing feature X"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(end_resp.status(), StatusCode::OK);
        let body = body_json(end_resp).await;
        assert_eq!(body["ok"], true);
    }
}