routa-server 0.2.10

Routa.js HTTP Server — axum adapter on top of routa-core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Instant;

use axum::{
    extract::{Query, State},
    http::StatusCode,
    routing::{get, post},
    Json, Router,
};
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::process::Command;

use crate::api::repo_context::{
    extract_frontmatter, json_error, read_to_string, resolve_repo_root, RepoContextQuery,
};
use crate::error::ServerError;
use crate::state::AppState;

const FITNESS_PROFILES: [&str; 2] = ["generic", "agent_orchestrator"];

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/analyze", post(analyze_fitness))
        .route("/plan", get(get_fitness_plan))
        .route("/report", get(get_fitness_report))
        .route("/specs", get(get_fitness_specs))
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AnalyzeRequest {
    workspace_id: Option<String>,
    codebase_id: Option<String>,
    repo_path: Option<String>,
    run_both: Option<bool>,
    profile: Option<String>,
    profiles: Option<Vec<String>>,
    compare_last: Option<bool>,
    no_save: Option<bool>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FitnessPlanQuery {
    workspace_id: Option<String>,
    codebase_id: Option<String>,
    repo_path: Option<String>,
    tier: Option<String>,
    scope: Option<String>,
}

async fn analyze_fitness(
    State(state): State<AppState>,
    Json(body): Json<AnalyzeRequest>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let repo_root = resolve_repo_root(
        &state,
        body.workspace_id.as_deref(),
        body.codebase_id.as_deref(),
        body.repo_path.as_deref(),
        "缺少 fitness 分析上下文,请提供 workspaceId / codebaseId / repoPath 之一",
    )
    .await
    .map_err(map_context_error(
        "Fitness 分析上下文无效",
        "Fitness 分析调用失败",
    ))?;

    let profiles = normalize_profiles(&body);
    let compare_last = body.compare_last.unwrap_or(true);
    let no_save = body.no_save.unwrap_or(false);
    let mut results = Vec::with_capacity(profiles.len());

    for profile in &profiles {
        results.push(run_fitness_profile(&repo_root, profile, compare_last, no_save).await);
    }

    Ok(Json(json!({
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "requestedProfiles": profiles,
        "profiles": results,
    })))
}

async fn get_fitness_report(
    State(state): State<AppState>,
    Query(query): Query<RepoContextQuery>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let repo_root = resolve_repo_root(
        &state,
        query.workspace_id.as_deref(),
        query.codebase_id.as_deref(),
        query.repo_path.as_deref(),
        "缺少 fitness 上下文,请提供 workspaceId / codebaseId / repoPath 之一",
    )
    .await
    .map_err(map_context_error(
        "Fitness 快照上下文无效",
        "获取 Fitness 快照失败",
    ))?;

    let profiles = FITNESS_PROFILES
        .iter()
        .map(|profile| {
            let snapshot_path = profile_snapshot_path(&repo_root, profile);
            match std::fs::read_to_string(&snapshot_path) {
                Ok(raw) => match serde_json::from_str::<Value>(&raw) {
                    Ok(report) => json!({
                        "profile": profile,
                        "source": "snapshot",
                        "status": "ok",
                        "report": report,
                    }),
                    Err(error) => json!({
                        "profile": profile,
                        "source": "snapshot",
                        "status": "error",
                        "error": error.to_string(),
                    }),
                },
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => json!({
                    "profile": profile,
                    "source": "snapshot",
                    "status": "missing",
                    "error": "快照文件不存在",
                }),
                Err(error) => json!({
                    "profile": profile,
                    "source": "snapshot",
                    "status": "error",
                    "error": error.to_string(),
                }),
            }
        })
        .collect::<Vec<_>>();

    Ok(Json(json!({
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "requestedProfiles": FITNESS_PROFILES,
        "profiles": profiles,
    })))
}

async fn get_fitness_plan(
    State(state): State<AppState>,
    Query(query): Query<FitnessPlanQuery>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let repo_root = resolve_repo_root(
        &state,
        query.workspace_id.as_deref(),
        query.codebase_id.as_deref(),
        query.repo_path.as_deref(),
        "缺少 fitness 上下文,请提供 workspaceId / codebaseId / repoPath 之一",
    )
    .await
    .map_err(map_context_error(
        "Fitness plan 上下文无效",
        "构建 Fitness plan 失败",
    ))?;

    let tier = parse_tier(query.tier.as_deref());
    let scope = parse_scope(query.scope.as_deref());
    let fitness_dir = repo_root.join("docs/fitness");

    // Return empty plan if fitness directory doesn't exist (generic repos may not have it)
    if !fitness_dir.exists() {
        return Ok(Json(json!({
            "generatedAt": chrono::Utc::now().to_rfc3339(),
            "repoRoot": repo_root,
            "tier": format!("{tier:?}"),
            "scope": format!("{scope:?}"),
            "dimensions": [],
            "runnerCounts": { "shell": 0, "graph": 0, "sarif": 0 },
            "metricCount": 0,
            "hardGateCount": 0,
        })));
    }

    let entries =
        std::fs::read_dir(&fitness_dir).map_err(map_io_error("构建 Fitness plan 失败"))?;

    let mut markdown_by_path = BTreeMap::new();
    let mut manifest_entries = Vec::new();

    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
            continue;
        };

        if name == "manifest.yaml" {
            manifest_entries = parse_manifest_entries(&path);
            continue;
        }
        if !name.ends_with(".md") || name == "README.md" || name == "REVIEW.md" {
            continue;
        }

        let raw = read_to_string(&path).map_err(map_internal_error("构建 Fitness plan 失败"))?;
        markdown_by_path.insert(name.to_string(), raw.clone());
        markdown_by_path.insert(format!("docs/fitness/{name}"), raw);
    }

    let mut ordered = Vec::new();
    let mut seen = HashSet::new();
    for manifest_entry in manifest_entries {
        if let Some(raw) = markdown_by_path.get(&manifest_entry) {
            seen.insert(manifest_entry.clone());
            ordered.push((manifest_entry.clone(), raw.clone()));
        }
    }
    for (key, raw) in markdown_by_path {
        if !key.starts_with("docs/fitness/") && seen.insert(key.clone()) {
            ordered.push((key, raw));
        }
    }

    let mut dimensions = Vec::new();
    let mut runner_counts = json!({ "shell": 0, "graph": 0, "sarif": 0 });
    let mut metric_count = 0;
    let mut hard_gate_count = 0;

    for (name, raw) in ordered {
        let Some(frontmatter) = parse_markdown_frontmatter(&raw) else {
            continue;
        };
        let metrics = frontmatter
            .get("metrics")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .map(normalize_plan_metric)
            .filter(|metric| tier_passes(metric["tier"].as_str().unwrap_or("normal"), tier))
            .filter(|metric| metric["executionScope"].as_str().unwrap_or("local") == scope)
            .collect::<Vec<_>>();

        if metrics.is_empty() {
            continue;
        }

        for metric in &metrics {
            metric_count += 1;
            if metric["hardGate"].as_bool().unwrap_or(false) {
                hard_gate_count += 1;
            }
            let runner = metric["runner"].as_str().unwrap_or("shell");
            runner_counts[runner] = json!(runner_counts[runner].as_i64().unwrap_or(0) + 1);
        }

        let threshold = frontmatter
            .get("threshold")
            .cloned()
            .unwrap_or_else(|| json!({}));
        dimensions.push(json!({
            "name": frontmatter.get("dimension").and_then(Value::as_str).unwrap_or(name.trim_end_matches(".md")),
            "weight": frontmatter.get("weight").and_then(Value::as_i64).unwrap_or(0),
            "thresholdPass": threshold.get("pass").and_then(Value::as_i64).unwrap_or(90),
            "thresholdWarn": threshold.get("warn").and_then(Value::as_i64).unwrap_or(80),
            "sourceFile": name,
            "metrics": metrics,
        }));
    }

    Ok(Json(json!({
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "tier": tier,
        "scope": scope,
        "repoRoot": repo_root,
        "dimensionCount": dimensions.len(),
        "metricCount": metric_count,
        "hardGateCount": hard_gate_count,
        "runnerCounts": runner_counts,
        "dimensions": dimensions,
    })))
}

async fn get_fitness_specs(
    State(state): State<AppState>,
    Query(query): Query<RepoContextQuery>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let repo_root = resolve_repo_root(
        &state,
        query.workspace_id.as_deref(),
        query.codebase_id.as_deref(),
        query.repo_path.as_deref(),
        "缺少 fitness 上下文,请提供 workspaceId / codebaseId / repoPath 之一",
    )
    .await
    .map_err(map_context_error(
        "Fitness specs 上下文无效",
        "读取 Fitness specs 失败",
    ))?;

    let fitness_dir = repo_root.join("docs/fitness");

    // Return empty result if fitness directory doesn't exist (generic repos may not have it)
    if !fitness_dir.exists() {
        return Ok(Json(json!({
            "generatedAt": chrono::Utc::now().to_rfc3339(),
            "repoRoot": repo_root,
            "fitnessDir": fitness_dir,
            "files": [],
        })));
    }

    let entries =
        std::fs::read_dir(&fitness_dir).map_err(map_io_error("读取 Fitness specs 失败"))?;

    let mut files = Vec::new();
    let mut by_path = BTreeMap::<String, Value>::new();
    let mut manifest_spec: Option<Value> = None;

    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
            continue;
        };
        if is_fluency_model_spec(name) {
            continue;
        }
        let raw = read_to_string(&path).map_err(map_internal_error("读取 Fitness specs 失败"))?;
        let spec = if name.ends_with(".md") {
            parse_markdown_spec(name, &raw)
        } else if name == "manifest.yaml" {
            parse_manifest_spec(name, &raw)
        } else if name.ends_with(".yaml") || name.ends_with(".yml") {
            parse_non_markdown_spec(name, &raw)
        } else {
            continue;
        };
        files.push(spec.clone());
        by_path.insert(name.to_string(), spec.clone());
        by_path.insert(format!("docs/fitness/{name}"), spec.clone());
        if name == "manifest.yaml" {
            manifest_spec = Some(spec);
        }
    }

    let mut ordered = Vec::new();
    let mut seen = HashSet::new();
    let mut push = |spec: Option<&Value>| {
        if let Some(spec) = spec {
            let key = spec["relativePath"]
                .as_str()
                .unwrap_or_default()
                .to_string();
            if !key.is_empty() && seen.insert(key) {
                ordered.push(spec.clone());
            }
        }
    };

    push(by_path.get("README.md"));
    push(manifest_spec.as_ref());
    if let Some(manifest_entries) = manifest_spec
        .as_ref()
        .and_then(|spec| spec["manifestEntries"].as_array())
    {
        for entry in manifest_entries.iter().filter_map(Value::as_str) {
            push(by_path.get(entry));
        }
    }
    for spec in &files {
        push(Some(spec));
    }

    Ok(Json(json!({
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "repoRoot": repo_root,
        "fitnessDir": fitness_dir,
        "files": ordered,
    })))
}

fn normalize_profiles(body: &AnalyzeRequest) -> Vec<String> {
    let mut configured = body.profiles.clone().unwrap_or_default();
    if configured.is_empty() {
        if let Some(profile) = &body.profile {
            configured.push(profile.clone());
        }
    }
    if body.run_both == Some(true) && configured.is_empty() {
        return FITNESS_PROFILES
            .iter()
            .map(|value| value.to_string())
            .collect();
    }

    let mut deduped = Vec::new();
    for profile in configured {
        if FITNESS_PROFILES.contains(&profile.as_str()) && !deduped.contains(&profile) {
            deduped.push(profile);
        }
    }

    if deduped.is_empty() {
        vec!["generic".to_string()]
    } else {
        deduped
    }
}

async fn run_fitness_profile(
    repo_root: &Path,
    profile: &str,
    compare_last: bool,
    no_save: bool,
) -> Value {
    let started_at = Instant::now();
    let mut args = vec![
        "run",
        "-p",
        "routa-cli",
        "--",
        "fitness",
        "fluency",
        "--format",
        "json",
        "--profile",
        profile,
    ];
    if compare_last {
        args.push("--compare-last");
    }
    if no_save {
        args.push("--no-save");
    }

    let output = Command::new("cargo")
        .args(&args)
        .current_dir(repo_root)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await;

    let duration_ms = started_at.elapsed().as_millis() as u64;
    match output {
        Ok(output) if output.status.success() => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            match extract_json_output(&stdout)
                .and_then(|text| serde_json::from_str::<Value>(&text).map_err(|e| e.to_string()))
            {
                Ok(report) => json!({
                    "profile": profile,
                    "source": "analysis",
                    "status": "ok",
                    "durationMs": duration_ms,
                    "report": report,
                }),
                Err(error) => json!({
                    "profile": profile,
                    "source": "analysis",
                    "status": "error",
                    "durationMs": duration_ms,
                    "error": error,
                }),
            }
        }
        Ok(output) => json!({
            "profile": profile,
            "source": "analysis",
            "status": "error",
            "durationMs": duration_ms,
            "error": format!(
                "Command failed (exit {}): {}",
                output.status.code().unwrap_or(1),
                String::from_utf8_lossy(&output.stderr).trim()
            ),
        }),
        Err(error) => json!({
            "profile": profile,
            "source": "analysis",
            "status": "error",
            "durationMs": duration_ms,
            "error": error.to_string(),
        }),
    }
}

fn profile_snapshot_path(repo_root: &Path, profile: &str) -> PathBuf {
    repo_root
        .join("docs/fitness/reports")
        .join(if profile == "generic" {
            "harness-fluency-latest.json"
        } else {
            "harness-fluency-agent-orchestrator-latest.json"
        })
}

fn extract_json_output(raw: &str) -> Result<String, String> {
    let candidate = raw.trim();
    if candidate.is_empty() {
        return Err("Command produced no output".to_string());
    }
    if serde_json::from_str::<Value>(candidate).is_ok() {
        return Ok(candidate.to_string());
    }
    for (index, ch) in candidate.char_indices().rev() {
        if ch != '{' {
            continue;
        }
        let snippet = candidate[index..].trim();
        if snippet.ends_with('}') && serde_json::from_str::<Value>(snippet).is_ok() {
            return Ok(snippet.to_string());
        }
    }
    Err("Unable to parse command JSON output".to_string())
}

fn parse_manifest_entries(path: &Path) -> Vec<String> {
    let Ok(raw) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    let Ok(value) = serde_yaml::from_str::<serde_yaml::Value>(&raw) else {
        return Vec::new();
    };
    value
        .get("evidence_files")
        .and_then(serde_yaml::Value::as_sequence)
        .map(|entries| {
            entries
                .iter()
                .filter_map(serde_yaml::Value::as_str)
                .map(ToString::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn parse_markdown_frontmatter(raw: &str) -> Option<Value> {
    let (frontmatter, _) = extract_frontmatter(raw)?;
    serde_yaml::from_str::<serde_yaml::Value>(&frontmatter)
        .ok()
        .and_then(|value| serde_json::to_value(value).ok())
}

fn normalize_plan_metric(metric: Value) -> Value {
    let hard_gate = metric
        .get("hard_gate")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let tier = match metric.get("tier").and_then(Value::as_str) {
        Some("fast" | "normal" | "deep") => metric["tier"].as_str().unwrap_or("normal"),
        _ => "normal",
    };
    let execution_scope = match metric.get("execution_scope").and_then(Value::as_str) {
        Some("ci" | "staging" | "prod_observation") => {
            metric["execution_scope"].as_str().unwrap_or("local")
        }
        _ => "local",
    };
    json!({
        "name": metric.get("name").and_then(Value::as_str).unwrap_or("unknown"),
        "command": metric.get("command").and_then(Value::as_str).unwrap_or(""),
        "description": metric.get("description").and_then(Value::as_str).unwrap_or(""),
        "tier": tier,
        "gate": metric.get("gate").and_then(Value::as_str).unwrap_or(if hard_gate { "hard" } else { "soft" }),
        "hardGate": hard_gate,
        "runner": map_runner(&metric),
        "executionScope": execution_scope,
    })
}

fn parse_markdown_spec(relative_path: &str, raw: &str) -> Value {
    let frontmatter = parse_markdown_frontmatter(raw).unwrap_or_else(|| json!({}));
    let metrics = frontmatter
        .get("metrics")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let frontmatter_source =
        extract_frontmatter(raw).map(|(frontmatter, _)| format!("---\n{frontmatter}\n---"));

    if relative_path == "README.md" {
        return json!({
            "name": relative_path,
            "relativePath": relative_path,
            "kind": "rulebook",
            "language": "markdown",
            "metricCount": 0,
            "metrics": [],
            "source": raw,
            "frontmatterSource": frontmatter_source,
        });
    }

    if metrics.is_empty() {
        return json!({
            "name": relative_path,
            "relativePath": relative_path,
            "kind": "narrative",
            "language": "markdown",
            "metricCount": 0,
            "metrics": [],
            "source": raw,
            "frontmatterSource": frontmatter_source,
        });
    }

    let threshold = frontmatter
        .get("threshold")
        .cloned()
        .unwrap_or_else(|| json!({}));
    let normalized_metrics = metrics
        .into_iter()
        .enumerate()
        .map(|(index, metric)| {
            let hard_gate = metric
                .get("hard_gate")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            json!({
                "name": metric.get("name").and_then(Value::as_str).unwrap_or(&format!("metric-{}", index + 1)),
                "command": metric.get("command").and_then(Value::as_str).unwrap_or(""),
                "description": metric.get("description").and_then(Value::as_str).unwrap_or(""),
                "tier": metric.get("tier").and_then(Value::as_str).unwrap_or("normal"),
                "hardGate": hard_gate,
                "gate": metric.get("gate").and_then(Value::as_str).unwrap_or(if hard_gate { "hard" } else { "soft" }),
                "runner": map_runner(&metric),
                "pattern": metric.get("pattern").and_then(Value::as_str),
                "evidenceType": metric.get("evidence_type").and_then(Value::as_str),
                "scope": normalize_string_list(metric.get("scope")),
                "runWhenChanged": normalize_string_list(metric.get("run_when_changed")),
            })
        })
        .collect::<Vec<_>>();

    json!({
        "name": relative_path,
        "relativePath": relative_path,
        "kind": "dimension",
        "language": "markdown",
        "dimension": frontmatter.get("dimension").and_then(Value::as_str).unwrap_or("unknown"),
        "weight": frontmatter.get("weight").and_then(Value::as_i64).unwrap_or(0),
        "thresholdPass": threshold.get("pass").and_then(Value::as_i64).unwrap_or(90),
        "thresholdWarn": threshold.get("warn").and_then(Value::as_i64).unwrap_or(80),
        "metricCount": normalized_metrics.len(),
        "metrics": normalized_metrics,
        "source": raw,
        "frontmatterSource": frontmatter_source,
    })
}

fn parse_manifest_spec(relative_path: &str, raw: &str) -> Value {
    let parsed = serde_yaml::from_str::<serde_yaml::Value>(raw).unwrap_or_default();
    let manifest_entries = parsed
        .get("evidence_files")
        .and_then(serde_yaml::Value::as_sequence)
        .map(|entries| {
            entries
                .iter()
                .filter_map(serde_yaml::Value::as_str)
                .map(ToString::to_string)
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    json!({
        "name": relative_path,
        "relativePath": relative_path,
        "kind": "manifest",
        "language": "yaml",
        "metricCount": manifest_entries.len(),
        "metrics": [],
        "source": raw,
        "manifestEntries": manifest_entries,
    })
}

fn parse_non_markdown_spec(relative_path: &str, raw: &str) -> Value {
    json!({
        "name": relative_path,
        "relativePath": relative_path,
        "kind": "policy",
        "language": "yaml",
        "metricCount": 0,
        "metrics": [],
        "source": raw,
    })
}

fn is_fluency_model_spec(relative_path: &str) -> bool {
    matches!(
        relative_path,
        "harness-fluency.model.yaml" | "harness-fluency.model.yml"
    ) || (relative_path.starts_with("harness-fluency.profile.")
        && (relative_path.ends_with(".yaml") || relative_path.ends_with(".yml")))
}

fn normalize_string_list(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(Value::as_array)
        .map(|values| {
            values
                .iter()
                .filter_map(Value::as_str)
                .map(ToString::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn map_runner(metric: &Value) -> &'static str {
    if metric.get("evidence_type").and_then(Value::as_str) == Some("sarif")
        || metric.get("evidenceType").and_then(Value::as_str) == Some("sarif")
    {
        "sarif"
    } else if metric
        .get("command")
        .and_then(Value::as_str)
        .is_some_and(|command| command.starts_with("graph:"))
    {
        "graph"
    } else {
        "shell"
    }
}

fn parse_tier(value: Option<&str>) -> &'static str {
    match value {
        Some("fast") => "fast",
        Some("deep") => "deep",
        _ => "normal",
    }
}

fn parse_scope(value: Option<&str>) -> &'static str {
    match value {
        Some("ci") => "ci",
        Some("staging") => "staging",
        Some("prod_observation") => "prod_observation",
        _ => "local",
    }
}

fn tier_passes(metric_tier: &str, filter_tier: &str) -> bool {
    tier_rank(metric_tier) <= tier_rank(filter_tier)
}

fn tier_rank(tier: &str) -> u8 {
    match tier {
        "fast" => 0,
        "normal" => 1,
        "deep" => 2,
        _ => 1,
    }
}

fn map_context_error(
    public_error: &'static str,
    internal_error: &'static str,
) -> impl Fn(ServerError) -> (StatusCode, Json<Value>) + Clone {
    move |error| match error {
        ServerError::BadRequest(details) => (
            StatusCode::BAD_REQUEST,
            Json(json_error(public_error, details)),
        ),
        other => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json_error(internal_error, other.to_string())),
        ),
    }
}

fn map_internal_error(
    public_error: &'static str,
) -> impl Fn(ServerError) -> (StatusCode, Json<Value>) + Clone {
    move |error| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json_error(public_error, error.to_string())),
        )
    }
}

fn map_io_error(
    public_error: &'static str,
) -> impl Fn(std::io::Error) -> (StatusCode, Json<Value>) + Clone {
    move |error| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json_error(public_error, error.to_string())),
        )
    }
}