Skip to main content

funcspec_client/
models.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4// ---------------------------------------------------------------------------
5// API envelope
6// ---------------------------------------------------------------------------
7
8#[derive(Debug, Serialize, Deserialize)]
9pub struct ApiResponse<T> {
10    pub data: T,
11}
12
13#[derive(Debug, Serialize, Deserialize)]
14pub struct ApiListResponse<T> {
15    pub data: Vec<T>,
16    pub meta: Option<PaginationMeta>,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct PaginationMeta {
21    pub page: u32,
22    pub per: u32,
23    pub total: u32,
24    #[serde(default)]
25    pub total_pages: u32,
26}
27
28// ---------------------------------------------------------------------------
29// Auth / User
30// ---------------------------------------------------------------------------
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct UserInfo {
34    pub id: String,
35    pub email: String,
36    pub name: String,
37    pub org_id: String,
38    pub org_name: String,
39}
40
41// ---------------------------------------------------------------------------
42// Project
43// ---------------------------------------------------------------------------
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Project {
47    pub id: u64,
48    #[serde(rename = "type")]
49    pub resource_type: String,
50    pub attributes: ProjectAttributes,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ProjectAttributes {
55    pub name: String,
56    pub description: Option<String>,
57    pub slug: String,
58    pub created_at: DateTime<Utc>,
59    pub updated_at: DateTime<Utc>,
60}
61
62// ---------------------------------------------------------------------------
63// Spec Item
64// ---------------------------------------------------------------------------
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct SpecItem {
68    pub id: u64,
69    #[serde(rename = "type")]
70    pub resource_type: String,
71    pub attributes: SpecItemAttributes,
72}
73
74/// A lightweight reference to a release version an item belongs to, as
75/// embedded in a spec item's \`release_versions\` array (semver + name only).
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct ReleaseVersionRef {
78    #[serde(default)]
79    pub semver: Option<String>,
80    #[serde(default)]
81    pub name: Option<String>,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct SpecItemAttributes {
86    pub title: String,
87    pub description: Option<String>,
88    pub type_of: ItemType,
89    pub state: String,
90    #[serde(default)]
91    pub implementation_status: Option<ImplementationStatus>,
92    pub permalink: String,
93    pub url: String,
94    pub version: u32,
95    pub priority: Option<i32>,
96    pub position: Option<i32>,
97    #[serde(default)]
98    pub tags: Vec<String>,
99    pub parent_id: Option<u64>,
100    pub project_id: u64,
101    /// Agent-feedback status: none/pending/in_progress/resolved/escalated.
102    #[serde(default)]
103    pub feedback_status: Option<String>,
104    /// Whether the item is out-of-scope (deprecated).
105    #[serde(default)]
106    pub deprecated: Option<bool>,
107    #[serde(default)]
108    pub deprecated_at: Option<DateTime<Utc>>,
109    #[serde(default)]
110    pub deprecation_reason: Option<String>,
111    /// Release versions this item is a member of (semver + name).
112    #[serde(default)]
113    pub release_versions: Vec<ReleaseVersionRef>,
114    pub review: Option<ReviewSummary>,
115    #[serde(default)]
116    pub share_url: Option<String>,
117    pub created_at: DateTime<Utc>,
118    pub updated_at: DateTime<Utc>,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122#[serde(rename_all = "snake_case")]
123pub enum ItemType {
124    Functional,
125    Technical,
126    /// Fallback for any value the server adds later, so a single unexpected
127    /// variant never fails the whole response decode.
128    #[serde(other)]
129    Unknown,
130}
131
132impl std::fmt::Display for ItemType {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        match self {
135            ItemType::Functional => write!(f, "functional"),
136            ItemType::Technical => write!(f, "technical"),
137            ItemType::Unknown => write!(f, "unknown"),
138        }
139    }
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
143#[serde(rename_all = "snake_case")]
144pub enum ImplementationStatus {
145    NotStarted,
146    InProgress,
147    Implemented,
148    Verified,
149    Released,
150    /// Fallback for any value the server adds later.
151    #[serde(other)]
152    Unknown,
153}
154
155impl std::fmt::Display for ImplementationStatus {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        match self {
158            ImplementationStatus::NotStarted => write!(f, "not_started"),
159            ImplementationStatus::InProgress => write!(f, "in_progress"),
160            ImplementationStatus::Implemented => write!(f, "implemented"),
161            ImplementationStatus::Verified => write!(f, "verified"),
162            ImplementationStatus::Released => write!(f, "released"),
163            ImplementationStatus::Unknown => write!(f, "unknown"),
164        }
165    }
166}
167
168// ---------------------------------------------------------------------------
169// Review
170// ---------------------------------------------------------------------------
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct ReviewSummary {
174    pub coverage_score: Option<f64>,
175    pub verdict: Option<String>,
176    pub review_type: Option<String>,
177    pub reviewed_at: Option<DateTime<Utc>>,
178    pub fresh: Option<bool>,
179    // Tech-review fields (review_type == "tech_review")
180    pub coverage_map: Option<serde_json::Value>,
181    pub gaps: Option<Vec<String>>,
182    pub suggestions: Option<Vec<String>>,
183    // Func-review fields (review_type == "func_review")
184    #[serde(default)]
185    pub ambiguities: Option<Vec<String>>,
186    #[serde(default)]
187    pub missing_acceptance_criteria: Option<Vec<String>>,
188    #[serde(default)]
189    pub decomposition_suggestions: Option<Vec<String>>,
190    #[serde(default)]
191    pub clarity_score: Option<f64>,
192    #[serde(default)]
193    pub completeness_score: Option<f64>,
194    #[serde(default)]
195    pub testability_score: Option<f64>,
196    // Shared
197    #[serde(default)]
198    pub risks: Option<Vec<String>>,
199}
200
201/// Returned by `POST /projects/:id/work_package/:id/review`.
202/// The API does not include a top-level `id` field.
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct Review {
205    #[serde(default)]
206    pub id: Option<u64>,
207    #[serde(rename = "type")]
208    pub resource_type: String,
209    pub attributes: ReviewAttributes,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct ReviewAttributes {
214    #[serde(default)]
215    pub coverage_score: Option<f64>,
216    #[serde(default)]
217    pub collective_coverage_score: Option<f64>,
218    #[serde(default)]
219    pub verdict: Option<String>,
220    #[serde(default)]
221    pub tech_item_id: Option<u64>,
222    #[serde(default)]
223    pub tech_item_title: Option<String>,
224    #[serde(default)]
225    pub func_item_ids: Vec<u64>,
226    #[serde(default)]
227    pub functional_requirements_parsed: Vec<String>,
228    /// Map of requirement → coverage entry (status, covered_by, notes).
229    #[serde(default)]
230    pub coverage_map: std::collections::HashMap<String, serde_json::Value>,
231    #[serde(default)]
232    pub gaps: Vec<String>,
233    #[serde(default)]
234    pub suggestions: Vec<String>,
235    #[serde(default)]
236    pub risks: Vec<String>,
237    #[serde(default)]
238    pub reviewed_at: Option<DateTime<Utc>>,
239}
240
241// ---------------------------------------------------------------------------
242// AI — Proposal
243// ---------------------------------------------------------------------------
244
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct Proposal {
247    pub id: u64,
248    #[serde(rename = "type")]
249    pub resource_type: String,
250    pub attributes: ProposalAttributes,
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize)]
254pub struct ProposalAttributes {
255    pub spec_item_id: u64,
256    pub original_description: Option<String>,
257    pub proposed_description: Option<String>,
258    pub rationale: Option<String>,
259    pub status: String,
260    pub created_at: DateTime<Utc>,
261}
262
263// ---------------------------------------------------------------------------
264// AI — Tech Proposals
265// ---------------------------------------------------------------------------
266
267/// A single proposed technical spec item.
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct TechProposal {
270    pub title: String,
271    pub description: Option<String>,
272    pub type_of: String,
273    pub rationale: Option<String>,
274}
275
276/// Collection of tech spec proposals generated from a functional item.
277#[derive(Debug, Clone, Serialize, Deserialize)]
278pub struct TechProposals {
279    pub functional_item_id: u64,
280    pub functional_item_permalink: String,
281    #[serde(default)]
282    pub proposals: Vec<TechProposal>,
283}
284
285// ---------------------------------------------------------------------------
286// Audit
287// ---------------------------------------------------------------------------
288
289/// A code-audit result. The server returns a flat `data` object (not the
290/// `{id,type,attributes}` envelope used elsewhere), so this maps the fields
291/// directly. Unknown/absent fields are tolerated via `#[serde(default)]`.
292#[derive(Debug, Clone, Serialize, Deserialize)]
293pub struct AuditResult {
294    pub id: u64,
295    /// e.g. "implemented", "partial", "not_implemented".
296    #[serde(default)]
297    pub status_recommendation: String,
298    /// e.g. "high", "medium", "low".
299    #[serde(default)]
300    pub confidence: String,
301    #[serde(default)]
302    pub files_discovered: u64,
303    #[serde(default)]
304    pub coverage_percentage: f64,
305    #[serde(default)]
306    pub criteria_coverage: Vec<CriterionCoverage>,
307    #[serde(default)]
308    pub notes: String,
309    pub created_at: DateTime<Utc>,
310}
311
312/// Per-acceptance-criterion coverage within an [`AuditResult`].
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct CriterionCoverage {
315    #[serde(default)]
316    pub criterion: String,
317    #[serde(default)]
318    pub status: String,
319    #[serde(default)]
320    pub evidence: Vec<CriterionEvidence>,
321}
322
323/// A single file/line evidence entry for a criterion.
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct CriterionEvidence {
326    #[serde(default)]
327    pub file: String,
328    #[serde(default)]
329    pub lines: String,
330    #[serde(default)]
331    pub note: String,
332}
333
334// ---------------------------------------------------------------------------
335// Snapshot
336// ---------------------------------------------------------------------------
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct Snapshot {
340    pub id: u64,
341    #[serde(rename = "type")]
342    pub resource_type: String,
343    pub attributes: SnapshotAttributes,
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct SnapshotAttributes {
348    #[serde(default)]
349    pub project_id: Option<u64>,
350    pub name: String,
351    pub description: Option<String>,
352    /// Full spec items — present in older single-snapshot responses, absent in
353    /// current create/show responses (which return counts instead).
354    #[serde(default)]
355    pub spec_items: Vec<SpecItem>,
356    /// Number of spec items captured — returned by create/show (metadata: true).
357    #[serde(default)]
358    pub item_count: Option<u64>,
359    /// Number of dependency edges captured — returned by create/show (metadata: true).
360    #[serde(default)]
361    pub edge_count: Option<u64>,
362    #[serde(default)]
363    pub git_sha: Option<String>,
364    pub created_at: DateTime<Utc>,
365}
366
367// ---------------------------------------------------------------------------
368// ---------------------------------------------------------------------------
369// Release version
370// ---------------------------------------------------------------------------
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct ReleaseVersion {
374    pub id: u64,
375    #[serde(rename = "type")]
376    pub resource_type: String,
377    pub attributes: ReleaseVersionAttributes,
378}
379
380#[derive(Debug, Clone, Serialize, Deserialize)]
381pub struct ReleaseVersionAttributes {
382    pub name: Option<String>,
383    pub semver: String,
384    #[serde(default)]
385    pub lifecycle_state: Option<String>,
386    #[serde(default)]
387    pub description: Option<String>,
388    #[serde(default)]
389    pub branch: Option<String>,
390    #[serde(default)]
391    pub item_count: Option<u64>,
392    /// Member items — present when the version is fetched with items: true (show).
393    #[serde(default)]
394    pub items: Vec<VersionMember>,
395    #[serde(default)]
396    pub created_at: Option<DateTime<Utc>>,
397    #[serde(default)]
398    pub updated_at: Option<DateTime<Utc>>,
399}
400
401/// A spec item that is a member of a release version.
402#[derive(Debug, Clone, Serialize, Deserialize)]
403pub struct VersionMember {
404    pub id: u64,
405    pub permalink: String,
406    pub title: String,
407    pub type_of: String,
408    pub state: String,
409    pub implementation_status: String,
410    #[serde(default)]
411    pub parent_id: Option<u64>,
412    #[serde(default)]
413    pub position: Option<i64>,
414    #[serde(default)]
415    pub deprecated: Option<bool>,
416}
417
418// ---------------------------------------------------------------------------
419// Implementation report-back (T-511 ingest contract)
420// ---------------------------------------------------------------------------
421
422/// Batch implementation report-back payload. Maps 1:1 to the server's
423/// POST /projects/:pid/implementation_reports endpoint.
424#[derive(Debug, Clone, Serialize, Deserialize, Default)]
425pub struct ImplementationReport {
426    /// Release version (semver "1.2.0" or numeric id) to scope the report +
427    /// link newly-created items to.
428    #[serde(skip_serializing_if = "Option::is_none")]
429    pub release_version: Option<String>,
430    #[serde(default)]
431    pub items: Vec<ReportItem>,
432    #[serde(default, skip_serializing_if = "Vec::is_empty")]
433    pub new_items: Vec<ReportNewItem>,
434}
435
436/// One existing spec item in a report-back payload.
437#[derive(Debug, Clone, Serialize, Deserialize, Default)]
438pub struct ReportItem {
439    pub permalink: String,
440    /// Target implementation status; server steps the state machine to reach it.
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub status: Option<String>,
443    #[serde(skip_serializing_if = "Option::is_none")]
444    pub drift: Option<ReportDrift>,
445    #[serde(skip_serializing_if = "Option::is_none")]
446    pub notes: Option<String>,
447}
448
449/// Drift detail for a reported item.
450#[derive(Debug, Clone, Serialize, Deserialize, Default)]
451pub struct ReportDrift {
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub summary: Option<String>,
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub diff: Option<String>,
456}
457
458/// A newly-created item discovered during implementation.
459#[derive(Debug, Clone, Serialize, Deserialize, Default)]
460pub struct ReportNewItem {
461    pub title: String,
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub description: Option<String>,
464    /// "functional" or "technical"; server defaults to functional.
465    #[serde(skip_serializing_if = "Option::is_none")]
466    pub type_of: Option<String>,
467}
468
469/// Server response from an implementation report-back.
470#[derive(Debug, Clone, Serialize, Deserialize, Default)]
471pub struct ImplementationReportResult {
472    #[serde(default)]
473    pub report_id: Option<u64>,
474    #[serde(default)]
475    pub items_processed: u64,
476    #[serde(default)]
477    pub new_items_created: u64,
478    #[serde(default)]
479    pub new_item_ids: Vec<u64>,
480    #[serde(default)]
481    pub errors: Vec<String>,
482}
483
484// ---------------------------------------------------------------------------
485// Version diff (T-509)
486// ---------------------------------------------------------------------------
487
488/// Result of comparing two release versions by membership.
489#[derive(Debug, Clone, Serialize, Deserialize, Default)]
490pub struct VersionDiff {
491    pub from: VersionDiffSide,
492    pub to: VersionDiffSide,
493    #[serde(default)]
494    pub added: Vec<VersionDiffItem>,
495    #[serde(default)]
496    pub removed: Vec<VersionDiffItem>,
497    #[serde(default)]
498    pub changed: Vec<VersionDiffItem>,
499}
500
501#[derive(Debug, Clone, Serialize, Deserialize, Default)]
502pub struct VersionDiffSide {
503    #[serde(default)]
504    pub id: Option<u64>,
505    #[serde(default)]
506    pub semver: Option<String>,
507    #[serde(default)]
508    pub name: Option<String>,
509}
510
511#[derive(Debug, Clone, Serialize, Deserialize, Default)]
512pub struct VersionDiffItem {
513    #[serde(default)]
514    pub id: Option<u64>,
515    #[serde(default)]
516    pub permalink: Option<String>,
517    #[serde(default)]
518    pub title: Option<String>,
519    #[serde(default)]
520    pub state: Option<String>,
521    #[serde(default)]
522    pub implementation_status: Option<String>,
523}
524
525// ---------------------------------------------------------------------------
526// Async job reference (F-463: review/func_review 202 response)
527// ---------------------------------------------------------------------------
528
529/// The 202 response from an async endpoint: { data: { job_id, status } }.
530#[derive(Debug, Clone, Serialize, Deserialize, Default)]
531pub struct AsyncJobRef {
532    #[serde(default)]
533    pub job_id: Option<u64>,
534    #[serde(default)]
535    pub status: Option<String>,
536}
537
538// Job
539// ---------------------------------------------------------------------------
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub struct Job {
543    pub id: u64,
544    /// The batch_jobs endpoint returns a FLAT object (no JSON-API type wrapper),
545    /// so `type` is optional and the job fields flatten into `attributes`.
546    #[serde(rename = "type", default)]
547    pub resource_type: String,
548    #[serde(flatten)]
549    pub attributes: JobAttributes,
550}
551
552#[derive(Debug, Clone, Serialize, Deserialize)]
553pub struct JobAttributes {
554    pub job_type: String,
555    pub status: JobStatus,
556    /// Progress is polymorphic server-side: a float percentage for some job
557    /// types, a structured object (e.g. { item_id, verdict, ... }) for review
558    /// jobs. Accept any JSON value so polling never fails to decode.
559    #[serde(default)]
560    pub progress: Option<serde_json::Value>,
561    #[serde(default)]
562    pub result: Option<String>,
563    pub created_at: DateTime<Utc>,
564    pub updated_at: DateTime<Utc>,
565}
566
567#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
568#[serde(rename_all = "snake_case")]
569pub enum JobStatus {
570    Queued,
571    Pending,
572    Running,
573    Completed,
574    Failed,
575    /// Fallback for any value the server adds later.
576    #[serde(other)]
577    Unknown,
578}
579
580impl std::fmt::Display for JobStatus {
581    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
582        match self {
583            JobStatus::Queued => write!(f, "queued"),
584            JobStatus::Pending => write!(f, "pending"),
585            JobStatus::Running => write!(f, "running"),
586            JobStatus::Completed => write!(f, "completed"),
587            JobStatus::Failed => write!(f, "failed"),
588            JobStatus::Unknown => write!(f, "unknown"),
589        }
590    }
591}
592
593// ---------------------------------------------------------------------------
594// Usage Log (flat row returned by /projects/:id/usage/logs)
595// ---------------------------------------------------------------------------
596
597#[derive(Debug, Clone, Serialize, Deserialize)]
598pub struct UsageLogEntry {
599    #[serde(default)]
600    pub id: u64,
601    #[serde(default)]
602    pub llm_model: String,
603    #[serde(default)]
604    pub action_type: String,
605    #[serde(default)]
606    pub spec_item_id: Option<u64>,
607    #[serde(default)]
608    pub spec_item_title: Option<String>,
609    #[serde(default)]
610    pub input_tokens: u64,
611    #[serde(default)]
612    pub output_tokens: u64,
613    #[serde(default)]
614    pub estimated_cost_cents: u64,
615    #[serde(default)]
616    pub created_at: String,
617}
618
619// ---------------------------------------------------------------------------
620// Request params
621// ---------------------------------------------------------------------------
622
623#[derive(Debug, Default, Serialize)]
624pub struct CreateProjectParams {
625    pub name: String,
626    #[serde(skip_serializing_if = "Option::is_none")]
627    pub description: Option<String>,
628    #[serde(skip_serializing_if = "Option::is_none")]
629    pub slug: Option<String>,
630}
631
632#[derive(Debug, Default, Serialize)]
633pub struct UpdateProjectParams {
634    #[serde(skip_serializing_if = "Option::is_none")]
635    pub name: Option<String>,
636    #[serde(skip_serializing_if = "Option::is_none")]
637    pub description: Option<String>,
638}
639
640#[derive(Debug, Default, Serialize)]
641pub struct CreateItemParams {
642    pub title: String,
643    pub type_of: String,
644    #[serde(skip_serializing_if = "Option::is_none")]
645    pub description: Option<String>,
646    #[serde(skip_serializing_if = "Option::is_none")]
647    pub parent_id: Option<u64>,
648    #[serde(skip_serializing_if = "Option::is_none")]
649    pub tags: Option<String>,
650}
651
652#[derive(Debug, Default, Serialize)]
653pub struct UpdateItemParams {
654    #[serde(skip_serializing_if = "Option::is_none")]
655    pub title: Option<String>,
656    #[serde(skip_serializing_if = "Option::is_none")]
657    pub description: Option<String>,
658    #[serde(skip_serializing_if = "Option::is_none")]
659    pub implementation_status: Option<String>,
660    #[serde(skip_serializing_if = "Option::is_none")]
661    pub tags: Option<String>,
662    /// Some(Some(id)) = set parent, Some(None) = clear parent, None = no change
663    #[serde(skip_serializing_if = "Option::is_none")]
664    pub parent_id: Option<serde_json::Value>,
665}
666
667#[derive(Debug, Default, Serialize)]
668pub struct CreateReviewParams {
669    pub status: String,
670    #[serde(skip_serializing_if = "Option::is_none")]
671    pub comment: Option<String>,
672}
673
674#[derive(Debug, Default, Serialize)]
675pub struct LinkCommitParams {
676    pub sha: String,
677    #[serde(skip_serializing_if = "Option::is_none")]
678    pub message: Option<String>,
679    #[serde(skip_serializing_if = "Option::is_none")]
680    pub committed_at: Option<String>,
681    #[serde(skip_serializing_if = "Option::is_none")]
682    pub source: Option<String>,
683    #[serde(skip_serializing_if = "Option::is_none")]
684    pub agent_run_id: Option<u64>,
685}
686
687#[derive(Debug, Default, Serialize)]
688pub struct RecordRunParams {
689    #[serde(skip_serializing_if = "Option::is_none")]
690    pub session_key: Option<String>,
691    #[serde(skip_serializing_if = "Option::is_none")]
692    pub model: Option<String>,
693    #[serde(skip_serializing_if = "Option::is_none")]
694    pub provider: Option<String>,
695    #[serde(skip_serializing_if = "Option::is_none")]
696    pub status: Option<String>,
697    /// Freeform implementation note / drift text. Stored server-side as the
698    /// run's prompt_text; must NOT be routed into `status` (that field is
699    /// validated against the fixed run-status enum). See T-582.
700    #[serde(skip_serializing_if = "Option::is_none")]
701    pub prompt_text: Option<String>,
702    #[serde(skip_serializing_if = "Option::is_none")]
703    pub input_tokens: Option<u64>,
704    #[serde(skip_serializing_if = "Option::is_none")]
705    pub output_tokens: Option<u64>,
706    #[serde(skip_serializing_if = "Option::is_none")]
707    pub cost: Option<f64>,
708    #[serde(skip_serializing_if = "Option::is_none")]
709    pub instruction_version: Option<u32>,
710}
711
712/// Minimal response from `POST /work_package/:id/record_run`.
713#[derive(Debug, Clone, Serialize, Deserialize, Default)]
714pub struct AgentRun {
715    #[serde(default)]
716    pub id: Option<u64>,
717    #[serde(default)]
718    pub spec_item_id: Option<u64>,
719    #[serde(default)]
720    pub status: Option<String>,
721}
722
723// ---------------------------------------------------------------------------
724// Query filters
725// ---------------------------------------------------------------------------
726
727#[derive(Debug, Default)]
728pub struct ItemFilter {
729    pub type_of: Option<ItemType>,
730    pub status: Option<ImplementationStatus>,
731    pub tag: Option<String>,
732    pub q: Option<String>,
733    pub has_review: Option<bool>,
734    pub review_verdict: Option<String>,
735    pub parent_id: Option<u64>,
736    pub sort: Option<String>,
737    pub page: Option<u32>,
738    pub per: Option<u32>,
739    /// Workflow state filter (inbox/draft/accepted/integrated).
740    pub state: Option<String>,
741    /// Include out-of-scope (deprecated) items when true.
742    pub include_deprecated: Option<bool>,
743    /// Scope to a release version's members (semver or id).
744    pub release_version: Option<String>,
745}
746
747impl ItemFilter {
748    pub fn to_query_pairs(&self) -> Vec<(String, String)> {
749        let mut pairs = Vec::new();
750        if let Some(ref t) = self.type_of {
751            pairs.push(("type_of".into(), t.to_string()));
752        }
753        if let Some(ref s) = self.status {
754            pairs.push(("implementation_status".into(), s.to_string()));
755        }
756        if let Some(ref tag) = self.tag {
757            pairs.push(("tag".into(), tag.clone()));
758        }
759        if let Some(ref q) = self.q {
760            pairs.push(("q".into(), q.clone()));
761        }
762        if let Some(true) = self.has_review {
763            pairs.push(("has_review".into(), "true".into()));
764        }
765        if let Some(ref v) = self.review_verdict {
766            pairs.push(("review_verdict".into(), v.clone()));
767        }
768        if let Some(id) = self.parent_id {
769            pairs.push(("parent_id".into(), id.to_string()));
770        }
771        if let Some(ref s) = self.sort {
772            pairs.push(("sort".into(), s.clone()));
773        }
774        if let Some(p) = self.page {
775            pairs.push(("page".into(), p.to_string()));
776        }
777        if let Some(p) = self.per {
778            pairs.push(("per".into(), p.to_string()));
779        }
780        if let Some(ref st) = self.state {
781            pairs.push(("state".into(), st.clone()));
782        }
783        if let Some(true) = self.include_deprecated {
784            pairs.push(("include_deprecated".into(), "true".into()));
785        }
786        if let Some(ref rv) = self.release_version {
787            pairs.push(("release_version".into(), rv.clone()));
788        }
789        pairs
790    }
791}
792
793// ---------------------------------------------------------------------------
794// Stats
795// ---------------------------------------------------------------------------
796
797/// Returned by `GET /projects/:id/stats` (inside `{"data": {...}}`).
798#[derive(Debug, Clone, Serialize, Deserialize)]
799pub struct ProjectStats {
800    #[serde(rename = "type", default)]
801    pub resource_type: Option<String>,
802    pub spec_items: StatsSpecItems,
803    pub reviews: StatsReviews,
804    pub coverage: StatsCoverage,
805    pub recent_activity: StatsRecentActivity,
806}
807
808#[derive(Debug, Clone, Serialize, Deserialize, Default)]
809pub struct StatsSpecItems {
810    #[serde(default)]
811    pub total: u32,
812    #[serde(default)]
813    pub by_type: std::collections::HashMap<String, u32>,
814    #[serde(default)]
815    pub by_state: std::collections::HashMap<String, u32>,
816    #[serde(default)]
817    pub by_implementation: std::collections::HashMap<String, u32>,
818}
819
820#[derive(Debug, Clone, Serialize, Deserialize, Default)]
821pub struct StatsReviews {
822    #[serde(default)]
823    pub tech_reviewed: i32,
824    #[serde(default)]
825    pub tech_unreviewed: i32,
826    #[serde(default)]
827    pub func_reviewed: i32,
828    #[serde(default)]
829    pub func_unreviewed: i32,
830    #[serde(default)]
831    pub avg_tech_score: Option<f64>,
832    #[serde(default)]
833    pub avg_func_score: Option<f64>,
834    #[serde(default)]
835    pub by_verdict: std::collections::HashMap<String, u32>,
836}
837
838#[derive(Debug, Clone, Serialize, Deserialize, Default)]
839pub struct StatsCoverage {
840    #[serde(default)]
841    pub functional_with_tech: u32,
842    #[serde(default)]
843    pub functional_without_tech: u32,
844}
845
846#[derive(Debug, Clone, Serialize, Deserialize, Default)]
847pub struct StatsRecentActivity {
848    #[serde(default)]
849    pub items_updated_24h: u32,
850    #[serde(default)]
851    pub reviews_24h: u32,
852    #[serde(default)]
853    pub agent_runs_24h: u32,
854}
855
856/// Flat summary returned by GET /projects/:id/usage (no JSON:API wrapper).
857#[derive(Debug, Clone, Serialize, Deserialize, Default)]
858pub struct UsageStats {
859    #[serde(default)]
860    pub year: i32,
861    #[serde(default)]
862    pub month: u32,
863    #[serde(default)]
864    pub total_calls: u64,
865    #[serde(default)]
866    pub total_tokens: u64,
867    #[serde(default)]
868    pub total_cost_cents: u64,
869    #[serde(default)]
870    pub by_action_type: Vec<ActionTypeUsage>,
871    #[serde(default)]
872    pub by_model: Vec<ModelUsage>,
873}
874
875#[derive(Debug, Clone, Serialize, Deserialize, Default)]
876pub struct ActionTypeUsage {
877    #[serde(default)]
878    pub action_type: String,
879    #[serde(default)]
880    pub call_count: u64,
881    #[serde(default)]
882    pub total_input_tokens: u64,
883    #[serde(default)]
884    pub total_output_tokens: u64,
885    #[serde(default)]
886    pub total_cost_cents: u64,
887}
888
889#[derive(Debug, Clone, Serialize, Deserialize, Default)]
890pub struct ModelUsage {
891    #[serde(default)]
892    pub llm_model: String,
893    #[serde(default)]
894    pub call_count: u64,
895    #[serde(default)]
896    pub total_input_tokens: u64,
897    #[serde(default)]
898    pub total_output_tokens: u64,
899    #[serde(default)]
900    pub total_cost_cents: u64,
901}
902
903// ---------------------------------------------------------------------------
904// Usage filter
905// ---------------------------------------------------------------------------
906
907#[derive(Debug, Default)]
908pub struct UsageFilter {
909    pub year: Option<i32>,
910    pub month: Option<u32>,
911    pub action_type: Option<String>,
912    pub page: Option<u32>,
913    pub per: Option<u32>,
914}
915
916impl UsageFilter {
917    pub fn to_query_pairs(&self) -> Vec<(String, String)> {
918        let mut pairs = Vec::new();
919        if let Some(y) = self.year {
920            pairs.push(("year".into(), y.to_string()));
921        }
922        if let Some(m) = self.month {
923            pairs.push(("month".into(), m.to_string()));
924        }
925        if let Some(ref a) = self.action_type {
926            pairs.push(("action_type".into(), a.clone()));
927        }
928        if let Some(p) = self.page {
929            pairs.push(("page".into(), p.to_string()));
930        }
931        if let Some(p) = self.per {
932            pairs.push(("per".into(), p.to_string()));
933        }
934        pairs
935    }
936}
937
938// ---------------------------------------------------------------------------
939// Snapshot diff
940// ---------------------------------------------------------------------------
941
942/// A single modified item in a snapshot diff.
943#[derive(Debug, Clone, Serialize, Deserialize)]
944pub struct SnapshotDiffModified {
945    pub permalink: String,
946    pub before: serde_json::Value,
947    pub after: serde_json::Value,
948    pub changes: std::collections::HashMap<String, serde_json::Value>,
949}
950
951/// Spec-item changes in a snapshot diff.
952#[derive(Debug, Clone, Serialize, Deserialize)]
953pub struct SnapshotDiffItems {
954    pub added: Vec<serde_json::Value>,
955    pub removed: Vec<serde_json::Value>,
956    pub modified: Vec<SnapshotDiffModified>,
957}
958
959/// Edge changes in a snapshot diff.
960#[derive(Debug, Clone, Serialize, Deserialize)]
961pub struct SnapshotDiffEdges {
962    pub added: Vec<serde_json::Value>,
963    pub removed: Vec<serde_json::Value>,
964}
965
966/// Summary counts in a snapshot diff.
967#[derive(Debug, Clone, Serialize, Deserialize)]
968pub struct SnapshotDiffSummary {
969    pub items_added: u32,
970    pub items_removed: u32,
971    pub items_modified: u32,
972    pub edges_added: u32,
973    pub edges_removed: u32,
974}
975
976/// Diff between a snapshot and the current project state.
977#[derive(Debug, Clone, Serialize, Deserialize)]
978pub struct SnapshotDiff {
979    pub spec_items: SnapshotDiffItems,
980    pub edges: SnapshotDiffEdges,
981    pub summary: SnapshotDiffSummary,
982}
983
984// ---------------------------------------------------------------------------
985// AuditRun
986// ---------------------------------------------------------------------------
987
988#[derive(Debug, Clone, Serialize, Deserialize)]
989pub struct AuditRun {
990    pub id: u64,
991    pub name: Option<String>,
992    pub state: String,
993    pub requested_concurrency: u32,
994    pub effective_concurrency: u32,
995    pub filter_criteria: Option<serde_json::Value>,
996    /// F-517/F-293: the release version this run is scoped to (if any).
997    #[serde(default)]
998    pub release_version_id: Option<u64>,
999    /// F-517/F-293: the code branch audited (snapshotted from the version's
1000    /// branch at creation). Null = the repository's default branch was used.
1001    #[serde(default)]
1002    pub audit_branch: Option<String>,
1003    pub created_by_user_id: Option<u64>,
1004    pub started_at: Option<DateTime<Utc>>,
1005    pub completed_at: Option<DateTime<Utc>>,
1006    pub created_at: DateTime<Utc>,
1007    pub updated_at: DateTime<Utc>,
1008    pub stats: AuditRunStats,
1009    #[serde(default)]
1010    pub items: Vec<AuditRunItem>,
1011    pub page: Option<u32>,
1012    pub total_pages: Option<u32>,
1013}
1014
1015#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1016pub struct AuditRunStats {
1017    #[serde(default)]
1018    pub total: u32,
1019    #[serde(default)]
1020    pub pending: u32,
1021    #[serde(default)]
1022    pub running: u32,
1023    #[serde(default)]
1024    pub done: u32,
1025    #[serde(default)]
1026    pub failed: u32,
1027    #[serde(default)]
1028    pub failed_permanently: u32,
1029    #[serde(default)]
1030    pub cancelled: u32,
1031    #[serde(default)]
1032    pub improved: u32,
1033    #[serde(default)]
1034    pub regressed: u32,
1035    #[serde(default)]
1036    pub unchanged: u32,
1037    pub avg_score_before: Option<f64>,
1038    pub avg_score_after: Option<f64>,
1039}
1040
1041#[derive(Debug, Clone, Serialize, Deserialize)]
1042pub struct AuditRunItem {
1043    pub id: u64,
1044    pub spec_item_id: u64,
1045    pub permalink: Option<String>,
1046    pub title: Option<String>,
1047    pub state: String,
1048    #[serde(default)]
1049    pub attempt_count: u32,
1050    pub old_score: Option<f64>,
1051    pub new_score: Option<f64>,
1052    pub delta: Option<f64>,
1053    pub verdict: Option<String>,
1054    pub top_gaps: Option<serde_json::Value>,
1055    pub error_message: Option<String>,
1056    pub updated_at: DateTime<Utc>,
1057}
1058
1059// ---------------------------------------------------------------------------
1060// Request params — AuditRun
1061// ---------------------------------------------------------------------------
1062
1063#[derive(Debug, Default, Serialize)]
1064pub struct CreateRunParams {
1065    #[serde(skip_serializing_if = "Option::is_none")]
1066    pub type_of: Option<String>,
1067    #[serde(skip_serializing_if = "Option::is_none")]
1068    pub status: Option<String>,
1069    #[serde(skip_serializing_if = "Option::is_none")]
1070    pub score_below: Option<u32>,
1071    #[serde(skip_serializing_if = "Option::is_none")]
1072    pub tag: Option<String>,
1073    #[serde(skip_serializing_if = "Vec::is_empty")]
1074    pub item_ids: Vec<u64>,
1075    #[serde(skip_serializing_if = "Option::is_none")]
1076    pub concurrency: Option<u32>,
1077    #[serde(skip_serializing_if = "Option::is_none")]
1078    pub name: Option<String>,
1079    #[serde(skip_serializing_if = "Option::is_none")]
1080    pub no_start: Option<bool>,
1081    /// F-517/F-293: scope the run to a release version (semver like "0.1.0" or
1082    /// its id). The server scopes to that version's member items and sets
1083    /// audit_branch from the version's branch, so the audit targets that code.
1084    #[serde(skip_serializing_if = "Option::is_none")]
1085    pub release_version: Option<String>,
1086    /// Acknowledges a multi-item run. The server rejects a create resolving to
1087    /// more than one item unless this is set.
1088    #[serde(skip_serializing_if = "Option::is_none")]
1089    pub confirmed: Option<bool>,
1090}
1091
1092#[derive(Debug, Default, Serialize)]
1093pub struct UpdateRunParams {
1094    #[serde(skip_serializing_if = "Option::is_none")]
1095    pub name: Option<String>,
1096}
1097
1098/// Result of `POST /runs/preview` — the item set a create would resolve to,
1099/// without persisting a run. `items` is capped server-side; `count` is exact.
1100#[derive(Debug, Clone, Serialize, Deserialize)]
1101pub struct RunPreview {
1102    pub count: u32,
1103    #[serde(default)]
1104    pub truncated: bool,
1105    pub filter_criteria: Option<serde_json::Value>,
1106    #[serde(default)]
1107    pub items: Vec<RunPreviewItem>,
1108}
1109
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub struct RunPreviewItem {
1112    pub id: u64,
1113    pub permalink: Option<String>,
1114    pub title: Option<String>,
1115    pub type_of: Option<String>,
1116}
1117
1118// ---------------------------------------------------------------------------
1119// Request params — Snapshot
1120// ---------------------------------------------------------------------------
1121
1122#[derive(Debug, Serialize)]
1123pub struct CreateSnapshotParams {
1124    pub name: String,
1125    #[serde(skip_serializing_if = "Option::is_none")]
1126    pub description: Option<String>,
1127}
1128
1129// ---------------------------------------------------------------------------
1130// Tests
1131// ---------------------------------------------------------------------------
1132
1133#[cfg(test)]
1134mod tests {
1135    use super::*;
1136
1137    #[test]
1138    fn create_run_params_serializes_confirmed_when_set() {
1139        let p = CreateRunParams {
1140            confirmed: Some(true),
1141            ..Default::default()
1142        };
1143        let json = serde_json::to_string(&p).unwrap();
1144        assert!(json.contains("\"confirmed\":true"), "got: {json}");
1145    }
1146
1147    #[test]
1148    fn create_run_params_omits_confirmed_when_none() {
1149        let p = CreateRunParams::default();
1150        let json = serde_json::to_string(&p).unwrap();
1151        assert!(!json.contains("confirmed"), "got: {json}");
1152    }
1153
1154    #[test]
1155    fn item_type_display() {
1156        assert_eq!(ItemType::Functional.to_string(), "functional");
1157        assert_eq!(ItemType::Technical.to_string(), "technical");
1158    }
1159
1160    #[test]
1161    fn item_type_serde_roundtrip() {
1162        let json = r#""functional""#;
1163        let t: ItemType = serde_json::from_str(json).unwrap();
1164        assert_eq!(t, ItemType::Functional);
1165        assert_eq!(serde_json::to_string(&t).unwrap(), json);
1166    }
1167
1168    #[test]
1169    fn impl_status_display() {
1170        assert_eq!(ImplementationStatus::NotStarted.to_string(), "not_started");
1171        assert_eq!(ImplementationStatus::InProgress.to_string(), "in_progress");
1172        assert_eq!(ImplementationStatus::Implemented.to_string(), "implemented");
1173        assert_eq!(ImplementationStatus::Verified.to_string(), "verified");
1174        assert_eq!(ImplementationStatus::Released.to_string(), "released");
1175    }
1176
1177    #[test]
1178    fn impl_status_serde_roundtrip() {
1179        let json = r#""in_progress""#;
1180        let s: ImplementationStatus = serde_json::from_str(json).unwrap();
1181        assert_eq!(s, ImplementationStatus::InProgress);
1182    }
1183
1184    #[test]
1185    fn impl_status_verified_released_roundtrip() {
1186        let v: ImplementationStatus = serde_json::from_str(r#""verified""#).unwrap();
1187        assert_eq!(v, ImplementationStatus::Verified);
1188        let r: ImplementationStatus = serde_json::from_str(r#""released""#).unwrap();
1189        assert_eq!(r, ImplementationStatus::Released);
1190        assert_eq!(serde_json::to_string(&v).unwrap(), r#""verified""#);
1191        assert_eq!(serde_json::to_string(&r).unwrap(), r#""released""#);
1192    }
1193
1194    #[test]
1195    fn link_commit_params_skips_none_fields() {
1196        let p = LinkCommitParams {
1197            sha: "abc123".into(),
1198            ..Default::default()
1199        };
1200        let json = serde_json::to_string(&p).unwrap();
1201        assert!(json.contains("abc123"));
1202        assert!(!json.contains("message"));
1203        assert!(!json.contains("source"));
1204    }
1205
1206    #[test]
1207    fn record_run_params_skips_none_fields() {
1208        let p = RecordRunParams::default();
1209        let json = serde_json::to_string(&p).unwrap();
1210        assert_eq!(json, "{}");
1211    }
1212
1213    #[test]
1214    fn agent_run_deserialize_with_id() {
1215        let json = r#"{"data": {"id": 9, "spec_item_id": 756, "status": "pending"}}"#;
1216        let resp: serde_json::Value = serde_json::from_str(json).unwrap();
1217        let id = resp
1218            .get("data")
1219            .and_then(|d| d.get("id"))
1220            .and_then(|v| v.as_u64());
1221        assert_eq!(id, Some(9));
1222    }
1223
1224    #[test]
1225    fn agent_run_deserialize_missing_id() {
1226        let json = r#"{"data": {"spec_item_id": 756}}"#;
1227        let resp: serde_json::Value = serde_json::from_str(json).unwrap();
1228        let id = resp
1229            .get("data")
1230            .and_then(|d| d.get("id"))
1231            .and_then(|v| v.as_u64());
1232        assert_eq!(id, None);
1233    }
1234
1235    #[test]
1236    fn job_status_display() {
1237        assert_eq!(JobStatus::Pending.to_string(), "pending");
1238        assert_eq!(JobStatus::Completed.to_string(), "completed");
1239        assert_eq!(JobStatus::Failed.to_string(), "failed");
1240    }
1241
1242    #[test]
1243    fn project_deserialize() {
1244        let json = r#"{
1245            "id": 42,
1246            "type": "project",
1247            "attributes": {
1248                "name": "My Project",
1249                "description": "desc",
1250                "slug": "my-project",
1251                "created_at": "2024-01-01T00:00:00Z",
1252                "updated_at": "2024-06-01T00:00:00Z"
1253            }
1254        }"#;
1255        let p: Project = serde_json::from_str(json).unwrap();
1256        assert_eq!(p.id, 42);
1257        assert_eq!(p.attributes.name, "My Project");
1258        assert_eq!(p.attributes.slug, "my-project");
1259    }
1260
1261    #[test]
1262    fn spec_item_deserialize_minimal() {
1263        let json = r#"{
1264            "id": 1,
1265            "type": "spec_item",
1266            "attributes": {
1267                "title": "Feature X",
1268                "description": null,
1269                "type_of": "functional",
1270                "state": "active",
1271                "implementation_status": "not_started",
1272                "permalink": "F-1",
1273                "url": "https://funcspec.net/items/1",
1274                "version": 1,
1275                "priority": null,
1276                "position": null,
1277                "tags": [],
1278                "parent_id": null,
1279                "project_id": 1,
1280                "review": null,
1281                "created_at": "2024-01-01T00:00:00Z",
1282                "updated_at": "2024-01-01T00:00:00Z"
1283            }
1284        }"#;
1285        let item: SpecItem = serde_json::from_str(json).unwrap();
1286        assert_eq!(item.id, 1);
1287        assert_eq!(item.attributes.permalink, "F-1");
1288        assert_eq!(item.attributes.type_of, ItemType::Functional);
1289        assert_eq!(
1290            item.attributes.implementation_status,
1291            Some(ImplementationStatus::NotStarted)
1292        );
1293    }
1294
1295    #[test]
1296    fn spec_item_with_review_deserialize() {
1297        let json = r#"{
1298            "id": 5,
1299            "type": "spec_item",
1300            "attributes": {
1301                "title": "Auth flow",
1302                "description": "Login/logout",
1303                "type_of": "technical",
1304                "state": "active",
1305                "implementation_status": "implemented",
1306                "permalink": "T-5",
1307                "url": "https://funcspec.net/items/5",
1308                "version": 2,
1309                "priority": 1,
1310                "position": 1,
1311                "tags": ["auth", "backend"],
1312                "parent_id": null,
1313                "project_id": 1,
1314                "review": {
1315                    "id": 10,
1316                    "coverage_score": 85.5,
1317                    "verdict": "looks good",
1318                    "updated_at": "2024-06-01T00:00:00Z"
1319                },
1320                "created_at": "2024-01-01T00:00:00Z",
1321                "updated_at": "2024-06-01T00:00:00Z"
1322            }
1323        }"#;
1324        let item: SpecItem = serde_json::from_str(json).unwrap();
1325        let review = item.attributes.review.unwrap();
1326        assert_eq!(review.coverage_score, Some(85.5));
1327        assert_eq!(review.verdict.as_deref(), Some("looks good"));
1328    }
1329
1330    #[test]
1331    fn api_list_response_deserialize() {
1332        let json = r#"{
1333            "data": [],
1334            "meta": {"page": 1, "per": 25, "total": 0, "total_pages": 0}
1335        }"#;
1336        let resp: ApiListResponse<Project> = serde_json::from_str(json).unwrap();
1337        assert!(resp.data.is_empty());
1338        let meta = resp.meta.unwrap();
1339        assert_eq!(meta.page, 1);
1340        assert_eq!(meta.total, 0);
1341    }
1342
1343    #[test]
1344    fn api_list_response_no_meta() {
1345        let json = r#"{"data": [], "meta": null}"#;
1346        let resp: ApiListResponse<Project> = serde_json::from_str(json).unwrap();
1347        assert!(resp.meta.is_none());
1348    }
1349
1350    #[test]
1351    fn item_filter_to_query_pairs_empty() {
1352        let filter = ItemFilter::default();
1353        assert!(filter.to_query_pairs().is_empty());
1354    }
1355
1356    #[test]
1357    fn item_filter_sort_param() {
1358        let filter = ItemFilter {
1359            sort: Some("score".into()),
1360            ..Default::default()
1361        };
1362        let pairs = filter.to_query_pairs();
1363        assert!(pairs.iter().any(|(k, v)| k == "sort" && v == "score"));
1364    }
1365
1366    #[test]
1367    fn project_stats_deserialize() {
1368        let json = r#"{
1369            "type": "project_stats",
1370            "spec_items": {
1371                "total": 42,
1372                "by_type": {"functional": 12, "technical": 30},
1373                "by_state": {"inbox": 42},
1374                "by_implementation": {"implemented": 28, "in_progress": 8, "not_started": 6}
1375            },
1376            "reviews": {
1377                "tech_reviewed": 30,
1378                "tech_unreviewed": 0,
1379                "func_reviewed": 5,
1380                "func_unreviewed": 7,
1381                "avg_tech_score": 87.2,
1382                "avg_func_score": null,
1383                "by_verdict": {"pass": 20, "needs_refinement": 12, "major_gaps": 3}
1384            },
1385            "coverage": {
1386                "functional_with_tech": 5,
1387                "functional_without_tech": 7
1388            },
1389            "recent_activity": {
1390                "items_updated_24h": 2,
1391                "reviews_24h": 3,
1392                "agent_runs_24h": 0
1393            }
1394        }"#;
1395        let s: ProjectStats = serde_json::from_str(json).unwrap();
1396        assert_eq!(s.spec_items.total, 42);
1397        assert_eq!(s.spec_items.by_type.get("functional"), Some(&12u32));
1398        assert_eq!(s.spec_items.by_type.get("technical"), Some(&30u32));
1399        assert_eq!(
1400            s.spec_items.by_implementation.get("implemented"),
1401            Some(&28u32)
1402        );
1403        assert_eq!(s.reviews.tech_reviewed, 30);
1404        assert_eq!(s.reviews.avg_tech_score, Some(87.2));
1405        assert_eq!(s.reviews.avg_func_score, None);
1406        assert_eq!(s.reviews.by_verdict.get("pass"), Some(&20u32));
1407        assert_eq!(s.reviews.by_verdict.get("needs_refinement"), Some(&12u32));
1408        assert_eq!(s.coverage.functional_with_tech, 5);
1409        assert_eq!(s.recent_activity.items_updated_24h, 2);
1410        assert_eq!(s.recent_activity.reviews_24h, 3);
1411    }
1412
1413    #[test]
1414    fn project_stats_negative_unreviewed() {
1415        // Server can return negative values when review count exceeds item count (server bug).
1416        // The client must accept them rather than panic.
1417        let json = r#"{
1418            "type": "project_stats",
1419            "spec_items": {"total": 90, "by_type": {}, "by_state": {}, "by_implementation": {}},
1420            "reviews": {
1421                "tech_reviewed": 92,
1422                "tech_unreviewed": -2,
1423                "func_reviewed": 0,
1424                "func_unreviewed": 0,
1425                "avg_tech_score": null,
1426                "avg_func_score": null,
1427                "by_verdict": {}
1428            },
1429            "coverage": {"functional_with_tech": 0, "functional_without_tech": 0},
1430            "recent_activity": {"items_updated_24h": 0, "reviews_24h": 0, "agent_runs_24h": 0}
1431        }"#;
1432        let s: ProjectStats = serde_json::from_str(json).unwrap();
1433        assert_eq!(s.reviews.tech_reviewed, 92);
1434        assert_eq!(s.reviews.tech_unreviewed, -2);
1435    }
1436
1437    #[test]
1438    fn usage_stats_deserialize() {
1439        let json = r#"{
1440            "year": 2026,
1441            "month": 3,
1442            "total_calls": 120,
1443            "total_tokens": 45200,
1444            "total_cost_cents": 1234,
1445            "by_action_type": [
1446                {"action_type": "review", "call_count": 80,
1447                 "total_input_tokens": 20000, "total_output_tokens": 10000,
1448                 "total_cost_cents": 800}
1449            ],
1450            "by_model": [
1451                {"llm_model": "gpt-4o", "call_count": 80,
1452                 "total_input_tokens": 20000, "total_output_tokens": 10000,
1453                 "total_cost_cents": 800}
1454            ]
1455        }"#;
1456        let s: UsageStats = serde_json::from_str(json).unwrap();
1457        assert_eq!(s.year, 2026);
1458        assert_eq!(s.month, 3);
1459        assert_eq!(s.total_tokens, 45200);
1460        assert_eq!(s.total_cost_cents, 1234);
1461        assert_eq!(s.by_action_type.len(), 1);
1462        assert_eq!(s.by_action_type[0].action_type, "review");
1463        assert_eq!(s.by_model[0].llm_model, "gpt-4o");
1464    }
1465
1466    #[test]
1467    fn review_attributes_with_ai_fields_deserialize() {
1468        let json = r#"{
1469            "data": {
1470                "type": "review",
1471                "attributes": {
1472                    "coverage_score": 87.5,
1473                    "collective_coverage_score": null,
1474                    "verdict": "pass",
1475                    "tech_item_id": 10,
1476                    "tech_item_title": "JWT service",
1477                    "func_item_ids": [5],
1478                    "functional_requirements_parsed": ["Login", "logout", "reset"],
1479                    "coverage_map": {
1480                        "Authentication flow": {"status": "covered", "covered_by": "JWT service", "notes": ""}
1481                    },
1482                    "gaps": ["Missing edge case for expired tokens"],
1483                    "suggestions": ["Add retry logic"],
1484                    "risks": ["Token expiry race condition"],
1485                    "reviewed_at": "2026-01-01T00:00:00Z"
1486                }
1487            }
1488        }"#;
1489        let resp: ApiResponse<Review> = serde_json::from_str(json).unwrap();
1490        let attrs = &resp.data.attributes;
1491        assert_eq!(attrs.coverage_score, Some(87.5));
1492        assert_eq!(attrs.coverage_map.len(), 1);
1493        assert_eq!(attrs.gaps.len(), 1);
1494        assert_eq!(attrs.suggestions.len(), 1);
1495        assert_eq!(attrs.risks.len(), 1);
1496        assert_eq!(attrs.gaps[0], "Missing edge case for expired tokens");
1497        assert_eq!(attrs.tech_item_title.as_deref(), Some("JWT service"));
1498    }
1499
1500    #[test]
1501    fn review_attributes_missing_ai_fields_defaults_empty() {
1502        let json = r#"{
1503            "data": {
1504                "type": "review",
1505                "attributes": {
1506                    "coverage_score": null,
1507                    "verdict": null
1508                }
1509            }
1510        }"#;
1511        let resp: ApiResponse<Review> = serde_json::from_str(json).unwrap();
1512        let attrs = &resp.data.attributes;
1513        assert!(attrs.coverage_map.is_empty());
1514        assert!(attrs.gaps.is_empty());
1515        assert!(attrs.suggestions.is_empty());
1516        assert!(attrs.risks.is_empty());
1517    }
1518
1519    #[test]
1520    fn proposal_deserialize() {
1521        let json = r#"{
1522            "data": {
1523                "id": 10,
1524                "type": "proposal",
1525                "attributes": {
1526                    "spec_item_id": 5,
1527                    "original_description": "User can log in with email.",
1528                    "proposed_description": "User can log in with email and password. The system validates credentials and returns a JWT.",
1529                    "rationale": "More detail improves clarity",
1530                    "status": "pending",
1531                    "created_at": "2026-03-01T00:00:00Z"
1532                }
1533            }
1534        }"#;
1535        let resp: ApiResponse<Proposal> = serde_json::from_str(json).unwrap();
1536        let attrs = &resp.data.attributes;
1537        assert_eq!(attrs.spec_item_id, 5);
1538        assert_eq!(attrs.status, "pending");
1539        assert!(
1540            attrs
1541                .proposed_description
1542                .as_deref()
1543                .unwrap()
1544                .contains("JWT")
1545        );
1546        assert!(attrs.rationale.is_some());
1547    }
1548
1549    #[test]
1550    fn tech_proposals_deserialize() {
1551        let json = r#"{
1552            "data": {
1553                "functional_item_id": 1,
1554                "functional_item_permalink": "F-1",
1555                "proposals": [
1556                    {
1557                        "title": "Database schema for users",
1558                        "description": "Create users table",
1559                        "type_of": "technical",
1560                        "rationale": "Required for auth"
1561                    },
1562                    {
1563                        "title": "JWT middleware",
1564                        "description": null,
1565                        "type_of": "technical",
1566                        "rationale": null
1567                    }
1568                ]
1569            }
1570        }"#;
1571        let resp: ApiResponse<TechProposals> = serde_json::from_str(json).unwrap();
1572        let tp = &resp.data;
1573        assert_eq!(tp.functional_item_id, 1);
1574        assert_eq!(tp.functional_item_permalink, "F-1");
1575        assert_eq!(tp.proposals.len(), 2);
1576        assert_eq!(tp.proposals[0].title, "Database schema for users");
1577        assert!(tp.proposals[0].rationale.is_some());
1578        assert!(tp.proposals[1].rationale.is_none());
1579    }
1580
1581    #[test]
1582    fn tech_proposals_empty_proposals_defaults() {
1583        let json = r#"{
1584            "data": {
1585                "functional_item_id": 99,
1586                "functional_item_permalink": "F-99"
1587            }
1588        }"#;
1589        let resp: ApiResponse<TechProposals> = serde_json::from_str(json).unwrap();
1590        assert!(resp.data.proposals.is_empty());
1591    }
1592
1593    #[test]
1594    fn usage_filter_query_pairs() {
1595        let f = UsageFilter {
1596            year: Some(2026),
1597            month: Some(3),
1598            action_type: Some("review".into()),
1599            page: Some(2),
1600            per: Some(20),
1601        };
1602        let pairs = f.to_query_pairs();
1603        assert!(pairs.iter().any(|(k, v)| k == "year" && v == "2026"));
1604        assert!(pairs.iter().any(|(k, v)| k == "month" && v == "3"));
1605        assert!(
1606            pairs
1607                .iter()
1608                .any(|(k, v)| k == "action_type" && v == "review")
1609        );
1610        assert!(pairs.iter().any(|(k, v)| k == "page" && v == "2"));
1611        assert!(pairs.iter().any(|(k, v)| k == "per" && v == "20"));
1612    }
1613
1614    #[test]
1615    fn item_filter_to_query_pairs_full() {
1616        let filter = ItemFilter {
1617            type_of: Some(ItemType::Functional),
1618            status: Some(ImplementationStatus::InProgress),
1619            tag: Some("auth".into()),
1620            q: Some("login".into()),
1621            has_review: Some(true),
1622            review_verdict: Some("approved".into()),
1623            parent_id: Some(42),
1624            sort: Some("score".into()),
1625            page: Some(2),
1626            per: Some(10),
1627            state: Some("accepted".into()),
1628            include_deprecated: Some(true),
1629            release_version: Some("0.1.0".into()),
1630        };
1631        let pairs = filter.to_query_pairs();
1632        assert!(
1633            pairs
1634                .iter()
1635                .any(|(k, v)| k == "type_of" && v == "functional")
1636        );
1637        assert!(
1638            pairs
1639                .iter()
1640                .any(|(k, v)| k == "implementation_status" && v == "in_progress")
1641        );
1642        assert!(pairs.iter().any(|(k, v)| k == "tag" && v == "auth"));
1643        assert!(pairs.iter().any(|(k, v)| k == "q" && v == "login"));
1644        assert!(pairs.iter().any(|(k, v)| k == "has_review" && v == "true"));
1645        assert!(
1646            pairs
1647                .iter()
1648                .any(|(k, v)| k == "review_verdict" && v == "approved")
1649        );
1650        assert!(pairs.iter().any(|(k, v)| k == "parent_id" && v == "42"));
1651        assert!(pairs.iter().any(|(k, v)| k == "sort" && v == "score"));
1652        assert!(pairs.iter().any(|(k, v)| k == "page" && v == "2"));
1653        assert!(pairs.iter().any(|(k, v)| k == "per" && v == "10"));
1654    }
1655}
1656
1657// ---------------------------------------------------------------------------
1658// Dependency Edge (Graph)
1659// ---------------------------------------------------------------------------
1660
1661#[derive(Debug, Clone, Serialize, Deserialize)]
1662pub struct DependencyEdge {
1663    pub id: u64,
1664    #[serde(rename = "type")]
1665    pub resource_type: String,
1666    pub attributes: DependencyEdgeAttributes,
1667}
1668
1669#[derive(Debug, Clone, Serialize, Deserialize)]
1670pub struct DependencyEdgeAttributes {
1671    pub source_id: u64,
1672    pub target_id: u64,
1673    pub edge_type: String,
1674    pub created_at: DateTime<Utc>,
1675}
1676
1677#[derive(Debug, Serialize, Deserialize)]
1678pub struct CreateEdgeParams {
1679    pub source_id: u64,
1680    pub target_id: u64,
1681    pub edge_type: String,
1682}
1683
1684// ---------------------------------------------------------------------------
1685// Agent Instructions
1686// ---------------------------------------------------------------------------
1687
1688/// Content returned by the agent_instructions endpoint.
1689#[derive(Debug, Clone, Serialize, Deserialize)]
1690pub struct AgentInstructions {
1691    pub content: String,
1692}
1693
1694// Export
1695// ---------------------------------------------------------------------------
1696
1697/// Data returned by the export API.
1698#[derive(Debug)]
1699pub enum ExportData {
1700    /// Text-based format (markdown, json, csv, html).
1701    Text(String),
1702    /// Binary format (pdf, docx).
1703    Binary(Vec<u8>),
1704}
1705
1706// ---------------------------------------------------------------------------
1707// Import
1708// ---------------------------------------------------------------------------
1709
1710/// One item in an import payload — used both for the parsed items returned by
1711/// `preview_import` and as the request body elements for `commit_import`.
1712#[derive(Debug, Clone, Serialize, Deserialize)]
1713pub struct ImportItem {
1714    pub title: String,
1715    #[serde(default, skip_serializing_if = "Option::is_none")]
1716    pub description: Option<String>,
1717    pub type_of: String,
1718    #[serde(default, skip_serializing_if = "Option::is_none")]
1719    pub parent_title: Option<String>,
1720    #[serde(default, skip_serializing_if = "Option::is_none")]
1721    pub position: Option<i64>,
1722}
1723
1724/// Response from `POST .../import/preview`.
1725/// Wrapped in `ApiResponse<ImportPreview>`.
1726#[derive(Debug, Clone, Serialize, Deserialize)]
1727pub struct ImportPreview {
1728    #[serde(rename = "type", default)]
1729    pub resource_type: String,
1730    pub attributes: ImportPreviewAttributes,
1731}
1732
1733#[derive(Debug, Clone, Serialize, Deserialize)]
1734pub struct ImportPreviewAttributes {
1735    #[serde(default)]
1736    pub format: String,
1737    #[serde(default)]
1738    pub total: u32,
1739    #[serde(default)]
1740    pub functional_count: u32,
1741    #[serde(default)]
1742    pub technical_count: u32,
1743    #[serde(default)]
1744    pub duplicate_titles: Vec<String>,
1745    /// Parsed items from the file — same shape as the `commit_import` request body.
1746    #[serde(default)]
1747    pub items: Vec<ImportItem>,
1748    #[serde(default)]
1749    pub warnings: Vec<String>,
1750}
1751
1752/// Response from `POST .../import/commit`.
1753/// Wrapped in `ApiResponse<ImportResult>`.
1754#[derive(Debug, Clone, Serialize, Deserialize)]
1755pub struct ImportResult {
1756    #[serde(rename = "type", default)]
1757    pub resource_type: String,
1758    pub attributes: ImportResultAttributes,
1759}
1760
1761#[derive(Debug, Clone, Serialize, Deserialize)]
1762pub struct ImportResultAttributes {
1763    #[serde(default)]
1764    pub created: u32,
1765    #[serde(default)]
1766    pub items: Vec<ImportResultItem>,
1767}
1768
1769/// A single item created by `commit_import`.
1770#[derive(Debug, Clone, Serialize, Deserialize)]
1771pub struct ImportResultItem {
1772    #[serde(default)]
1773    pub id: u64,
1774    #[serde(default)]
1775    pub permalink: String,
1776    #[serde(default)]
1777    pub title: String,
1778    #[serde(default)]
1779    pub type_of: String,
1780}
1781
1782// ---------------------------------------------------------------------------
1783// Document import sessions (T-540 server / T-528 client)
1784//
1785// These endpoints return top-level JSON (NOT wrapped in `data:`).
1786// ---------------------------------------------------------------------------
1787
1788/// Response from `POST /projects/:id/import/upload` (201).
1789#[derive(Debug, Clone, Serialize, Deserialize)]
1790pub struct DocumentUpload {
1791    pub session_id: u64,
1792    #[serde(default)]
1793    pub status: String,
1794    #[serde(default, skip_serializing_if = "Option::is_none")]
1795    pub original_filename: Option<String>,
1796    #[serde(default)]
1797    pub sections_count: u64,
1798    #[serde(default)]
1799    pub warnings: Vec<String>,
1800}
1801
1802/// Response from `POST .../import/sessions/:sid/{extract,enrich}` (202).
1803#[derive(Debug, Clone, Serialize, Deserialize)]
1804pub struct ImportStageStarted {
1805    #[serde(default)]
1806    pub session_id: u64,
1807    #[serde(default)]
1808    pub status: String,
1809    #[serde(default, skip_serializing_if = "Option::is_none")]
1810    pub stage: Option<String>,
1811}
1812
1813/// A candidate item extracted from a document. Also the element type of the
1814/// optional commit body; `included: Some(false)` skips the item on commit.
1815#[derive(Debug, Clone, Serialize, Deserialize)]
1816pub struct DocumentImportItem {
1817    #[serde(default)]
1818    pub title: String,
1819    #[serde(default, skip_serializing_if = "Option::is_none")]
1820    pub description: Option<String>,
1821    #[serde(default)]
1822    pub type_of: String,
1823    /// LLM confidence — kept as raw JSON (number or label) so decode never fails.
1824    #[serde(default, skip_serializing_if = "Option::is_none")]
1825    pub confidence: Option<serde_json::Value>,
1826    #[serde(default, skip_serializing_if = "Option::is_none")]
1827    pub parent_title: Option<String>,
1828    #[serde(default, skip_serializing_if = "Option::is_none")]
1829    pub position: Option<i64>,
1830    #[serde(default, skip_serializing_if = "Option::is_none")]
1831    pub included: Option<bool>,
1832}
1833
1834/// Lifecycle of a document import session:
1835/// uploaded -> extracting -> reviewing -> committing -> committed, plus failed / cancelled.
1836#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1837#[serde(rename_all = "snake_case")]
1838pub enum ImportSessionStatus {
1839    Uploaded,
1840    Extracting,
1841    Reviewing,
1842    Committing,
1843    Committed,
1844    Failed,
1845    Cancelled,
1846    #[serde(other)]
1847    Unknown,
1848}
1849
1850impl ImportSessionStatus {
1851    /// True when a background extract/enrich run is no longer in progress.
1852    pub fn is_settled(self) -> bool {
1853        !matches!(
1854            self,
1855            ImportSessionStatus::Extracting | ImportSessionStatus::Committing
1856        )
1857    }
1858}
1859
1860impl std::fmt::Display for ImportSessionStatus {
1861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1862        let s = match self {
1863            ImportSessionStatus::Uploaded => "uploaded",
1864            ImportSessionStatus::Extracting => "extracting",
1865            ImportSessionStatus::Reviewing => "reviewing",
1866            ImportSessionStatus::Committing => "committing",
1867            ImportSessionStatus::Committed => "committed",
1868            ImportSessionStatus::Failed => "failed",
1869            ImportSessionStatus::Cancelled => "cancelled",
1870            ImportSessionStatus::Unknown => "unknown",
1871        };
1872        f.write_str(s)
1873    }
1874}
1875
1876/// Response from `GET /projects/:id/import/sessions/:sid`.
1877#[derive(Debug, Clone, Serialize, Deserialize)]
1878pub struct ImportSession {
1879    pub session_id: u64,
1880    pub status: ImportSessionStatus,
1881    #[serde(default, skip_serializing_if = "Option::is_none")]
1882    pub original_filename: Option<String>,
1883    #[serde(default)]
1884    pub items: Vec<DocumentImportItem>,
1885    #[serde(default)]
1886    pub item_count: u64,
1887    #[serde(default)]
1888    pub cost_cents: u64,
1889    #[serde(default, skip_serializing_if = "Option::is_none")]
1890    pub cost_limit_cents: Option<u64>,
1891    #[serde(default)]
1892    pub warnings: Vec<String>,
1893    #[serde(default, skip_serializing_if = "Option::is_none")]
1894    pub error_code: Option<String>,
1895    #[serde(default, skip_serializing_if = "Option::is_none")]
1896    pub error_message: Option<String>,
1897}
1898
1899/// Response from `POST .../import/sessions/:sid/commit` (201).
1900#[derive(Debug, Clone, Serialize, Deserialize)]
1901pub struct DocumentImportCommit {
1902    #[serde(default)]
1903    pub session_id: u64,
1904    #[serde(default)]
1905    pub status: String,
1906    #[serde(default)]
1907    pub created: u32,
1908    #[serde(default)]
1909    pub items: Vec<ImportResultItem>,
1910}
1911
1912// ---------------------------------------------------------------------------
1913// ProjectRepository
1914// ---------------------------------------------------------------------------
1915
1916#[derive(Debug, Clone, Serialize, Deserialize)]
1917pub struct ProjectRepository {
1918    pub id: u64,
1919    #[serde(rename = "type", default)]
1920    pub resource_type: String,
1921    pub attributes: ProjectRepositoryAttributes,
1922}
1923
1924#[derive(Debug, Clone, Serialize, Deserialize)]
1925pub struct ProjectRepositoryAttributes {
1926    #[serde(default)]
1927    pub name: String,
1928    #[serde(default)]
1929    pub github_url: String,
1930    #[serde(default)]
1931    pub branch: String,
1932    #[serde(default)]
1933    pub status: String,
1934    #[serde(default)]
1935    pub is_primary: bool,
1936    #[serde(default)]
1937    pub sync_frequency: String,
1938    #[serde(default, skip_serializing_if = "Option::is_none")]
1939    pub last_sync_at: Option<DateTime<Utc>>,
1940    #[serde(default, skip_serializing_if = "Option::is_none")]
1941    pub commit_sha: Option<String>,
1942    #[serde(default, skip_serializing_if = "Option::is_none")]
1943    pub error_message: Option<String>,
1944    pub created_at: DateTime<Utc>,
1945    pub updated_at: DateTime<Utc>,
1946}
1947
1948#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1949pub struct CreateRepositoryParams {
1950    pub github_url: String,
1951    pub branch: String,
1952    #[serde(skip_serializing_if = "Option::is_none")]
1953    pub name: Option<String>,
1954    #[serde(skip_serializing_if = "Option::is_none")]
1955    pub sync_frequency: Option<String>,
1956}
1957
1958#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1959pub struct UpdateRepositoryParams {
1960    #[serde(skip_serializing_if = "Option::is_none")]
1961    pub name: Option<String>,
1962    #[serde(skip_serializing_if = "Option::is_none")]
1963    pub branch: Option<String>,
1964    #[serde(skip_serializing_if = "Option::is_none")]
1965    pub sync_frequency: Option<String>,
1966}