prompthive 0.2.8

Open source prompt manager for developers. Terminal-native, sub-15ms operations, works with any AI tool.
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
use crate::storage::{PromptMetadata, Storage};
use anyhow::{Context, Result};
use regex::Regex;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;

pub struct Importer {
    storage: Storage,
}

impl Importer {
    pub fn new(storage: Storage) -> Self {
        Self { storage }
    }

    /// Import prompts from a directory or file
    pub fn import_from_path(&self, path: &str) -> Result<ImportResult> {
        let path = Path::new(path);

        if !path.exists() {
            return Err(anyhow::anyhow!("Path does not exist: {}", path.display()));
        }

        let mut result = ImportResult::new();

        if path.is_file() {
            self.import_file(path, &mut result)?;
        } else if path.is_dir() {
            self.import_directory(path, &mut result)?;
        }

        Ok(result)
    }

    /// Enhanced import with custom naming, force overwrite, versioning, skip, and update support
    pub fn import_from_path_enhanced(
        &self,
        path: &str,
        custom_name: Option<&str>,
        force: bool,
        version: bool,
        skip: bool,
        update: bool,
    ) -> Result<ImportResult> {
        let path = Path::new(path);

        if !path.exists() {
            return Err(anyhow::anyhow!("Path does not exist: {}", path.display()));
        }

        let mut result = ImportResult::new();

        if path.is_file() {
            self.import_file_enhanced(
                path,
                custom_name,
                force,
                version,
                skip,
                update,
                &mut result,
            )?;
        } else if path.is_dir() {
            self.import_directory_enhanced(
                path,
                custom_name,
                force,
                version,
                skip,
                update,
                &mut result,
            )?;
        }

        Ok(result)
    }

    /// Import from Claude Code session files
    pub fn import_claude_session(&self, session_path: &str) -> Result<ImportResult> {
        let path = Path::new(session_path);
        let mut result = ImportResult::new();

        // Look for .md files that look like prompts
        for entry in WalkDir::new(path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("md"))
        {
            if self.looks_like_prompt(entry.path())? {
                self.import_file(entry.path(), &mut result)?;
            }
        }

        Ok(result)
    }

    fn import_file(&self, file_path: &Path, result: &mut ImportResult) -> Result<()> {
        let content = fs::read_to_string(file_path)
            .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

        // Extract filename as prompt name
        let name = file_path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| anyhow::anyhow!("Invalid filename: {}", file_path.display()))?;

        // Clean up name for prompt use
        let clean_name = self.clean_prompt_name(name);

        // Parse content
        let (metadata, body) = self.parse_content(&content, &clean_name, false)?;

        // Check if prompt already exists
        if self.storage.prompt_path(&clean_name).exists() {
            result.add_skipped(&clean_name, "Already exists");
            return Ok(());
        }

        // Write prompt
        self.storage.write_prompt(&clean_name, &metadata, &body)?;
        result.add_imported(&clean_name);

        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn import_file_enhanced(
        &self,
        file_path: &Path,
        custom_name: Option<&str>,
        force: bool,
        version: bool,
        skip: bool,
        update: bool,
        result: &mut ImportResult,
    ) -> Result<()> {
        let content = fs::read_to_string(file_path)
            .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

        // Determine prompt name
        let prompt_name = if let Some(name) = custom_name {
            // Use custom name (Gap 1 fix)
            self.clean_prompt_name(name)
        } else {
            // Extract filename as prompt name (original behavior)
            let name = file_path
                .file_stem()
                .and_then(|s| s.to_str())
                .ok_or_else(|| anyhow::anyhow!("Invalid filename: {}", file_path.display()))?;
            self.clean_prompt_name(name)
        };

        // Handle versioning
        let final_name = if version {
            self.find_next_version_name(&prompt_name)
        } else {
            prompt_name
        };

        // Parse content
        let (metadata, body) = self.parse_content(&content, &final_name, version)?;

        // Check if prompt already exists with enhanced conflict resolution
        let prompt_path = self.storage.prompt_path(&final_name);
        if prompt_path.exists() {
            if skip {
                result.add_skipped(&final_name, "Skipped (already exists)");
                return Ok(());
            } else if update {
                // Check if source is newer than target
                let source_modified = fs::metadata(file_path)?.modified()?;
                let target_modified = fs::metadata(&prompt_path)?.modified()?;

                if source_modified <= target_modified {
                    result.add_skipped(&final_name, "Skipped (target is newer or same)");
                    return Ok(());
                }
                // Continue with update since source is newer
            } else if !force {
                result.add_skipped(&final_name, "Already exists");
                return Ok(());
            }
        }

        // Write prompt (will overwrite if force=true)
        self.storage.write_prompt(&final_name, &metadata, &body)?;
        result.add_imported(&final_name);

        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn import_directory_enhanced(
        &self,
        dir_path: &Path,
        custom_name: Option<&str>,
        force: bool,
        version: bool,
        skip: bool,
        update: bool,
        result: &mut ImportResult,
    ) -> Result<()> {
        // Check if this is a bank directory (contains bank.yaml or looks like a bank)
        let bank_yaml = dir_path.join("bank.yaml");
        let is_bank = bank_yaml.exists()
            || dir_path.starts_with("banks/")
            || (dir_path.parent().is_some_and(|p| p.ends_with("banks")));

        if is_bank {
            // Import as a bank - preserve structure
            let bank_name = custom_name.unwrap_or_else(|| {
                dir_path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or("imported-bank")
            });

            self.import_bank(dir_path, bank_name, force, skip, update, result)?;
        } else {
            // Regular directory import - flatten structure
            for entry in WalkDir::new(dir_path)
                .into_iter()
                .filter_map(|e| e.ok())
                .filter(|e| e.file_type().is_file())
            {
                let path = entry.path();

                // Skip hidden files and non-text files
                if path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .is_none_or(|s| s.starts_with('.'))
                {
                    continue;
                }

                // Only import text-like files
                if self.is_text_file(path)? {
                    if let Err(e) =
                        self.import_file_enhanced(path, None, force, version, skip, update, result)
                    {
                        result.add_error(path.to_string_lossy().to_string(), e.to_string());
                    }
                }
            }
        }

        Ok(())
    }

    fn import_directory(&self, dir_path: &Path, result: &mut ImportResult) -> Result<()> {
        for entry in WalkDir::new(dir_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
        {
            let path = entry.path();

            // Skip hidden files and non-text files
            if path
                .file_name()
                .and_then(|s| s.to_str())
                .is_none_or(|s| s.starts_with('.'))
            {
                continue;
            }

            // Only import text-like files
            if self.is_text_file(path)? {
                if let Err(e) = self.import_file(path, result) {
                    result.add_error(path.to_string_lossy().to_string(), e.to_string());
                }
            }
        }

        Ok(())
    }

    fn parse_content(
        &self,
        content: &str,
        name: &str,
        version_flag: bool,
    ) -> Result<(PromptMetadata, String)> {
        // Try to parse existing frontmatter
        if content.starts_with("---") {
            return self.storage.parse_prompt_content(content);
        }

        // Auto-generate metadata for files without frontmatter
        let description = self
            .extract_description(content)
            .unwrap_or_else(|| format!("Imported from {}", name));

        let metadata = PromptMetadata {
            id: name.to_string(),
            description,
            tags: Some(vec!["imported".to_string()]),
            created_at: Some(chrono::Utc::now().to_rfc3339()),
            updated_at: None,
            version: if version_flag {
                Some("v1.0".to_string())
            } else {
                None
            },
            git_hash: None,
            parent_version: None,
        };

        Ok((metadata, content.to_string()))
    }

    fn extract_description(&self, content: &str) -> Option<String> {
        let lines: Vec<&str> = content.lines().collect();

        // Look for first line that looks like a title or description
        for line in lines.iter().take(10) {
            let line = line.trim();

            // Skip empty lines
            if line.is_empty() {
                continue;
            }

            // If it starts with #, use as title
            if line.starts_with('#') {
                return Some(line.trim_start_matches('#').trim().to_string());
            }

            // If it's a reasonable length and looks descriptive
            if line.len() > 10 && line.len() < 100 && !line.starts_with("```") {
                return Some(line.to_string());
            }
        }

        None
    }

    fn clean_prompt_name(&self, name: &str) -> String {
        // Replace spaces and special chars with hyphens
        let re = Regex::new(r"[^a-zA-Z0-9\-_]").unwrap();
        let cleaned = re.replace_all(name, "-");

        // Remove multiple consecutive hyphens
        let re = Regex::new(r"-+").unwrap();
        let cleaned = re.replace_all(&cleaned, "-");

        // Trim hyphens from start/end
        cleaned.trim_matches('-').to_lowercase()
    }

    fn find_next_version_name(&self, base_name: &str) -> String {
        // Check if base name exists
        if !self.storage.prompt_path(base_name).exists() {
            return base_name.to_string();
        }

        // Find next available version (file-v2, file-v3, etc.)
        let mut version = 2;
        loop {
            let versioned_name = format!("{}-v{}", base_name, version);
            if !self.storage.prompt_path(&versioned_name).exists() {
                return versioned_name;
            }
            version += 1;

            // Safety check to prevent infinite loop
            if version > 1000 {
                return format!("{}-v{}", base_name, chrono::Utc::now().timestamp());
            }
        }
    }

    /// Import an entire bank preserving structure
    fn import_bank(
        &self,
        bank_path: &Path,
        bank_name: &str,
        force: bool,
        skip: bool,
        update: bool,
        result: &mut ImportResult,
    ) -> Result<()> {
        // Ensure bank directory exists in storage
        let target_bank_dir = self.storage.base_dir().join("banks").join(bank_name);
        fs::create_dir_all(&target_bank_dir)?;

        // Copy bank.yaml if it exists
        let bank_yaml_src = bank_path.join("bank.yaml");
        if bank_yaml_src.exists() {
            let bank_yaml_dest = target_bank_dir.join("bank.yaml");
            fs::copy(&bank_yaml_src, &bank_yaml_dest)?;
        }

        // Copy README.md if it exists
        let readme_src = bank_path.join("README.md");
        if readme_src.exists() {
            let readme_dest = target_bank_dir.join("README.md");
            fs::copy(&readme_src, &readme_dest)?;
        }

        // Import all markdown files in the bank
        for entry in fs::read_dir(bank_path)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("md") {
                if let Some(file_name) = path.file_stem().and_then(|s| s.to_str()) {
                    // Skip README
                    if file_name.eq_ignore_ascii_case("readme") {
                        continue;
                    }

                    let prompt_name = format!("{}/{}", bank_name, file_name);

                    // Check if prompt already exists with enhanced conflict resolution
                    let prompt_path = self.storage.prompt_path(&prompt_name);
                    if prompt_path.exists() {
                        if skip {
                            result.add_skipped(&prompt_name, "Skipped (already exists)");
                            continue;
                        } else if update {
                            // Check if source is newer than target
                            let source_modified = fs::metadata(&path)?.modified()?;
                            let target_modified = fs::metadata(&prompt_path)?.modified()?;

                            if source_modified <= target_modified {
                                result
                                    .add_skipped(&prompt_name, "Skipped (target is newer or same)");
                                continue;
                            }
                            // Continue with update since source is newer
                        } else if !force {
                            result.add_skipped(&prompt_name, "Already exists");
                            continue;
                        }
                    }

                    // Read and parse the prompt
                    let content = fs::read_to_string(&path)?;
                    let (metadata, body) = self.parse_content(&content, file_name, false)?;

                    // Write prompt with bank prefix
                    self.storage.write_prompt(&prompt_name, &metadata, &body)?;
                    result.add_imported(&prompt_name);
                }
            } else if path.is_dir() {
                // Handle subdirectories (like static/ and dynamic/ in snippets bank)
                let subdir_name = path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or("subdir");
                let subdir_target = target_bank_dir.join(subdir_name);
                fs::create_dir_all(&subdir_target)?;

                // Import files from subdirectory
                for subentry in fs::read_dir(&path)? {
                    let subentry = subentry?;
                    let subpath = subentry.path();

                    if subpath.is_file()
                        && subpath.extension().and_then(|s| s.to_str()) == Some("md")
                    {
                        if let Some(file_name) = subpath.file_stem().and_then(|s| s.to_str()) {
                            let prompt_name =
                                format!("{}/{}/{}", bank_name, subdir_name, file_name);

                            let prompt_path = self.storage.prompt_path(&prompt_name);
                            if prompt_path.exists() {
                                if skip {
                                    result.add_skipped(&prompt_name, "Skipped (already exists)");
                                    continue;
                                } else if update {
                                    // Check if source is newer than target
                                    let source_modified = fs::metadata(&subpath)?.modified()?;
                                    let target_modified = fs::metadata(&prompt_path)?.modified()?;

                                    if source_modified <= target_modified {
                                        result.add_skipped(
                                            &prompt_name,
                                            "Skipped (target is newer or same)",
                                        );
                                        continue;
                                    }
                                    // Continue with update since source is newer
                                } else if !force {
                                    result.add_skipped(&prompt_name, "Already exists");
                                    continue;
                                }
                            }

                            let content = fs::read_to_string(&subpath)?;
                            let (metadata, body) =
                                self.parse_content(&content, file_name, false)?;

                            self.storage.write_prompt(&prompt_name, &metadata, &body)?;
                            result.add_imported(&prompt_name);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn looks_like_prompt(&self, path: &Path) -> Result<bool> {
        let content = fs::read_to_string(path)?;

        // Check for prompt indicators
        let indicators = [
            "prompt",
            "instruction",
            "template",
            "system:",
            "user:",
            "assistant:",
            "{", // Has placeholders
        ];

        let content_lower = content.to_lowercase();
        Ok(indicators
            .iter()
            .any(|&indicator| content_lower.contains(indicator)))
    }

    fn is_text_file(&self, path: &Path) -> Result<bool> {
        let extensions = ["md", "txt", "prompt", "tmpl", "template"];

        if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
            return Ok(extensions.contains(&ext.to_lowercase().as_str()));
        }

        // Check if file looks like text by reading first few bytes
        let mut buffer = [0; 512];
        if let Ok(mut file) = fs::File::open(path) {
            use std::io::Read;
            if let Ok(bytes_read) = file.read(&mut buffer) {
                // Simple heuristic: if most bytes are printable ASCII, it's probably text
                let printable_count = buffer[..bytes_read]
                    .iter()
                    .filter(|&&b| b.is_ascii_graphic() || b.is_ascii_whitespace())
                    .count();

                return Ok(printable_count as f32 / bytes_read as f32 > 0.8);
            }
        }

        Ok(false)
    }
}

#[derive(Debug)]
pub struct ImportResult {
    imported: Vec<String>,
    skipped: Vec<(String, String)>,
    errors: Vec<(String, String)>,
}

impl ImportResult {
    fn new() -> Self {
        Self {
            imported: Vec::new(),
            skipped: Vec::new(),
            errors: Vec::new(),
        }
    }

    fn add_imported(&mut self, name: &str) {
        self.imported.push(name.to_string());
    }

    fn add_skipped(&mut self, name: &str, reason: &str) {
        self.skipped.push((name.to_string(), reason.to_string()));
    }

    fn add_error(&mut self, file: String, error: String) {
        self.errors.push((file, error));
    }

    pub fn display(&self) {
        println!("Import complete");

        if !self.imported.is_empty() {
            println!("  Imported: {}", self.imported.len());
            for name in &self.imported {
                println!("    {}", name);
            }
        }

        if !self.skipped.is_empty() {
            println!("  Skipped: {}", self.skipped.len());
            for (name, reason) in &self.skipped {
                println!("    {} ({})", name, reason);
            }
        }

        if !self.errors.is_empty() {
            println!("  Failed: {}", self.errors.len());
            for (file, error) in &self.errors {
                println!("    {} ({})", file, error);
            }
        }
    }

    pub fn summary(&self) -> String {
        format!(
            "Imported: {}, Skipped: {}, Errors: {}",
            self.imported.len(),
            self.skipped.len(),
            self.errors.len()
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_clean_prompt_name() {
        let storage = Storage::new().unwrap();
        let importer = Importer::new(storage);

        assert_eq!(importer.clean_prompt_name("My Prompt!"), "my-prompt");
        assert_eq!(importer.clean_prompt_name("API Design"), "api-design");
        assert_eq!(importer.clean_prompt_name("test_file.md"), "test_file-md");
    }

    #[test]
    fn test_extract_description() {
        let storage = Storage::new().unwrap();
        let importer = Importer::new(storage);

        let content = "# API Design\n\nThis is a prompt for designing APIs";
        assert_eq!(importer.extract_description(content).unwrap(), "API Design");

        let content = "Design a REST API with the following requirements:";
        assert_eq!(
            importer.extract_description(content).unwrap(),
            "Design a REST API with the following requirements:"
        );
    }
}