git-paw 0.7.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
//! Spec scanning and discovery.
//!
//! Defines the `SpecBackend` trait for format-specific spec scanning,
//! `SpecEntry` as the universal spec representation, and `scan_specs()`
//! as the entry point for discovering pending specs.

mod markdown;
mod openspec;
pub mod resolve;
pub mod speckit;

use std::collections::HashMap;
use std::fmt;
use std::path::Path;

use crate::config::PawConfig;
use crate::error::PawError;
use openspec::OpenSpecBackend;
use speckit::SpecKitBackend;

/// A discovered spec ready for session launch.
///
/// Represents a single pending spec with all the information needed
/// to create a worktree and launch an AI coding session. The `backend`
/// field identifies the `SpecBackend` implementation that produced the
/// entry, so downstream consumers (notably `build_task_prompt`) can
/// dispatch behaviour per backend without re-reading configuration.
#[derive(Debug, Clone)]
pub struct SpecEntry {
    /// Unique identifier (folder name or filename).
    pub id: String,
    /// The `SpecBackend` implementation that produced this entry.
    pub backend: SpecBackendKind,
    /// Derived branch name: `branch_prefix` + `id`.
    pub branch: String,
    /// Per-spec CLI override (from `paw_cli` frontmatter).
    pub cli: Option<String>,
    /// Content to inject into the worktree `AGENTS.md`.
    pub prompt: String,
    /// File ownership if declared by the spec.
    pub owned_files: Option<Vec<String>>,
}

/// Trait for format-specific spec scanning backends.
///
/// Each spec format (`OpenSpec`, `Markdown`) implements this trait to provide
/// discovery of pending specs within a directory.
pub trait SpecBackend: fmt::Debug {
    /// Scans `dir` for pending specs and returns them as `SpecEntry` values.
    fn scan(&self, dir: &Path) -> Result<Vec<SpecEntry>, PawError>;
}

/// The per-entry tag a `SpecBackend` implementation sets on every
/// `SpecEntry` it returns.
///
/// Downstream consumers (notably `build_task_prompt`) dispatch on this
/// field so per-backend behaviour does not have to re-read configuration
/// or maintain a parallel map of entry → backend identity.
// NOTE: tasks.md 1.3 of the `openspec-apply-boot-prompt` change predicted
// that the `SpecKit` variant would be added by the `spec-kit-format`
// change. That change shipped before this one and did not extend the
// enum, so we add the variant here to keep the field non-optional across
// every backend the codebase actually carries today. The Spec Kit branch
// of `build_task_prompt` falls through to the generic AGENTS.md pointer
// (same shape as `Markdown`); the `/speckit:apply` slash-command shape,
// if it ever lands, will replace that branch in a follow-up change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecBackendKind {
    /// Produced by `OpenSpecBackend` (`openspec/changes/<id>/` layout).
    OpenSpec,
    /// Produced by `MarkdownBackend` (flat `.md` files with frontmatter).
    Markdown,
    /// Produced by `SpecKitBackend` (`.specify/specs/<feature>/` layout).
    SpecKit,
}

use markdown::MarkdownBackend;

/// Parses YAML frontmatter delimited by `---` lines.
///
/// Returns `(Some(fields), body)` if frontmatter is found, or `(None, content)` if not.
pub(crate) fn parse_frontmatter(content: &str) -> (Option<HashMap<String, String>>, &str) {
    let trimmed = content.trim_start();
    if !trimmed.starts_with("---") {
        return (None, content);
    }

    // Find the opening `---` line end
    let after_open = match trimmed.strip_prefix("---") {
        Some(rest) => {
            // Skip to end of line
            match rest.find('\n') {
                Some(idx) => &rest[idx + 1..],
                None => return (None, content),
            }
        }
        None => return (None, content),
    };

    // Find the closing `---`
    let close_pos = after_open
        .lines()
        .enumerate()
        .find(|(_, line)| line.trim() == "---");

    let (frontmatter_str, body) = match close_pos {
        Some((line_idx, _)) => {
            let byte_offset: usize = after_open.lines().take(line_idx).map(|l| l.len() + 1).sum();
            let fm = &after_open[..byte_offset];
            let after_close = &after_open[byte_offset..];
            // Skip the closing `---` line
            let body = match after_close.find('\n') {
                Some(idx) => &after_close[idx + 1..],
                None => "",
            };
            (fm, body)
        }
        None => return (None, content),
    };

    let mut fields = HashMap::new();
    for line in frontmatter_str.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Some((key, value)) = line.split_once(':') {
            fields.insert(key.trim().to_string(), value.trim().to_string());
        }
    }

    (Some(fields), body)
}

/// Returns the appropriate backend for the given spec format type.
fn backend_for_type(spec_type: &str) -> Result<Box<dyn SpecBackend>, PawError> {
    match spec_type {
        "openspec" => Ok(Box::new(OpenSpecBackend)),
        "markdown" => Ok(Box::new(MarkdownBackend)),
        "speckit" => Ok(Box::new(SpecKitBackend)),
        _ => Err(PawError::SpecError(format!(
            "unknown spec type: {spec_type}"
        ))),
    }
}

/// Derives a branch name by concatenating `prefix` and `id`.
///
/// Inserts a `/` separator if `prefix` does not already end with one.
fn derive_branch(prefix: &str, id: &str) -> String {
    if prefix.ends_with('/') {
        format!("{prefix}{id}")
    } else {
        format!("{prefix}/{id}")
    }
}

/// Resolves the effective spec configuration with auto-detection and CLI
/// override applied.
///
/// Precedence (highest to lowest):
/// 1. `format_override` (typically the `--specs-format` CLI value).
/// 2. Explicit `[specs]` section in TOML config.
/// 3. Auto-detection of `.specify/specs/` at the repo root → Spec Kit defaults.
///
/// Returns `None` when no source resolves a usable configuration.
fn resolve_specs_config(
    config: &PawConfig,
    repo_root: &Path,
    format_override: Option<&str>,
) -> Option<crate::config::SpecsConfig> {
    if let Some(format) = format_override {
        let mut base = config.specs.clone().unwrap_or_default();
        base.spec_type = Some(format.to_string());
        if base.dir.is_none() && format == "speckit" {
            base.dir = Some(".specify/specs".to_string());
        }
        return Some(base);
    }

    if config.specs.is_some() {
        return config.specs.clone();
    }

    // Auto-detect Spec Kit when `.specify/specs/` exists at the repo root.
    let specify = repo_root.join(".specify");
    if specify.is_dir() && specify.join("specs").is_dir() {
        return Some(crate::config::SpecsConfig {
            dir: Some(".specify/specs".to_string()),
            spec_type: Some("speckit".to_string()),
        });
    }

    None
}

/// Resolves the effective spec engine type for a repo, or `None` when no
/// spec source is configured or auto-detected.
///
/// Applies the same precedence as [`scan_specs`] (explicit `[specs]` config,
/// then `.specify/` auto-detection) and resolves a present-but-untyped
/// `[specs]` section to the `"openspec"` default that `scan_specs` would use.
/// Consumers that need to gate a capability on the `OpenSpec` engine — notably
/// the `opsx-role-gating` guard — call this and compare against `"openspec"`.
#[must_use]
pub fn resolved_spec_type(config: &PawConfig, repo_root: &Path) -> Option<String> {
    resolve_specs_config(config, repo_root, None)
        .map(|c| c.spec_type.unwrap_or_else(|| "openspec".to_string()))
}

/// Scans for pending specs using the configuration from `[specs]`.
///
/// Reads the spec directory and format type from `config`, selects the
/// appropriate backend, scans for pending specs, and derives branch names.
///
/// Returns an error if:
/// - No `[specs]` section exists in config and no `.specify/` is auto-detected
/// - The spec directory does not exist or is not a directory
/// - The spec type is unknown
pub fn scan_specs(config: &PawConfig, repo_root: &Path) -> Result<Vec<SpecEntry>, PawError> {
    scan_specs_with_override(config, repo_root, None)
}

/// Like [`scan_specs`], but honours a CLI `--specs-format` override.
pub fn scan_specs_with_override(
    config: &PawConfig,
    repo_root: &Path,
    format_override: Option<&str>,
) -> Result<Vec<SpecEntry>, PawError> {
    let specs_config = resolve_specs_config(config, repo_root, format_override)
        .ok_or_else(|| PawError::SpecError("no [specs] section in config".to_string()))?;

    let dir = specs_config.dir.as_deref().unwrap_or("specs");
    let specs_dir = repo_root.join(dir);

    if !specs_dir.exists() {
        return Err(PawError::SpecError(format!(
            "specs directory does not exist: {}",
            specs_dir.display()
        )));
    }
    if !specs_dir.is_dir() {
        return Err(PawError::SpecError(format!(
            "specs path is not a directory: {}",
            specs_dir.display()
        )));
    }

    let spec_type = specs_config.spec_type.as_deref().unwrap_or("openspec");
    let backend = backend_for_type(spec_type)?;

    let branch_prefix = config.branch_prefix.as_deref().unwrap_or("spec/");
    let mut entries = backend.scan(&specs_dir)?;

    // Backends that set their own branch name (e.g. SpecKit's `task/` and
    // `phase/` prefixes) keep it. Backends that leave `branch` empty get the
    // `<branch_prefix><id>` convention applied here.
    for entry in &mut entries {
        if entry.branch.is_empty() {
            entry.branch = derive_branch(branch_prefix, &entry.id);
        }
    }

    Ok(entries)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::SpecsConfig;
    use std::fs;

    #[test]
    fn spec_entry_all_fields() {
        let entry = SpecEntry {
            id: "add-auth".to_string(),
            backend: SpecBackendKind::OpenSpec,
            branch: "spec/add-auth".to_string(),
            cli: Some("claude".to_string()),
            prompt: "implement auth".to_string(),
            owned_files: Some(vec!["src/auth.rs".to_string()]),
        };
        assert_eq!(entry.id, "add-auth");
        assert_eq!(entry.backend, SpecBackendKind::OpenSpec);
        assert_eq!(entry.branch, "spec/add-auth");
        assert_eq!(entry.cli.as_deref(), Some("claude"));
        assert_eq!(entry.prompt, "implement auth");
        assert_eq!(entry.owned_files.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn spec_entry_optional_fields_absent() {
        let entry = SpecEntry {
            id: "fix-bug".to_string(),
            backend: SpecBackendKind::Markdown,
            branch: "spec/fix-bug".to_string(),
            cli: None,
            prompt: "fix the bug".to_string(),
            owned_files: None,
        };
        assert_eq!(entry.backend, SpecBackendKind::Markdown);
        assert!(entry.cli.is_none());
        assert!(entry.owned_files.is_none());
    }

    #[test]
    fn derive_branch_default_prefix() {
        assert_eq!(derive_branch("spec/", "add-auth"), "spec/add-auth");
    }

    #[test]
    fn derive_branch_custom_prefix_with_trailing_slash() {
        assert_eq!(derive_branch("feat/", "login"), "feat/login");
    }

    #[test]
    fn derive_branch_custom_prefix_without_trailing_slash() {
        assert_eq!(derive_branch("feat", "login"), "feat/login");
    }

    #[test]
    fn backend_for_type_openspec() {
        assert!(backend_for_type("openspec").is_ok());
    }

    #[test]
    fn backend_for_type_markdown() {
        assert!(backend_for_type("markdown").is_ok());
    }

    #[test]
    fn backend_for_type_speckit() {
        assert!(backend_for_type("speckit").is_ok());
    }

    #[test]
    fn backend_for_type_unknown() {
        let err = backend_for_type("unknown").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown spec type"), "got: {msg}");
    }

    #[test]
    fn scan_specs_no_specs_config() {
        let config = PawConfig::default();
        let tmp = tempfile::tempdir().unwrap();
        let err = scan_specs(&config, tmp.path()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("[specs]"), "got: {msg}");
    }

    #[test]
    fn scan_specs_nonexistent_directory() {
        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("nonexistent".to_string()),
                spec_type: Some("openspec".to_string()),
            }),
            ..Default::default()
        };
        let tmp = tempfile::tempdir().unwrap();
        let err = scan_specs(&config, tmp.path()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("does not exist"), "got: {msg}");
        assert!(msg.contains("nonexistent"), "got: {msg}");
    }

    #[test]
    fn scan_specs_file_instead_of_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let file_path = tmp.path().join("specs");
        fs::write(&file_path, "not a directory").unwrap();
        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("specs".to_string()),
                spec_type: Some("openspec".to_string()),
            }),
            ..Default::default()
        };
        let err = scan_specs(&config, tmp.path()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("not a directory"), "got: {msg}");
    }

    #[test]
    fn scan_specs_valid_config_stub_backend() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir(tmp.path().join("specs")).unwrap();
        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("specs".to_string()),
                spec_type: Some("openspec".to_string()),
            }),
            ..Default::default()
        };
        let entries = scan_specs(&config, tmp.path()).unwrap();
        assert!(entries.is_empty());
    }

    // --- Auto-detection of .specify/ ---

    #[test]
    fn auto_detect_specify_activates_speckit() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join(".specify").join("specs")).unwrap();
        let config = PawConfig::default();
        // The path exists but has no features — backend returns empty Vec.
        let entries = scan_specs(&config, tmp.path()).unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn auto_detect_skipped_when_specs_section_present() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join(".specify").join("specs")).unwrap();
        fs::create_dir(tmp.path().join("my-specs")).unwrap();
        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("my-specs".to_string()),
                spec_type: Some("markdown".to_string()),
            }),
            ..Default::default()
        };
        let resolved = resolve_specs_config(&config, tmp.path(), None).unwrap();
        assert_eq!(resolved.spec_type.as_deref(), Some("markdown"));
        assert_eq!(resolved.dir.as_deref(), Some("my-specs"));
    }

    #[test]
    fn auto_detect_skipped_when_no_specify_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let config = PawConfig::default();
        assert!(resolve_specs_config(&config, tmp.path(), None).is_none());
    }

    #[test]
    fn auto_detect_skipped_when_specify_missing_specs_subdir() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join(".specify").join("memory")).unwrap();
        let config = PawConfig::default();
        assert!(resolve_specs_config(&config, tmp.path(), None).is_none());
    }

    // Maps to scenario `Explicit config in TOML wins over auto-detection`
    // from spec-kit-format. The repo has BOTH a `.specify/specs/` directory
    // (which would normally auto-activate the SpecKit backend) AND an
    // explicit `[specs] type = "markdown"` config. The explicit config
    // must win: the Markdown backend is selected, not SpecKit.
    // (test-coverage-v0-5-0 task 11.5)
    #[test]
    fn explicit_config_wins_over_auto_detection() {
        let tmp = tempfile::tempdir().unwrap();
        // Seed `.specify/specs/` so the auto-detection branch *would* fire.
        fs::create_dir_all(tmp.path().join(".specify").join("specs")).unwrap();
        // Seed a markdown specs directory the explicit config points at.
        let md_dir = tmp.path().join("specs");
        fs::create_dir(&md_dir).unwrap();

        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("specs".to_string()),
                spec_type: Some("markdown".to_string()),
            }),
            ..Default::default()
        };

        // resolve_specs_config must select the explicit config without
        // falling through to auto-detection.
        let resolved = resolve_specs_config(&config, tmp.path(), None)
            .expect("explicit config should resolve");
        assert_eq!(
            resolved.spec_type.as_deref(),
            Some("markdown"),
            "explicit type = markdown must win over the auto-detected speckit"
        );
        assert_eq!(
            resolved.dir.as_deref(),
            Some("specs"),
            "explicit dir = specs must win over the auto-detected .specify/specs"
        );

        // End-to-end: scan_specs must run the Markdown backend and NOT the
        // SpecKit backend. With an empty markdown specs/ dir the result is
        // an empty entry list; with SpecKit on the `.specify/specs/` dir
        // we would similarly get zero entries — but a SpecKit-routed scan
        // would set up the `.specify/specs/` dir as its source. We assert
        // success on the markdown path explicitly.
        let entries = scan_specs(&config, tmp.path()).unwrap();
        assert!(
            entries.is_empty(),
            "empty markdown specs dir should produce no entries; got: {entries:?}"
        );
    }

    #[test]
    fn format_override_wins_over_specs_config_and_auto_detection() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join(".specify").join("specs")).unwrap();
        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("my-specs".to_string()),
                spec_type: Some("markdown".to_string()),
            }),
            ..Default::default()
        };
        let resolved = resolve_specs_config(&config, tmp.path(), Some("openspec")).unwrap();
        assert_eq!(resolved.spec_type.as_deref(), Some("openspec"));
        assert_eq!(resolved.dir.as_deref(), Some("my-specs"));
    }

    #[test]
    fn format_override_speckit_supplies_default_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let config = PawConfig::default();
        let resolved = resolve_specs_config(&config, tmp.path(), Some("speckit")).unwrap();
        assert_eq!(resolved.spec_type.as_deref(), Some("speckit"));
        assert_eq!(resolved.dir.as_deref(), Some(".specify/specs"));
    }

    #[test]
    fn scan_specs_with_override_routes_to_speckit() {
        let tmp = tempfile::tempdir().unwrap();
        let specify = tmp.path().join(".specify").join("specs");
        let feat = specify.join("001-feature");
        fs::create_dir_all(&feat).unwrap();
        fs::write(
            feat.join("tasks.md"),
            "## Phase 1: Setup\n- [ ] T001 do thing\n",
        )
        .unwrap();

        let config = PawConfig::default();
        let entries = scan_specs_with_override(&config, tmp.path(), Some("speckit")).unwrap();
        assert_eq!(entries.len(), 1);
        // SpecKit-supplied branch name is preserved (not overwritten with `spec/...`).
        assert!(
            entries[0].branch.starts_with("phase/"),
            "got branch: {}",
            entries[0].branch
        );
    }

    #[test]
    fn scan_specs_openspec_still_gets_branch_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let specs_dir = tmp.path().join("specs");
        let change = specs_dir.join("add-auth");
        fs::create_dir_all(&change).unwrap();
        fs::write(change.join("tasks.md"), "implement auth").unwrap();

        let config = PawConfig {
            specs: Some(SpecsConfig {
                dir: Some("specs".to_string()),
                spec_type: Some("openspec".to_string()),
            }),
            ..Default::default()
        };
        let entries = scan_specs(&config, tmp.path()).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].branch, "spec/add-auth");
    }
}