qualityd 0.1.0-alpha.2

Quality Studio HTTP surface for Weavatrix Quality
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
//! Exception-first Quality Studio API. Spec §31 and §58.
//!
//! Every endpoint is a projection of the shared command bus. The dashboard shows
//! unresolved exceptions, never hundreds of green cases, and a human decision is
//! always one reviewer against one subject.

use std::sync::{Arc, Mutex, MutexGuard};

use serde::{Deserialize, Serialize};
use wvq_command_bus::{
    ApplicationSurfaceView, AuthorDraftCommand, AuthorHealCommand, AuthorPreviewCommand,
    BehaviorSurfaceView,
    AuthorPromoteCommand, AuthorValidateCommand, BusError, ChangesCommand,
    CheapestEvidencePlanView, DebtCommand, DebtReply, EvidenceCell, EvidenceCommand,
    EvidenceProducer, ExplainCommand, ProofSummary, QualityService, RecordCommand, StatusCommand,
    SurfaceEvidenceMatrixView, SurfaceEvidenceRow, VerifyCommand,
};
use wvq_domain::{
    ContentHash, HumanDecision, HumanDecisionId, HumanRole, NewDecision, VerificationDecision,
};
use wvq_proof::{BlockingReason, ChangeQualityVerdict, Limitation, ProtectionView, UiFindingRef};
use wvq_spec_recovery::RecoveryDesk;
use wvq_store::{Store, StoredAiUsage};

use crate::http::{HttpRequest, HttpResponse};

/// One Studio endpoint and the single method it accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Route<'a> {
    Cockpit,
    StudioScript,
    Changes,
    Summary(&'a str),
    RequirementProofs(&'a str),
    Finding(&'a str),
    Run(&'a str),
    Artifact(&'a str),
    HumanDecisions,
    RecoveryReview,
    RecoveryQuestions,
    RecoveryPatch,
    RecoveryDecisions,
    Protection,
    ProtectionTest(&'a str),
    ProtectionFlow(&'a str),
    AuthorDraft,
    AuthorValidate,
    AuthorPreview,
    AuthorRecord,
    AuthorPromote,
    AuthorHeal,
}

impl Route<'_> {
    fn method(self) -> &'static str {
        match self {
            Self::HumanDecisions
            | Self::RecoveryDecisions
            | Self::AuthorDraft
            | Self::AuthorValidate
            | Self::AuthorPreview
            | Self::AuthorRecord
            | Self::AuthorPromote
            | Self::AuthorHeal => "POST",
            _ => "GET",
        }
    }
}

/// AI budget consumption for one change. Absent when nothing was measured.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct AiBody {
    planning_tokens: u64,
    runtime_tokens: u64,
    browser_escape_calls: u64,
    vision_calls: u64,
    cost_micros: u64,
}

impl From<StoredAiUsage> for AiBody {
    fn from(usage: StoredAiUsage) -> Self {
        Self {
            planning_tokens: usage.planning_tokens,
            runtime_tokens: usage.runtime_tokens,
            browser_escape_calls: usage.browser_escape_calls,
            vision_calls: usage.vision_calls,
            cost_micros: usage.cost_micros,
        }
    }
}

/// Change dashboard. Passing proofs are counted, never listed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct SummaryBody {
    change: String,
    verdict: String,
    blocking: bool,
    /// Composite state token (`BLOCKED`, `PASS_WITH_WARNINGS`, …).
    state: String,
    requirements: usize,
    obligations: usize,
    proven: usize,
    /// Only unresolved proofs reach the dashboard, each as an exception card.
    needs_attention: Vec<ExceptionCard>,
    /// How many green proofs were deliberately hidden.
    suppressed_passing: usize,
    debt: DebtReply,
    /// `null` when no AI usage was recorded. Unmeasured is not zero.
    ai: Option<AiBody>,
    /// Per-axis states, so a reviewer sees which axes were never measured.
    axes: Vec<AxisBody>,
    /// Every policy rule that fired, most important first.
    blocking_reasons: Vec<BlockingReason>,
    /// Everything in scope that was not measured.
    limitations: Vec<Limitation>,
    /// Exception-only UI-integrity projection. Healthy elements are never listed.
    ui_integrity: UiIntegrityBody,
    /// Read-only Application Surface Graph. Never a gate.
    application_surface: ApplicationSurfaceView,
    /// Read-only Behavior Surface projection. Never a gate.
    behavior_surface: BehaviorSurfaceView,
    /// Read-only Surface Evidence Matrix. Never a gate.
    surface_evidence: SurfaceEvidenceMatrixView,
    /// Read-only cheapest-evidence plan. Never a gate.
    evidence_plan: CheapestEvidencePlanView,
}

/// One unresolved proof plus the measured evidence around it.
///
/// Missing matrix or plan data stays `unmeasured`. The card never invents a
/// surface join, a failure reel, or a visual region.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct ExceptionCard {
    id: String,
    requirement: String,
    obligation: String,
    verdict: String,
    /// `OpenSpec` requirement identity. Intent is not the test column.
    intent: String,
    /// Matched Application Surface Graph id, or `unmeasured`.
    surface: String,
    protection: String,
    proof: String,
    runtime: String,
    coverage: String,
    ui: String,
    a11y: String,
    mutation: String,
    code_impact: String,
    behavior_delta: String,
    visual_region: String,
    failure_reel: Option<String>,
    cheapest_next: Option<String>,
    source_candidates: Vec<String>,
}

fn exception_card(
    proof: ProofSummary,
    matrix: &SurfaceEvidenceMatrixView,
    plan: &CheapestEvidencePlanView,
) -> ExceptionCard {
    let row = matching_surface(&proof, matrix);
    let (cheapest_next, source_candidates) = cheapest_for(&proof, row, plan);
    ExceptionCard {
        intent: proof.requirement.clone(),
        surface: row.map_or_else(|| "unmeasured".into(), |row| row.surface.clone()),
        protection: cell_token(row.map(|row| row.protection)),
        proof: cell_token(row.map(|row| row.proof)),
        runtime: cell_token(row.map(|row| row.runtime)),
        coverage: cell_token(row.map(|row| row.coverage)),
        ui: cell_token(row.map(|row| row.ui)),
        a11y: cell_token(row.map(|row| row.a11y)),
        mutation: cell_token(row.map(|row| row.mutation)),
        code_impact: "unmeasured".into(),
        behavior_delta: cell_token(row.map(|row| row.runtime)),
        visual_region: "unmeasured".into(),
        failure_reel: None,
        cheapest_next,
        source_candidates,
        id: proof.id,
        requirement: proof.requirement,
        obligation: proof.obligation,
        verdict: proof.verdict,
    }
}

fn matching_surface<'a>(
    proof: &ProofSummary,
    matrix: &'a SurfaceEvidenceMatrixView,
) -> Option<&'a SurfaceEvidenceRow> {
    if !matrix.present {
        return None;
    }
    matrix
        .surfaces
        .iter()
        .find(|row| row.surface == proof.obligation || row.surface == proof.requirement)
}

fn cheapest_for(
    proof: &ProofSummary,
    row: Option<&SurfaceEvidenceRow>,
    plan: &CheapestEvidencePlanView,
) -> (Option<String>, Vec<String>) {
    if !plan.present {
        return (None, Vec::new());
    }
    let surface = row.map(|row| row.surface.as_str());
    let gap = plan.gaps.iter().find(|gap| {
        Some(gap.surface.as_str()) == surface
            || gap.surface == proof.obligation
            || gap.surface == proof.requirement
    });
    let Some(gap) = gap else {
        return (None, Vec::new());
    };
    let candidates = gap
        .producers
        .iter()
        .map(|offer| producer_token(offer.producer))
        .collect();
    (gap.cheapest.map(producer_token), candidates)
}

fn cell_token(cell: Option<EvidenceCell>) -> String {
    match cell {
        Some(EvidenceCell::Present) => "present",
        Some(EvidenceCell::Absent) => "absent",
        Some(EvidenceCell::Unmeasured) | None => "unmeasured",
    }
    .to_owned()
}

fn producer_token(producer: EvidenceProducer) -> String {
    serde_json::to_value(producer)
        .ok()
        .and_then(|value| value.as_str().map(ToOwned::to_owned))
        .unwrap_or_else(|| "unmeasured".into())
}

/// One axis reduced to its state for the dashboard header.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct AxisBody {
    axis: String,
    state: String,
}

/// What changed for the worse in the UI, plus what was fixed or never measured.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct UiIntegrityBody {
    state: String,
    /// Duplicates, occlusions, and overflow first seen on head.
    new: Vec<UiFindingRef>,
    /// Findings that were fixed and came back.
    returned: Vec<UiFindingRef>,
    /// Old UI debt, counted and never listed.
    suppressed_existing: u64,
    /// UI debt this change removed.
    fixed: u64,
    /// Route/state/viewport combinations with no snapshot.
    unmeasured_states: Vec<String>,
    /// Whether a snapshot hit its node bound.
    truncated: bool,
}

fn axes_of(quality: &ChangeQualityVerdict) -> Vec<AxisBody> {
    [
        ("proof", quality.proof.state),
        ("protection", quality.protection.state),
        ("debt", quality.debt.state),
        ("stability", quality.stability.state),
        ("ai", quality.ai.state),
        ("ui_integrity", quality.ui_integrity.state),
        ("delta_triangle", quality.delta_triangle.state),
    ]
    .into_iter()
    .map(|(axis, state)| AxisBody {
        axis: axis.to_owned(),
        state: state.as_str().to_owned(),
    })
    .collect()
}

/// Requirement drill-down. Detail screens may show green proofs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RequirementProofsBody {
    requirement: String,
    change: String,
    proofs: Vec<ProofSummary>,
}

/// Incoming human decision. Unknown fields are refused, so a body carrying
/// `accept_all` or a `subjects` list never reaches the domain.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct DecisionRequest {
    id: String,
    reviewer: String,
    role: HumanRole,
    subject: String,
    artifact_digest: String,
    decision: VerificationDecision,
    #[serde(default)]
    comment: Option<String>,
    decided_at: String,
}

/// Proposed `OpenSpec` patch text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RecoveryPatchBody {
    patch: String,
}

/// Where one candidate now stands on the mandatory verification path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RecoveryStateBody {
    candidate: String,
    state: &'static str,
}

/// Stored decision plus what it permits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct DecisionBody {
    #[serde(flatten)]
    decision: HumanDecision,
    /// Whether this decision may carry the subject towards a seal.
    seal_eligible: bool,
    /// Whether it blocks sealing pending someone else's answer.
    escalates: bool,
}

/// Quality Studio over the shared command bus.
pub struct Studio {
    service: Arc<dyn QualityService>,
    store: Mutex<Store>,
    recovery: Option<Arc<Mutex<RecoveryDesk>>>,
    protection: Option<Arc<Mutex<ProtectionView>>>,
}

impl Studio {
    /// Serve `service`, recording decisions and reading AI usage from `store`.
    #[must_use]
    pub fn new(service: Arc<dyn QualityService>, store: Store) -> Self {
        Self {
            service,
            store: Mutex::new(store),
            recovery: None,
            protection: None,
        }
    }

    /// Attach a computed protection view, enabling the continuity screens.
    #[must_use]
    pub fn with_protection(mut self, view: Arc<Mutex<ProtectionView>>) -> Self {
        self.protection = Some(view);
        self
    }

    /// Enable the spec-recovery screens over a desk the host has populated.
    ///
    /// Recovery is opt-in: a repository with complete `OpenSpec` never needs it.
    #[must_use]
    pub fn with_recovery(mut self, desk: Arc<Mutex<RecoveryDesk>>) -> Self {
        self.recovery = Some(desk);
        self
    }

    /// Route and answer one request.
    #[must_use]
    pub fn handle(&self, request: &HttpRequest) -> HttpResponse {
        let path = request.path.trim_matches('/').to_owned();
        let Some(route) = parse_route(&path) else {
            return HttpResponse::error(404, "unknown route");
        };
        if request.method != route.method() {
            return HttpResponse::error(405, "method not allowed for this route");
        }
        match route {
            Route::Cockpit => crate::frontend::cockpit(),
            Route::StudioScript => crate::frontend::script(),
            Route::Changes => self.changes(),
            Route::Summary(change) => self.summary(change),
            Route::RequirementProofs(requirement) => self.requirement_proofs(requirement),
            Route::Finding(id) => self.finding(id),
            Route::Run(id) => self.run(id),
            Route::Artifact(id) => self.artifact(id),
            Route::HumanDecisions => self.record_decision(&request.body),
            Route::RecoveryReview => self.with_desk(|desk| ok(&desk.review())),
            Route::RecoveryQuestions => self.with_desk(|desk| ok(&desk.questions())),
            Route::RecoveryPatch => self.with_desk(|desk| {
                ok(&RecoveryPatchBody {
                    patch: desk.preview_patch(),
                })
            }),
            Route::RecoveryDecisions => self.record_recovery_decision(&request.body),
            Route::Protection => self.read_protection(|view| ok(&view.report())),
            Route::ProtectionTest(test) => {
                self.read_protection(|view| match view.lineage_of(test) {
                    Some(record) => ok(record),
                    None => HttpResponse::error(404, "no lineage recorded for that test"),
                })
            }
            Route::ProtectionFlow(flow) => self.read_protection(|view| match view.flow(flow) {
                Some(record) => ok(record),
                None => HttpResponse::error(404, "that flow is not in the impacted surface"),
            }),
            Route::AuthorDraft => self.author_draft(&request.body),
            Route::AuthorValidate => self.author_validate(&request.body),
            Route::AuthorPreview => self.author_preview(&request.body),
            Route::AuthorRecord => self.author_record(&request.body),
            Route::AuthorPromote => self.author_promote(&request.body),
            Route::AuthorHeal => self.author_heal(&request.body),
        }
    }

    /// Run `body` against the protection view, or answer 404 when it is off.
    fn read_protection<F>(&self, body: F) -> HttpResponse
    where
        F: FnOnce(&ProtectionView) -> HttpResponse,
    {
        let Some(view) = &self.protection else {
            return HttpResponse::error(404, "protection continuity has not been computed");
        };
        let guard = view
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        body(&guard)
    }

    /// Run `body` against the recovery desk, or answer 404 when it is off.
    fn with_desk<F>(&self, body: F) -> HttpResponse
    where
        F: FnOnce(&RecoveryDesk) -> HttpResponse,
    {
        let Some(desk) = &self.recovery else {
            return HttpResponse::error(404, "spec recovery is not enabled for this repository");
        };
        let guard = desk
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        body(&guard)
    }

    fn record_recovery_decision(&self, body: &str) -> HttpResponse {
        let Some(desk) = &self.recovery else {
            return HttpResponse::error(404, "spec recovery is not enabled for this repository");
        };
        let decision = match parse_decision(body) {
            Ok(value) => value,
            Err(response) => return response,
        };
        let mut guard = desk
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match guard.decide(&decision) {
            Ok(state) => ok(&RecoveryStateBody {
                candidate: decision.subject,
                state: state.as_str(),
            }),
            Err(err) => HttpResponse::error(422, &err.to_string()),
        }
    }

    fn changes(&self) -> HttpResponse {
        match self.service.changes(&ChangesCommand::default()) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn summary(&self, change: &str) -> HttpResponse {
        let verify = match self.service.verify(&VerifyCommand {
            observe_only: false,
            change: change.to_owned(),
        }) {
            Ok(reply) => reply,
            Err(err) => return bus_error(&err),
        };
        // Debt must use the same revision range the run measured. Hardcoding
        // HEAD/WORKTREE mixes a committed-PR verdict with a different debt view.
        let (base, head) = match (&verify.base, &verify.head) {
            (Some(base), Some(head)) => (base.clone(), head.clone()),
            _ => ("HEAD".into(), "WORKTREE".into()),
        };
        let debt = match self.service.debt(&DebtCommand {
            change: change.to_owned(),
            base,
            head,
        }) {
            Ok(reply) => reply,
            Err(err) => return bus_error(&err),
        };
        let ai = match self.lock_store().ai_usage_for_change(&verify.change) {
            Ok(usage) => usage.map(AiBody::from),
            Err(err) => return HttpResponse::error(500, &err.to_string()),
        };
        let mut requirements: Vec<&str> = verify
            .proofs
            .iter()
            .map(|proof| proof.requirement.as_str())
            .collect();
        requirements.sort_unstable();
        requirements.dedup();
        let requirement_count = requirements.len();
        let obligations = verify.proofs.len();
        let (passing, needs_attention): (Vec<ProofSummary>, Vec<ProofSummary>) = verify
            .proofs
            .into_iter()
            .partition(ProofSummary::is_passing);
        let needs_attention = needs_attention
            .into_iter()
            .map(|proof| exception_card(proof, &verify.surface_evidence, &verify.evidence_plan))
            .collect();
        let quality = verify.quality;
        let axes = axes_of(&quality);
        let ui_integrity = UiIntegrityBody {
            state: quality.ui_integrity.state.as_str().to_owned(),
            new: quality.ui_integrity.new,
            returned: quality.ui_integrity.returned,
            suppressed_existing: quality.ui_integrity.existing,
            fixed: quality.ui_integrity.fixed,
            unmeasured_states: quality.ui_integrity.unmeasured_states,
            truncated: quality.ui_integrity.truncated,
        };
        ok(&SummaryBody {
            change: verify.change,
            verdict: verify.verdict,
            blocking: verify.blocking,
            state: verify.state,
            requirements: requirement_count,
            obligations,
            proven: passing.len(),
            needs_attention,
            suppressed_passing: passing.len(),
            debt,
            ai,
            axes,
            blocking_reasons: quality.blocking_reasons,
            limitations: quality.limitations,
            ui_integrity,
            application_surface: verify.application_surface,
            behavior_surface: verify.behavior_surface,
            surface_evidence: verify.surface_evidence,
            evidence_plan: verify.evidence_plan,
        })
    }

    fn requirement_proofs(&self, requirement: &str) -> HttpResponse {
        let changes = match self.service.changes(&ChangesCommand::default()) {
            Ok(reply) => reply.changes,
            Err(err) => return bus_error(&err),
        };
        for change in changes {
            let Ok(verify) = self.service.verify(&VerifyCommand {
                observe_only: false,
                change: change.clone(),
            }) else {
                continue;
            };
            let proofs: Vec<ProofSummary> = verify
                .proofs
                .into_iter()
                .filter(|proof| proof.requirement == requirement)
                .collect();
            if !proofs.is_empty() {
                return ok(&RequirementProofsBody {
                    requirement: requirement.to_owned(),
                    change: verify.change,
                    proofs,
                });
            }
        }
        HttpResponse::error(404, "no proofs for that requirement")
    }

    fn finding(&self, id: &str) -> HttpResponse {
        match self.service.explain(&ExplainCommand { id: id.to_owned() }) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn run(&self, id: &str) -> HttpResponse {
        match self.service.status(&StatusCommand {
            run_id: Some(id.to_owned()),
        }) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn artifact(&self, id: &str) -> HttpResponse {
        match self.service.evidence(&EvidenceCommand {
            handle: id.to_owned(),
        }) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_draft(&self, body: &str) -> HttpResponse {
        let command: AuthorDraftCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.author_draft(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_validate(&self, body: &str) -> HttpResponse {
        let command: AuthorValidateCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.author_validate(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_preview(&self, body: &str) -> HttpResponse {
        let command: AuthorPreviewCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.author_preview(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_record(&self, body: &str) -> HttpResponse {
        let command: RecordCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.record(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_promote(&self, body: &str) -> HttpResponse {
        let command: AuthorPromoteCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.author_promote(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn author_heal(&self, body: &str) -> HttpResponse {
        let command: AuthorHealCommand = match parse_json_body(body) {
            Ok(command) => command,
            Err(response) => return response,
        };
        match self.service.author_heal(&command) {
            Ok(reply) => ok(&reply),
            Err(err) => bus_error(&err),
        }
    }

    fn record_decision(&self, body: &str) -> HttpResponse {
        let decision = match parse_decision(body) {
            Ok(value) => value,
            Err(response) => return response,
        };
        if let Err(err) = self.lock_store().put_human_decision(&decision) {
            return HttpResponse::error(500, &err.to_string());
        }
        let body = DecisionBody {
            seal_eligible: decision.decision.seal_eligible(),
            escalates: decision.decision.escalates(),
            decision,
        };
        match serde_json::to_string(&body) {
            Ok(json) => HttpResponse::new(201, json),
            Err(err) => HttpResponse::error(500, &err.to_string()),
        }
    }

    fn lock_store(&self) -> MutexGuard<'_, Store> {
        self.store
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

/// Parse one decision body, refusing bulk fields and malformed identities.
fn parse_decision(body: &str) -> Result<HumanDecision, HttpResponse> {
    let request: DecisionRequest =
        serde_json::from_str(body).map_err(|err| HttpResponse::error(400, &err.to_string()))?;
    let id = HumanDecisionId::new(&request.id)
        .map_err(|_| HttpResponse::error(400, "decision id must be a non-empty token"))?;
    let digest = ContentHash::new(&request.artifact_digest)
        .map_err(|_| HttpResponse::error(400, "artifact_digest must be lowercase hex"))?;
    HumanDecision::new(NewDecision {
        id,
        reviewer: request.reviewer,
        role: request.role,
        subject: request.subject,
        artifact_digest: digest,
        decision: request.decision,
        comment: request.comment,
        decided_at: request.decided_at,
    })
    .map_err(|err| HttpResponse::error(422, &err.to_string()))
}

fn parse_json_body<T: serde::de::DeserializeOwned>(body: &str) -> Result<T, HttpResponse> {
    serde_json::from_str(body).map_err(|err| HttpResponse::error(400, &err.to_string()))
}

fn parse_route(path: &str) -> Option<Route<'_>> {
    let segments: Vec<&str> = path.split('/').collect();
    match segments.as_slice() {
        ["" | "index.html"] => Some(Route::Cockpit),
        ["studio.js"] => Some(Route::StudioScript),
        ["api", "v1", "recovery", "review"] => Some(Route::RecoveryReview),
        ["api", "v1", "recovery", "questions"] => Some(Route::RecoveryQuestions),
        ["api", "v1", "recovery", "patch"] => Some(Route::RecoveryPatch),
        ["api", "v1", "recovery", "decisions"] => Some(Route::RecoveryDecisions),
        ["api", "v1", "protection"] => Some(Route::Protection),
        ["api", "v1", "protection", "tests", test] => Some(Route::ProtectionTest(test)),
        ["api", "v1", "protection", "flows", flow] => Some(Route::ProtectionFlow(flow)),
        ["api", "v1", "changes"] => Some(Route::Changes),
        ["api", "v1", "changes", change, "summary"] => Some(Route::Summary(change)),
        ["api", "v1", "requirements", requirement, "proofs"] => {
            Some(Route::RequirementProofs(requirement))
        }
        ["api", "v1", "findings", id] => Some(Route::Finding(id)),
        ["api", "v1", "runs", id] => Some(Route::Run(id)),
        ["api", "v1", "artifacts", id] => Some(Route::Artifact(id)),
        ["api", "v1", "human-decisions"] => Some(Route::HumanDecisions),
        ["api", "v1", "authoring", "draft"] => Some(Route::AuthorDraft),
        ["api", "v1", "authoring", "validate"] => Some(Route::AuthorValidate),
        ["api", "v1", "authoring", "preview"] => Some(Route::AuthorPreview),
        ["api", "v1", "authoring", "record"] => Some(Route::AuthorRecord),
        ["api", "v1", "authoring", "promote"] => Some(Route::AuthorPromote),
        ["api", "v1", "authoring", "heal"] => Some(Route::AuthorHeal),
        _ => None,
    }
}

fn ok<T: Serialize>(body: &T) -> HttpResponse {
    match serde_json::to_string(body) {
        Ok(json) => HttpResponse::new(200, json),
        Err(err) => HttpResponse::error(500, &err.to_string()),
    }
}

fn bus_error(err: &BusError) -> HttpResponse {
    let status = match err {
        BusError::NotFound(_) => 404,
        BusError::Ambiguous(_) => 409,
        BusError::Unknown { .. } | BusError::Identity(_) | BusError::InvalidInput(_) => 400,
        BusError::Spec(_) => 422,
        BusError::Runtime(_)
        | BusError::Intelligence(_)
        | BusError::Store(_)
        | BusError::Model(_) => 503,
    };
    HttpResponse::error(status, &err.to_string())
}