1use std::time::Duration;
2
3use reqwest::Client;
4use reqwest::header::{HeaderMap, HeaderValue};
5use tracing::{debug, warn};
6
7use crate::error::Error;
8use crate::models::*;
9use crate::pagination::PagedResponse;
10
11const DEFAULT_TIMEOUT_SECS: u64 = 30;
12const MAX_RETRIES: u32 = 3;
13
14#[derive(Clone)]
16pub struct FuncspecClient {
17 http: Client,
18 base_url: String,
19 max_retries: u32,
20}
21
22impl FuncspecClient {
23 pub fn new(base_url: &str, api_key: &str) -> Result<Self, Error> {
25 Self::with_timeout(base_url, api_key, Duration::from_secs(DEFAULT_TIMEOUT_SECS))
26 }
27
28 pub fn with_timeout(base_url: &str, api_key: &str, timeout: Duration) -> Result<Self, Error> {
30 let mut headers = HeaderMap::new();
31 headers.insert(
32 "X-Api-Key",
33 HeaderValue::from_str(api_key).map_err(|e| Error::Other(e.to_string()))?,
34 );
35
36 let http = Client::builder()
37 .default_headers(headers)
38 .user_agent(format!("funcspec-cli/{}", env!("CARGO_PKG_VERSION")))
39 .timeout(timeout)
40 .build()?;
41
42 let base_url = base_url.trim_end_matches('/').to_string();
43
44 Ok(Self {
45 http,
46 base_url,
47 max_retries: MAX_RETRIES,
48 })
49 }
50
51 fn api_url(&self, path: &str) -> String {
52 format!("{}/api/v1{}", self.base_url, path)
53 }
54
55 async fn request_with_retry<F, Fut>(&self, make_request: F) -> Result<reqwest::Response, Error>
59 where
60 F: Fn() -> Fut,
61 Fut: std::future::Future<Output = Result<reqwest::Response, reqwest::Error>>,
62 {
63 let mut attempt = 0u32;
64 loop {
65 match make_request().await {
66 Ok(resp) => {
67 if resp.status().as_u16() == 429 && attempt < self.max_retries {
68 let retry_after = resp
69 .headers()
70 .get("retry-after")
71 .and_then(|v| v.to_str().ok())
72 .and_then(|s| s.parse::<u64>().ok())
73 .unwrap_or_else(|| {
74 1u64 << attempt.min(6)
76 });
77 let delay = Duration::from_secs(retry_after.min(60));
78 warn!(
79 attempt,
80 retry_after_secs = retry_after,
81 "Rate limited, backing off"
82 );
83 tokio::time::sleep(delay).await;
84 attempt += 1;
85 continue;
86 }
87 return Ok(resp);
88 }
89 Err(e) if attempt < self.max_retries => {
90 if e.is_connect() {
95 let delay = Duration::from_secs(1u64 << attempt.min(6));
96 warn!(attempt, error = %e, "Connection error, retrying");
97 tokio::time::sleep(delay).await;
98 attempt += 1;
99 continue;
100 }
101 return Err(Error::from(e));
102 }
103 Err(e) => return Err(Error::from(e)),
104 }
105 }
106 }
107
108 pub async fn validate_auth(&self) -> Result<UserInfo, Error> {
112 let projects = self.list_projects().await?;
116 let project_count = projects.len();
117 Ok(UserInfo {
118 id: String::new(),
119 email: String::new(),
120 name: format!("{project_count} project(s) accessible"),
121 org_id: String::new(),
122 org_name: String::new(),
123 })
124 }
125
126 pub async fn list_projects(&self) -> Result<Vec<Project>, Error> {
129 let url = self.api_url("/projects");
130 debug!(%url, "list_projects");
131 let resp = self
132 .request_with_retry(|| self.http.get(&url).send())
133 .await?;
134 if !resp.status().is_success() {
135 return Err(Error::from_response(resp).await);
136 }
137 let body: ApiListResponse<Project> = resp.json().await?;
138 Ok(body.data)
139 }
140
141 pub async fn list_projects_paged(
142 &self,
143 page: u32,
144 per_page: u32,
145 ) -> Result<PagedResponse<Project>, Error> {
146 let url = self.api_url("/projects");
147 let resp = self
148 .request_with_retry(|| {
149 self.http
150 .get(&url)
151 .query(&[("page", page), ("per", per_page)])
152 .send()
153 })
154 .await?;
155 if !resp.status().is_success() {
156 return Err(Error::from_response(resp).await);
157 }
158 let body: ApiListResponse<Project> = resp.json().await?;
159 Ok((body.data, body.meta).into())
160 }
161
162 pub async fn get_project(&self, slug_or_id: &str) -> Result<Project, Error> {
163 let url = self.api_url(&format!("/projects/{slug_or_id}"));
164 debug!(%url, "get_project");
165 let resp = self
166 .request_with_retry(|| self.http.get(&url).send())
167 .await?;
168 if !resp.status().is_success() {
169 return Err(Error::from_response(resp).await);
170 }
171 let body: ApiResponse<Project> = resp.json().await?;
172 Ok(body.data)
173 }
174
175 pub async fn create_project(&self, params: &CreateProjectParams) -> Result<Project, Error> {
176 let url = self.api_url("/projects");
177 let resp = self
178 .request_with_retry(|| self.http.post(&url).json(params).send())
179 .await?;
180 if !resp.status().is_success() {
181 return Err(Error::from_response(resp).await);
182 }
183 let body: ApiResponse<Project> = resp.json().await?;
184 Ok(body.data)
185 }
186
187 pub async fn delete_project(&self, slug_or_id: &str) -> Result<(), Error> {
188 let url = self.api_url(&format!("/projects/{slug_or_id}"));
189 let resp = self
190 .request_with_retry(|| self.http.delete(&url).send())
191 .await?;
192 if !resp.status().is_success() {
193 return Err(Error::from_response(resp).await);
194 }
195 Ok(())
196 }
197
198 pub async fn list_items(
201 &self,
202 project_id: u64,
203 filter: &ItemFilter,
204 ) -> Result<(Vec<SpecItem>, Option<PaginationMeta>), Error> {
205 let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
206 debug!(%url, "list_items");
207 let resp = self
208 .request_with_retry(|| self.http.get(&url).query(&filter.to_query_pairs()).send())
209 .await?;
210 if !resp.status().is_success() {
211 return Err(Error::from_response(resp).await);
212 }
213 let body: ApiListResponse<SpecItem> = resp.json().await?;
214 Ok((body.data, body.meta))
215 }
216
217 pub async fn list_items_paged(
218 &self,
219 project_id: u64,
220 filter: &ItemFilter,
221 page: u32,
222 per_page: u32,
223 ) -> Result<PagedResponse<SpecItem>, Error> {
224 let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
225 let mut pairs = filter.to_query_pairs();
226 pairs.push(("page".into(), page.to_string()));
227 pairs.push(("per".into(), per_page.to_string()));
228 let resp = self
229 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
230 .await?;
231 if !resp.status().is_success() {
232 return Err(Error::from_response(resp).await);
233 }
234 let body: ApiListResponse<SpecItem> = resp.json().await?;
235 Ok((body.data, body.meta).into())
236 }
237
238 pub async fn list_all_items(
245 &self,
246 project_id: u64,
247 filter: &ItemFilter,
248 ) -> Result<Vec<SpecItem>, Error> {
249 const PER: u32 = 100;
250 let mut all: Vec<SpecItem> = Vec::new();
251 let mut page: u32 = 1;
252 loop {
253 let resp = self.list_items_paged(project_id, filter, page, PER).await?;
254 let total_pages = resp.total_pages;
255 let items = resp.data;
256 let got = items.len() as u32;
257 all.extend(items);
258 let more = if total_pages > 0 {
259 page < total_pages
260 } else {
261 got == PER
262 };
263 if !more {
264 break;
265 }
266 page += 1;
267 }
268 Ok(all)
269 }
270
271 pub async fn search_items(
275 &self,
276 project_id: u64,
277 query: &str,
278 filter: &ItemFilter,
279 ) -> Result<PagedResponse<SpecItem>, Error> {
280 let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
281 debug!(%url, %query, "search_items");
282 let mut pairs = filter.to_query_pairs();
284 pairs.retain(|(k, _)| k != "q");
285 pairs.push(("q".into(), query.to_string()));
286 let resp = self
287 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
288 .await?;
289 if !resp.status().is_success() {
290 return Err(Error::from_response(resp).await);
291 }
292 let body: ApiListResponse<SpecItem> = resp.json().await?;
293 Ok((body.data, body.meta).into())
294 }
295
296 pub async fn resolve_item_id(
301 &self,
302 project_id: u64,
303 id_or_permalink: &str,
304 ) -> Result<u64, Error> {
305 if let Ok(numeric) = id_or_permalink.parse::<u64>() {
307 return Ok(numeric);
308 }
309
310 let url = self.api_url(&format!(
313 "/projects/{project_id}/spec/items/{id_or_permalink}"
314 ));
315 debug!(%url, "resolve_item_id via permalink");
316 let resp = self
317 .request_with_retry(|| self.http.get(&url).send())
318 .await?;
319 if !resp.status().is_success() {
320 return Err(Error::NotFound(format!(
321 "Item with permalink \"{id_or_permalink}\" not found"
322 )));
323 }
324 let body: ApiResponse<SpecItem> = resp.json().await?;
325 Ok(body.data.id)
326 }
327
328 pub async fn get_item(
329 &self,
330 project_id: u64,
331 id_or_permalink: &str,
332 ) -> Result<SpecItem, Error> {
333 let url = self.api_url(&format!(
335 "/projects/{project_id}/spec/items/{id_or_permalink}"
336 ));
337 debug!(%url, "get_item");
338 let resp = self
339 .request_with_retry(|| self.http.get(&url).send())
340 .await?;
341 if !resp.status().is_success() {
342 return Err(Error::from_response(resp).await);
343 }
344 let body: ApiResponse<SpecItem> = resp.json().await?;
345 Ok(body.data)
346 }
347
348 pub async fn create_item(
349 &self,
350 project_id: u64,
351 params: &CreateItemParams,
352 ) -> Result<SpecItem, Error> {
353 let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
354 let resp = self
355 .request_with_retry(|| self.http.post(&url).json(params).send())
356 .await?;
357 if !resp.status().is_success() {
358 return Err(Error::from_response(resp).await);
359 }
360 let body: ApiResponse<SpecItem> = resp.json().await?;
361 Ok(body.data)
362 }
363
364 pub async fn update_item(
365 &self,
366 project_id: u64,
367 item_id: u64,
368 params: &UpdateItemParams,
369 ) -> Result<SpecItem, Error> {
370 let url = self.api_url(&format!("/projects/{project_id}/spec/items/{item_id}"));
371 let resp = self
372 .request_with_retry(|| self.http.patch(&url).json(params).send())
373 .await?;
374 if !resp.status().is_success() {
375 return Err(Error::from_response(resp).await);
376 }
377 let body: ApiResponse<SpecItem> = resp.json().await?;
378 Ok(body.data)
379 }
380
381 pub async fn delete_item(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
382 let url = self.api_url(&format!("/projects/{project_id}/spec/items/{item_id}"));
383 let resp = self
384 .request_with_retry(|| self.http.delete(&url).send())
385 .await?;
386 if !resp.status().is_success() {
387 return Err(Error::from_response(resp).await);
388 }
389 Ok(())
390 }
391
392 pub async fn deprecate_item(
396 &self,
397 project_id: u64,
398 permalink: &str,
399 reason: Option<&str>,
400 confirm: bool,
401 ) -> Result<(), Error> {
402 let url = self.api_url(&format!(
403 "/projects/{project_id}/spec/items/{permalink}/deprecate"
404 ));
405 debug!(%url, "deprecate_item");
406 let mut body = serde_json::Map::new();
407 if let Some(r) = reason {
408 body.insert("reason".into(), serde_json::Value::String(r.to_string()));
409 }
410 if confirm {
411 body.insert("confirm".into(), serde_json::Value::Bool(true));
412 }
413 let resp = self
414 .request_with_retry(|| self.http.post(&url).json(&body).send())
415 .await?;
416 if !resp.status().is_success() {
417 return Err(Error::from_response(resp).await);
418 }
419 Ok(())
420 }
421
422 pub async fn undeprecate_item(&self, project_id: u64, permalink: &str) -> Result<(), Error> {
425 let url = self.api_url(&format!(
426 "/projects/{project_id}/spec/items/{permalink}/undeprecate"
427 ));
428 debug!(%url, "undeprecate_item");
429 let resp = self
430 .request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
431 .await?;
432 if !resp.status().is_success() {
433 return Err(Error::from_response(resp).await);
434 }
435 Ok(())
436 }
437
438 pub async fn transition_item_state(
446 &self,
447 project_id: u64,
448 permalink: &str,
449 state: &str,
450 ) -> Result<SpecItem, Error> {
451 let url = self.api_url(&format!(
452 "/projects/{project_id}/spec/items/{permalink}/transition"
453 ));
454 debug!(%url, %state, "transition_item_state");
455 let body = serde_json::json!({ "state": state });
456 let resp = self
457 .request_with_retry(|| self.http.post(&url).json(&body).send())
458 .await?;
459 if !resp.status().is_success() {
460 return Err(Error::from_response(resp).await);
461 }
462 let body: ApiResponse<SpecItem> = resp.json().await?;
463 Ok(body.data)
464 }
465
466 pub async fn list_reviews(&self, spec_item_id: u64) -> Result<Vec<Review>, Error> {
469 let url = self.api_url(&format!("/spec/items/{spec_item_id}/reviews"));
470 let resp = self
471 .request_with_retry(|| self.http.get(&url).send())
472 .await?;
473 if !resp.status().is_success() {
474 return Err(Error::from_response(resp).await);
475 }
476 let body: ApiListResponse<Review> = resp.json().await?;
477 Ok(body.data)
478 }
479
480 pub async fn create_review(
481 &self,
482 spec_item_id: u64,
483 params: &CreateReviewParams,
484 ) -> Result<Review, Error> {
485 let url = self.api_url(&format!("/spec/items/{spec_item_id}/reviews"));
486 let resp = self
487 .request_with_retry(|| self.http.post(&url).json(params).send())
488 .await?;
489 if !resp.status().is_success() {
490 return Err(Error::from_response(resp).await);
491 }
492 let body: ApiResponse<Review> = resp.json().await?;
493 Ok(body.data)
494 }
495
496 pub async fn list_jobs(&self) -> Result<Vec<Job>, Error> {
499 let url = self.api_url("/jobs");
500 let resp = self
501 .request_with_retry(|| self.http.get(&url).send())
502 .await?;
503 if !resp.status().is_success() {
504 return Err(Error::from_response(resp).await);
505 }
506 let body: ApiListResponse<Job> = resp.json().await?;
507 Ok(body.data)
508 }
509
510 pub async fn get_job(&self, project_id: u64, job_id: u64) -> Result<Job, Error> {
511 let url = self.api_url(&format!("/projects/{project_id}/jobs/{job_id}"));
512 let resp = self
513 .request_with_retry(|| self.http.get(&url).send())
514 .await?;
515 if !resp.status().is_success() {
516 return Err(Error::from_response(resp).await);
517 }
518 let body: ApiResponse<Job> = resp.json().await?;
519 Ok(body.data)
520 }
521
522 pub async fn review_item(&self, project_id: u64, item_id: u64) -> Result<Review, Error> {
528 self.review_item_async(project_id, item_id, "review").await
529 }
530
531 async fn review_item_async(
535 &self,
536 project_id: u64,
537 item_id: u64,
538 kind: &str,
539 ) -> Result<Review, Error> {
540 let url = self.api_url(&format!(
541 "/projects/{project_id}/work_package/{item_id}/{kind}"
542 ));
543 debug!(%url, "review_item_async");
544 let resp = self
545 .request_with_retry(|| self.http.post(&url).send())
546 .await?;
547 if !resp.status().is_success() {
548 return Err(Error::from_response(resp).await);
549 }
550 let body: ApiResponse<AsyncJobRef> = resp.json().await?;
551 let job_id = body
552 .data
553 .job_id
554 .ok_or_else(|| Error::Other("review response did not include a job_id".into()))?;
555 let job = self
557 .poll_job_until_done(project_id, job_id, Duration::from_secs(300))
558 .await?;
559 if job.attributes.status == JobStatus::Failed {
560 return Err(Error::Other(format!("AI review job {job_id} failed")));
561 }
562 let _ = kind;
566 let item = self.get_item(project_id, &item_id.to_string()).await?;
567 let summary = item.attributes.review.ok_or_else(|| {
568 Error::Other("review job completed but no review is present on the item".into())
569 })?;
570 let coverage_map = summary
571 .coverage_map
572 .and_then(|v| serde_json::from_value(v).ok())
573 .unwrap_or_default();
574 Ok(Review {
575 id: None,
576 resource_type: "review".to_string(),
577 attributes: ReviewAttributes {
578 coverage_score: summary.coverage_score,
579 collective_coverage_score: None,
580 verdict: summary.verdict,
581 tech_item_id: None,
582 tech_item_title: None,
583 func_item_ids: Vec::new(),
584 functional_requirements_parsed: Vec::new(),
585 coverage_map,
586 gaps: summary.gaps.unwrap_or_default(),
587 suggestions: summary.suggestions.unwrap_or_default(),
588 risks: summary.risks.unwrap_or_default(),
589 reviewed_at: summary.reviewed_at,
590 },
591 })
592 }
593
594 pub async fn review_all(&self, project_id: u64) -> Result<u64, Error> {
599 let url = self.api_url(&format!("/projects/{project_id}/work_package/review_all"));
600 debug!(%url, "review_all");
601 let resp = self
602 .request_with_retry(|| self.http.post(&url).send())
603 .await?;
604 if !resp.status().is_success() {
605 return Err(Error::from_response(resp).await);
606 }
607 let body: ApiResponse<AsyncJobRef> = resp.json().await?;
609 body.data
610 .job_id
611 .ok_or_else(|| Error::Other("review_all response had no job_id".into()))
612 }
613
614 pub async fn propose_improvement(
618 &self,
619 project_id: u64,
620 item_id: u64,
621 ) -> Result<Proposal, Error> {
622 let url = self.api_url(&format!(
623 "/projects/{project_id}/work_package/{item_id}/propose"
624 ));
625 debug!(%url, "propose_improvement");
626 let resp = self
627 .request_with_retry(|| self.http.post(&url).send())
628 .await?;
629 if !resp.status().is_success() {
630 return Err(Error::from_response(resp).await);
631 }
632 let body: ApiResponse<Proposal> = resp.json().await?;
633 Ok(body.data)
634 }
635
636 pub async fn accept_proposal(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
640 let url = self.api_url(&format!(
641 "/projects/{project_id}/work_package/{item_id}/accept"
642 ));
643 debug!(%url, "accept_proposal");
644 let resp = self
645 .request_with_retry(|| self.http.post(&url).send())
646 .await?;
647 if !resp.status().is_success() {
648 return Err(Error::from_response(resp).await);
649 }
650 Ok(())
651 }
652
653 pub async fn reject_proposal(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
657 let url = self.api_url(&format!(
658 "/projects/{project_id}/work_package/{item_id}/reject"
659 ));
660 debug!(%url, "reject_proposal");
661 let resp = self
662 .request_with_retry(|| self.http.post(&url).send())
663 .await?;
664 if !resp.status().is_success() {
665 return Err(Error::from_response(resp).await);
666 }
667 Ok(())
668 }
669
670 pub async fn generate_tech(
674 &self,
675 project_id: u64,
676 item_id: u64,
677 ) -> Result<TechProposals, Error> {
678 let url = self.api_url(&format!(
679 "/projects/{project_id}/work_package/{item_id}/generate_tech"
680 ));
681 debug!(%url, "generate_tech");
682 let resp = self
683 .request_with_retry(|| self.http.post(&url).send())
684 .await?;
685 if !resp.status().is_success() {
686 return Err(Error::from_response(resp).await);
687 }
688 let body: ApiResponse<TechProposals> = resp.json().await?;
689 Ok(body.data)
690 }
691
692 pub async fn audit_item(&self, project_id: u64, item_id: u64) -> Result<AuditResult, Error> {
696 let url = self.api_url(&format!(
697 "/projects/{project_id}/work_package/{item_id}/audit"
698 ));
699 debug!(%url, "audit_item");
700 let resp = self
701 .request_with_retry(|| self.http.post(&url).send())
702 .await?;
703 if !resp.status().is_success() {
704 return Err(Error::from_response(resp).await);
705 }
706 let body: ApiResponse<AuditResult> = resp.json().await?;
707 Ok(body.data)
708 }
709
710 pub async fn get_project_job(&self, project_id: u64, job_id: u64) -> Result<Job, Error> {
714 let url = self.api_url(&format!("/projects/{project_id}/jobs/{job_id}"));
715 debug!(%url, "get_project_job");
716 let resp = self
717 .request_with_retry(|| self.http.get(&url).send())
718 .await?;
719 if !resp.status().is_success() {
720 return Err(Error::from_response(resp).await);
721 }
722 let body: ApiResponse<Job> = resp.json().await?;
723 Ok(body.data)
724 }
725
726 pub async fn poll_job_until_done(
731 &self,
732 project_id: u64,
733 job_id: u64,
734 timeout: Duration,
735 ) -> Result<Job, Error> {
736 let start = std::time::Instant::now();
737 let poll_interval = Duration::from_millis(500);
738 loop {
739 let job = self.get_job(project_id, job_id).await?;
740 match job.attributes.status {
741 JobStatus::Completed | JobStatus::Failed => return Ok(job),
742 _ => {}
743 }
744 if start.elapsed() >= timeout {
745 return Err(Error::Timeout {
746 secs: timeout.as_secs(),
747 });
748 }
749 tokio::time::sleep(poll_interval).await;
750 }
751 }
752
753 pub async fn transition_item_implementation(
758 &self,
759 project_id: u64,
760 item_id: u64,
761 status: &str,
762 ) -> Result<(), Error> {
763 let url = self.api_url(&format!(
764 "/projects/{project_id}/spec/items/{item_id}/transition_implementation"
765 ));
766 debug!(%url, %status, "transition_item_implementation");
767 let body = serde_json::json!({ "implementation_status": status });
768 let resp = self
769 .request_with_retry(|| self.http.post(&url).json(&body).send())
770 .await?;
771 if !resp.status().is_success() {
772 return Err(Error::from_response(resp).await);
773 }
774 Ok(())
775 }
776
777 pub async fn link_commit(
780 &self,
781 project_id: u64,
782 item_id: u64,
783 params: &LinkCommitParams,
784 ) -> Result<(), Error> {
785 let url = self.api_url(&format!(
786 "/projects/{project_id}/work_package/{item_id}/link_commit"
787 ));
788 debug!(%url, sha = %params.sha, "link_commit");
789 let resp = self
790 .request_with_retry(|| self.http.post(&url).json(params).send())
791 .await?;
792 if !resp.status().is_success() {
793 return Err(Error::from_response(resp).await);
794 }
795 Ok(())
796 }
797
798 pub async fn record_run(
801 &self,
802 project_id: u64,
803 item_id: u64,
804 params: &RecordRunParams,
805 ) -> Result<Option<u64>, Error> {
806 let url = self.api_url(&format!(
807 "/projects/{project_id}/work_package/{item_id}/record_run"
808 ));
809 debug!(%url, "record_run");
810 let resp = self
811 .request_with_retry(|| self.http.post(&url).json(params).send())
812 .await?;
813 if !resp.status().is_success() {
814 return Err(Error::from_response(resp).await);
815 }
816 let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
817 let run_id = body
818 .get("data")
819 .and_then(|d| d.get("id"))
820 .and_then(|v| v.as_u64());
821 Ok(run_id)
822 }
823
824 pub async fn review_item_functional(
827 &self,
828 project_id: u64,
829 item_id: u64,
830 ) -> Result<Review, Error> {
831 self.review_item_async(project_id, item_id, "func_review")
832 .await
833 }
834
835 pub async fn list_usage(&self) -> Result<Vec<UsageLogEntry>, Error> {
838 let url = self.api_url("/usage");
839 let resp = self
840 .request_with_retry(|| self.http.get(&url).send())
841 .await?;
842 if !resp.status().is_success() {
843 return Err(Error::from_response(resp).await);
844 }
845 let body: ApiListResponse<UsageLogEntry> = resp.json().await?;
846 Ok(body.data)
847 }
848
849 pub async fn get_project_stats(
857 &self,
858 project_id: u64,
859 release_version: Option<&str>,
860 ) -> Result<ProjectStats, Error> {
861 let url = self.api_url(&format!("/projects/{project_id}/stats"));
862 debug!(%url, ?release_version, "get_project_stats");
863 let mut pairs: Vec<(String, String)> = Vec::new();
864 if let Some(rv) = release_version {
865 pairs.push(("release_version".into(), rv.to_string()));
866 }
867 let resp = self
868 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
869 .await?;
870 if !resp.status().is_success() {
871 return Err(Error::from_response(resp).await);
872 }
873 let text = resp
874 .text()
875 .await
876 .map_err(|e| Error::Network(e.to_string()))?;
877 let body: ApiResponse<ProjectStats> = serde_json::from_str(&text).map_err(|e| {
878 Error::Other(format!("Failed to parse stats response: {e}\nBody: {text}"))
879 })?;
880 Ok(body.data)
881 }
882
883 pub async fn get_usage_logs(
885 &self,
886 project_id: u64,
887 filter: &UsageFilter,
888 ) -> Result<PagedResponse<UsageLogEntry>, Error> {
889 let url = self.api_url(&format!("/projects/{project_id}/usage/logs"));
890 debug!(%url, "get_usage_logs");
891 let pairs = filter.to_query_pairs();
892 let resp = self
893 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
894 .await?;
895 if !resp.status().is_success() {
896 return Err(Error::from_response(resp).await);
897 }
898 let body: ApiListResponse<UsageLogEntry> = resp.json().await?;
899 Ok((body.data, body.meta).into())
900 }
901
902 pub async fn get_usage_stats(
905 &self,
906 project_id: u64,
907 year: Option<i32>,
908 month: Option<u32>,
909 ) -> Result<UsageStats, Error> {
910 let url = self.api_url(&format!("/projects/{project_id}/usage"));
911 debug!(%url, "get_usage_stats");
912 let mut pairs: Vec<(String, String)> = Vec::new();
913 if let Some(y) = year {
914 pairs.push(("year".into(), y.to_string()));
915 }
916 if let Some(m) = month {
917 pairs.push(("month".into(), m.to_string()));
918 }
919 let resp = self
920 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
921 .await?;
922 if !resp.status().is_success() {
923 return Err(Error::from_response(resp).await);
924 }
925 let text = resp
926 .text()
927 .await
928 .map_err(|e| Error::Network(e.to_string()))?;
929 let body: UsageStats = serde_json::from_str(&text).map_err(|e| {
930 Error::Other(format!(
931 "Failed to parse usage stats: {e}
932Body: {text}"
933 ))
934 })?;
935 Ok(body)
936 }
937
938 pub async fn export_project(
948 &self,
949 project_id: u64,
950 format: &str,
951 item_type: Option<&str>,
952 tag: Option<&str>,
953 release_version: Option<&str>,
954 ) -> Result<ExportData, Error> {
955 let format_path = match format {
957 "md" => "markdown",
958 "json" => "json",
959 "csv" => "csv",
960 "html" => "html",
961 "pdf" => "pdf",
962 "docx" => "docx",
963 other => other,
964 };
965 let url = self.api_url(&format!("/projects/{project_id}/export/{format_path}"));
966 debug!(%url, %format, "export_project");
967 let mut pairs: Vec<(String, String)> = vec![];
968 if let Some(t) = item_type {
969 pairs.push(("type_of".into(), t.to_string()));
970 }
971 if let Some(t) = tag {
972 pairs.push(("tag".into(), t.to_string()));
973 }
974 if let Some(rv) = release_version {
975 pairs.push(("release_version".into(), rv.to_string()));
976 }
977 let resp = self
978 .request_with_retry(|| self.http.get(&url).query(&pairs).send())
979 .await?;
980 if !resp.status().is_success() {
981 return Err(Error::from_response(resp).await);
982 }
983 let is_binary = matches!(format, "pdf" | "docx");
984 if is_binary {
985 let bytes = resp.bytes().await.map_err(Error::from)?;
986 Ok(ExportData::Binary(bytes.to_vec()))
987 } else {
988 let text = resp.text().await.map_err(Error::from)?;
989 Ok(ExportData::Text(text))
990 }
991 }
992
993 pub async fn get_viewable_html(&self, project_id: u64) -> Result<String, Error> {
998 let url = self.api_url(&format!("/projects/{project_id}/spec/view"));
999 debug!(%url, "get_viewable_html");
1000 let resp = self
1001 .request_with_retry(|| self.http.get(&url).send())
1002 .await?;
1003 if !resp.status().is_success() {
1004 return Err(Error::from_response(resp).await);
1005 }
1006 resp.text().await.map_err(Error::from)
1007 }
1008
1009 pub async fn list_snapshots(&self, project_id: u64) -> Result<Vec<Snapshot>, Error> {
1015 let url = self.api_url(&format!("/projects/{project_id}/snapshots"));
1016 debug!(%url, "list_snapshots");
1017 let resp = self
1018 .request_with_retry(|| self.http.get(&url).send())
1019 .await?;
1020 if !resp.status().is_success() {
1021 return Err(Error::from_response(resp).await);
1022 }
1023 let body: ApiListResponse<Snapshot> = resp.json().await?;
1024 Ok(body.data)
1025 }
1026
1027 pub async fn create_snapshot(
1031 &self,
1032 project_id: u64,
1033 params: &CreateSnapshotParams,
1034 ) -> Result<Snapshot, Error> {
1035 let url = self.api_url(&format!("/projects/{project_id}/snapshots"));
1036 debug!(%url, "create_snapshot");
1037 let resp = self
1038 .request_with_retry(|| self.http.post(&url).json(params).send())
1039 .await?;
1040 if !resp.status().is_success() {
1041 return Err(Error::from_response(resp).await);
1042 }
1043 let body: ApiResponse<Snapshot> = resp.json().await?;
1044 Ok(body.data)
1045 }
1046
1047 pub async fn get_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<Snapshot, Error> {
1051 let url = self.api_url(&format!("/projects/{project_id}/snapshots/{snapshot_id}"));
1052 debug!(%url, "get_snapshot");
1053 let resp = self
1054 .request_with_retry(|| self.http.get(&url).send())
1055 .await?;
1056 if !resp.status().is_success() {
1057 return Err(Error::from_response(resp).await);
1058 }
1059 let body: ApiResponse<Snapshot> = resp.json().await?;
1060 Ok(body.data)
1061 }
1062
1063 pub async fn restore_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<(), Error> {
1067 let url = self.api_url(&format!(
1068 "/projects/{project_id}/snapshots/{snapshot_id}/restore"
1069 ));
1070 debug!(%url, "restore_snapshot");
1071 let resp = self
1072 .request_with_retry(|| self.http.post(&url).send())
1073 .await?;
1074 if !resp.status().is_success() {
1075 return Err(Error::from_response(resp).await);
1076 }
1077 Ok(())
1078 }
1079
1080 pub async fn delete_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<(), Error> {
1084 let url = self.api_url(&format!("/projects/{project_id}/snapshots/{snapshot_id}"));
1085 debug!(%url, "delete_snapshot");
1086 let resp = self
1087 .request_with_retry(|| self.http.delete(&url).send())
1088 .await?;
1089 if !resp.status().is_success() {
1090 return Err(Error::from_response(resp).await);
1091 }
1092 Ok(())
1093 }
1094
1095 pub async fn diff_snapshot(
1099 &self,
1100 project_id: u64,
1101 snapshot_id: u64,
1102 ) -> Result<SnapshotDiff, Error> {
1103 let url = self.api_url(&format!(
1104 "/projects/{project_id}/snapshots/{snapshot_id}/diff"
1105 ));
1106 debug!(%url, "diff_snapshot");
1107 let resp = self
1108 .request_with_retry(|| self.http.get(&url).send())
1109 .await?;
1110 if !resp.status().is_success() {
1111 return Err(Error::from_response(resp).await);
1112 }
1113 let body: ApiResponse<SnapshotDiff> = resp.json().await?;
1114 Ok(body.data)
1115 }
1116
1117 pub async fn list_edges(
1123 &self,
1124 project_id: u64,
1125 source_id: Option<u64>,
1126 target_id: Option<u64>,
1127 edge_type: Option<&str>,
1128 ) -> Result<Vec<DependencyEdge>, Error> {
1129 let url = self.api_url(&format!("/projects/{project_id}/graph/edges"));
1130 debug!(%url, "list_edges");
1131 let mut params: Vec<(&str, String)> = vec![];
1132 if let Some(sid) = source_id {
1133 params.push(("source_id", sid.to_string()));
1134 }
1135 if let Some(tid) = target_id {
1136 params.push(("target_id", tid.to_string()));
1137 }
1138 if let Some(et) = edge_type {
1139 params.push(("edge_type", et.to_string()));
1140 }
1141 let resp = self
1142 .request_with_retry(|| self.http.get(&url).query(¶ms).send())
1143 .await?;
1144 if !resp.status().is_success() {
1145 return Err(Error::from_response(resp).await);
1146 }
1147 #[derive(serde::Deserialize)]
1148 struct Resp {
1149 data: Vec<DependencyEdge>,
1150 }
1151 let body: Resp = resp.json().await?;
1152 Ok(body.data)
1153 }
1154
1155 pub async fn create_edge(
1159 &self,
1160 project_id: u64,
1161 params: &CreateEdgeParams,
1162 ) -> Result<DependencyEdge, Error> {
1163 let url = self.api_url(&format!("/projects/{project_id}/graph/edges"));
1164 debug!(%url, "create_edge");
1165 let body = serde_json::json!({ "dependency_edge": params });
1166 let resp = self
1167 .request_with_retry(|| self.http.post(&url).json(&body).send())
1168 .await?;
1169 if !resp.status().is_success() {
1170 return Err(Error::from_response(resp).await);
1171 }
1172 let resp_body: ApiResponse<DependencyEdge> = resp.json().await?;
1173 Ok(resp_body.data)
1174 }
1175
1176 pub async fn get_edge(&self, project_id: u64, edge_id: u64) -> Result<DependencyEdge, Error> {
1180 let url = self.api_url(&format!("/projects/{project_id}/graph/edges/{edge_id}"));
1181 debug!(%url, "get_edge");
1182 let resp = self
1183 .request_with_retry(|| self.http.get(&url).send())
1184 .await?;
1185 if !resp.status().is_success() {
1186 return Err(Error::from_response(resp).await);
1187 }
1188 let body: ApiResponse<DependencyEdge> = resp.json().await?;
1189 Ok(body.data)
1190 }
1191
1192 pub async fn delete_edge(&self, project_id: u64, edge_id: u64) -> Result<(), Error> {
1196 let url = self.api_url(&format!("/projects/{project_id}/graph/edges/{edge_id}"));
1197 debug!(%url, "delete_edge");
1198 let resp = self
1199 .request_with_retry(|| self.http.delete(&url).send())
1200 .await?;
1201 if !resp.status().is_success() {
1202 return Err(Error::from_response(resp).await);
1203 }
1204 Ok(())
1205 }
1206 pub async fn get_org_slug(&self) -> Result<String, Error> {
1212 let url = self.api_url("/settings");
1213 debug!(%url, "get_org_slug");
1214 let resp = self
1215 .request_with_retry(|| self.http.get(&url).send())
1216 .await?;
1217 if !resp.status().is_success() {
1218 return Err(Error::from_response(resp).await);
1219 }
1220 let body: serde_json::Value = resp.json().await?;
1221 let slug = body
1222 .get("data")
1223 .and_then(|d| d.get("attributes"))
1224 .and_then(|a| a.get("slug"))
1225 .and_then(|s| s.as_str())
1226 .unwrap_or("")
1227 .to_string();
1228 Ok(slug)
1229 }
1230
1231 pub async fn get_agent_instructions(
1239 &self,
1240 project_slug: &str,
1241 ) -> Result<serde_json::Value, Error> {
1242 let url = self.api_url(&format!("/projects/{project_slug}/agent_instructions"));
1243 debug!(%url, "get_agent_instructions");
1244 let resp = self
1245 .request_with_retry(|| self.http.get(&url).send())
1246 .await?;
1247 if !resp.status().is_success() {
1248 return Err(Error::from_response(resp).await);
1249 }
1250 let body: serde_json::Value = resp.json().await?;
1251 Ok(body)
1252 }
1253
1254 pub async fn list_runs(
1257 &self,
1258 project_id: u64,
1259 page: u32,
1260 per: u32,
1261 ) -> Result<(Vec<AuditRun>, Option<PaginationMeta>), Error> {
1262 let url = self.api_url(&format!("/projects/{project_id}/runs"));
1263 debug!(%url, "list_runs");
1264 let resp = self
1265 .request_with_retry(|| {
1266 self.http
1267 .get(&url)
1268 .query(&[("page", page), ("per", per)])
1269 .send()
1270 })
1271 .await?;
1272 if !resp.status().is_success() {
1273 return Err(Error::from_response(resp).await);
1274 }
1275 let body: ApiListResponse<AuditRun> = resp.json().await?;
1276 Ok((body.data, body.meta))
1277 }
1278
1279 pub async fn preview_run(
1281 &self,
1282 project_id: u64,
1283 params: &CreateRunParams,
1284 ) -> Result<RunPreview, Error> {
1285 let url = self.api_url(&format!("/projects/{project_id}/runs/preview"));
1286 debug!(%url, "preview_run");
1287 let resp = self
1288 .request_with_retry(|| self.http.post(&url).json(params).send())
1289 .await?;
1290 if !resp.status().is_success() {
1291 return Err(Error::from_response(resp).await);
1292 }
1293 let body: ApiResponse<RunPreview> = resp.json().await?;
1294 Ok(body.data)
1295 }
1296
1297 pub async fn create_run(
1298 &self,
1299 project_id: u64,
1300 params: &CreateRunParams,
1301 ) -> Result<AuditRun, Error> {
1302 let url = self.api_url(&format!("/projects/{project_id}/runs"));
1303 debug!(%url, "create_run");
1304 let resp = self
1305 .request_with_retry(|| self.http.post(&url).json(params).send())
1306 .await?;
1307 if !resp.status().is_success() {
1308 return Err(Error::from_response(resp).await);
1309 }
1310 let body: ApiResponse<AuditRun> = resp.json().await?;
1311 Ok(body.data)
1312 }
1313
1314 pub async fn get_run(
1315 &self,
1316 project_id: u64,
1317 run_id: u64,
1318 page: u32,
1319 per: u32,
1320 ) -> Result<AuditRun, Error> {
1321 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
1322 debug!(%url, "get_run");
1323 let resp = self
1324 .request_with_retry(|| {
1325 self.http
1326 .get(&url)
1327 .query(&[("page", page), ("per", per)])
1328 .send()
1329 })
1330 .await?;
1331 if !resp.status().is_success() {
1332 return Err(Error::from_response(resp).await);
1333 }
1334 let body: ApiResponse<AuditRun> = resp.json().await?;
1335 Ok(body.data)
1336 }
1337
1338 pub async fn update_run(
1339 &self,
1340 project_id: u64,
1341 run_id: u64,
1342 params: &UpdateRunParams,
1343 ) -> Result<AuditRun, Error> {
1344 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
1345 debug!(%url, "update_run");
1346 let resp = self
1347 .request_with_retry(|| self.http.patch(&url).json(params).send())
1348 .await?;
1349 if !resp.status().is_success() {
1350 return Err(Error::from_response(resp).await);
1351 }
1352 let body: ApiResponse<AuditRun> = resp.json().await?;
1353 Ok(body.data)
1354 }
1355
1356 pub async fn start_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
1357 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/start"));
1358 debug!(%url, "start_run");
1359 let resp = self
1360 .request_with_retry(|| self.http.post(&url).send())
1361 .await?;
1362 if !resp.status().is_success() {
1363 return Err(Error::from_response(resp).await);
1364 }
1365 let body: ApiResponse<AuditRun> = resp.json().await?;
1366 Ok(body.data)
1367 }
1368
1369 pub async fn pause_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
1370 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/pause"));
1371 debug!(%url, "pause_run");
1372 let resp = self
1373 .request_with_retry(|| self.http.post(&url).send())
1374 .await?;
1375 if !resp.status().is_success() {
1376 return Err(Error::from_response(resp).await);
1377 }
1378 let body: ApiResponse<AuditRun> = resp.json().await?;
1379 Ok(body.data)
1380 }
1381
1382 pub async fn resume_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
1383 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/resume"));
1384 debug!(%url, "resume_run");
1385 let resp = self
1386 .request_with_retry(|| self.http.post(&url).send())
1387 .await?;
1388 if !resp.status().is_success() {
1389 return Err(Error::from_response(resp).await);
1390 }
1391 let body: ApiResponse<AuditRun> = resp.json().await?;
1392 Ok(body.data)
1393 }
1394
1395 pub async fn cancel_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
1396 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/cancel"));
1397 debug!(%url, "cancel_run");
1398 let resp = self
1399 .request_with_retry(|| self.http.post(&url).send())
1400 .await?;
1401 if !resp.status().is_success() {
1402 return Err(Error::from_response(resp).await);
1403 }
1404 let body: ApiResponse<AuditRun> = resp.json().await?;
1405 Ok(body.data)
1406 }
1407
1408 pub async fn delete_run(&self, project_id: u64, run_id: u64) -> Result<(), Error> {
1409 let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
1410 debug!(%url, "delete_run");
1411 let resp = self
1412 .request_with_retry(|| self.http.delete(&url).send())
1413 .await?;
1414 if !resp.status().is_success() {
1415 return Err(Error::from_response(resp).await);
1416 }
1417 Ok(())
1418 }
1419
1420 pub async fn add_items_to_version(
1424 &self,
1425 project_id: u64,
1426 version: &str,
1427 spec_item_keys: &[String],
1428 ) -> Result<(), Error> {
1429 let url = self.api_url(&format!(
1430 "/projects/{project_id}/release_versions/{version}/items"
1431 ));
1432 debug!(%url, "add_items_to_version");
1433 let body = serde_json::json!({ "spec_item_ids": spec_item_keys });
1434 let resp = self
1435 .request_with_retry(|| self.http.post(&url).json(&body).send())
1436 .await?;
1437 if !resp.status().is_success() {
1438 return Err(Error::from_response(resp).await);
1439 }
1440 Ok(())
1441 }
1442
1443 pub async fn remove_item_from_version(
1446 &self,
1447 project_id: u64,
1448 version: &str,
1449 spec_item_key: &str,
1450 ) -> Result<(), Error> {
1451 let url = self.api_url(&format!(
1452 "/projects/{project_id}/release_versions/{version}/items/{spec_item_key}"
1453 ));
1454 debug!(%url, "remove_item_from_version");
1455 let resp = self
1456 .request_with_retry(|| self.http.delete(&url).send())
1457 .await?;
1458 if !resp.status().is_success() {
1459 return Err(Error::from_response(resp).await);
1460 }
1461 Ok(())
1462 }
1463
1464 pub async fn diff_versions(
1467 &self,
1468 project_id: u64,
1469 version: &str,
1470 other: &str,
1471 ) -> Result<VersionDiff, Error> {
1472 let url = self.api_url(&format!(
1473 "/projects/{project_id}/release_versions/{version}/diff/{other}"
1474 ));
1475 debug!(%url, "diff_versions");
1476 let resp = self
1477 .request_with_retry(|| self.http.get(&url).send())
1478 .await?;
1479 if !resp.status().is_success() {
1480 return Err(Error::from_response(resp).await);
1481 }
1482 let body: ApiResponse<VersionDiff> = resp.json().await?;
1483 Ok(body.data)
1484 }
1485
1486 pub async fn clone_version(
1489 &self,
1490 project_id: u64,
1491 version: &str,
1492 semver: &str,
1493 name: Option<&str>,
1494 description: Option<&str>,
1495 branch: Option<&str>,
1496 ) -> Result<ReleaseVersion, Error> {
1497 let url = self.api_url(&format!(
1498 "/projects/{project_id}/release_versions/{version}/clone"
1499 ));
1500 debug!(%url, "clone_version");
1501 let mut rv = serde_json::Map::new();
1502 rv.insert(
1503 "semver".into(),
1504 serde_json::Value::String(semver.to_string()),
1505 );
1506 if let Some(n) = name {
1507 rv.insert("name".into(), serde_json::Value::String(n.to_string()));
1508 }
1509 if let Some(d) = description {
1510 rv.insert(
1511 "description".into(),
1512 serde_json::Value::String(d.to_string()),
1513 );
1514 }
1515 if let Some(b) = branch {
1516 rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
1517 }
1518 let body = serde_json::json!({ "release_version": rv });
1519 let resp = self
1520 .request_with_retry(|| self.http.post(&url).json(&body).send())
1521 .await?;
1522 if !resp.status().is_success() {
1523 return Err(Error::from_response(resp).await);
1524 }
1525 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1526 Ok(body.data)
1527 }
1528
1529 pub async fn delete_version(&self, project_id: u64, version: &str) -> Result<(), Error> {
1532 let url = self.api_url(&format!(
1533 "/projects/{project_id}/release_versions/{version}"
1534 ));
1535 debug!(%url, "delete_version");
1536 let resp = self
1537 .request_with_retry(|| self.http.delete(&url).send())
1538 .await?;
1539 if !resp.status().is_success() {
1540 return Err(Error::from_response(resp).await);
1541 }
1542 Ok(())
1543 }
1544
1545 pub async fn create_version(
1548 &self,
1549 project_id: u64,
1550 semver: &str,
1551 name: Option<&str>,
1552 description: Option<&str>,
1553 branch: Option<&str>,
1554 ) -> Result<ReleaseVersion, Error> {
1555 let url = self.api_url(&format!("/projects/{project_id}/release_versions"));
1556 debug!(%url, "create_version");
1557 let mut rv = serde_json::Map::new();
1558 rv.insert(
1559 "semver".into(),
1560 serde_json::Value::String(semver.to_string()),
1561 );
1562 if let Some(n) = name {
1563 rv.insert("name".into(), serde_json::Value::String(n.to_string()));
1564 }
1565 if let Some(d) = description {
1566 rv.insert(
1567 "description".into(),
1568 serde_json::Value::String(d.to_string()),
1569 );
1570 }
1571 if let Some(b) = branch {
1572 rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
1573 }
1574 let body = serde_json::json!({ "release_version": rv });
1575 let resp = self
1576 .request_with_retry(|| self.http.post(&url).json(&body).send())
1577 .await?;
1578 if !resp.status().is_success() {
1579 return Err(Error::from_response(resp).await);
1580 }
1581 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1582 Ok(body.data)
1583 }
1584
1585 pub async fn update_version(
1589 &self,
1590 project_id: u64,
1591 version: &str,
1592 semver: Option<&str>,
1593 name: Option<&str>,
1594 description: Option<&str>,
1595 branch: Option<&str>,
1596 ) -> Result<ReleaseVersion, Error> {
1597 let url = self.api_url(&format!(
1598 "/projects/{project_id}/release_versions/{version}"
1599 ));
1600 debug!(%url, "update_version");
1601 let mut rv = serde_json::Map::new();
1602 if let Some(s) = semver {
1603 rv.insert("semver".into(), serde_json::Value::String(s.to_string()));
1604 }
1605 if let Some(n) = name {
1606 rv.insert("name".into(), serde_json::Value::String(n.to_string()));
1607 }
1608 if let Some(d) = description {
1609 rv.insert(
1610 "description".into(),
1611 serde_json::Value::String(d.to_string()),
1612 );
1613 }
1614 if let Some(b) = branch {
1615 rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
1616 }
1617 let body = serde_json::json!({ "release_version": rv });
1618 let resp = self
1619 .request_with_retry(|| self.http.patch(&url).json(&body).send())
1620 .await?;
1621 if !resp.status().is_success() {
1622 return Err(Error::from_response(resp).await);
1623 }
1624 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1625 Ok(body.data)
1626 }
1627
1628 pub async fn transition_version(
1631 &self,
1632 project_id: u64,
1633 version: &str,
1634 lifecycle_state: &str,
1635 ) -> Result<ReleaseVersion, Error> {
1636 let url = self.api_url(&format!(
1637 "/projects/{project_id}/release_versions/{version}/transition"
1638 ));
1639 debug!(%url, "transition_version");
1640 let body = serde_json::json!({ "lifecycle_state": lifecycle_state });
1641 let resp = self
1642 .request_with_retry(|| self.http.post(&url).json(&body).send())
1643 .await?;
1644 if !resp.status().is_success() {
1645 return Err(Error::from_response(resp).await);
1646 }
1647 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1648 Ok(body.data)
1649 }
1650
1651 pub async fn move_item_in_version(
1654 &self,
1655 project_id: u64,
1656 version: &str,
1657 spec_item_key: &str,
1658 position: i64,
1659 ) -> Result<ReleaseVersion, Error> {
1660 let url = self.api_url(&format!(
1661 "/projects/{project_id}/release_versions/{version}/items/{spec_item_key}"
1662 ));
1663 debug!(%url, "move_item_in_version");
1664 let body = serde_json::json!({ "position": position });
1665 let resp = self
1666 .request_with_retry(|| self.http.patch(&url).json(&body).send())
1667 .await?;
1668 if !resp.status().is_success() {
1669 return Err(Error::from_response(resp).await);
1670 }
1671 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1672 Ok(body.data)
1673 }
1674
1675 pub async fn list_versions(&self, project_id: u64) -> Result<Vec<ReleaseVersion>, Error> {
1678 let url = self.api_url(&format!("/projects/{project_id}/release_versions"));
1679 debug!(%url, "list_versions");
1680 let resp = self
1681 .request_with_retry(|| self.http.get(&url).send())
1682 .await?;
1683 if !resp.status().is_success() {
1684 return Err(Error::from_response(resp).await);
1685 }
1686 let body: ApiListResponse<ReleaseVersion> = resp.json().await?;
1687 Ok(body.data)
1688 }
1689
1690 pub async fn get_version(
1693 &self,
1694 project_id: u64,
1695 version: &str,
1696 include_deprecated: bool,
1697 ) -> Result<ReleaseVersion, Error> {
1698 let url = self.api_url(&format!(
1699 "/projects/{project_id}/release_versions/{version}"
1700 ));
1701 debug!(%url, "get_version");
1702 let mut req = self.http.get(&url);
1703 if include_deprecated {
1704 req = req.query(&[("include_deprecated", "true")]);
1705 }
1706 let resp = self
1707 .request_with_retry(|| req.try_clone().unwrap().send())
1708 .await?;
1709 if !resp.status().is_success() {
1710 return Err(Error::from_response(resp).await);
1711 }
1712 let body: ApiResponse<ReleaseVersion> = resp.json().await?;
1713 Ok(body.data)
1714 }
1715
1716 pub async fn report_implementation(
1722 &self,
1723 project_id: u64,
1724 report: &ImplementationReport,
1725 ) -> Result<ImplementationReportResult, Error> {
1726 let url = self.api_url(&format!("/projects/{project_id}/implementation_reports"));
1727 debug!(%url, "report_implementation");
1728 let resp = self
1729 .request_with_retry(|| self.http.post(&url).json(report).send())
1730 .await?;
1731 if !resp.status().is_success() {
1732 return Err(Error::from_response(resp).await);
1733 }
1734 let body: ApiResponse<ImplementationReportResult> = resp.json().await?;
1735 Ok(body.data)
1736 }
1737
1738 pub async fn preview_import(
1746 &self,
1747 project_id: u64,
1748 raw_body: &str,
1749 ) -> Result<ImportPreview, Error> {
1750 let url = self.api_url(&format!("/projects/{project_id}/import/preview"));
1751 debug!(%url, "preview_import");
1752 let body_bytes = raw_body.as_bytes().to_vec();
1753 let resp = self
1754 .request_with_retry(|| {
1755 self.http
1756 .post(&url)
1757 .header("Content-Type", "text/plain")
1758 .body(body_bytes.clone())
1759 .send()
1760 })
1761 .await?;
1762 if !resp.status().is_success() {
1763 return Err(Error::from_response(resp).await);
1764 }
1765 let body: ApiResponse<ImportPreview> = resp.json().await?;
1766 Ok(body.data)
1767 }
1768
1769 pub async fn commit_import(
1776 &self,
1777 project_id: u64,
1778 items: &[ImportItem],
1779 ) -> Result<ImportResult, Error> {
1780 let url = self.api_url(&format!("/projects/{project_id}/import/commit"));
1781 debug!(%url, items_count = items.len(), "commit_import");
1782 let body = serde_json::json!({ "items": items });
1783 let resp = self
1784 .request_with_retry(|| self.http.post(&url).json(&body).send())
1785 .await?;
1786 if !resp.status().is_success() {
1787 return Err(Error::from_response(resp).await);
1788 }
1789 let body: ApiResponse<ImportResult> = resp.json().await?;
1790 Ok(body.data)
1791 }
1792
1793 pub async fn upload_document(
1802 &self,
1803 project_id: u64,
1804 filename: &str,
1805 mime_type: &str,
1806 bytes: Vec<u8>,
1807 ) -> Result<DocumentUpload, Error> {
1808 let url = self.api_url(&format!("/projects/{project_id}/import/upload"));
1809 debug!(%url, filename, size = bytes.len(), "upload_document");
1810 reqwest::multipart::Part::bytes(Vec::new()).mime_str(mime_type)?;
1812 let resp = self
1813 .request_with_retry(|| {
1814 let part = reqwest::multipart::Part::bytes(bytes.clone())
1815 .file_name(filename.to_string())
1816 .mime_str(mime_type)
1817 .expect("mime type validated above");
1818 let form = reqwest::multipart::Form::new().part("file", part);
1819 self.http.post(&url).multipart(form).send()
1820 })
1821 .await?;
1822 if !resp.status().is_success() {
1823 return Err(Error::from_coded_response(resp).await);
1824 }
1825 Ok(resp.json().await?)
1826 }
1827
1828 pub async fn start_extract(
1831 &self,
1832 project_id: u64,
1833 session_id: u64,
1834 ) -> Result<ImportStageStarted, Error> {
1835 self.start_import_stage(project_id, session_id, "extract")
1836 .await
1837 }
1838
1839 pub async fn start_enrich(
1841 &self,
1842 project_id: u64,
1843 session_id: u64,
1844 ) -> Result<ImportStageStarted, Error> {
1845 self.start_import_stage(project_id, session_id, "enrich")
1846 .await
1847 }
1848
1849 async fn start_import_stage(
1850 &self,
1851 project_id: u64,
1852 session_id: u64,
1853 stage: &str,
1854 ) -> Result<ImportStageStarted, Error> {
1855 let url = self.api_url(&format!(
1856 "/projects/{project_id}/import/sessions/{session_id}/{stage}"
1857 ));
1858 debug!(%url, "start_import_stage");
1859 let resp = self
1860 .request_with_retry(|| self.http.post(&url).send())
1861 .await?;
1862 if !resp.status().is_success() {
1863 return Err(Error::from_coded_response(resp).await);
1864 }
1865 Ok(resp.json().await?)
1866 }
1867
1868 pub async fn poll_import_session(
1871 &self,
1872 project_id: u64,
1873 session_id: u64,
1874 ) -> Result<ImportSession, Error> {
1875 let url = self.api_url(&format!(
1876 "/projects/{project_id}/import/sessions/{session_id}"
1877 ));
1878 debug!(%url, "poll_import_session");
1879 let resp = self
1880 .request_with_retry(|| self.http.get(&url).send())
1881 .await?;
1882 if !resp.status().is_success() {
1883 return Err(Error::from_coded_response(resp).await);
1884 }
1885 Ok(resp.json().await?)
1886 }
1887
1888 pub async fn commit_import_session(
1893 &self,
1894 project_id: u64,
1895 session_id: u64,
1896 items: Option<&[DocumentImportItem]>,
1897 ) -> Result<DocumentImportCommit, Error> {
1898 let url = self.api_url(&format!(
1899 "/projects/{project_id}/import/sessions/{session_id}/commit"
1900 ));
1901 debug!(%url, "commit_import_session");
1902 let body = match items {
1903 Some(items) => serde_json::json!({ "items": items }),
1904 None => serde_json::json!({}),
1905 };
1906 let resp = self
1907 .request_with_retry(|| self.http.post(&url).json(&body).send())
1908 .await?;
1909 if !resp.status().is_success() {
1910 return Err(Error::from_coded_response(resp).await);
1911 }
1912 Ok(resp.json().await?)
1913 }
1914
1915 pub async fn list_repositories(
1920 &self,
1921 project_id: u64,
1922 ) -> Result<Vec<ProjectRepository>, Error> {
1923 let url = self.api_url(&format!("/projects/{project_id}/repositories"));
1924 let resp = self
1925 .request_with_retry(|| self.http.get(&url).send())
1926 .await?;
1927 if !resp.status().is_success() {
1928 return Err(Error::from_response(resp).await);
1929 }
1930 let body: ApiListResponse<ProjectRepository> = resp.json().await?;
1931 Ok(body.data)
1932 }
1933
1934 pub async fn get_repository(
1935 &self,
1936 project_id: u64,
1937 repo_id: u64,
1938 ) -> Result<ProjectRepository, Error> {
1939 let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
1940 let resp = self
1941 .request_with_retry(|| self.http.get(&url).send())
1942 .await?;
1943 if !resp.status().is_success() {
1944 return Err(Error::from_response(resp).await);
1945 }
1946 let body: ApiResponse<ProjectRepository> = resp.json().await?;
1947 Ok(body.data)
1948 }
1949
1950 pub async fn create_repository(
1951 &self,
1952 project_id: u64,
1953 params: &CreateRepositoryParams,
1954 ) -> Result<ProjectRepository, Error> {
1955 let url = self.api_url(&format!("/projects/{project_id}/repositories"));
1956 let body = serde_json::json!({ "project_repository": params });
1957 let resp = self
1958 .request_with_retry(|| self.http.post(&url).json(&body).send())
1959 .await?;
1960 if !resp.status().is_success() {
1961 return Err(Error::from_response(resp).await);
1962 }
1963 let body: ApiResponse<ProjectRepository> = resp.json().await?;
1964 Ok(body.data)
1965 }
1966
1967 pub async fn update_repository(
1968 &self,
1969 project_id: u64,
1970 repo_id: u64,
1971 params: &UpdateRepositoryParams,
1972 ) -> Result<ProjectRepository, Error> {
1973 let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
1974 let body = serde_json::json!({ "project_repository": params });
1975 let resp = self
1976 .request_with_retry(|| self.http.patch(&url).json(&body).send())
1977 .await?;
1978 if !resp.status().is_success() {
1979 return Err(Error::from_response(resp).await);
1980 }
1981 let body: ApiResponse<ProjectRepository> = resp.json().await?;
1982 Ok(body.data)
1983 }
1984
1985 pub async fn delete_repository(&self, project_id: u64, repo_id: u64) -> Result<(), Error> {
1986 let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
1987 let resp = self
1988 .request_with_retry(|| self.http.delete(&url).send())
1989 .await?;
1990 if !resp.status().is_success() {
1991 return Err(Error::from_response(resp).await);
1992 }
1993 Ok(())
1994 }
1995
1996 pub async fn sync_repository(
1997 &self,
1998 project_id: u64,
1999 repo_id: u64,
2000 ) -> Result<ProjectRepository, Error> {
2001 let url = self.api_url(&format!(
2002 "/projects/{project_id}/repositories/{repo_id}/sync"
2003 ));
2004 let resp = self
2005 .request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
2006 .await?;
2007 if !resp.status().is_success() {
2008 return Err(Error::from_response(resp).await);
2009 }
2010 let body: ApiResponse<ProjectRepository> = resp.json().await?;
2011 Ok(body.data)
2012 }
2013
2014 pub async fn set_primary_repository(
2015 &self,
2016 project_id: u64,
2017 repo_id: u64,
2018 ) -> Result<ProjectRepository, Error> {
2019 let url = self.api_url(&format!(
2020 "/projects/{project_id}/repositories/{repo_id}/set_primary"
2021 ));
2022 let resp = self
2023 .request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
2024 .await?;
2025 if !resp.status().is_success() {
2026 return Err(Error::from_response(resp).await);
2027 }
2028 let body: ApiResponse<ProjectRepository> = resp.json().await?;
2029 Ok(body.data)
2030 }
2031}
2032#[cfg(test)]
2033mod tests {
2034 use super::*;
2035 use wiremock::matchers::{method, path, query_param};
2036 use wiremock::{Mock, MockServer, ResponseTemplate};
2037
2038 async fn make_client(base_url: &str) -> FuncspecClient {
2039 FuncspecClient::new(base_url, "test-key").unwrap()
2040 }
2041
2042 #[tokio::test]
2043 async fn get_agent_instructions_returns_full_json() {
2044 let server = MockServer::start().await;
2045 Mock::given(method("GET"))
2046 .and(path("/api/v1/projects/my-proj/agent_instructions"))
2047 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2048 "data": {
2049 "id": 1,
2050 "type": "agent_instruction",
2051 "attributes": {
2052 "content": "# Instructions\n\nDo the thing.",
2053 "scope": "project",
2054 "version": 1
2055 }
2056 }
2057 })))
2058 .mount(&server)
2059 .await;
2060
2061 let client = make_client(&server.uri()).await;
2062 let result = client.get_agent_instructions("my-proj").await.unwrap();
2063 let content = result["data"]["attributes"]["content"].as_str().unwrap();
2064 assert!(content.contains("# Instructions"));
2065 }
2066
2067 #[tokio::test]
2068 async fn get_agent_instructions_propagates_auth_error() {
2069 let server = MockServer::start().await;
2070 Mock::given(method("GET"))
2071 .and(path("/api/v1/projects/secret/agent_instructions"))
2072 .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
2073 "error": "Unauthorized"
2074 })))
2075 .mount(&server)
2076 .await;
2077
2078 let client = make_client(&server.uri()).await;
2079 let err = client.get_agent_instructions("secret").await.unwrap_err();
2080 assert!(matches!(err, crate::error::Error::Auth(_)));
2081 }
2082
2083 #[tokio::test]
2084 async fn get_agent_instructions_propagates_not_found() {
2085 let server = MockServer::start().await;
2086 Mock::given(method("GET"))
2087 .and(path("/api/v1/projects/no-such/agent_instructions"))
2088 .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
2089 "error": "Not found"
2090 })))
2091 .mount(&server)
2092 .await;
2093
2094 let client = make_client(&server.uri()).await;
2095 let err = client.get_agent_instructions("no-such").await.unwrap_err();
2096 assert!(matches!(err, crate::error::Error::NotFound(_)));
2097 }
2098
2099 #[tokio::test]
2100 async fn export_project_text_format() {
2101 let server = MockServer::start().await;
2102 Mock::given(method("GET"))
2103 .and(path("/api/v1/projects/42/export/markdown"))
2104 .respond_with(ResponseTemplate::new(200).set_body_string("# My Spec\n\nContent here."))
2105 .mount(&server)
2106 .await;
2107
2108 let client = make_client(&server.uri()).await;
2109 let result = client
2110 .export_project(42, "markdown", None, None, None)
2111 .await
2112 .unwrap();
2113 match result {
2114 ExportData::Text(text) => assert!(text.contains("# My Spec")),
2115 ExportData::Binary(_) => panic!("expected text"),
2116 }
2117 }
2118
2119 #[tokio::test]
2120 async fn export_project_with_filters() {
2121 let server = MockServer::start().await;
2122 Mock::given(method("GET"))
2123 .and(path("/api/v1/projects/42/export/csv"))
2124 .and(query_param("type_of", "functional"))
2125 .and(query_param("tag", "v1"))
2126 .respond_with(ResponseTemplate::new(200).set_body_string("id,title\n1,Login"))
2127 .mount(&server)
2128 .await;
2129
2130 let client = make_client(&server.uri()).await;
2131 let result = client
2132 .export_project(42, "csv", Some("functional"), Some("v1"), None)
2133 .await
2134 .unwrap();
2135 match result {
2136 ExportData::Text(text) => assert!(text.contains("id,title")),
2137 ExportData::Binary(_) => panic!("expected text"),
2138 }
2139 }
2140
2141 #[tokio::test]
2142 async fn export_project_binary_format() {
2143 let server = MockServer::start().await;
2144 let pdf_bytes = b"%PDF-1.4 fake pdf content".to_vec();
2145 Mock::given(method("GET"))
2146 .and(path("/api/v1/projects/7/export/pdf"))
2147 .respond_with(ResponseTemplate::new(200).set_body_bytes(pdf_bytes.clone()))
2148 .mount(&server)
2149 .await;
2150
2151 let client = make_client(&server.uri()).await;
2152 let result = client
2153 .export_project(7, "pdf", None, None, None)
2154 .await
2155 .unwrap();
2156 match result {
2157 ExportData::Binary(bytes) => assert_eq!(bytes, pdf_bytes),
2158 ExportData::Text(_) => panic!("expected binary"),
2159 }
2160 }
2161
2162 #[tokio::test]
2163 async fn export_project_docx_binary() {
2164 let server = MockServer::start().await;
2165 let docx_bytes = b"PK\x03\x04fake docx".to_vec();
2166 Mock::given(method("GET"))
2167 .and(path("/api/v1/projects/5/export/docx"))
2168 .respond_with(ResponseTemplate::new(200).set_body_bytes(docx_bytes.clone()))
2169 .mount(&server)
2170 .await;
2171
2172 let client = make_client(&server.uri()).await;
2173 let result = client
2174 .export_project(5, "docx", None, None, None)
2175 .await
2176 .unwrap();
2177 match result {
2178 ExportData::Binary(bytes) => assert_eq!(bytes, docx_bytes),
2179 ExportData::Text(_) => panic!("expected binary"),
2180 }
2181 }
2182
2183 #[tokio::test]
2184 async fn export_project_error_response() {
2185 let server = MockServer::start().await;
2186 Mock::given(method("GET"))
2187 .and(path("/api/v1/projects/99/export/markdown"))
2188 .respond_with(
2189 ResponseTemplate::new(404)
2190 .set_body_json(serde_json::json!({"error": "Project not found"})),
2191 )
2192 .mount(&server)
2193 .await;
2194
2195 let client = make_client(&server.uri()).await;
2196 let result = client
2197 .export_project(99, "markdown", None, None, None)
2198 .await;
2199 assert!(matches!(result, Err(Error::NotFound(_))));
2200 }
2201
2202 #[tokio::test]
2203 async fn get_viewable_html_returns_string() {
2204 let server = MockServer::start().await;
2205 Mock::given(method("GET"))
2206 .and(path("/api/v1/projects/3/spec/view"))
2207 .respond_with(
2208 ResponseTemplate::new(200).set_body_string("<html><body>Spec</body></html>"),
2209 )
2210 .mount(&server)
2211 .await;
2212
2213 let client = make_client(&server.uri()).await;
2214 let html = client.get_viewable_html(3).await.unwrap();
2215 assert!(html.contains("<html>"));
2216 }
2217
2218 #[tokio::test]
2219 async fn get_viewable_html_error() {
2220 let server = MockServer::start().await;
2221 Mock::given(method("GET"))
2222 .and(path("/api/v1/projects/0/spec/view"))
2223 .respond_with(
2224 ResponseTemplate::new(403).set_body_json(serde_json::json!({"error": "Forbidden"})),
2225 )
2226 .mount(&server)
2227 .await;
2228
2229 let client = make_client(&server.uri()).await;
2230 let result = client.get_viewable_html(0).await;
2231 assert!(matches!(result, Err(Error::Forbidden(_))));
2232 }
2233
2234 #[tokio::test]
2237 async fn review_item_returns_review() {
2238 let server = MockServer::start().await;
2239 Mock::given(method("POST"))
2242 .and(path("/api/v1/projects/1/work_package/5/review"))
2243 .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
2244 "data": { "job_id": 77, "status": "queued" }
2245 })))
2246 .mount(&server)
2247 .await;
2248 Mock::given(method("GET"))
2249 .and(path("/api/v1/projects/1/jobs/77"))
2250 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2251 "data": { "id": 77, "job_type": "review", "status": "completed",
2252 "progress": null, "result": null,
2253 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z" }
2254 })))
2255 .mount(&server)
2256 .await;
2257 Mock::given(method("GET"))
2258 .and(path("/api/v1/projects/1/spec/items/5"))
2259 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2260 "data": { "id": 5, "type": "spec_item", "attributes": {
2261 "title": "Auth service", "description": "x", "type_of": "technical",
2262 "state": "accepted", "implementation_status": "implemented",
2263 "permalink": "T-5", "url": "/o/p/T-5", "version": 1, "priority": null,
2264 "position": null, "tags": [], "parent_id": null, "project_id": 1,
2265 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z",
2266 "review": {
2267 "coverage_score": 90.0, "verdict": "pass", "review_type": "tech_review",
2268 "reviewed_at": "2026-01-01T00:00:00Z", "fresh": true,
2269 "coverage_map": {
2270 "Auth flow": {"status": "covered"}, "Error cases": {"status": "covered"}
2271 },
2272 "gaps": [], "suggestions": ["Consider adding retry logic"], "risks": []
2273 }
2274 } }
2275 })))
2276 .mount(&server)
2277 .await;
2278
2279 let client = make_client(&server.uri()).await;
2280 let review = client.review_item(1, 5).await.unwrap();
2281 assert_eq!(review.attributes.coverage_score, Some(90.0));
2282 assert_eq!(review.attributes.verdict.as_deref(), Some("pass"));
2283 assert_eq!(review.attributes.coverage_map.len(), 2);
2284 assert!(review.attributes.gaps.is_empty());
2285 assert_eq!(review.attributes.suggestions.len(), 1);
2286 }
2287
2288 #[tokio::test]
2289 async fn review_item_not_found() {
2290 let server = MockServer::start().await;
2291 Mock::given(method("POST"))
2292 .and(path("/api/v1/projects/1/work_package/999/review"))
2293 .respond_with(
2294 ResponseTemplate::new(404).set_body_json(serde_json::json!({"error": "Not found"})),
2295 )
2296 .mount(&server)
2297 .await;
2298
2299 let client = make_client(&server.uri()).await;
2300 let result = client.review_item(1, 999).await;
2301 assert!(matches!(result, Err(Error::NotFound(_))));
2302 }
2303
2304 #[tokio::test]
2305 async fn review_all_returns_job() {
2306 let server = MockServer::start().await;
2307 Mock::given(method("POST"))
2308 .and(path("/api/v1/projects/2/work_package/review_all"))
2309 .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
2310 "data": { "job_id": 77, "status": "queued" }
2311 })))
2312 .mount(&server)
2313 .await;
2314
2315 let client = make_client(&server.uri()).await;
2316 let job_id = client.review_all(2).await.unwrap();
2317 assert_eq!(job_id, 77);
2318 }
2319
2320 #[tokio::test]
2321 async fn propose_improvement_returns_proposal() {
2322 let server = MockServer::start().await;
2323 Mock::given(method("POST"))
2324 .and(path("/api/v1/projects/3/work_package/10/propose"))
2325 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2326 "data": {
2327 "id": 1,
2328 "type": "proposal",
2329 "attributes": {
2330 "spec_item_id": 10,
2331 "original_description": "User logs in.",
2332 "proposed_description": "User logs in with email and password.",
2333 "rationale": "More specific",
2334 "status": "pending",
2335 "created_at": "2026-01-01T00:00:00Z"
2336 }
2337 }
2338 })))
2339 .mount(&server)
2340 .await;
2341
2342 let client = make_client(&server.uri()).await;
2343 let proposal = client.propose_improvement(3, 10).await.unwrap();
2344 assert_eq!(proposal.attributes.spec_item_id, 10);
2345 assert_eq!(proposal.attributes.status, "pending");
2346 assert!(
2347 proposal
2348 .attributes
2349 .proposed_description
2350 .unwrap()
2351 .contains("email")
2352 );
2353 }
2354
2355 #[tokio::test]
2356 async fn accept_proposal_success() {
2357 let server = MockServer::start().await;
2358 Mock::given(method("POST"))
2359 .and(path("/api/v1/projects/4/work_package/20/accept"))
2360 .respond_with(ResponseTemplate::new(200).set_body_string(""))
2361 .mount(&server)
2362 .await;
2363
2364 let client = make_client(&server.uri()).await;
2365 assert!(client.accept_proposal(4, 20).await.is_ok());
2366 }
2367
2368 #[tokio::test]
2369 async fn reject_proposal_success() {
2370 let server = MockServer::start().await;
2371 Mock::given(method("POST"))
2372 .and(path("/api/v1/projects/4/work_package/20/reject"))
2373 .respond_with(ResponseTemplate::new(200).set_body_string(""))
2374 .mount(&server)
2375 .await;
2376
2377 let client = make_client(&server.uri()).await;
2378 assert!(client.reject_proposal(4, 20).await.is_ok());
2379 }
2380
2381 #[tokio::test]
2382 async fn generate_tech_returns_proposals() {
2383 let server = MockServer::start().await;
2384 Mock::given(method("POST"))
2385 .and(path("/api/v1/projects/5/work_package/30/generate_tech"))
2386 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2387 "data": {
2388 "functional_item_id": 30,
2389 "functional_item_permalink": "F-30",
2390 "proposals": [
2391 {
2392 "title": "Users table schema",
2393 "description": "Create users table",
2394 "type_of": "technical",
2395 "rationale": "Required for auth"
2396 },
2397 {
2398 "title": "JWT service",
2399 "description": null,
2400 "type_of": "technical",
2401 "rationale": null
2402 }
2403 ]
2404 }
2405 })))
2406 .mount(&server)
2407 .await;
2408
2409 let client = make_client(&server.uri()).await;
2410 let tp = client.generate_tech(5, 30).await.unwrap();
2411 assert_eq!(tp.functional_item_id, 30);
2412 assert_eq!(tp.functional_item_permalink, "F-30");
2413 assert_eq!(tp.proposals.len(), 2);
2414 assert_eq!(tp.proposals[0].title, "Users table schema");
2415 }
2416
2417 #[tokio::test]
2418 async fn audit_item_returns_result() {
2419 let server = MockServer::start().await;
2420 Mock::given(method("POST"))
2421 .and(path("/api/v1/projects/6/work_package/40/audit"))
2422 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2423 "data": {
2424 "id": 55,
2425 "status_recommendation": "implemented",
2426 "confidence": "high",
2427 "files_discovered": 28,
2428 "coverage_percentage": 73.3,
2429 "criteria_coverage": [
2430 {
2431 "criterion": "All requirements covered",
2432 "status": "implemented",
2433 "evidence": [
2434 {"file": "app/models/foo.rb", "lines": "1-10", "note": "present"}
2435 ]
2436 }
2437 ],
2438 "notes": "All requirements covered",
2439 "created_at": "2026-01-01T00:00:00Z"
2440 }
2441 })))
2442 .mount(&server)
2443 .await;
2444
2445 let client = make_client(&server.uri()).await;
2446 let audit = client.audit_item(6, 40).await.unwrap();
2447 assert_eq!(audit.status_recommendation, "implemented");
2448 assert_eq!(audit.confidence, "high");
2449 assert_eq!(audit.files_discovered, 28);
2450 assert_eq!(audit.criteria_coverage.len(), 1);
2451 assert_eq!(audit.criteria_coverage[0].status, "implemented");
2452 }
2453
2454 #[tokio::test]
2455 async fn get_project_job_returns_job() {
2456 let server = MockServer::start().await;
2457 Mock::given(method("GET"))
2458 .and(path("/api/v1/projects/7/jobs/88"))
2459 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2460 "data": {
2461 "id": 88, "job_type": "review", "status": "completed",
2462 "progress": 100.0, "result": "All items reviewed",
2463 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:01:00Z"
2464 }
2465 })))
2466 .mount(&server)
2467 .await;
2468
2469 let client = make_client(&server.uri()).await;
2470 let job = client.get_project_job(7, 88).await.unwrap();
2471 assert_eq!(job.id, 88);
2472 assert_eq!(job.attributes.status, JobStatus::Completed);
2473 }
2474
2475 #[tokio::test]
2476 async fn poll_job_until_done_completes_immediately() {
2477 let server = MockServer::start().await;
2478 Mock::given(method("GET"))
2480 .and(path("/api/v1/projects/1/jobs/99"))
2481 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2482 "data": {
2483 "id": 99, "job_type": "review", "status": "completed",
2484 "progress": 100.0, "result": "Done",
2485 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:30Z"
2486 }
2487 })))
2488 .mount(&server)
2489 .await;
2490
2491 let client = make_client(&server.uri()).await;
2492 let job = client
2493 .poll_job_until_done(1, 99, Duration::from_secs(30))
2494 .await
2495 .unwrap();
2496 assert_eq!(job.attributes.status, JobStatus::Completed);
2497 }
2498
2499 #[tokio::test]
2502 async fn transition_item_implementation_success() {
2503 let server = MockServer::start().await;
2504 Mock::given(method("POST"))
2505 .and(path(
2506 "/api/v1/projects/1/spec/items/5/transition_implementation",
2507 ))
2508 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
2509 .mount(&server)
2510 .await;
2511
2512 let client = make_client(&server.uri()).await;
2513 client
2514 .transition_item_implementation(1, 5, "in_progress")
2515 .await
2516 .unwrap();
2517 }
2518
2519 #[tokio::test]
2520 async fn transition_item_implementation_422_returns_validation_error() {
2521 let server = MockServer::start().await;
2522 Mock::given(method("POST"))
2523 .and(path(
2524 "/api/v1/projects/1/spec/items/5/transition_implementation",
2525 ))
2526 .respond_with(ResponseTemplate::new(422).set_body_json(
2527 serde_json::json!({"error": "Cannot transition from released to not_started"}),
2528 ))
2529 .mount(&server)
2530 .await;
2531
2532 let client = make_client(&server.uri()).await;
2533 let err = client
2534 .transition_item_implementation(1, 5, "not_started")
2535 .await
2536 .unwrap_err();
2537 assert!(matches!(err, Error::Validation(_)));
2538 }
2539
2540 #[tokio::test]
2541 async fn link_commit_sends_sha_and_optional_fields() {
2542 let server = MockServer::start().await;
2543 Mock::given(method("POST"))
2544 .and(path("/api/v1/projects/1/work_package/5/link_commit"))
2545 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
2546 .mount(&server)
2547 .await;
2548
2549 let client = make_client(&server.uri()).await;
2550 let params = LinkCommitParams {
2551 sha: "abc1234".into(),
2552 message: Some("Fix auth".into()),
2553 source: Some("cli".into()),
2554 agent_run_id: Some(9),
2555 ..Default::default()
2556 };
2557 client.link_commit(1, 5, ¶ms).await.unwrap();
2558 }
2559
2560 #[tokio::test]
2561 async fn link_commit_bare_sha_only() {
2562 let server = MockServer::start().await;
2563 Mock::given(method("POST"))
2564 .and(path("/api/v1/projects/2/work_package/7/link_commit"))
2565 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
2566 .mount(&server)
2567 .await;
2568
2569 let client = make_client(&server.uri()).await;
2570 let params = LinkCommitParams {
2571 sha: "deadbeef".into(),
2572 ..Default::default()
2573 };
2574 client.link_commit(2, 7, ¶ms).await.unwrap();
2575 }
2576
2577 #[tokio::test]
2578 async fn record_run_returns_run_id() {
2579 let server = MockServer::start().await;
2580 Mock::given(method("POST"))
2581 .and(path("/api/v1/projects/1/work_package/5/record_run"))
2582 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2583 "data": {"id": 42, "spec_item_id": 5, "status": "pending"}
2584 })))
2585 .mount(&server)
2586 .await;
2587
2588 let client = make_client(&server.uri()).await;
2589 let params = RecordRunParams {
2590 model: Some("claude-sonnet-4-6".into()),
2591 provider: Some("anthropic".into()),
2592 ..Default::default()
2593 };
2594 let run_id = client.record_run(1, 5, ¶ms).await.unwrap();
2595 assert_eq!(run_id, Some(42));
2596 }
2597
2598 #[tokio::test]
2599 async fn record_run_returns_none_when_no_id_in_response() {
2600 let server = MockServer::start().await;
2601 Mock::given(method("POST"))
2602 .and(path("/api/v1/projects/1/work_package/5/record_run"))
2603 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
2604 .mount(&server)
2605 .await;
2606
2607 let client = make_client(&server.uri()).await;
2608 let run_id = client
2609 .record_run(1, 5, &RecordRunParams::default())
2610 .await
2611 .unwrap();
2612 assert_eq!(run_id, None);
2613 }
2614
2615 #[tokio::test]
2616 async fn review_item_functional_returns_review() {
2617 let server = MockServer::start().await;
2618 Mock::given(method("POST"))
2619 .and(path("/api/v1/projects/1/work_package/5/func_review"))
2620 .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
2621 "data": { "job_id": 88, "status": "queued" }
2622 })))
2623 .mount(&server)
2624 .await;
2625 Mock::given(method("GET"))
2626 .and(path("/api/v1/projects/1/jobs/88"))
2627 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2628 "data": { "id": 88, "job_type": "func_review", "status": "completed",
2629 "progress": null, "result": null,
2630 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z" }
2631 })))
2632 .mount(&server)
2633 .await;
2634 Mock::given(method("GET"))
2635 .and(path("/api/v1/projects/1/spec/items/5"))
2636 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2637 "data": { "id": 5, "type": "spec_item", "attributes": {
2638 "title": "Rate limiter", "description": "x", "type_of": "functional",
2639 "state": "accepted", "implementation_status": "implemented",
2640 "permalink": "F-5", "url": "/o/p/F-5", "version": 1, "priority": null,
2641 "position": null, "tags": [], "parent_id": null, "project_id": 1,
2642 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z",
2643 "review": {
2644 "coverage_score": 75.0, "verdict": "needs_refinement",
2645 "review_type": "func_review", "reviewed_at": "2026-01-01T00:00:00Z",
2646 "fresh": true, "coverage_map": {},
2647 "gaps": ["Missing burst allowance detail"], "suggestions": [], "risks": []
2648 }
2649 } }
2650 })))
2651 .mount(&server)
2652 .await;
2653
2654 let client = make_client(&server.uri()).await;
2655 let review = client.review_item_functional(1, 5).await.unwrap();
2656 assert_eq!(review.attributes.coverage_score, Some(75.0));
2657 assert_eq!(
2658 review.attributes.verdict.as_deref(),
2659 Some("needs_refinement")
2660 );
2661 assert_eq!(review.attributes.gaps.len(), 1);
2662 }
2663
2664 #[tokio::test]
2665 async fn poll_job_until_done_returns_failed_job() {
2666 let server = MockServer::start().await;
2667 Mock::given(method("GET"))
2668 .and(path("/api/v1/projects/1/jobs/100"))
2669 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2670 "data": {
2671 "id": 100, "job_type": "audit", "status": "failed",
2672 "progress": null, "result": "Internal error",
2673 "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z"
2674 }
2675 })))
2676 .mount(&server)
2677 .await;
2678
2679 let client = make_client(&server.uri()).await;
2680 let job = client
2681 .poll_job_until_done(1, 100, Duration::from_secs(30))
2682 .await
2683 .unwrap();
2684 assert_eq!(job.attributes.status, JobStatus::Failed);
2686 }
2687
2688 #[tokio::test]
2689 async fn preview_run_returns_count_and_items() {
2690 let server = MockServer::start().await;
2691 Mock::given(method("POST"))
2692 .and(path("/api/v1/projects/1/runs/preview"))
2693 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2694 "data": {
2695 "count": 2,
2696 "truncated": false,
2697 "filter_criteria": { "type_of": "functional" },
2698 "items": [
2699 { "id": 10, "permalink": "F-10", "title": "Login", "type_of": "functional" },
2700 { "id": 11, "permalink": "F-11", "title": "Logout", "type_of": "functional" }
2701 ]
2702 }
2703 })))
2704 .mount(&server)
2705 .await;
2706
2707 let client = make_client(&server.uri()).await;
2708 let params = CreateRunParams {
2709 type_of: Some("functional".into()),
2710 ..Default::default()
2711 };
2712 let preview = client.preview_run(1, ¶ms).await.unwrap();
2713 assert_eq!(preview.count, 2);
2714 assert!(!preview.truncated);
2715 assert_eq!(preview.items.len(), 2);
2716 assert_eq!(preview.items[0].permalink.as_deref(), Some("F-10"));
2717 }
2718
2719 #[tokio::test]
2720 async fn preview_run_empty_result() {
2721 let server = MockServer::start().await;
2722 Mock::given(method("POST"))
2723 .and(path("/api/v1/projects/1/runs/preview"))
2724 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2725 "data": { "count": 0, "truncated": false, "filter_criteria": {}, "items": [] }
2726 })))
2727 .mount(&server)
2728 .await;
2729
2730 let client = make_client(&server.uri()).await;
2731 let preview = client
2732 .preview_run(1, &CreateRunParams::default())
2733 .await
2734 .unwrap();
2735 assert_eq!(preview.count, 0);
2736 assert!(preview.items.is_empty());
2737 }
2738}