crosslink 0.9.0-beta.1

A synced issue tracker CLI for multi-agent AI development
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
//! GitHub integration REST surface (design doc §14 Phase 4).
//!
//! Token management + org repo enumeration. Token is stored encrypted
//! in the dashboard DB; see [`super::github`] for the storage layer.
//!
//! Endpoints:
//! - `GET  /api/v1/dashboard/github/config` — token-present flag +
//!   default org (never returns the raw token).
//! - `POST /api/v1/dashboard/github/config` — set token and/or default
//!   org. Empty string for `token` deletes the stored secret.
//! - `GET  /api/v1/dashboard/github/orgs/{org}/repos` — enumerate
//!   crosslink-touched repos in `org` (has a `crosslink/hub` branch).
//! - `POST /api/v1/dashboard/github/orgs/{org}/track-all` — walk the
//!   org, clone+track every repo that already has a hub branch.

use anyhow::Result;
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};

use super::db::DashboardDb;
use super::github;
use crate::server::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/github/config", get(get_config).post(set_config))
        .route("/github/orgs/{org}/repos", get(list_repos))
        .route("/github/orgs/{org}/track-all", post(track_all))
}

#[derive(Debug, Serialize)]
struct ConfigView {
    token_present: bool,
    /// First 8 + last 4 chars of the stored token (masked) so the UI
    /// can show *which* token is configured without revealing it.
    token_fingerprint: Option<String>,
    default_org: Option<String>,
    /// Where the effective token comes from:
    /// - `"stored"` — encrypted PAT in the dashboard DB
    /// - `"gh-cli"` — falling back to `gh auth token`
    /// - `null`     — no token available from either source
    token_source: Option<&'static str>,
}

const fn source_tag(s: github::TokenSource) -> &'static str {
    match s {
        github::TokenSource::Stored => "stored",
        github::TokenSource::GhCli => "gh-cli",
    }
}

// The nested Option<Option<String>> on default_org is load-bearing
// PATCH semantics: absent field = "no change", `null` = "clear org",
// string value = "set org". Flattening it to Option<String> loses the
// "no change" case.
#[allow(clippy::option_option)]
#[derive(Debug, Deserialize)]
struct SetConfigBody {
    /// `Some("")` deletes the stored token; `None` leaves it unchanged.
    #[serde(default)]
    token: Option<String>,
    #[serde(default)]
    default_org: Option<Option<String>>,
}

async fn get_config(State(state): State<AppState>) -> Result<Json<ConfigView>, GitHubApiError> {
    let db_path = require_db_path(&state)?;
    let view = tokio::task::spawn_blocking(move || -> Result<ConfigView, GitHubApiError> {
        let db = DashboardDb::open(&db_path)
            .map_err(|e| GitHubApiError::Internal(format!("open db: {e}")))?;
        let effective = github::get_effective_token(&db, &db_path)
            .map_err(|e| GitHubApiError::Internal(format!("read token: {e}")))?;
        let default_org = github::get_plain(&db, github::KEY_DEFAULT_ORG)
            .map_err(|e| GitHubApiError::Internal(format!("read org: {e}")))?;
        Ok(match effective {
            Some((tok, src)) => ConfigView {
                token_present: true,
                token_fingerprint: Some(mask_token(&tok)),
                default_org,
                token_source: Some(source_tag(src)),
            },
            None => ConfigView {
                token_present: false,
                token_fingerprint: None,
                default_org,
                token_source: None,
            },
        })
    })
    .await
    .map_err(|e| GitHubApiError::Internal(format!("task panicked: {e}")))??;
    Ok(Json(view))
}

async fn set_config(
    State(state): State<AppState>,
    Json(body): Json<SetConfigBody>,
) -> Result<Json<ConfigView>, GitHubApiError> {
    let db_path = require_db_path(&state)?;

    // Minimum-viable token shape check — github PATs are ~40-ish
    // base36 chars starting with `ghp_` / `github_pat_`. We don't
    // reject exotic tokens (enterprise, SSO) — just catch obvious
    // paste errors.
    if let Some(ref t) = body.token {
        if !t.is_empty() && t.len() < 10 {
            return Err(GitHubApiError::BadRequest(
                "token looks too short — paste the full PAT".into(),
            ));
        }
    }

    let view = tokio::task::spawn_blocking(move || -> Result<ConfigView, GitHubApiError> {
        let db = DashboardDb::open(&db_path)
            .map_err(|e| GitHubApiError::Internal(format!("open db: {e}")))?;
        if let Some(t) = body.token.as_deref() {
            github::set_token(&db, t, &db_path)
                .map_err(|e| GitHubApiError::Internal(format!("set token: {e}")))?;
        }
        if let Some(org_change) = body.default_org {
            github::set_plain(&db, github::KEY_DEFAULT_ORG, org_change.as_deref())
                .map_err(|e| GitHubApiError::Internal(format!("set org: {e}")))?;
        }
        let effective = github::get_effective_token(&db, &db_path)
            .map_err(|e| GitHubApiError::Internal(format!("read token: {e}")))?;
        let default_org = github::get_plain(&db, github::KEY_DEFAULT_ORG)
            .map_err(|e| GitHubApiError::Internal(format!("read org: {e}")))?;
        Ok(match effective {
            Some((tok, src)) => ConfigView {
                token_present: true,
                token_fingerprint: Some(mask_token(&tok)),
                default_org,
                token_source: Some(source_tag(src)),
            },
            None => ConfigView {
                token_present: false,
                token_fingerprint: None,
                default_org,
                token_source: None,
            },
        })
    })
    .await
    .map_err(|e| GitHubApiError::Internal(format!("task panicked: {e}")))??;
    Ok(Json(view))
}

/// Show a non-reversible hint of the token: first 8 + "…" + last 4.
/// GitHub PATs aren't predictable from the prefix, so this is safe to
/// display on screen.
fn mask_token(t: &str) -> String {
    if t.len() <= 12 {
        return "*".repeat(t.len());
    }
    let (head, tail) = t.split_at(8);
    let tail_start = tail.len().saturating_sub(4);
    format!("{head}{}", &tail[tail_start..])
}

#[derive(Debug, Serialize)]
struct RepoHit {
    owner: String,
    repo: String,
    full_name: String,
    default_branch: String,
    ssh_url: String,
    https_url: String,
    /// True if the repo has a `crosslink/hub` branch (our criterion
    /// for "crosslink-touched"). Non-matching repos are filtered out
    /// server-side; this field is always `true` in responses.
    has_hub_branch: bool,
}

async fn list_repos(
    State(state): State<AppState>,
    Path(org): Path<String>,
) -> Result<Json<Vec<RepoHit>>, GitHubApiError> {
    let db_path = require_db_path(&state)?;
    let token = load_token(&db_path).await?;

    let hits = enumerate_org_crosslink_repos(&org, &token)
        .await
        .map_err(|e| GitHubApiError::Upstream(e.to_string()))?;
    Ok(Json(hits))
}

#[derive(Debug, Deserialize)]
struct TrackAllBody {
    /// Root under which to clone new repos. Defaults to `$HOME`, so
    /// each repo lands at `~/<repo>` (flat, matching the user's
    /// manual-clone layout — `~/crosslink`, `~/ferrotorch`, not
    /// `~/<owner>/<repo>`). Existing clones matching the repo's
    /// slug are adopted in-place.
    #[serde(default)]
    clone_root: Option<String>,
    /// When `true`, run `crosslink init --defaults` and
    /// `crosslink agent init <agent_id>` in each freshly-cloned repo
    /// so dashboard write actions (close issue, release lock, etc.)
    /// work without manual bootstrap. Default `false`.
    #[serde(default)]
    init: bool,
    /// Agent identifier for `crosslink agent init`. Required when
    /// `init == true` and a PAT-only track-all is running.
    #[serde(default)]
    agent_id: Option<String>,
}

#[derive(Debug, Serialize)]
struct TrackAllOutcome {
    tracked: Vec<String>,
    skipped: Vec<SkippedRepo>,
}

#[derive(Debug, Serialize)]
struct SkippedRepo {
    slug: String,
    reason: String,
}

async fn track_all(
    State(state): State<AppState>,
    Path(org): Path<String>,
    Json(body): Json<TrackAllBody>,
) -> Result<Json<TrackAllOutcome>, GitHubApiError> {
    let db_path = require_db_path(&state)?;
    let token = load_token(&db_path).await?;

    let hits = enumerate_org_crosslink_repos(&org, &token)
        .await
        .map_err(|e| GitHubApiError::Upstream(e.to_string()))?;

    // Default to `$HOME` so each repo lands at `~/<owner>/<repo>`
    // alongside the user's other clones. The dashboard's
    // filesystem-discover walker already scans `$HOME` for repos
    // with `.crosslink/`, so this layout gets picked up natively
    // without needing to special-case a "tracked" subdir.
    let clone_root = body
        .clone_root
        .clone()
        .unwrap_or_else(|| std::env::var("HOME").unwrap_or_else(|_| "/tmp".into()));

    // Up-front validation: if init was requested, we need an agent_id
    // before we start any clones — rejecting here saves the user from
    // partially-initialised state.
    let init_config = if body.init {
        let id = body
            .agent_id
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                GitHubApiError::BadRequest(
                    "init=true requires agent_id (alphanumeric + hyphens + underscores)".into(),
                )
            })?;
        Some(id.to_string())
    } else {
        None
    };

    let mut tracked = Vec::new();
    let mut skipped = Vec::new();
    for hit in hits {
        let slug = hit.full_name.clone();
        // Clone directly into <clone_root>/<repo> — same flat shape
        // the user already keeps manual clones in (`~/crosslink`,
        // `~/ferrotorch`, etc.). If two orgs happen to share a repo
        // name, `ensure_clone_and_track` will either adopt the
        // existing clone in-place (`--slug` override resolves the
        // collision) or surface the already-tracked error; either
        // way we don't silently park one of them under a sub-path.
        let target = std::path::PathBuf::from(&clone_root).join(&hit.repo);
        let result = tokio::task::spawn_blocking({
            let db_path = db_path.clone();
            let target = target.clone();
            let ssh_url = hit.ssh_url.clone();
            let https_url = hit.https_url.clone();
            let slug = slug.clone();
            let init = init_config.clone();
            move || {
                ensure_clone_and_track(
                    &db_path,
                    &target,
                    &ssh_url,
                    &https_url,
                    &slug,
                    init.as_deref(),
                )
            }
        })
        .await
        .map_err(|e| GitHubApiError::Internal(format!("track task panicked: {e}")))?;
        match result {
            Ok(()) => tracked.push(slug),
            Err(e) => skipped.push(SkippedRepo {
                slug,
                reason: e.to_string(),
            }),
        }
    }

    Ok(Json(TrackAllOutcome { tracked, skipped }))
}

/// Clone `ssh_url` (falling back to `https_url`) into `target` if the
/// dir doesn't already exist, then register it in the dashboard DB.
/// Idempotent — already-tracked slugs are left alone and surface as
/// "already tracked".
///
/// When `init_agent_id` is `Some`, also run `crosslink init --defaults`
/// and `crosslink agent init <id>` in the freshly-cloned workspace so
/// dashboard write actions work without a manual bootstrap step. If
/// init fails, we still register the project — the tile just surfaces
/// as `write_capability: "not_initialized"` / `"agent_missing"` and
/// the operator can retry via the retrofit endpoint.
fn ensure_clone_and_track(
    db_path: &std::path::Path,
    target: &std::path::Path,
    ssh_url: &str,
    https_url: &str,
    slug: &str,
    init_agent_id: Option<&str>,
) -> Result<()> {
    let freshly_cloned = !target.is_dir();
    if freshly_cloned {
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let clone_res = std::process::Command::new("git")
            .args([
                "clone",
                "--quiet",
                ssh_url,
                target.to_string_lossy().as_ref(),
            ])
            .status();
        let cloned = matches!(clone_res, Ok(s) if s.success());
        if !cloned {
            // Retry via HTTPS — common in CI where SSH isn't set up.
            let https = std::process::Command::new("git")
                .args([
                    "clone",
                    "--quiet",
                    https_url,
                    target.to_string_lossy().as_ref(),
                ])
                .status()?;
            anyhow::ensure!(https.success(), "git clone failed for {slug}");
        }
    }

    // Run init + agent init BEFORE track_at_path so the `write_capability`
    // reflected in the very first tile render is correct. The helper
    // is idempotent-on-Ready (skips if .crosslink/ + driver-key.pub
    // are already in place).
    if let Some(agent_id) = init_agent_id {
        if super::projects::write_capability(target) != super::projects::WriteCapability::Ready {
            super::projects::run_init_and_agent_in(target, agent_id)?;
        }
    }

    super::projects::track_at_path(target, Some(slug), db_path)?;
    Ok(())
}

fn require_db_path(state: &AppState) -> Result<std::path::PathBuf, GitHubApiError> {
    state
        .dashboard_db_path
        .clone()
        .ok_or_else(|| GitHubApiError::BadRequest("dashboard DB not configured".into()))
}

async fn load_token(db_path: &std::path::Path) -> Result<String, GitHubApiError> {
    let db_path_owned = db_path.to_path_buf();
    let resolved = tokio::task::spawn_blocking(move || {
        let db = DashboardDb::open(&db_path_owned).ok()?;
        github::get_effective_token(&db, &db_path_owned)
            .ok()
            .flatten()
    })
    .await
    .map_err(|e| GitHubApiError::Internal(format!("load token task panicked: {e}")))?;
    resolved.map(|(tok, _src)| tok).ok_or_else(|| {
        GitHubApiError::BadRequest(
            "no GitHub token available — store a PAT via POST /github/config, \
             or run `gh auth login` in a shell"
                .into(),
        )
    })
}

/// Hit the GitHub API to list repos in `org` and keep only those with
/// a `crosslink/hub` branch. Uses the v3 REST API with per-page=100
/// pagination and a short circuit: checks the branch via the
/// lightweight `/branches/<name>` endpoint (404 = no hub).
async fn enumerate_org_crosslink_repos(org: &str, token: &str) -> Result<Vec<RepoHit>> {
    let client = reqwest::Client::builder()
        .user_agent("crosslink-dashboard")
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    let mut out = Vec::new();
    let mut page = 1u32;
    loop {
        let url =
            format!("https://api.github.com/orgs/{org}/repos?per_page=100&page={page}&type=all");
        let resp = client
            .get(&url)
            .bearer_auth(token)
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", "2022-11-28")
            .send()
            .await?;
        let status = resp.status();
        if status == reqwest::StatusCode::UNAUTHORIZED {
            anyhow::bail!("GitHub API returned 401 — token invalid or lacks org access");
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("GitHub API {status}: {}", body.trim());
        }
        let repos: Vec<RepoListItem> = resp.json().await?;
        if repos.is_empty() {
            break;
        }
        for repo in &repos {
            // Check for crosslink/hub cheaply — a 200 means yes, 404
            // means no, anything else we propagate.
            let check_url = format!(
                "https://api.github.com/repos/{}/{}/branches/crosslink%2Fhub",
                repo.owner.login, repo.name
            );
            let check = client
                .get(&check_url)
                .bearer_auth(token)
                .header("Accept", "application/vnd.github+json")
                .send()
                .await?;
            if check.status().is_success() {
                out.push(RepoHit {
                    owner: repo.owner.login.clone(),
                    repo: repo.name.clone(),
                    full_name: repo.full_name.clone(),
                    default_branch: repo.default_branch.clone(),
                    ssh_url: repo.ssh_url.clone(),
                    https_url: repo.clone_url.clone(),
                    has_hub_branch: true,
                });
            }
        }
        if repos.len() < 100 {
            break;
        }
        page += 1;
    }
    Ok(out)
}

#[derive(Debug, Deserialize)]
struct RepoListItem {
    name: String,
    full_name: String,
    default_branch: String,
    ssh_url: String,
    clone_url: String,
    owner: RepoOwner,
}

#[derive(Debug, Deserialize)]
struct RepoOwner {
    login: String,
}

#[derive(Debug)]
enum GitHubApiError {
    BadRequest(String),
    Upstream(String),
    Internal(String),
}

impl IntoResponse for GitHubApiError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            Self::BadRequest(m) => (StatusCode::BAD_REQUEST, m),
            Self::Upstream(m) => (StatusCode::BAD_GATEWAY, m),
            Self::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),
        };
        (status, Json(serde_json::json!({"error": msg}))).into_response()
    }
}

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

    #[test]
    fn test_mask_token_short() {
        assert_eq!(mask_token(""), "");
        assert_eq!(mask_token("abc"), "***");
        assert_eq!(mask_token("0123456789ab"), "************");
    }

    #[test]
    fn test_mask_token_realistic() {
        let s = mask_token("ghp_1234567890abcdefghij");
        assert!(s.starts_with("ghp_1234"));
        assert!(s.ends_with("ghij"));
        assert!(s.contains(''));
    }
}