thoughts-tool 0.12.0

Flexible thought management using filesystem mounts for git repositories
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
//! Library-level document management for `thoughts_tool`.
//!
//! This module provides reusable functions for writing and listing documents,
//! and is used by both the MCP layer and other crates that depend on `thoughts_tool`.

use crate::error::Result as TResult;
use crate::error::ThoughtsError;
use crate::repo_identity::RepoIdentity;
use crate::utils::validation::validate_simple_filename;
use crate::workspace::ActiveWork;
use crate::workspace::ensure_active_work;
use atomicwrites::AtomicFile;
use atomicwrites::OverwriteBehavior;
use chrono::DateTime;
use chrono::Utc;
use percent_encoding::AsciiSet;
use percent_encoding::CONTROLS;
use percent_encoding::utf8_percent_encode;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::fs;
use std::path::PathBuf;

/// Document type categories for thoughts workspace.
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DocumentType {
    Research,
    Plan,
    Artifact,
    Log,
}

impl DocumentType {
    /// Returns the path for this document type's directory within `ActiveWork`.
    pub fn subdir<'a>(&self, aw: &'a ActiveWork) -> &'a PathBuf {
        match self {
            Self::Research => &aw.research,
            Self::Plan => &aw.plans,
            Self::Artifact => &aw.artifacts,
            Self::Log => &aw.logs,
        }
    }

    /// Returns the plural directory name (for physical directory paths).
    /// Note: serde serialization uses singular forms ("plan", "artifact", "research", "log"),
    /// while physical directories use plural forms ("plans", "artifacts", "research", "logs").
    /// This matches conventional filesystem naming while keeping API values consistent.
    pub fn subdir_name(&self) -> &'static str {
        match self {
            Self::Research => "research",
            Self::Plan => "plans",
            Self::Artifact => "artifacts",
            Self::Log => "logs",
        }
    }

    /// Returns the singular label for this document type (used in output/reporting).
    pub fn singular_label(&self) -> &'static str {
        match self {
            Self::Research => "research",
            Self::Plan => "plan",
            Self::Artifact => "artifact",
            Self::Log => "log",
        }
    }
}

// Custom deserializer: accept singular/plural in a case-insensitive manner
impl<'de> serde::Deserialize<'de> for DocumentType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let norm = s.trim().to_ascii_lowercase();
        match norm.as_str() {
            "research" => Ok(Self::Research),
            "plan" | "plans" => Ok(Self::Plan),
            "artifact" | "artifacts" => Ok(Self::Artifact),
            "log" | "logs" => Ok(Self::Log), // accepts both for backward compat
            other => Err(serde::de::Error::custom(format!(
                "invalid doc_type '{other}'; expected research|plan(s)|artifact(s)|log(s)"
            ))),
        }
    }
}

/// Result of successfully writing a document.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WriteDocumentOk {
    pub path: String,
    pub bytes_written: u64,
    /// GitHub URL for the document (available after sync).
    /// None if the remote is not GitHub-hosted or URL couldn't be computed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub github_url: Option<String>,
}

/// Metadata about a single document file.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentInfo {
    pub path: String,
    pub doc_type: String,
    pub size: u64,
    pub modified: String,
}

/// Result of listing documents in the active work directory.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActiveDocuments {
    pub base: String,
    pub files: Vec<DocumentInfo>,
}

/// Compute GitHub blob URL if the remote is GitHub-hosted.
///
/// Returns None if:
/// - No remote URL is available
/// - No git ref is available
/// - The remote is not GitHub-hosted
/// - The URL couldn't be parsed
const GITHUB_PATH_SEGMENT_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'!')
    .add(b'"')
    .add(b'#')
    .add(b'$')
    .add(b'%')
    .add(b'&')
    .add(b'\'')
    .add(b'(')
    .add(b')')
    .add(b'*')
    .add(b'+')
    .add(b',')
    .add(b':')
    .add(b';')
    .add(b'<')
    .add(b'=')
    .add(b'>')
    .add(b'?')
    .add(b'@')
    .add(b'[')
    .add(b'\\')
    .add(b']')
    .add(b'^')
    .add(b'`')
    .add(b'{')
    .add(b'|')
    .add(b'}');

fn encode_path_segment(value: &str) -> String {
    value
        .split('/')
        .map(|segment| utf8_percent_encode(segment, GITHUB_PATH_SEGMENT_ENCODE_SET).to_string())
        .collect::<Vec<_>>()
        .join("/")
}

fn compute_github_url(
    remote_url: Option<&str>,
    repo_subpath: Option<&str>,
    git_ref: Option<&str>,
    dir_name: &str,
    doc_type: &DocumentType,
    filename: &str,
) -> Option<String> {
    let remote = remote_url?;
    let git_ref = git_ref?;
    let identity = RepoIdentity::parse(remote).ok()?;

    // Only generate URLs for GitHub
    if identity.host != "github.com" {
        return None;
    }

    // Guard against single-segment remotes that produce empty org_path
    if identity.org_path.is_empty() {
        return None;
    }

    // Build the path within the repo
    // Structure: {subpath}/{dir_name}/{doc_type_dir}/{filename}
    let mut path_parts = Vec::new();
    if let Some(subpath) = repo_subpath {
        let subpath = subpath.trim().trim_matches('/');
        if !subpath.is_empty() {
            path_parts.push(encode_path_segment(subpath));
        }
    }
    path_parts.push(encode_path_segment(dir_name));
    path_parts.push(doc_type.subdir_name().to_string());
    path_parts.push(encode_path_segment(filename));

    let path_in_repo = path_parts.join("/");

    Some(format!(
        "https://github.com/{}/{}/blob/{}/{}",
        encode_path_segment(&identity.org_path),
        encode_path_segment(&identity.repo),
        encode_path_segment(git_ref),
        path_in_repo
    ))
}

/// Write a document to the active work directory.
///
/// # Arguments
/// * `doc_type` - The type of document (research, plan, artifact, log)
/// * `filename` - The filename (validated for safety)
/// * `content` - The content to write
///
/// # Returns
/// A `WriteDocumentOk` with the path, bytes written, and optional GitHub URL on success.
pub fn write_document(
    doc_type: &DocumentType,
    filename: &str,
    content: &str,
) -> TResult<WriteDocumentOk> {
    validate_simple_filename(filename)?;
    let aw = ensure_active_work()?;
    let dir = doc_type.subdir(&aw);
    let target = dir.join(filename);
    let bytes_written = content.len() as u64;

    AtomicFile::new(&target, OverwriteBehavior::AllowOverwrite)
        .write(|f| std::io::Write::write_all(f, content.as_bytes()))
        .map_err(|e| ThoughtsError::Io(std::io::Error::other(e)))?;

    let github_url = compute_github_url(
        aw.remote_url.as_deref(),
        aw.repo_subpath.as_deref(),
        aw.thoughts_git_ref.as_deref(),
        &aw.dir_name,
        doc_type,
        filename,
    );

    Ok(WriteDocumentOk {
        path: format!(
            "./thoughts/{}/{}/{}",
            aw.dir_name,
            doc_type.subdir_name(),
            filename
        ),
        bytes_written,
        github_url,
    })
}

/// List documents in the active work directory.
///
/// # Arguments
/// * `subdir` - Optional filter for a specific document type. If None, lists research, plans, artifacts
///   (but NOT logs by default - logs must be explicitly requested).
///
/// # Returns
/// An `ActiveDocuments` with the base path and list of files.
pub fn list_documents(subdir: Option<&DocumentType>) -> TResult<ActiveDocuments> {
    let aw = ensure_active_work()?;
    let base = format!("./thoughts/{}", aw.dir_name);

    // Determine which subdirs to scan
    // Tuple: (singular_label for doc_type output, plural_dirname for paths, PathBuf)
    let sets: Vec<(&str, &str, PathBuf)> = match subdir {
        Some(d) => {
            vec![(d.singular_label(), d.subdir_name(), d.subdir(&aw).clone())]
        }
        None => vec![
            ("research", "research", aw.research.clone()),
            ("plan", "plans", aw.plans.clone()),
            ("artifact", "artifacts", aw.artifacts),
            // Do NOT include logs by default - must be explicitly requested
        ],
    };

    let mut files = Vec::new();
    for (singular_label, dirname, dir) in sets {
        if !dir.exists() {
            continue;
        }
        for entry in fs::read_dir(&dir)? {
            let entry = entry?;
            let meta = entry.metadata()?;
            if meta.is_file() {
                let modified: DateTime<Utc> = meta
                    .modified()
                    .map_or_else(|_| Utc::now(), std::convert::Into::into);
                let file_name = entry.file_name().to_string_lossy().to_string();
                files.push(DocumentInfo {
                    path: format!("{base}/{dirname}/{file_name}"),
                    doc_type: singular_label.to_string(),
                    size: meta.len(),
                    modified: modified.to_rfc3339(),
                });
            }
        }
    }

    Ok(ActiveDocuments { base, files })
}

/// Get the path to the logs directory in the active work, ensuring it exists.
///
/// This is a convenience function for other crates that need to write log files
/// directly (e.g., `agentic_logging`).
///
/// # Returns
/// The absolute path to the logs directory.
pub fn active_logs_dir() -> TResult<PathBuf> {
    let aw = ensure_active_work()?;
    if !aw.logs.exists() {
        std::fs::create_dir_all(&aw.logs)?;
    }
    Ok(aw.logs)
}

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

    #[test]
    fn test_document_type_deserialize_singular() {
        let research: DocumentType = serde_json::from_str("\"research\"").unwrap();
        assert!(matches!(research, DocumentType::Research));

        let plan: DocumentType = serde_json::from_str("\"plan\"").unwrap();
        assert!(matches!(plan, DocumentType::Plan));

        let artifact: DocumentType = serde_json::from_str("\"artifact\"").unwrap();
        assert!(matches!(artifact, DocumentType::Artifact));

        let log: DocumentType = serde_json::from_str("\"log\"").unwrap();
        assert!(matches!(log, DocumentType::Log));
    }

    #[test]
    fn test_document_type_deserialize_plural() {
        let plans: DocumentType = serde_json::from_str("\"plans\"").unwrap();
        assert!(matches!(plans, DocumentType::Plan));

        let artifacts: DocumentType = serde_json::from_str("\"artifacts\"").unwrap();
        assert!(matches!(artifacts, DocumentType::Artifact));

        let logs: DocumentType = serde_json::from_str("\"logs\"").unwrap();
        assert!(matches!(logs, DocumentType::Log));
    }

    #[test]
    fn test_document_type_deserialize_case_insensitive() {
        let plan: DocumentType = serde_json::from_str("\"PLAN\"").unwrap();
        assert!(matches!(plan, DocumentType::Plan));

        let research: DocumentType = serde_json::from_str("\"Research\"").unwrap();
        assert!(matches!(research, DocumentType::Research));

        let log: DocumentType = serde_json::from_str("\"LOG\"").unwrap();
        assert!(matches!(log, DocumentType::Log));

        let logs: DocumentType = serde_json::from_str("\"LOGS\"").unwrap();
        assert!(matches!(logs, DocumentType::Log));
    }

    #[test]
    fn test_document_type_deserialize_invalid() {
        let result: Result<DocumentType, _> = serde_json::from_str("\"invalid\"");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("invalid doc_type"));
    }

    #[test]
    fn test_document_type_serialize() {
        let plan = DocumentType::Plan;
        let serialized = serde_json::to_string(&plan).unwrap();
        assert_eq!(serialized, "\"plan\"");

        let artifact = DocumentType::Artifact;
        let serialized = serde_json::to_string(&artifact).unwrap();
        assert_eq!(serialized, "\"artifact\"");

        let log = DocumentType::Log;
        let serialized = serde_json::to_string(&log).unwrap();
        assert_eq!(serialized, "\"log\"");
    }

    #[test]
    fn test_subdir_names() {
        assert_eq!(DocumentType::Research.subdir_name(), "research");
        assert_eq!(DocumentType::Plan.subdir_name(), "plans");
        assert_eq!(DocumentType::Artifact.subdir_name(), "artifacts");
        assert_eq!(DocumentType::Log.subdir_name(), "logs");
    }

    #[test]
    fn test_singular_labels() {
        assert_eq!(DocumentType::Research.singular_label(), "research");
        assert_eq!(DocumentType::Plan.singular_label(), "plan");
        assert_eq!(DocumentType::Artifact.singular_label(), "artifact");
        assert_eq!(DocumentType::Log.singular_label(), "log");
    }

    #[test]
    fn test_compute_github_url_ssh() {
        let url = compute_github_url(
            Some("git@github.com:org/repo.git"),
            None,
            Some("main"),
            "main",
            &DocumentType::Research,
            "doc.md",
        );
        assert_eq!(
            url,
            Some("https://github.com/org/repo/blob/main/main/research/doc.md".to_string())
        );
    }

    #[test]
    fn test_compute_github_url_https() {
        let url = compute_github_url(
            Some("https://github.com/org/repo.git"),
            Some("docs/thoughts"),
            Some("main"),
            "feature-branch",
            &DocumentType::Plan,
            "plan.md",
        );
        assert_eq!(
            url,
            Some(
                "https://github.com/org/repo/blob/main/docs/thoughts/feature-branch/plans/plan.md"
                    .to_string()
            )
        );
    }

    #[test]
    fn test_compute_github_url_non_github() {
        let url = compute_github_url(
            Some("git@gitlab.com:org/repo.git"),
            None,
            Some("main"),
            "main",
            &DocumentType::Research,
            "doc.md",
        );
        assert_eq!(url, None);
    }

    #[test]
    fn test_compute_github_url_none_remote() {
        let url = compute_github_url(
            None,
            None,
            Some("main"),
            "main",
            &DocumentType::Research,
            "doc.md",
        );
        assert_eq!(url, None);
    }

    #[test]
    fn test_compute_github_url_no_subpath() {
        let url = compute_github_url(
            Some("git@github.com:General-Wisdom/thoughts.git"),
            None,
            Some("main"),
            "allison-feature",
            &DocumentType::Artifact,
            "test.md",
        );
        assert_eq!(
            url,
            Some("https://github.com/General-Wisdom/thoughts/blob/main/allison-feature/artifacts/test.md".to_string())
        );
    }

    #[test]
    fn test_compute_github_url_empty_org_path() {
        // Single-segment remotes produce empty org_path; should return None
        // to avoid malformed URLs like https://github.com//repo/...
        let url = compute_github_url(
            Some("git@github.com:repo.git"),
            None,
            Some("main"),
            "main",
            &DocumentType::Research,
            "doc.md",
        );
        assert_eq!(url, None);
    }

    #[test]
    fn test_compute_github_url_slash_branch() {
        let url = compute_github_url(
            Some("git@github.com:org/repo.git"),
            None,
            Some("main"),
            "feature/login",
            &DocumentType::Research,
            "notes.md",
        );
        assert_eq!(
            url,
            Some(
                "https://github.com/org/repo/blob/main/feature/login/research/notes.md".to_string()
            )
        );
    }

    #[test]
    fn test_compute_github_url_special_chars() {
        let url = compute_github_url(
            Some("git@github.com:org/repo.git"),
            None,
            Some("main"),
            "feat#1%",
            &DocumentType::Plan,
            "plan.md",
        );
        assert_eq!(
            url,
            Some("https://github.com/org/repo/blob/main/feat%231%25/plans/plan.md".to_string())
        );
    }

    #[test]
    fn test_compute_github_url_detached_head() {
        let url = compute_github_url(
            Some("git@github.com:org/repo.git"),
            None,
            None,
            "some-branch",
            &DocumentType::Research,
            "doc.md",
        );
        assert_eq!(url, None);
    }

    #[test]
    fn test_compute_github_url_space_in_branch() {
        let url = compute_github_url(
            Some("git@github.com:org/repo.git"),
            None,
            Some("main"),
            "my branch",
            &DocumentType::Artifact,
            "out.md",
        );
        assert_eq!(
            url,
            Some("https://github.com/org/repo/blob/main/my%20branch/artifacts/out.md".to_string())
        );
    }
}