rototo 0.1.0-alpha.5

Control plane for runtime configuration of your application.
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
use axum::Json;
use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::routing::get;
use serde_json::{Value as JsonValue, json};
use std::collections::HashSet;

use super::api::{
    ApiError, ApiResult, SharedState, fixed_source_scope, fixed_source_workspace_ids,
    require_github_token, require_user, source_token, workspace_belongs_to_fixed_source,
};
use super::capabilities::{classify_workspace_source, workspace_capabilities};
use super::inventory::{
    WorkspaceInventory, inspect_workspace_inventory, read_workspace_definition,
};
use super::resolve_preview::{
    SavedContextInput, qualifier_context_evaluations, resolve_saved_contexts,
};
use super::store::{SessionUser, WorkspaceRecord};
use super::workspace_source::{
    github_repo_for_workspace, runtime_workspace_for_base, semantic_workspace_for_base,
    workspace_source_for_base,
};

const MAX_PREVIEW_CONTEXTS: usize = 4;
const WORKSPACE_SUMMARY_CONCURRENCY: usize = 4;
/// Compare calls are one GitHub request per branch; keep the scan bounded.
const MAX_COMPARED_BRANCHES: usize = 25;
const BRANCH_CANDIDATE_COMPARE_CONCURRENCY: usize = 8;

/// Ordered workspace summary result from a bounded background task.
///
/// The index preserves the user's source tree/workspace ordering after concurrent
/// staging and lint work finishes.
type WorkspaceSummaryResult = (usize, JsonValue);

/// Ordered GitHub branch comparison result used while scanning branch candidates.
///
/// Each value is produced by one GitHub compare request and discarded after the
/// route has filtered it into a small browser-facing branch summary.
type BranchCandidateCompareResult = (
    usize,
    String,
    super::github::GitHubResult<super::github::RefComparison>,
);

pub fn routes() -> axum::Router<SharedState> {
    axum::Router::new()
        .route("/workspaces/summaries", get(workspace_summaries))
        .route("/workspaces/{workspace_id}/lint", get(workspace_lint))
        .route("/workspaces/{workspace_id}/summary", get(workspace_summary))
        .route("/workspaces/{workspace_id}/data", get(workspace_data))
        .route("/workspaces/{workspace_id}/entity", get(workspace_entity))
        .route(
            "/workspaces/{workspace_id}/branch-candidates",
            get(branch_candidates),
        )
}

pub async fn load_workspace(
    state: &super::api::ConsoleState,
    user: &SessionUser,
    workspace_id: &str,
) -> ApiResult<WorkspaceRecord> {
    let fixed_source = fixed_source_scope(state, &user.principal_id).await?;
    let workspace = state
        .store
        .get_workspace_for_user(workspace_id, &user.principal_id)
        .await?
        .ok_or_else(|| ApiError::not_found("workspace not found"))?;
    if let Some(source_tree) = fixed_source.as_ref()
        && !workspace_belongs_to_fixed_source(&workspace, source_tree)
    {
        return Err(ApiError::not_found("workspace not found"));
    }
    Ok(workspace)
}

/// `{root, diagnostics}` with the wire shape the TypeScript SDK produced.
pub fn lint_json(lint: &crate::model::WorkspaceLint) -> JsonValue {
    json!({
        "root": lint.root.display().to_string(),
        "diagnostics": lint.diagnostics,
    })
}

pub fn lint_error_json(root: &str, error: &str) -> JsonValue {
    json!({ "root": root, "diagnostics": [], "error": error })
}

pub fn workspace_capabilities_json(
    state: &super::api::ConsoleState,
    user: &SessionUser,
    workspace: &WorkspaceRecord,
) -> JsonValue {
    let source_kind = classify_workspace_source(&workspace.source);
    json!({
        "sourceKind": source_kind,
        "capabilities": workspace_capabilities(
            source_kind,
            state.write_policy,
            &state.deployment,
            user.github_token.is_some(),
        ),
    })
}

async fn workspace_lint(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Path(workspace_id): Path<String>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let workspace = load_workspace(&state, &user, &workspace_id).await?;
    let workspace_source =
        workspace_source_for_base(&state, &user.principal_id, source_token(&user), &workspace)
            .await?;
    let inspected = state
        .stage
        .get_inspected_workspace(workspace_source, source_token(&user))
        .await
        .map_err(|err| ApiError::internal(err.to_string()))?;
    let lint = inspected
        .lint()
        .await
        .map_err(|err| ApiError::internal(err.to_string()))?;
    Ok(Json(
        json!({ "workspace": workspace, "lint": lint_json(&lint) }),
    ))
}

/// Query string for the workspace summaries endpoint.
///
/// The optional source tree id scopes a request to one registered source tree. It is
/// parsed per request and never stored; discovery state remains in SQLite.
#[derive(serde::Deserialize, Default)]
struct WorkspaceSummariesQuery {
    #[serde(rename = "sourceTreeId")]
    source_tree_id: Option<String>,
}

async fn workspace_summaries(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Query(query): Query<WorkspaceSummariesQuery>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let fixed_source = fixed_source_scope(&state, &user.principal_id).await?;
    let mut workspaces = state
        .store
        .list_workspaces_for_user(&user.principal_id)
        .await?;
    if let Some(source_tree) = fixed_source.as_ref() {
        let workspace_ids = fixed_source_workspace_ids(source_tree);
        workspaces.retain(|workspace| workspace_ids.contains(&workspace.id));
    }
    if let Some(source_tree_id) = query.source_tree_id.as_deref() {
        workspaces.retain(|workspace| workspace.source_tree_id == source_tree_id);
    }

    let mut summaries = Vec::new();
    let mut jobs = tokio::task::JoinSet::new();
    for (index, workspace) in workspaces.into_iter().enumerate() {
        let state = state.clone();
        let user = user.clone();
        jobs.spawn(async move {
            (
                index,
                workspace_summary_json(&state, &user, &workspace).await,
            )
        });
        if jobs.len() >= WORKSPACE_SUMMARY_CONCURRENCY {
            collect_workspace_summary(&mut jobs, &mut summaries).await;
        }
    }
    while !jobs.is_empty() {
        collect_workspace_summary(&mut jobs, &mut summaries).await;
    }
    summaries.sort_by_key(|(index, _)| *index);
    let summaries: Vec<JsonValue> = summaries.into_iter().map(|(_, summary)| summary).collect();

    Ok(Json(json!({ "summaries": summaries })))
}

async fn workspace_summary(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Path(workspace_id): Path<String>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let workspace = load_workspace(&state, &user, &workspace_id).await?;
    Ok(Json(
        workspace_summary_json(&state, &user, &workspace).await,
    ))
}

async fn collect_workspace_summary(
    jobs: &mut tokio::task::JoinSet<WorkspaceSummaryResult>,
    summaries: &mut Vec<WorkspaceSummaryResult>,
) {
    let Some(joined) = jobs.join_next().await else {
        return;
    };
    if let Ok(summary) = joined {
        summaries.push(summary);
    }
}

async fn workspace_summary_json(
    state: &super::api::ConsoleState,
    user: &SessionUser,
    workspace: &WorkspaceRecord,
) -> JsonValue {
    match workspace_inventory(state, user, workspace).await {
        Ok((_, inventory)) => workspace_summary_success_json(workspace, &inventory),
        Err(error) => json!({
            "workspaceId": workspace.id,
            "workspaceSlug": workspace.slug,
            "variables": 0,
            "qualifiers": 0,
            "catalogs": 0,
            "error": error,
        }),
    }
}

fn workspace_summary_success_json(
    workspace: &WorkspaceRecord,
    inventory: &WorkspaceInventory,
) -> JsonValue {
    json!({
        "workspaceId": workspace.id,
        "workspaceSlug": workspace.slug,
        "variables": inventory.variables.len(),
        "qualifiers": inventory.qualifiers.len(),
        "catalogs": inventory.catalogs.len(),
        "error": JsonValue::Null,
    })
}

async fn workspace_data(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Path(workspace_id): Path<String>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let workspace = load_workspace(&state, &user, &workspace_id).await?;
    let branches = state
        .store
        .list_active_branches_for_workspace(&workspace.id, &user.principal_id)
        .await?;

    let staged =
        semantic_workspace_for_base(&state, &user.principal_id, source_token(&user), &workspace)
            .await;
    let (inventory, inventory_error, lint, model, definitions) = match staged {
        Ok(semantic) => {
            let inventory =
                inspect_workspace_inventory(&workspace, &semantic.model, semantic.workspace.root())
                    .await;
            let lint = match semantic.workspace.lint().await {
                Ok(lint) => lint_json(&lint),
                Err(err) => lint_error_json(&workspace.source, &err.to_string()),
            };
            match inventory {
                Ok(inventory) => {
                    let definitions =
                        workspace_definitions(&workspace, semantic.workspace.root(), &inventory)
                            .await;
                    (
                        serde_json::to_value(inventory).expect("inventory serializes"),
                        JsonValue::Null,
                        lint,
                        serde_json::to_value(semantic.model.as_ref()).expect("model serializes"),
                        definitions,
                    )
                }
                Err(err) => (
                    serde_json::to_value(WorkspaceInventory::default())
                        .expect("inventory serializes"),
                    json!(err.to_string()),
                    lint,
                    serde_json::to_value(semantic.model.as_ref()).expect("model serializes"),
                    JsonValue::Array(Vec::new()),
                ),
            }
        }
        Err(err) => {
            let message = err.message;
            (
                serde_json::to_value(WorkspaceInventory::default()).expect("inventory serializes"),
                json!(message.clone()),
                lint_error_json(&workspace.source, &message),
                JsonValue::Null,
                JsonValue::Array(Vec::new()),
            )
        }
    };

    let capabilities = workspace_capabilities_json(&state, &user, &workspace);
    Ok(Json(json!({
        "workspace": workspace,
        "branches": branches,
        "inventory": inventory,
        "inventoryError": inventory_error,
        "definitions": definitions,
        "lint": lint,
        "model": model,
        "sourceKind": capabilities["sourceKind"].clone(),
        "capabilities": capabilities["capabilities"].clone(),
    })))
}

async fn workspace_definitions(
    workspace: &WorkspaceRecord,
    staged_root: &std::path::Path,
    inventory: &WorkspaceInventory,
) -> JsonValue {
    let mut seen = HashSet::new();
    let mut definitions = Vec::new();
    for path in workspace_definition_paths(inventory) {
        if !seen.insert(path.clone()) {
            continue;
        }
        if let Ok(definition) = read_workspace_definition(workspace, staged_root, &path).await {
            definitions.push(serde_json::to_value(definition).expect("definition serializes"));
        }
    }
    JsonValue::Array(definitions)
}

fn workspace_definition_paths(inventory: &WorkspaceInventory) -> Vec<String> {
    let mut paths = Vec::new();
    paths.extend(inventory.variables.iter().map(|item| item.path.clone()));
    paths.extend(inventory.qualifiers.iter().map(|item| item.path.clone()));
    paths.extend(inventory.catalogs.iter().map(|item| item.path.clone()));
    paths.extend(
        inventory
            .catalog_entries
            .iter()
            .map(|item| item.path.clone()),
    );
    paths.extend(
        inventory
            .linters
            .iter()
            .filter_map(|item| item.path.clone()),
    );
    paths.extend(
        inventory
            .context
            .request_contexts
            .iter()
            .map(|item| item.path.clone()),
    );
    paths.extend(
        inventory
            .context
            .entries
            .iter()
            .map(|item| item.path.clone()),
    );
    paths
}

/// Query string used to fetch one workspace file for inspect/edit screens.
///
/// The path is a repository-relative workspace path from the inventory. The
/// route validates it by resolving through the staged workspace root before
/// reading text.
#[derive(serde::Deserialize)]
pub struct EntityQuery {
    pub path: String,
}

async fn workspace_entity(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Path(workspace_id): Path<String>,
    Query(query): Query<EntityQuery>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let workspace = load_workspace(&state, &user, &workspace_id).await?;
    let semantic =
        semantic_workspace_for_base(&state, &user.principal_id, source_token(&user), &workspace)
            .await?;
    let inventory =
        inspect_workspace_inventory(&workspace, &semantic.model, semantic.workspace.root())
            .await
            .map_err(|err| ApiError::internal(err.to_string()))?;

    let (definition, definition_error) =
        match read_workspace_definition(&workspace, semantic.workspace.root(), &query.path).await {
            Ok(definition) => (
                serde_json::to_value(definition).expect("definition serializes"),
                JsonValue::Null,
            ),
            Err(err) => (JsonValue::Null, json!(err.to_string())),
        };

    let contexts = load_saved_contexts(
        &workspace,
        semantic.workspace.root(),
        &inventory,
        MAX_PREVIEW_CONTEXTS,
    )
    .await;

    // Variables resolve against each saved context so the screen shows the
    // actual pathway, not just the declared rules.
    let mut context_resolutions = JsonValue::Array(Vec::new());
    if let Some(variable) = inventory
        .variables
        .iter()
        .find(|variable| variable.path == query.path)
        && !contexts.is_empty()
        && let Ok(runtime) =
            runtime_workspace_for_base(&state, &user.principal_id, source_token(&user), &workspace)
                .await
    {
        let contexts = compatible_variable_contexts(&semantic.model, &variable.id, &contexts);
        let resolutions =
            resolve_saved_contexts(&runtime, &semantic.model, &variable.id, &contexts).await;
        context_resolutions = serde_json::to_value(resolutions).expect("resolutions serialize");
    }

    // Qualifiers evaluate (with any nested qualifier references) against each
    // saved context.
    let mut qualifier_evaluations = JsonValue::Array(Vec::new());
    if let Some(qualifier) = inventory
        .qualifiers
        .iter()
        .find(|qualifier| qualifier.path == query.path)
        && !contexts.is_empty()
        && let Ok(runtime) =
            runtime_workspace_for_base(&state, &user.principal_id, source_token(&user), &workspace)
                .await
    {
        let contexts = compatible_qualifier_contexts(&semantic.model, &qualifier.id, &contexts);
        let evaluations =
            qualifier_context_evaluations(&runtime, &semantic.model, &qualifier.id, &contexts)
                .await;
        qualifier_evaluations = serde_json::to_value(evaluations).expect("evaluations serialize");
    }

    Ok(Json(json!({
        "definition": definition,
        "definitionError": definition_error,
        "contextResolutions": context_resolutions,
        "qualifierEvaluations": qualifier_evaluations,
    })))
}

fn compatible_variable_contexts(
    model: &crate::lint::WorkspaceSemanticModel,
    variable_id: &str,
    contexts: &[SavedContextInput],
) -> Vec<SavedContextInput> {
    let Some(compatibility) = model
        .variable_request_contexts
        .iter()
        .find(|compatibility| compatibility.variable == variable_id)
    else {
        return Vec::new();
    };
    contexts
        .iter()
        .filter(|context| {
            compatibility
                .request_contexts
                .iter()
                .any(|id| id == &context.request_context)
        })
        .cloned()
        .collect()
}

fn compatible_qualifier_contexts(
    model: &crate::lint::WorkspaceSemanticModel,
    qualifier_id: &str,
    contexts: &[SavedContextInput],
) -> Vec<SavedContextInput> {
    let Some(compatibility) = model
        .qualifier_request_contexts
        .iter()
        .find(|compatibility| compatibility.qualifier == qualifier_id)
    else {
        return Vec::new();
    };
    contexts
        .iter()
        .filter(|context| {
            compatibility
                .request_contexts
                .iter()
                .any(|id| id == &context.request_context)
        })
        .cloned()
        .collect()
}

async fn branch_candidates(
    State(state): State<SharedState>,
    headers: HeaderMap,
    Path(workspace_id): Path<String>,
) -> ApiResult<Json<JsonValue>> {
    let user = require_user(&state, &headers).await?;
    let workspace = load_workspace(&state, &user, &workspace_id).await?;
    if !matches!(
        classify_workspace_source(&workspace.source),
        super::capabilities::WorkspaceSourceKind::GitHubArchive
            | super::capabilities::WorkspaceSourceKind::GitHubGit
    ) {
        return Err(ApiError::bad_request(
            "only GitHub configuration sources support branch discovery",
        ));
    }
    let token = require_github_token(&user, "Scanning branches")?;
    let github_repo = github_repo_for_workspace(&workspace)
        .map_err(|err| ApiError::bad_request(err.to_string()))?;

    let known_branches: std::collections::HashSet<String> = state
        .store
        .list_active_branches_for_workspace(&workspace.id, &user.principal_id)
        .await?
        .into_iter()
        .map(|branch| branch.branch)
        .collect();
    let branches: Vec<String> = state
        .github
        .list_branches(token, &github_repo.owner, &github_repo.name)
        .await
        .map_err(|err| ApiError::github(&err, "Scanning branches"))?
        .into_iter()
        .filter(|branch| *branch != workspace.revision && !known_branches.contains(branch))
        .collect();
    let compared = &branches[..branches.len().min(MAX_COMPARED_BRANCHES)];
    let prefix = if workspace.path == "." {
        String::new()
    } else {
        format!("{}/", workspace.path)
    };

    let mut candidates = Vec::new();
    let mut comparisons = tokio::task::JoinSet::new();
    for (index, branch) in compared.iter().cloned().enumerate() {
        let github = state.github.clone();
        let token = token.to_owned();
        let github_repo = github_repo.clone();
        let base = workspace.revision.clone();
        comparisons.spawn(async move {
            let comparison = github
                .compare_refs(
                    &token,
                    &github_repo.owner,
                    &github_repo.name,
                    &base,
                    &branch,
                )
                .await;
            (index, branch, comparison)
        });
        if comparisons.len() >= BRANCH_CANDIDATE_COMPARE_CONCURRENCY {
            collect_branch_candidate(&mut comparisons, &prefix, &mut candidates).await;
        }
    }
    while !comparisons.is_empty() {
        collect_branch_candidate(&mut comparisons, &prefix, &mut candidates).await;
    }
    candidates.sort_by_key(|(index, _)| *index);
    let candidates: Vec<JsonValue> = candidates
        .into_iter()
        .map(|(_, candidate)| candidate)
        .collect();

    Ok(Json(json!({
        "candidates": candidates,
        "scanned": compared.len(),
        "skipped": branches.len() - compared.len(),
    })))
}

async fn collect_branch_candidate(
    comparisons: &mut tokio::task::JoinSet<BranchCandidateCompareResult>,
    prefix: &str,
    candidates: &mut Vec<(usize, JsonValue)>,
) {
    let Some(joined) = comparisons.join_next().await else {
        return;
    };
    // A branch that cannot be compared is not a candidate.
    let Ok((index, branch, Ok(comparison))) = joined else {
        return;
    };
    if let Some(candidate) = branch_candidate_json(index, branch, comparison, prefix) {
        candidates.push(candidate);
    }
}

fn branch_candidate_json(
    index: usize,
    branch: String,
    comparison: super::github::RefComparison,
    prefix: &str,
) -> Option<(usize, JsonValue)> {
    let workspace_only = comparison.ahead_by > 0
        && !comparison.files.is_empty()
        && comparison.files.iter().all(|file| file.starts_with(prefix));
    workspace_only.then(|| {
        (
            index,
            json!({
                "branch": branch,
                "aheadBy": comparison.ahead_by,
                "filesChanged": comparison.files.len(),
            }),
        )
    })
}

pub async fn workspace_inventory(
    state: &super::api::ConsoleState,
    user: &SessionUser,
    workspace: &WorkspaceRecord,
) -> std::result::Result<(std::sync::Arc<crate::sdk::Workspace>, WorkspaceInventory), String> {
    let semantic =
        semantic_workspace_for_base(state, &user.principal_id, source_token(user), workspace)
            .await
            .map_err(|err| err.message)?;
    let inventory =
        inspect_workspace_inventory(workspace, &semantic.model, semantic.workspace.root())
            .await
            .map_err(|err| err.to_string())?;
    Ok((semantic.workspace, inventory))
}

/// Reads up to `limit` saved request contexts from the staged checkout.
pub async fn load_saved_contexts(
    workspace: &WorkspaceRecord,
    staged_root: &std::path::Path,
    inventory: &WorkspaceInventory,
    limit: usize,
) -> Vec<SavedContextInput> {
    let mut contexts = Vec::new();
    for entry in inventory.context.entries.iter().take(limit) {
        let Ok(definition) = read_workspace_definition(workspace, staged_root, &entry.path).await
        else {
            continue;
        };
        contexts.push(SavedContextInput {
            name: entry.key.clone(),
            request_context: entry.request_context_id.clone(),
            path: entry.path.clone(),
            text: definition.text,
        });
    }
    contexts
}

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

    fn workspace() -> WorkspaceRecord {
        WorkspaceRecord {
            id: "workspace-id".to_owned(),
            slug: "configs".to_owned(),
            source_tree_id: "repo-id".to_owned(),
            source_tree_label: "octo/configs".to_owned(),
            display_path: ".".to_owned(),
            path: ".".to_owned(),
            revision: "main".to_owned(),
            source: "https://api.github.com/repos/octo/configs/tarball/main".to_owned(),
            discovered_at: "2026-06-13T00:00:00Z".to_owned(),
        }
    }

    fn catalog(id: &str) -> super::super::inventory::CatalogInventoryItem {
        super::super::inventory::CatalogInventoryItem {
            id: id.to_owned(),
            path: format!("catalogs/{id}.schema.json"),
            description: None,
            schema: None,
            entry_count: 0,
        }
    }

    fn catalog_entry(
        catalog_id: &str,
        key: &str,
    ) -> super::super::inventory::CatalogEntryInventoryItem {
        super::super::inventory::CatalogEntryInventoryItem {
            catalog_id: catalog_id.to_owned(),
            key: key.to_owned(),
            id: format!("{catalog_id}/{key}"),
            path: format!("catalogs/{catalog_id}-entries/{key}.toml"),
        }
    }

    fn comparison(ahead_by: i64, files: &[&str]) -> super::super::github::RefComparison {
        super::super::github::RefComparison {
            ahead_by,
            files: files.iter().map(|file| (*file).to_owned()).collect(),
        }
    }

    #[test]
    fn workspace_summary_counts_catalogs_without_entries() {
        let inventory = WorkspaceInventory {
            catalogs: vec![catalog("plans"), catalog("limits")],
            catalog_entries: vec![
                catalog_entry("plans", "free"),
                catalog_entry("plans", "pro"),
                catalog_entry("limits", "enterprise"),
            ],
            ..WorkspaceInventory::default()
        };

        let summary = workspace_summary_success_json(&workspace(), &inventory);

        assert_eq!(summary["catalogs"].as_u64(), Some(2));
    }

    #[test]
    fn branch_candidate_accepts_root_workspace_changes() {
        let candidate = branch_candidate_json(
            2,
            "feature".to_owned(),
            comparison(3, &["variables/checkout.toml", "README.md"]),
            "",
        );

        assert_eq!(
            candidate,
            Some((
                2,
                serde_json::json!({
                    "branch": "feature",
                    "aheadBy": 3,
                    "filesChanged": 2,
                })
            ))
        );
    }

    #[test]
    fn branch_candidate_rejects_empty_or_unrelated_changes() {
        assert!(
            branch_candidate_json(
                0,
                "empty".to_owned(),
                comparison(0, &["examples/basic/variables/checkout.toml"]),
                "examples/basic/",
            )
            .is_none()
        );
        assert!(
            branch_candidate_json(0, "empty".to_owned(), comparison(1, &[]), "examples/basic/",)
                .is_none()
        );
        assert!(
            branch_candidate_json(
                0,
                "mixed".to_owned(),
                comparison(1, &["examples/basic/variables/checkout.toml", "README.md"],),
                "examples/basic/",
            )
            .is_none()
        );
    }
}