1use anyhow::Context;
2use anyhow::Result;
3use schemars::JsonSchema;
4use serde::Deserialize;
5use serde::Serialize;
6use std::sync::Arc;
7use std::sync::OnceLock;
8use std::time::Duration;
9use tokio::sync::Semaphore;
10
11mod templates;
12
13use crate::config::ReferenceEntry;
14use crate::config::ReferenceMount;
15use crate::config::RepoConfigManager;
16use crate::config::RepoMappingManager;
17use crate::config::extract_org_repo_from_url;
18use crate::config::validation::canonical_reference_instance_key;
19use crate::config::validation::validate_pinned_ref_full_name_new_input;
20use crate::config::validation::validate_reference_url_https_only;
21use crate::git::ref_key::encode_ref_key;
22use crate::git::remote_refs::RemoteRef;
23use crate::git::remote_refs::discover_remote_refs;
24use crate::git::utils::get_control_repo_root;
25use crate::mount::MountSpace;
26use crate::mount::auto_mount::update_active_mounts;
27use crate::mount::get_mount_manager;
28use crate::platform::detect_platform;
29
30const DEFAULT_REPO_REFS_LIMIT: usize = 100;
31const MAX_REPO_REFS_LIMIT: usize = 200;
32const REPO_REFS_MAX_CONCURRENCY: usize = 4;
33const REPO_REFS_TIMEOUT_SECS: u64 = 20;
34
35static REPO_REFS_SEM: OnceLock<Arc<Semaphore>> = OnceLock::new();
36
37fn find_matching_existing_reference(
38 cfg: &crate::config::RepoConfigV2,
39 input_url: &str,
40 requested_ref_name: Option<&str>,
41) -> Option<(String, Option<String>)> {
42 let wanted = canonical_reference_instance_key(input_url, requested_ref_name).ok()?;
43
44 for entry in &cfg.references {
45 let (existing_url, existing_ref_name) = match entry {
46 ReferenceEntry::Simple(url) => (url.as_str(), None),
47 ReferenceEntry::WithMetadata(reference_mount) => (
48 reference_mount.remote.as_str(),
49 reference_mount.ref_name.as_deref(),
50 ),
51 };
52
53 let Ok(existing_key) = canonical_reference_instance_key(existing_url, existing_ref_name)
54 else {
55 continue;
56 };
57
58 if existing_key == wanted {
59 return Some((
60 existing_url.to_string(),
61 existing_ref_name.map(ToString::to_string),
62 ));
63 }
64 }
65
66 None
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
70#[serde(rename_all = "snake_case")]
71pub enum TemplateType {
72 Research,
73 Plan,
74 Requirements,
75 PrDescription,
76}
77
78impl TemplateType {
79 pub fn label(&self) -> &'static str {
80 match self {
81 Self::Research => "research",
82 Self::Plan => "plan",
83 Self::Requirements => "requirements",
84 Self::PrDescription => "pr_description",
85 }
86 }
87 pub fn content(&self) -> &'static str {
88 match self {
89 Self::Research => templates::RESEARCH_TEMPLATE_MD,
90 Self::Plan => templates::PLAN_TEMPLATE_MD,
91 Self::Requirements => templates::REQUIREMENTS_TEMPLATE_MD,
92 Self::PrDescription => templates::PR_DESCRIPTION_TEMPLATE_MD,
93 }
94 }
95 pub fn guidance(&self) -> &'static str {
96 match self {
97 Self::Research => templates::RESEARCH_GUIDANCE,
98 Self::Plan => templates::PLAN_GUIDANCE,
99 Self::Requirements => templates::REQUIREMENTS_GUIDANCE,
100 Self::PrDescription => templates::PR_DESCRIPTION_GUIDANCE,
101 }
102 }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
108pub struct ReferenceItem {
109 pub path: String,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 pub description: Option<String>,
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
115pub struct ReferencesList {
116 pub base: String,
117 pub entries: Vec<ReferenceItem>,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
121pub struct RepoRefsList {
122 pub url: String,
123 pub total: usize,
124 pub truncated: bool,
125 pub entries: Vec<RemoteRef>,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
129pub struct AddReferenceOk {
130 pub url: String,
131 #[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
132 pub ref_name: Option<String>,
133 pub org: String,
134 pub repo: String,
135 pub mount_path: String,
136 pub mount_target: String,
137 #[serde(skip_serializing_if = "Option::is_none")]
138 pub mapping_path: Option<String>,
139 pub already_existed: bool,
140 pub config_updated: bool,
141 pub cloned: bool,
142 pub mounted: bool,
143 #[serde(default)]
144 pub warnings: Vec<String>,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
148pub struct TemplateResponse {
149 pub template_type: TemplateType,
150}
151
152fn repo_refs_semaphore() -> Arc<Semaphore> {
155 Arc::clone(REPO_REFS_SEM.get_or_init(|| Arc::new(Semaphore::new(REPO_REFS_MAX_CONCURRENCY))))
156}
157
158fn get_repo_refs_blocking(input_url: String, limit: usize) -> Result<RepoRefsList> {
159 let repo_root =
160 get_control_repo_root(&std::env::current_dir().context("failed to get current directory")?)
161 .context("failed to get control repo root")?;
162 let mut refs = discover_remote_refs(&repo_root, &input_url)?;
163 refs.sort_by(|a, b| {
164 a.name
165 .cmp(&b.name)
166 .then_with(|| a.target.cmp(&b.target))
167 .then_with(|| a.oid.cmp(&b.oid))
168 .then_with(|| a.peeled.cmp(&b.peeled))
169 });
170
171 let total = refs.len();
172 let truncated = total > limit;
173 refs.truncate(limit);
174
175 Ok(RepoRefsList {
176 url: input_url,
177 total,
178 truncated,
179 entries: refs,
180 })
181}
182
183async fn run_blocking_repo_refs_with_deadline<R, F>(
184 sem: Arc<Semaphore>,
185 timeout: Duration,
186 op_label: String,
187 work: F,
188) -> Result<R>
189where
190 R: Send + 'static,
191 F: FnOnce() -> Result<R> + Send + 'static,
192{
193 let deadline = tokio::time::Instant::now() + timeout;
194
195 let permit = match tokio::time::timeout_at(deadline, sem.acquire_owned()).await {
196 Ok(permit) => permit.context("semaphore unexpectedly closed")?,
197 Err(_) => anyhow::bail!("timeout while waiting to start {op_label} after {timeout:?}"),
198 };
199
200 let mut handle = tokio::task::spawn_blocking(move || {
201 let _permit = permit;
202 work()
203 });
204
205 if let Ok(joined) = tokio::time::timeout_at(deadline, &mut handle).await {
206 joined.context("remote ref discovery task failed")?
207 } else {
208 tokio::spawn(async move {
209 let _ = handle.await;
210 });
211 anyhow::bail!("timeout while {op_label} after {timeout:?}");
212 }
213}
214
215pub async fn get_repo_refs_impl_adapter(url: String, limit: Option<usize>) -> Result<RepoRefsList> {
216 let input_url = url.trim().to_string();
217 validate_reference_url_https_only(&input_url)
218 .context("invalid input: URL failed HTTPS validation")?;
219 let limit = normalize_repo_ref_limit(limit)?;
220
221 let sem = repo_refs_semaphore();
222 let timeout = Duration::from_secs(REPO_REFS_TIMEOUT_SECS);
223 let op_label = format!("discovering remote refs for {input_url}");
224 let url_for_task = input_url.clone();
225
226 run_blocking_repo_refs_with_deadline(sem, timeout, op_label, move || {
227 get_repo_refs_blocking(url_for_task, limit)
228 })
229 .await
230}
231
232fn normalize_repo_ref_limit(limit: Option<usize>) -> Result<usize> {
233 match limit.unwrap_or(DEFAULT_REPO_REFS_LIMIT) {
234 0 => anyhow::bail!("invalid input: limit must be at least 1"),
235 limit if limit > MAX_REPO_REFS_LIMIT => {
236 anyhow::bail!("invalid input: limit must be at most {MAX_REPO_REFS_LIMIT}")
237 }
238 limit => Ok(limit),
239 }
240}
241
242fn response_identity_url<'a>(
243 input_url: &'a str,
244 matched_existing: Option<&'a (String, Option<String>)>,
245) -> &'a str {
246 matched_existing.map_or(input_url, |(stored_url, _)| stored_url.as_str())
247}
248
249pub async fn add_reference_impl_adapter(
262 url: String,
263 description: Option<String>,
264 ref_name: Option<String>,
265) -> Result<AddReferenceOk> {
266 let input_url = url.trim().to_string();
267 let requested_ref_name = match ref_name {
268 Some(ref_name) => {
269 let trimmed = ref_name.trim();
270 if trimmed.is_empty() {
271 anyhow::bail!("invalid input: ref cannot be empty");
272 }
273 Some(trimmed.to_string())
274 }
275 None => None,
276 };
277 if let Some(ref_name) = requested_ref_name.as_deref()
278 && let Err(e) = validate_pinned_ref_full_name_new_input(ref_name)
279 {
280 anyhow::bail!(
281 "invalid input: ref must be a full ref name like 'refs/heads/main' or 'refs/tags/v1.2.3' \
282(shorthand like 'main' is not supported). Details: {e}. \
283Tip: call thoughts_get_repo_refs to discover full refs."
284 );
285 }
286
287 validate_reference_url_https_only(&input_url)
289 .context("invalid input: URL failed HTTPS validation")?;
290
291 let repo_root =
293 get_control_repo_root(&std::env::current_dir().context("failed to get current directory")?)
294 .context("failed to get control repo root")?;
295
296 let mgr = RepoConfigManager::new(repo_root.clone());
297 let mut cfg = mgr
298 .ensure_v2_default()
299 .context("failed to ensure v2 config")?;
300
301 canonical_reference_instance_key(&input_url, requested_ref_name.as_deref())
302 .context("invalid input: failed to canonicalize URL")?;
303 let matched_existing =
304 find_matching_existing_reference(&cfg, &input_url, requested_ref_name.as_deref());
305 let already_existed = matched_existing.is_some();
306 let effective_ref_name = matched_existing
307 .as_ref()
308 .and_then(|(_, ref_name)| ref_name.clone())
309 .or_else(|| requested_ref_name.clone());
310 let identity_url = response_identity_url(&input_url, matched_existing.as_ref());
311 let (org, repo) = extract_org_repo_from_url(identity_url)
312 .context("invalid input: failed to extract org/repo from URL")?;
313 let ref_key = effective_ref_name
314 .as_deref()
315 .map(encode_ref_key)
316 .transpose()?;
317
318 let ds = mgr
320 .load_desired_state()
321 .context("failed to load desired state")?
322 .ok_or_else(|| anyhow::anyhow!("not found: no repository configuration found"))?;
323 let mount_space = MountSpace::Reference {
324 org_path: org.clone(),
325 repo: repo.clone(),
326 ref_key: ref_key.clone(),
327 };
328 let mount_path = mount_space.relative_path(&ds.mount_dirs);
329 let mount_target = repo_root
330 .join(".thoughts-data")
331 .join(&mount_path)
332 .to_string_lossy()
333 .to_string();
334
335 let repo_mapping =
337 RepoMappingManager::new().context("failed to create repo mapping manager")?;
338 let pre_mapping = repo_mapping
339 .resolve_reference_url(&input_url, effective_ref_name.as_deref())
340 .ok()
341 .flatten()
342 .map(|p| p.to_string_lossy().to_string());
343
344 let mut config_updated = false;
346 let mut warnings: Vec<String> = Vec::new();
347 let description = description.and_then(|desc| {
348 let trimmed = desc.trim();
349 (!trimmed.is_empty()).then(|| trimmed.to_string())
350 });
351 if !already_existed {
352 if description.is_some() || requested_ref_name.is_some() {
353 cfg.references
354 .push(ReferenceEntry::WithMetadata(ReferenceMount {
355 remote: input_url.clone(),
356 description: description.clone(),
357 ref_name: requested_ref_name.clone(),
358 }));
359 } else {
360 cfg.references
361 .push(ReferenceEntry::Simple(input_url.clone()));
362 }
363
364 let ws = mgr
365 .save_v2_validated(&cfg)
366 .context("failed to save config")?;
367 warnings.extend(ws);
368 config_updated = true;
369 } else if description.is_some() || requested_ref_name.is_some() {
370 warnings.push(
371 "Reference already exists; metadata was not updated (use CLI to modify metadata)"
372 .to_string(),
373 );
374 }
375
376 if let Err(e) = update_active_mounts().await {
378 warnings.push(format!("Mount synchronization encountered an error: {e}"));
379 }
380
381 let repo_mapping_post =
383 RepoMappingManager::new().context("failed to create repo mapping manager")?;
384 let post_mapping = repo_mapping_post
385 .resolve_reference_url(&input_url, effective_ref_name.as_deref())
386 .ok()
387 .flatten()
388 .map(|p| p.to_string_lossy().to_string());
389 let cloned = pre_mapping.is_none() && post_mapping.is_some();
390
391 let platform = detect_platform().context("failed to detect platform")?;
393 let mount_manager = get_mount_manager(&platform).context("failed to get mount manager")?;
394 let active = mount_manager
395 .list_mounts()
396 .await
397 .context("failed to list mounts")?;
398 let target_path = std::path::PathBuf::from(&mount_target);
399 let target_canon = std::fs::canonicalize(&target_path).unwrap_or(target_path);
400 let mut mounted = false;
401 for mi in active {
402 let canon = std::fs::canonicalize(&mi.target).unwrap_or_else(|_| mi.target.clone());
403 if canon == target_canon {
404 mounted = true;
405 break;
406 }
407 }
408
409 if post_mapping.is_none() {
411 warnings.push(
412 "Repository was not cloned or mapped. It may be private or network unavailable. \
413 You can retry or run 'thoughts references sync' via CLI."
414 .to_string(),
415 );
416 }
417 if !mounted {
418 warnings.push(
419 "Mount is not active. You can retry or run 'thoughts mount update' via CLI."
420 .to_string(),
421 );
422 }
423
424 Ok(AddReferenceOk {
425 url: input_url,
426 ref_name: effective_ref_name,
427 org,
428 repo,
429 mount_path,
430 mount_target,
431 mapping_path: post_mapping,
432 already_existed,
433 config_updated,
434 cloned,
435 mounted,
436 warnings,
437 })
438}
439
440#[cfg(test)]
443mod tests {
444 use super::*;
445 use crate::config::MountDirsV2;
446 use crate::config::RepoConfigV2;
447 use crate::documents::ActiveDocuments;
448 use crate::documents::DocumentInfo;
449 use crate::documents::WriteDocumentOk;
450 use crate::utils::human_size;
451 use agentic_tools_core::fmt::TextFormat;
452 use agentic_tools_core::fmt::TextOptions;
453 use std::sync::atomic::AtomicBool;
454 use std::sync::atomic::Ordering;
455 use std::sync::mpsc;
456
457 fn sample_remote_ref(name: &str) -> RemoteRef {
458 RemoteRef {
459 name: name.to_string(),
460 oid: Some("abc123".to_string()),
461 peeled: None,
462 target: None,
463 }
464 }
465
466 #[test]
467 fn normalize_repo_ref_limit_defaults_and_validates() {
468 assert_eq!(normalize_repo_ref_limit(None).unwrap(), 100);
469 assert_eq!(normalize_repo_ref_limit(Some(1)).unwrap(), 1);
470 assert!(normalize_repo_ref_limit(Some(0)).is_err());
471 assert!(normalize_repo_ref_limit(Some(201)).is_err());
472 }
473
474 #[test]
475 fn test_human_size_formatting() {
476 assert_eq!(human_size(0), "0 B");
477 assert_eq!(human_size(1), "1 B");
478 assert_eq!(human_size(1023), "1023 B");
479 assert_eq!(human_size(1024), "1.0 KB");
480 assert_eq!(human_size(2048), "2.0 KB");
481 assert_eq!(human_size(1024 * 1024), "1.0 MB");
482 assert_eq!(human_size(2 * 1024 * 1024), "2.0 MB");
483 }
484
485 #[test]
486 fn test_write_document_ok_format() {
487 let ok = WriteDocumentOk {
488 path: "./thoughts/feat/research/a.md".into(),
489 bytes_written: 2048,
490 github_url: None,
491 };
492 let text = ok.fmt_text(&TextOptions::default());
493 assert!(text.contains("2.0 KB"));
494 assert!(text.contains("\u{2713} Created")); assert!(text.contains("./thoughts/feat/research/a.md"));
496 }
497
498 #[test]
499 fn test_active_documents_empty() {
500 let docs = ActiveDocuments {
501 base: "./thoughts/x".into(),
502 files: vec![],
503 };
504 let s = docs.fmt_text(&TextOptions::default());
505 assert!(s.contains("<none>"));
506 assert!(s.contains("./thoughts/x"));
507 }
508
509 #[test]
510 fn test_active_documents_with_files() {
511 let docs = ActiveDocuments {
512 base: "./thoughts/feature".into(),
513 files: vec![DocumentInfo {
514 path: "./thoughts/feature/research/test.md".into(),
515 doc_type: "research".into(),
516 size: 1024,
517 modified: "2025-10-15T12:00:00Z".into(),
518 }],
519 };
520 let text = docs.fmt_text(&TextOptions::default());
521 assert!(text.contains("research/test.md"));
522 assert!(text.contains("2025-10-15 12:00 UTC"));
523 }
524
525 #[test]
528 fn test_references_list_empty() {
529 let refs = ReferencesList {
530 base: "references".into(),
531 entries: vec![],
532 };
533 let s = refs.fmt_text(&TextOptions::default());
534 assert!(s.contains("<none>"));
535 assert!(s.contains("references"));
536 }
537
538 #[test]
539 fn test_references_list_without_descriptions() {
540 let refs = ReferencesList {
541 base: "references".into(),
542 entries: vec![
543 ReferenceItem {
544 path: "references/org/repo1".into(),
545 description: None,
546 },
547 ReferenceItem {
548 path: "references/org/repo2".into(),
549 description: None,
550 },
551 ],
552 };
553 let text = refs.fmt_text(&TextOptions::default());
554 assert!(text.contains("org/repo1"));
555 assert!(text.contains("org/repo2"));
556 assert!(!text.contains("\u{2014}")); }
558
559 #[test]
560 fn test_references_list_with_descriptions() {
561 let refs = ReferencesList {
562 base: "references".into(),
563 entries: vec![
564 ReferenceItem {
565 path: "references/org/repo1".into(),
566 description: Some("First repo".into()),
567 },
568 ReferenceItem {
569 path: "references/org/repo2".into(),
570 description: Some("Second repo".into()),
571 },
572 ],
573 };
574 let text = refs.fmt_text(&TextOptions::default());
575 assert!(text.contains("org/repo1 \u{2014} First repo")); assert!(text.contains("org/repo2 \u{2014} Second repo"));
577 }
578
579 #[test]
580 fn test_repo_ref_sorting_is_deterministic() {
581 let mut refs = [
582 sample_remote_ref("refs/tags/v2"),
583 sample_remote_ref("refs/heads/main"),
584 ];
585 refs.sort_by(|a, b| {
586 a.name
587 .cmp(&b.name)
588 .then_with(|| a.target.cmp(&b.target))
589 .then_with(|| a.oid.cmp(&b.oid))
590 .then_with(|| a.peeled.cmp(&b.peeled))
591 });
592 assert_eq!(refs[0].name, "refs/heads/main");
593 assert_eq!(refs[1].name, "refs/tags/v2");
594 }
595
596 #[tokio::test]
597 async fn get_repo_refs_rejects_invalid_limit_async() {
598 let err = get_repo_refs_impl_adapter("https://github.com/org/repo".into(), Some(0))
599 .await
600 .unwrap_err();
601 assert!(err.to_string().contains("limit must be at least 1"));
602 }
603
604 #[tokio::test]
605 async fn get_repo_refs_rejects_ssh_url_async() {
606 let err = get_repo_refs_impl_adapter("git@github.com:org/repo.git".into(), None)
607 .await
608 .unwrap_err();
609 assert!(
610 format!("{err:#}").to_lowercase().contains("ssh"),
611 "unexpected error chain: {err:#}"
612 );
613 }
614
615 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
616 async fn repo_refs_deadline_includes_semaphore_acquire_time() {
617 let sem = Arc::new(Semaphore::new(1));
618 let _held = Arc::clone(&sem).acquire_owned().await.unwrap();
619 let work_started = Arc::new(AtomicBool::new(false));
620 let started = Arc::clone(&work_started);
621
622 let err = run_blocking_repo_refs_with_deadline(
623 sem,
624 Duration::from_millis(10),
625 "test operation".to_string(),
626 move || {
627 started.store(true, Ordering::SeqCst);
628 Ok(())
629 },
630 )
631 .await
632 .unwrap_err();
633
634 assert!(err.to_string().contains("waiting to start test operation"));
635 assert!(!work_started.load(Ordering::SeqCst));
636 }
637
638 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
639 async fn repo_refs_timeout_retains_permit_until_blocking_work_finishes() {
640 let sem = Arc::new(Semaphore::new(1));
641 let (started_tx, started_rx) = mpsc::channel();
642 let (release_tx, release_rx) = mpsc::channel();
643 let (finished_tx, finished_rx) = mpsc::channel();
644
645 let timed_out = tokio::spawn(run_blocking_repo_refs_with_deadline(
646 Arc::clone(&sem),
647 Duration::from_millis(20),
648 "test operation".to_string(),
649 move || {
650 started_tx.send(()).unwrap();
651 release_rx.recv().unwrap();
652 finished_tx.send(()).unwrap();
653 Ok(())
654 },
655 ));
656
657 started_rx
658 .recv_timeout(Duration::from_secs(1))
659 .expect("blocking work should have started");
660
661 let err = timed_out.await.unwrap().unwrap_err();
662 assert!(err.to_string().contains("timeout while test operation"));
663 assert_eq!(sem.available_permits(), 0, "permit should still be held");
664
665 let blocked_err = run_blocking_repo_refs_with_deadline(
666 Arc::clone(&sem),
667 Duration::from_millis(10),
668 "follow-up operation".to_string(),
669 || Ok(()),
670 )
671 .await
672 .unwrap_err();
673 assert!(
674 blocked_err
675 .to_string()
676 .contains("waiting to start follow-up operation"),
677 "unexpected error: {blocked_err:#}"
678 );
679
680 release_tx.send(()).unwrap();
681 finished_rx
682 .recv_timeout(Duration::from_secs(1))
683 .expect("blocking work should finish after release");
684
685 for _ in 0..20 {
686 if sem.available_permits() == 1 {
687 break;
688 }
689 tokio::time::sleep(Duration::from_millis(10)).await;
690 }
691
692 assert_eq!(
693 sem.available_permits(),
694 1,
695 "permit should be released after blocking work completes"
696 );
697
698 run_blocking_repo_refs_with_deadline(
699 sem,
700 Duration::from_secs(1),
701 "final operation".to_string(),
702 || Ok(()),
703 )
704 .await
705 .expect("follow-up work should succeed once permit is released");
706 }
707
708 #[test]
709 fn test_repo_refs_list_format() {
710 let refs = RepoRefsList {
711 url: "https://github.com/org/repo".into(),
712 total: 2,
713 truncated: false,
714 entries: vec![
715 RemoteRef {
716 name: "refs/heads/main".into(),
717 oid: Some("abc123".into()),
718 peeled: None,
719 target: None,
720 },
721 RemoteRef {
722 name: "refs/tags/v1.0.0".into(),
723 oid: Some("def456".into()),
724 peeled: Some("fedcba".into()),
725 target: None,
726 },
727 ],
728 };
729
730 let text = refs.fmt_text(&TextOptions::default());
731 assert!(text.contains("Remote refs for https://github.com/org/repo"));
732 assert!(text.contains("refs/heads/main"));
733 assert!(text.contains("oid=abc123"));
734 assert!(text.contains("peeled=fedcba"));
735 }
736
737 #[test]
738 fn test_add_reference_ok_format() {
739 let ok = AddReferenceOk {
740 url: "https://github.com/org/repo".into(),
741 ref_name: Some("refs/heads/main".into()),
742 org: "org".into(),
743 repo: "repo".into(),
744 mount_path: "references/org/repo".into(),
745 mount_target: "/abs/.thoughts-data/references/org/repo".into(),
746 mapping_path: Some("/home/user/.thoughts/clones/repo".into()),
747 already_existed: false,
748 config_updated: true,
749 cloned: true,
750 mounted: true,
751 warnings: vec!["note".into()],
752 };
753 let s = ok.fmt_text(&TextOptions::default());
754 assert!(s.contains("\u{2713} Added reference")); assert!(s.contains("Org/Repo: org/repo"));
756 assert!(s.contains("Ref: refs/heads/main"));
757 assert!(s.contains("Cloned: true"));
758 assert!(s.contains("Mounted: true"));
759 assert!(s.contains("Warnings:\n- note"));
760 }
761
762 #[test]
763 fn test_add_reference_ok_format_already_existed() {
764 let ok = AddReferenceOk {
765 url: "https://github.com/org/repo".into(),
766 ref_name: None,
767 org: "org".into(),
768 repo: "repo".into(),
769 mount_path: "references/org/repo".into(),
770 mount_target: "/abs/.thoughts-data/references/org/repo".into(),
771 mapping_path: Some("/home/user/.thoughts/clones/repo".into()),
772 already_existed: true,
773 config_updated: false,
774 cloned: false,
775 mounted: true,
776 warnings: vec![],
777 };
778 let s = ok.fmt_text(&TextOptions::default());
779 assert!(s.contains("\u{2713} Reference already exists (idempotent)"));
780 assert!(s.contains("Config updated: false"));
781 assert!(!s.contains("Warnings:"));
782 }
783
784 #[test]
785 fn test_add_reference_ok_format_no_mapping() {
786 let ok = AddReferenceOk {
787 url: "https://github.com/org/repo".into(),
788 ref_name: None,
789 org: "org".into(),
790 repo: "repo".into(),
791 mount_path: "references/org/repo".into(),
792 mount_target: "/abs/.thoughts-data/references/org/repo".into(),
793 mapping_path: None,
794 already_existed: false,
795 config_updated: true,
796 cloned: false,
797 mounted: false,
798 warnings: vec!["Clone failed".into()],
799 };
800 let s = ok.fmt_text(&TextOptions::default());
801 assert!(s.contains("Mapping: <none>"));
802 assert!(s.contains("Mounted: false"));
803 assert!(s.contains("- Clone failed"));
804 }
805
806 #[tokio::test]
807 async fn add_reference_rejects_shorthand_ref_early() {
808 let err = add_reference_impl_adapter(
809 "https://github.com/org/repo".into(),
810 None,
811 Some("main".into()),
812 )
813 .await
814 .unwrap_err();
815
816 assert!(
817 err.to_string()
818 .contains("invalid input: ref must be a full ref name")
819 );
820 }
821
822 #[tokio::test]
823 async fn add_reference_rejects_refs_remotes_early() {
824 let err = add_reference_impl_adapter(
825 "https://github.com/org/repo".into(),
826 None,
827 Some("refs/remotes/origin/main".into()),
828 )
829 .await
830 .unwrap_err();
831
832 assert!(
833 err.to_string()
834 .contains("invalid input: ref must be a full ref name"),
835 "unexpected error: {err:#}"
836 );
837 assert!(
838 err.to_string().contains("refs/heads/main"),
839 "unexpected error: {err:#}"
840 );
841 }
842
843 #[tokio::test]
844 async fn add_reference_rejects_bare_heads_prefix_early() {
845 let err = add_reference_impl_adapter(
846 "https://github.com/org/repo".into(),
847 None,
848 Some("refs/heads/".into()),
849 )
850 .await
851 .unwrap_err();
852
853 assert!(
854 err.to_string()
855 .contains("invalid input: ref must be a full ref name")
856 );
857 }
858
859 #[tokio::test]
860 async fn add_reference_rejects_bare_tags_prefix_early() {
861 let err = add_reference_impl_adapter(
862 "https://github.com/org/repo".into(),
863 None,
864 Some("refs/tags/".into()),
865 )
866 .await
867 .unwrap_err();
868
869 assert!(
870 err.to_string()
871 .contains("invalid input: ref must be a full ref name")
872 );
873 }
874
875 #[test]
876 fn find_matching_existing_reference_returns_legacy_ref_name_when_equivalent() {
877 let cfg = RepoConfigV2 {
878 version: "2.0".into(),
879 mount_dirs: MountDirsV2::default(),
880 thoughts_mount: None,
881 context_mounts: vec![],
882 references: vec![ReferenceEntry::WithMetadata(ReferenceMount {
883 remote: "https://github.com/org/repo".into(),
884 description: None,
885 ref_name: Some("refs/remotes/origin/main".into()),
886 })],
887 };
888
889 let found = find_matching_existing_reference(
890 &cfg,
891 "https://github.com/org/repo",
892 Some("refs/heads/main"),
893 )
894 .expect("should match by canonical identity");
895
896 assert_eq!(found.0, "https://github.com/org/repo");
897 assert_eq!(found.1.as_deref(), Some("refs/remotes/origin/main"));
898 }
899
900 #[test]
901 fn idempotent_add_reference_response_uses_matched_stored_url_identity_for_paths() {
902 let input_url = "https://github.com/org/repo";
903 let stored_url = "https://github.com/Org/Repo";
904 let matched_existing = Some((stored_url.to_string(), None));
905
906 let identity_url = response_identity_url(input_url, matched_existing.as_ref());
907 assert_eq!(identity_url, stored_url);
908
909 let (org, repo) = extract_org_repo_from_url(identity_url).unwrap();
910 let mount_dirs = MountDirsV2::default();
911 let mount_space = MountSpace::Reference {
912 org_path: org.clone(),
913 repo: repo.clone(),
914 ref_key: None,
915 };
916
917 assert_eq!(org, "Org");
918 assert_eq!(repo, "Repo");
919 assert_eq!(
920 mount_space.relative_path(&mount_dirs),
921 format!("{}/{}/{}", mount_dirs.references, org, repo)
922 );
923 }
924
925 #[test]
926 fn test_template_response_format_research() {
927 let resp = TemplateResponse {
928 template_type: TemplateType::Research,
929 };
930 let s = resp.fmt_text(&TextOptions::default());
931 assert!(s.starts_with("Here is the research template:"));
932 assert!(s.contains("```markdown"));
933 assert!(s.contains("# Research: [Topic]"));
935 assert!(s.contains("Stop. Before writing this document"));
937 }
938
939 #[test]
940 fn test_template_variants_non_empty() {
941 let all = [
942 TemplateType::Research,
943 TemplateType::Plan,
944 TemplateType::Requirements,
945 TemplateType::PrDescription,
946 ];
947 for t in all {
948 assert!(
949 !t.content().trim().is_empty(),
950 "Embedded content unexpectedly empty for {t:?}"
951 );
952 assert!(
953 !t.label().trim().is_empty(),
954 "Label unexpectedly empty for {t:?}"
955 );
956 }
957 }
958}