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