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
//! Handlers for project configuration endpoints.
//!
//! Implements:
//! - `GET /api/v1/config` — read the current hook-config.json
//! - `PATCH /api/v1/config` — merge-update hook-config.json fields

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

use crate::server::{
    errors::{bad_request, internal_error},
    state::AppState,
    types::{ApiError, ConfigResponse, UpdateConfigRequest},
};

/// Extract a `ConfigResponse` from a raw JSON Value.
///
/// Field name mapping between `hook-config.json` and the API response:
///
/// | hook-config.json key         | API response field           |
/// |------------------------------|------------------------------|
/// | `tracking_mode`              | `tracking_mode`              |
/// | `stale_lock_timeout_minutes` | `stale_lock_timeout_minutes` |
/// | `tracker_remote`             | `remote`                     |
/// | `signing_enforcement`        | `signing_enforcement`        |
/// | `intervention_tracking`      | `intervention_tracking`      |
/// | `auto_steal_stale_locks`     | `auto_steal_stale_locks`     |
///
/// Note: the file uses `tracker_remote` while the API exposes `remote`.
/// The `PATCH /api/v1/config` request body also uses `remote`.
fn config_from_value(v: &serde_json::Value) -> ConfigResponse {
    ConfigResponse {
        tracking_mode: v
            .get("tracking_mode")
            .and_then(|x| x.as_str())
            .unwrap_or("normal")
            .to_string(),
        stale_lock_timeout_minutes: v
            .get("stale_lock_timeout_minutes")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(30),
        remote: v
            .get("tracker_remote")
            .and_then(|x| x.as_str())
            .unwrap_or("origin")
            .to_string(),
        signing_enforcement: v
            .get("signing_enforcement")
            .and_then(|x| x.as_str())
            .unwrap_or("off")
            .to_string(),
        intervention_tracking: v
            .get("intervention_tracking")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false),
        auto_steal_stale_locks: v
            .get("auto_steal_stale_locks")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false),
    }
}

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

/// `GET /api/v1/config` — return the current project configuration.
///
/// # Errors
/// Returns an error if the config file cannot be read or parsed.
pub async fn get_config(
    State(state): State<AppState>,
) -> Result<Json<ConfigResponse>, (StatusCode, Json<ApiError>)> {
    let config_path = state.crosslink_dir.join("hook-config.json");

    let result = tokio::task::spawn_blocking(
        move || -> Result<ConfigResponse, (StatusCode, Json<ApiError>)> {
            // If no config file exists, return sensible defaults
            if !config_path.exists() {
                return Ok(ConfigResponse {
                    tracking_mode: "normal".to_string(),
                    stale_lock_timeout_minutes: 30,
                    remote: "origin".to_string(),
                    signing_enforcement: "off".to_string(),
                    intervention_tracking: false,
                    auto_steal_stale_locks: false,
                });
            }

            let content = std::fs::read_to_string(&config_path)
                .map_err(|e| internal_error("Failed to read config file", e))?;
            let value: serde_json::Value = serde_json::from_str(&content)
                .map_err(|e| internal_error("Failed to parse config file", e))?;

            Ok(config_from_value(&value))
        },
    )
    .await
    .map_err(|e| internal_error("Task join error", e))?;

    result.map(Json)
}

/// `PATCH /api/v1/config` — merge-update configuration fields.
///
/// Only provided (non-null) fields are updated; all others are left unchanged.
/// The full updated config is written back to `hook-config.json` and returned.
///
/// # Errors
/// Returns an error if validation fails, or the config file cannot be read or written.
pub async fn update_config(
    State(state): State<AppState>,
    Json(body): Json<UpdateConfigRequest>,
) -> Result<Json<ConfigResponse>, (StatusCode, Json<ApiError>)> {
    // Validate before entering spawn_blocking (these are pure checks).
    if let Some(ref mode) = body.tracking_mode {
        let valid_modes = ["strict", "normal", "relaxed"];
        if !valid_modes.contains(&mode.as_str()) {
            return Err(bad_request(format!(
                "Invalid tracking_mode '{}'. Must be one of: {}",
                mode,
                valid_modes.join(", ")
            )));
        }
    }
    if let Some(ref enforcement) = body.signing_enforcement {
        let valid = ["off", "audit", "warn", "enforce"];
        if !valid.contains(&enforcement.as_str()) {
            return Err(bad_request(format!(
                "Invalid signing_enforcement '{}'. Must be one of: {}",
                enforcement,
                valid.join(", ")
            )));
        }
    }

    let config_path = state.crosslink_dir.join("hook-config.json");

    let result = tokio::task::spawn_blocking(
        move || -> Result<ConfigResponse, (StatusCode, Json<ApiError>)> {
            // Read existing config (or start from empty object)
            let mut value: serde_json::Value = if config_path.exists() {
                let content = std::fs::read_to_string(&config_path)
                    .map_err(|e| internal_error("Failed to read config file", e))?;
                serde_json::from_str(&content)
                    .map_err(|e| internal_error("Failed to parse config file", e))?
            } else {
                serde_json::json!({})
            };

            let obj = value
                .as_object_mut()
                .ok_or_else(|| internal_error("Config file is not a JSON object", "expected {}"))?;

            if let Some(ref mode) = body.tracking_mode {
                obj.insert(
                    "tracking_mode".to_string(),
                    serde_json::Value::String(mode.clone()),
                );
            }

            if let Some(timeout) = body.stale_lock_timeout_minutes {
                obj.insert(
                    "stale_lock_timeout_minutes".to_string(),
                    serde_json::json!(timeout),
                );
            }

            if let Some(ref enforcement) = body.signing_enforcement {
                obj.insert(
                    "signing_enforcement".to_string(),
                    serde_json::Value::String(enforcement.clone()),
                );
            }

            if let Some(ref remote) = body.remote {
                obj.insert(
                    "tracker_remote".to_string(),
                    serde_json::Value::String(remote.clone()),
                );
            }

            if let Some(intervention) = body.intervention_tracking {
                obj.insert(
                    "intervention_tracking".to_string(),
                    serde_json::Value::Bool(intervention),
                );
            }

            if let Some(auto_steal) = body.auto_steal_stale_locks {
                obj.insert(
                    "auto_steal_stale_locks".to_string(),
                    serde_json::Value::Bool(auto_steal),
                );
            }

            // Write updated config back to disk
            let pretty = serde_json::to_string_pretty(&value)
                .map_err(|e| internal_error("Serialization failed", e))?;

            // Ensure .crosslink directory exists
            if let Some(parent) = config_path.parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| internal_error("Failed to create config directory", e))?;
            }

            std::fs::write(&config_path, format!("{pretty}\n"))
                .map_err(|e| internal_error("Failed to write config file", e))?;

            Ok(config_from_value(&value))
        },
    )
    .await
    .map_err(|e| internal_error("Task join error", e))?;

    result.map(Json)
}

// ---------------------------------------------------------------------------
// 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)
    }

    fn test_app_with_config(config: &Value) -> (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 config_path = crosslink_dir.join("hook-config.json");
        std::fs::write(&config_path, serde_json::to_string_pretty(config).unwrap()).unwrap();

        let state = AppState::new(db, crosslink_dir);
        (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_config_no_file_returns_defaults() {
        let (app, _dir) = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/config")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["tracking_mode"], "normal");
        assert_eq!(body["remote"], "origin");
        assert_eq!(body["intervention_tracking"], false);
        assert_eq!(body["auto_steal_stale_locks"], false);
    }

    #[tokio::test]
    async fn test_get_config_reads_existing_file() {
        let config = json!({
            "tracking_mode": "strict",
            "signing_enforcement": "audit",
            "intervention_tracking": true,
            "auto_steal_stale_locks": false,
            "tracker_remote": "upstream"
        });
        let (app, _dir) = test_app_with_config(&config);
        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/api/v1/config")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["tracking_mode"], "strict");
        assert_eq!(body["signing_enforcement"], "audit");
        assert_eq!(body["intervention_tracking"], true);
        assert_eq!(body["remote"], "upstream");
    }

    #[tokio::test]
    async fn test_update_config_creates_file_if_missing() {
        let (app, dir) = test_app();
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({"tracking_mode": "strict"}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["tracking_mode"], "strict");

        // Verify file was written
        let written = std::fs::read_to_string(crosslink_dir.join("hook-config.json")).unwrap();
        let parsed: Value = serde_json::from_str(&written).unwrap();
        assert_eq!(parsed["tracking_mode"], "strict");
    }

    #[tokio::test]
    async fn test_update_config_merges_fields() {
        let config = json!({
            "tracking_mode": "normal",
            "intervention_tracking": false,
            "extra_field": "preserved"
        });
        let (app, dir) = test_app_with_config(&config);

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        json!({"tracking_mode": "strict", "intervention_tracking": true})
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["tracking_mode"], "strict");
        assert_eq!(body["intervention_tracking"], true);

        // Verify that extra_field was preserved in the file
        let written =
            std::fs::read_to_string(dir.path().join(".crosslink/hook-config.json")).unwrap();
        let parsed: Value = serde_json::from_str(&written).unwrap();
        assert_eq!(parsed["extra_field"], "preserved");
    }

    #[tokio::test]
    async fn test_update_config_invalid_tracking_mode() {
        let (app, dir) = test_app();
        std::fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(json!({"tracking_mode": "invalid"}).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = body_json(resp).await;
        assert!(body["detail"]
            .as_str()
            .unwrap()
            .contains("Invalid tracking_mode"));
    }

    #[tokio::test]
    async fn test_update_config_invalid_signing_enforcement() {
        let (app, dir) = test_app();
        std::fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        json!({"signing_enforcement": "yolo"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = body_json(resp).await;
        assert!(body["detail"]
            .as_str()
            .unwrap()
            .contains("Invalid signing_enforcement"));
    }

    #[tokio::test]
    async fn test_update_config_empty_body_is_noop() {
        let config = json!({
            "tracking_mode": "strict",
            "intervention_tracking": true
        });
        let (app, _dir) = test_app_with_config(&config);

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .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;
        // Values should remain unchanged
        assert_eq!(body["tracking_mode"], "strict");
        assert_eq!(body["intervention_tracking"], true);
    }

    #[tokio::test]
    async fn test_update_config_all_fields() {
        let (app, dir) = test_app();
        std::fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        json!({
                            "tracking_mode": "strict",
                            "stale_lock_timeout_minutes": 45,
                            "signing_enforcement": "enforce",
                            "remote": "upstream",
                            "intervention_tracking": true,
                            "auto_steal_stale_locks": true
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["tracking_mode"], "strict");
        assert_eq!(body["signing_enforcement"], "enforce");
        assert_eq!(body["remote"], "upstream");
        assert_eq!(body["intervention_tracking"], true);
        assert_eq!(body["auto_steal_stale_locks"], true);

        // Verify written file has stale_lock_timeout_minutes
        let written =
            std::fs::read_to_string(dir.path().join(".crosslink/hook-config.json")).unwrap();
        let parsed: Value = serde_json::from_str(&written).unwrap();
        assert_eq!(parsed["stale_lock_timeout_minutes"], 45);
    }

    #[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::bad_request("invalid");
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json.detail.as_deref(), Some("invalid"));
    }

    #[test]
    fn test_config_from_value_defaults() {
        // Verify config_from_value returns sensible defaults when fields are missing.
        let empty = serde_json::json!({});
        let cfg = super::config_from_value(&empty);
        assert_eq!(cfg.tracking_mode, "normal");
        assert_eq!(cfg.stale_lock_timeout_minutes, 30);
        assert_eq!(cfg.remote, "origin");
        assert_eq!(cfg.signing_enforcement, "off");
        assert!(!cfg.intervention_tracking);
        assert!(!cfg.auto_steal_stale_locks);
    }

    #[test]
    fn test_config_from_value_with_all_fields() {
        let value = serde_json::json!({
            "tracking_mode": "strict",
            "stale_lock_timeout_minutes": 60,
            "tracker_remote": "upstream",
            "signing_enforcement": "enforce",
            "intervention_tracking": true,
            "auto_steal_stale_locks": true
        });
        let cfg = super::config_from_value(&value);
        assert_eq!(cfg.tracking_mode, "strict");
        assert_eq!(cfg.stale_lock_timeout_minutes, 60);
        assert_eq!(cfg.remote, "upstream");
        assert_eq!(cfg.signing_enforcement, "enforce");
        assert!(cfg.intervention_tracking);
        assert!(cfg.auto_steal_stale_locks);
    }

    #[tokio::test]
    async fn test_update_config_sets_remote() {
        let (app, dir) = test_app();
        std::fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"remote": "upstream"}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["remote"], "upstream");
    }

    #[tokio::test]
    async fn test_update_config_sets_auto_steal() {
        let (app, dir) = test_app();
        std::fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::PATCH)
                    .uri("/api/v1/config")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({"auto_steal_stale_locks": true}).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["auto_steal_stale_locks"], true);
    }
}