metis-docs-core 1.2.0

Core library for Flight Levels documentation management system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
use crate::application::services::DatabaseService;
use crate::domain::documents::traits::Document;
use crate::domain::documents::types::DocumentType;
use crate::Result;
use crate::{Adr, Initiative, MetisError, Strategy, Task, Vision};
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// Service for discovering documents by ID across all document types
pub struct DocumentDiscoveryService {
    workspace_dir: PathBuf,
}

/// Result of document discovery
#[derive(Debug)]
pub struct DocumentDiscoveryResult {
    pub document_type: DocumentType,
    pub file_path: PathBuf,
}

impl DocumentDiscoveryService {
    /// Create a new document discovery service for a workspace
    pub fn new<P: AsRef<Path>>(workspace_dir: P) -> Self {
        let path = workspace_dir.as_ref();

        // Ensure we have an absolute path first
        let absolute_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()
                .map(|cwd| cwd.join(path))
                .unwrap_or_else(|_| path.to_path_buf())
        };

        // Then canonicalize to handle symlinks (e.g., /tmp vs /private/tmp)
        let workspace_dir = absolute_path
            .canonicalize()
            .unwrap_or(absolute_path);

        Self {
            workspace_dir,
        }
    }

    /// Find a document by its short code across all document types
    pub async fn find_document_by_short_code(
        &self,
        short_code: &str,
    ) -> Result<DocumentDiscoveryResult> {
        // Determine document type from short code format (e.g., PROJ-V-0001 -> Vision)
        let doc_type = self.document_type_from_short_code(short_code)?;
        let file_path = self.construct_path_from_short_code(short_code, doc_type)?;

        if file_path.exists() {
            Ok(DocumentDiscoveryResult {
                document_type: doc_type,
                file_path,
            })
        } else {
            Err(MetisError::NotFound(format!(
                "Document with short code '{}' not found at path: {}",
                short_code,
                file_path.display()
            )))
        }
    }

    /// Find a document by its ID across all document types (legacy method)
    pub async fn find_document_by_id(&self, document_id: &str) -> Result<DocumentDiscoveryResult> {
        // Try each document type in order
        for doc_type in [
            DocumentType::Vision,
            DocumentType::Strategy,
            DocumentType::Initiative,
            DocumentType::Task,
            DocumentType::Adr,
        ] {
            if let Ok(file_path) = self.find_document_of_type(document_id, doc_type).await {
                return Ok(DocumentDiscoveryResult {
                    document_type: doc_type,
                    file_path,
                });
            }
        }

        Err(MetisError::NotFound(format!(
            "Document '{}' not found in workspace",
            document_id
        )))
    }

    /// Find a document by its ID within a specific document type
    pub async fn find_document_of_type(
        &self,
        document_id: &str,
        doc_type: DocumentType,
    ) -> Result<PathBuf> {
        match doc_type {
            DocumentType::Vision => {
                let file_path = self.workspace_dir.join("vision.md");
                if file_path.exists() {
                    let vision = Vision::from_file(&file_path)
                        .await
                        .map_err(|e| MetisError::InvalidDocument(e.to_string()))?;
                    if vision.id().to_string() == document_id {
                        return Ok(file_path);
                    }
                }
                Err(MetisError::NotFound(
                    "Vision document not found".to_string(),
                ))
            }

            DocumentType::Strategy => {
                let strategies_dir = self.workspace_dir.join("strategies");
                if !strategies_dir.exists() {
                    return Err(MetisError::NotFound(
                        "No strategies directory found".to_string(),
                    ));
                }

                for entry in fs::read_dir(&strategies_dir)
                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                {
                    let strategy_dir = entry
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                        .path();
                    if !strategy_dir.is_dir() {
                        continue;
                    }

                    let file_path = strategy_dir.join("strategy.md");
                    if file_path.exists() {
                        let strategy = Strategy::from_file(&file_path)
                            .await
                            .map_err(|e| MetisError::InvalidDocument(e.to_string()))?;
                        if strategy.id().to_string() == document_id {
                            return Ok(file_path);
                        }
                    }
                }
                Err(MetisError::NotFound(
                    "Strategy document not found".to_string(),
                ))
            }

            DocumentType::Initiative => {
                let strategies_dir = self.workspace_dir.join("strategies");
                if !strategies_dir.exists() {
                    return Err(MetisError::NotFound(
                        "No strategies directory found".to_string(),
                    ));
                }

                for strategy_entry in fs::read_dir(&strategies_dir)
                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                {
                    let strategy_dir = strategy_entry
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                        .path();
                    if !strategy_dir.is_dir() {
                        continue;
                    }

                    let initiatives_dir = strategy_dir.join("initiatives");
                    if !initiatives_dir.exists() {
                        continue;
                    }

                    for initiative_entry in fs::read_dir(&initiatives_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let initiative_dir = initiative_entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if !initiative_dir.is_dir() {
                            continue;
                        }

                        let file_path = initiative_dir.join("initiative.md");
                        if file_path.exists() {
                            let initiative = Initiative::from_file(&file_path)
                                .await
                                .map_err(|e| MetisError::InvalidDocument(e.to_string()))?;
                            if initiative.id().to_string() == document_id {
                                return Ok(file_path);
                            }
                        }
                    }
                }

                Err(MetisError::NotFound(
                    "Initiative document not found".to_string(),
                ))
            }

            DocumentType::Task => {
                // First check backlog directory for backlog tasks
                let backlog_dir = self.workspace_dir.join("backlog");
                if backlog_dir.exists() {
                    for entry in fs::read_dir(&backlog_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let task_path = entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if task_path.is_file()
                            && task_path.extension().is_some_and(|ext| ext == "md")
                        {
                            if let Ok(task) = Task::from_file(&task_path).await {
                                if task.id().to_string() == document_id {
                                    return Ok(task_path);
                                }
                            }
                        }
                    }
                }

                // Then check strategies directory for assigned tasks
                let strategies_dir = self.workspace_dir.join("strategies");
                if strategies_dir.exists() {
                    for strategy_entry in fs::read_dir(&strategies_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let strategy_dir = strategy_entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if !strategy_dir.is_dir() {
                            continue;
                        }

                        let initiatives_dir = strategy_dir.join("initiatives");
                        if !initiatives_dir.exists() {
                            continue;
                        }

                        for initiative_entry in fs::read_dir(&initiatives_dir)
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                        {
                            let initiative_dir = initiative_entry
                                .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                .path();
                            if !initiative_dir.is_dir() {
                                continue;
                            }

                            // Look for task files in the tasks subdirectory (NULL-based structure)
                            let tasks_dir = initiative_dir.join("tasks");
                            if !tasks_dir.exists() {
                                continue;
                            }

                            for task_entry in fs::read_dir(&tasks_dir)
                                .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            {
                                let task_path = task_entry
                                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                    .path();
                                if task_path.is_file()
                                    && task_path.extension().is_some_and(|ext| ext == "md")
                                {
                                    if let Ok(task) = Task::from_file(&task_path).await {
                                        if task.id().to_string() == document_id {
                                            return Ok(task_path);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Also check for direct configuration tasks (strategies/NULL/initiatives/NULL/tasks/)
                let direct_tasks_dir = self
                    .workspace_dir
                    .join("strategies")
                    .join("NULL")
                    .join("initiatives")
                    .join("NULL")
                    .join("tasks");

                if direct_tasks_dir.exists() {
                    for task_entry in fs::read_dir(&direct_tasks_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let task_path = task_entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if task_path.is_file()
                            && task_path.extension().is_some_and(|ext| ext == "md")
                        {
                            if let Ok(task) = Task::from_file(&task_path).await {
                                if task.id().to_string() == document_id {
                                    return Ok(task_path);
                                }
                            }
                        }
                    }
                }

                Err(MetisError::NotFound("Task document not found".to_string()))
            }

            DocumentType::Adr => {
                let adrs_dir = self.workspace_dir.join("adrs");
                if !adrs_dir.exists() {
                    return Err(MetisError::NotFound("No ADRs directory found".to_string()));
                }

                for entry in
                    fs::read_dir(&adrs_dir).map_err(|e| MetisError::FileSystem(e.to_string()))?
                {
                    let adr_path = entry
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                        .path();
                    if adr_path.is_file() && adr_path.extension().is_some_and(|ext| ext == "md") {
                        if let Ok(adr) = Adr::from_file(&adr_path).await {
                            if adr.id().to_string() == document_id {
                                return Ok(adr_path);
                            }
                        }
                    }
                }
                Err(MetisError::NotFound("ADR document not found".to_string()))
            }
        }
    }

    /// Find a document by its ID with a specific document type constraint
    pub async fn find_document_by_id_and_type(
        &self,
        document_id: &str,
        doc_type: DocumentType,
    ) -> Result<PathBuf> {
        self.find_document_of_type(document_id, doc_type).await
    }

    /// Check if a document with the given ID exists
    pub async fn document_exists(&self, document_id: &str) -> bool {
        self.find_document_by_id(document_id).await.is_ok()
    }

    /// Get all documents of a specific type
    pub async fn find_all_documents_of_type(&self, doc_type: DocumentType) -> Result<Vec<PathBuf>> {
        let mut documents = Vec::new();

        match doc_type {
            DocumentType::Vision => {
                let file_path = self.workspace_dir.join("vision.md");
                if file_path.exists() {
                    documents.push(file_path);
                }
            }

            DocumentType::Strategy => {
                let strategies_dir = self.workspace_dir.join("strategies");
                if strategies_dir.exists() {
                    for entry in fs::read_dir(&strategies_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let strategy_dir = entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if strategy_dir.is_dir() {
                            let file_path = strategy_dir.join("strategy.md");
                            if file_path.exists() {
                                documents.push(file_path);
                            }
                        }
                    }
                }
            }

            DocumentType::Initiative => {
                let strategies_dir = self.workspace_dir.join("strategies");
                if strategies_dir.exists() {
                    for strategy_entry in fs::read_dir(&strategies_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let strategy_dir = strategy_entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if !strategy_dir.is_dir() {
                            continue;
                        }

                        let initiatives_dir = strategy_dir.join("initiatives");
                        if initiatives_dir.exists() {
                            for initiative_entry in fs::read_dir(&initiatives_dir)
                                .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            {
                                let initiative_dir = initiative_entry
                                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                    .path();
                                if initiative_dir.is_dir() {
                                    let file_path = initiative_dir.join("initiative.md");
                                    if file_path.exists() {
                                        documents.push(file_path);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            DocumentType::Task => {
                let strategies_dir = self.workspace_dir.join("strategies");
                if strategies_dir.exists() {
                    for strategy_entry in fs::read_dir(&strategies_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let strategy_dir = strategy_entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if !strategy_dir.is_dir() {
                            continue;
                        }

                        let initiatives_dir = strategy_dir.join("initiatives");
                        if initiatives_dir.exists() {
                            for initiative_entry in fs::read_dir(&initiatives_dir)
                                .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            {
                                let initiative_dir = initiative_entry
                                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                    .path();
                                if !initiative_dir.is_dir() {
                                    continue;
                                }

                                for task_entry in fs::read_dir(&initiative_dir)
                                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                {
                                    let task_path = task_entry
                                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                                        .path();
                                    if task_path.is_file()
                                        && task_path.extension().is_some_and(|ext| ext == "md")
                                    {
                                        if task_path
                                            .file_name()
                                            .is_some_and(|name| name == "initiative.md")
                                        {
                                            continue;
                                        }
                                        documents.push(task_path);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            DocumentType::Adr => {
                let adrs_dir = self.workspace_dir.join("adrs");
                if adrs_dir.exists() {
                    for entry in fs::read_dir(&adrs_dir)
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    {
                        let adr_path = entry
                            .map_err(|e| MetisError::FileSystem(e.to_string()))?
                            .path();
                        if adr_path.is_file() && adr_path.extension().is_some_and(|ext| ext == "md")
                        {
                            documents.push(adr_path);
                        }
                    }
                }
            }
        }

        Ok(documents)
    }

    /// Find all documents in a strategy hierarchy using database lineage queries
    /// This is more efficient than filesystem-based discovery for large hierarchies
    pub async fn find_strategy_hierarchy_with_database(
        &self,
        strategy_id: &str,
        db_service: &mut DatabaseService,
    ) -> Result<Vec<DocumentDiscoveryResult>> {
        let hierarchy_docs = db_service.find_strategy_hierarchy(strategy_id)?;
        let mut results = Vec::new();

        for doc in hierarchy_docs {
            if let Ok(doc_type) = DocumentType::from_str(&doc.document_type) {
                // Convert relative path from DB to absolute path
                let absolute_path = self.workspace_dir.join(&doc.filepath);
                results.push(DocumentDiscoveryResult {
                    document_type: doc_type,
                    file_path: absolute_path,
                });
            }
        }

        Ok(results)
    }

    /// Find all documents in an initiative hierarchy using database lineage queries
    /// This is more efficient than filesystem-based discovery for large hierarchies
    pub async fn find_initiative_hierarchy_with_database(
        &self,
        initiative_id: &str,
        db_service: &mut DatabaseService,
    ) -> Result<Vec<DocumentDiscoveryResult>> {
        let hierarchy_docs = db_service.find_initiative_hierarchy(initiative_id)?;
        let mut results = Vec::new();

        for doc in hierarchy_docs {
            if let Ok(doc_type) = DocumentType::from_str(&doc.document_type) {
                // Convert relative path from DB to absolute path
                let absolute_path = self.workspace_dir.join(&doc.filepath);
                results.push(DocumentDiscoveryResult {
                    document_type: doc_type,
                    file_path: absolute_path,
                });
            }
        }

        Ok(results)
    }

    /// Find all documents belonging to a strategy using database lineage queries
    pub async fn find_documents_by_strategy_with_database(
        &self,
        strategy_id: &str,
        db_service: &mut DatabaseService,
    ) -> Result<Vec<DocumentDiscoveryResult>> {
        let docs = db_service.find_by_strategy_id(strategy_id)?;
        let mut results = Vec::new();

        for doc in docs {
            if let Ok(doc_type) = DocumentType::from_str(&doc.document_type) {
                // Convert relative path from DB to absolute path
                let absolute_path = self.workspace_dir.join(&doc.filepath);
                results.push(DocumentDiscoveryResult {
                    document_type: doc_type,
                    file_path: absolute_path,
                });
            }
        }

        Ok(results)
    }

    /// Find all documents belonging to an initiative using database lineage queries
    pub async fn find_documents_by_initiative_with_database(
        &self,
        initiative_id: &str,
        db_service: &mut DatabaseService,
    ) -> Result<Vec<DocumentDiscoveryResult>> {
        let docs = db_service.find_by_initiative_id(initiative_id)?;
        let mut results = Vec::new();

        for doc in docs {
            if let Ok(doc_type) = DocumentType::from_str(&doc.document_type) {
                // Convert relative path from DB to absolute path
                let absolute_path = self.workspace_dir.join(&doc.filepath);
                results.push(DocumentDiscoveryResult {
                    document_type: doc_type,
                    file_path: absolute_path,
                });
            }
        }

        Ok(results)
    }

    /// Fast document lookup using database instead of filesystem scanning
    /// This is more efficient when the database is synchronized
    pub async fn find_document_by_id_with_database(
        &self,
        document_id: &str,
        db_service: &mut DatabaseService,
    ) -> Result<DocumentDiscoveryResult> {
        let doc = db_service
            .find_by_id(document_id)?
            .ok_or_else(|| MetisError::NotFound(format!("Document '{}' not found", document_id)))?;

        let doc_type = DocumentType::from_str(&doc.document_type).map_err(|e| {
            MetisError::ValidationFailed {
                message: format!("Invalid document type: {}", e),
            }
        })?;

        // Convert relative path from DB to absolute path
        let absolute_path = self.workspace_dir.join(&doc.filepath);

        Ok(DocumentDiscoveryResult {
            document_type: doc_type,
            file_path: absolute_path,
        })
    }

    /// Extract document type from short code format (e.g., PROJ-V-0001 -> Vision)
    fn document_type_from_short_code(&self, short_code: &str) -> Result<DocumentType> {
        let parts: Vec<&str> = short_code.split('-').collect();
        if parts.len() != 3 {
            return Err(MetisError::ValidationFailed {
                message: format!(
                    "Invalid short code format: '{}'. Expected format: PREFIX-TYPE-NNNN",
                    short_code
                ),
            });
        }

        match parts[1] {
            "V" => Ok(DocumentType::Vision),
            "S" => Ok(DocumentType::Strategy),
            "I" => Ok(DocumentType::Initiative),
            "T" => Ok(DocumentType::Task),
            "A" => Ok(DocumentType::Adr),
            _ => Err(MetisError::ValidationFailed {
                message: format!(
                    "Unknown document type code: '{}' in short code '{}'",
                    parts[1], short_code
                ),
            }),
        }
    }

    /// Construct file path from short code and document type
    fn construct_path_from_short_code(
        &self,
        short_code: &str,
        doc_type: DocumentType,
    ) -> Result<PathBuf> {
        match doc_type {
            DocumentType::Vision => Ok(self.workspace_dir.join("vision.md")),
            DocumentType::Strategy => Ok(self
                .workspace_dir
                .join("strategies")
                .join(short_code)
                .join("strategy.md")),
            DocumentType::Initiative => {
                // For initiatives, we need to find via database lookup
                // Fall back to filesystem search if database is not available
                self.find_initiative_path_by_short_code(short_code)
            }
            DocumentType::Task => {
                // For tasks, we need to find via database lookup
                // Fall back to filesystem search if database is not available
                self.find_task_path_by_short_code(short_code)
            }
            DocumentType::Adr => Ok(self
                .workspace_dir
                .join("adrs")
                .join(format!("{}.md", short_code))),
        }
    }

    /// Find initiative path by short code using database lookup
    fn find_initiative_path_by_short_code(&self, short_code: &str) -> Result<PathBuf> {
        // Try database lookup first
        let db_path = self.workspace_dir.join("metis.db");
        if db_path.exists() {
            if let Ok(db) = crate::Database::new(&db_path.to_string_lossy()) {
                if let Ok(mut repo) = db.repository() {
                    if let Ok(Some(doc)) = repo.find_by_short_code(short_code) {
                        if let Some(strategy_id) = &doc.strategy_id {
                            // Find strategy short code from strategy ID
                            if let Ok(Some(strategy_doc)) = repo.find_by_id(strategy_id) {
                                return Ok(self
                                    .workspace_dir
                                    .join("strategies")
                                    .join(&strategy_doc.short_code)
                                    .join("initiatives")
                                    .join(short_code)
                                    .join("initiative.md"));
                            }
                        }
                    }
                }
            }
        }

        // Fall back to filesystem search
        let strategies_dir = self.workspace_dir.join("strategies");
        if !strategies_dir.exists() {
            return Err(MetisError::NotFound(format!(
                "Initiative '{}' not found - no strategies directory",
                short_code
            )));
        }

        for strategy_entry in
            fs::read_dir(&strategies_dir).map_err(|e| MetisError::FileSystem(e.to_string()))?
        {
            let strategy_dir = strategy_entry
                .map_err(|e| MetisError::FileSystem(e.to_string()))?
                .path();
            if !strategy_dir.is_dir() {
                continue;
            }

            let initiative_path = strategy_dir
                .join("initiatives")
                .join(short_code)
                .join("initiative.md");

            if initiative_path.exists() {
                return Ok(initiative_path);
            }
        }

        Err(MetisError::NotFound(format!(
            "Initiative '{}' not found in any strategy",
            short_code
        )))
    }

    /// Find task path by short code using database lookup
    fn find_task_path_by_short_code(&self, short_code: &str) -> Result<PathBuf> {
        // Try database lookup first
        let db_path = self.workspace_dir.join("metis.db");
        if db_path.exists() {
            if let Ok(db) = crate::Database::new(&db_path.to_string_lossy()) {
                if let Ok(mut repo) = db.repository() {
                    if let Ok(Some(doc)) = repo.find_by_short_code(short_code) {
                        // Convert relative path from DB to absolute path
                        return Ok(self.workspace_dir.join(&doc.filepath));
                    }
                }
            }
        }

        // Fall back to filesystem search - check backlog first
        let backlog_path = self
            .workspace_dir
            .join("backlog")
            .join(format!("{}.md", short_code));
        if backlog_path.exists() {
            return Ok(backlog_path);
        }

        // Then check initiative hierarchy
        let strategies_dir = self.workspace_dir.join("strategies");
        if strategies_dir.exists() {
            for strategy_entry in
                fs::read_dir(&strategies_dir).map_err(|e| MetisError::FileSystem(e.to_string()))?
            {
                let strategy_dir = strategy_entry
                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                    .path();
                if !strategy_dir.is_dir() {
                    continue;
                }

                let initiatives_dir = strategy_dir.join("initiatives");
                if !initiatives_dir.exists() {
                    continue;
                }

                for initiative_entry in fs::read_dir(&initiatives_dir)
                    .map_err(|e| MetisError::FileSystem(e.to_string()))?
                {
                    let initiative_dir = initiative_entry
                        .map_err(|e| MetisError::FileSystem(e.to_string()))?
                        .path();
                    if !initiative_dir.is_dir() {
                        continue;
                    }

                    let task_path = initiative_dir
                        .join("tasks")
                        .join(format!("{}.md", short_code));

                    if task_path.exists() {
                        return Ok(task_path);
                    }
                }
            }
        }

        Err(MetisError::NotFound(format!(
            "Task '{}' not found",
            short_code
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_find_vision_document() {
        let temp_dir = tempdir().unwrap();
        let workspace_dir = temp_dir.path().join(".metis");
        fs::create_dir_all(&workspace_dir).unwrap();

        // Create a simple vision document
        let vision_content = r##"---
id: test-vision
title: Test Vision
level: vision
created_at: 2023-01-01T00:00:00Z
updated_at: 2023-01-01T00:00:00Z
archived: false
short_code: TEST-V-9004
tags:
  - "#vision"
  - "#phase/draft"
exit_criteria_met: false
---

# Test Vision

This is a test vision document.
"##;
        fs::write(workspace_dir.join("vision.md"), vision_content).unwrap();

        let service = DocumentDiscoveryService::new(&workspace_dir);
        let result = service.find_document_by_id("test-vision").await.unwrap();

        assert_eq!(result.document_type, DocumentType::Vision);
        // Canonicalize expected path to match the service's canonical workspace_dir
        let expected_path = workspace_dir.canonicalize().unwrap().join("vision.md");
        assert_eq!(result.file_path, expected_path);
    }

    #[tokio::test]
    async fn test_document_not_found() {
        let temp_dir = tempdir().unwrap();
        let workspace_dir = temp_dir.path().join(".metis");
        fs::create_dir_all(&workspace_dir).unwrap();

        let service = DocumentDiscoveryService::new(&workspace_dir);
        let result = service.find_document_by_id("nonexistent-doc").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), MetisError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_find_all_documents_of_type() {
        let temp_dir = tempdir().unwrap();
        let workspace_dir = temp_dir.path().join(".metis");
        let adrs_dir = workspace_dir.join("adrs");
        fs::create_dir_all(&adrs_dir).unwrap();

        // Create multiple ADR documents
        let adr_content = r##"---
id: test-adr-1
title: Test ADR
level: adr
created_at: 2023-01-01T00:00:00Z
updated_at: 2023-01-01T00:00:00Z
archived: false
number: 1
slug: test-adr
tags:
  - "#adr"
  - "#phase/draft"
exit_criteria_met: false
---

# Test ADR

This is a test ADR document.
"##;
        fs::write(adrs_dir.join("001-test-adr.md"), adr_content).unwrap();
        fs::write(
            adrs_dir.join("002-another-adr.md"),
            adr_content.replace("test-adr-1", "test-adr-2"),
        )
        .unwrap();

        let service = DocumentDiscoveryService::new(&workspace_dir);
        let documents = service
            .find_all_documents_of_type(DocumentType::Adr)
            .await
            .unwrap();

        assert_eq!(documents.len(), 2);
    }
}