straymark-cli 3.14.1

CLI for StrayMark — the cognitive discipline your AI-assisted projects need
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
use anyhow::{bail, Context, Result};
use colored::Colorize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::config::Checksums;
use crate::download;
use crate::inject;
use crate::manifest::DistManifest;
use crate::utils;

pub fn run(path: &str, install_hooks: bool) -> Result<()> {
    let target = PathBuf::from(path)
        .canonicalize()
        .unwrap_or_else(|_| PathBuf::from(path));

    println!(
        "{} StrayMark in {}",
        "Initializing".cyan().bold(),
        target.display()
    );

    // Check if already initialized
    if target.join(".straymark").exists() {
        bail!(
            ".straymark/ already exists. Use {} to update.",
            "straymark update".yellow()
        );
    }

    // Download latest release
    utils::info("Fetching latest release...");
    let release = download::get_latest_release()?;
    println!(
        "  {} {}",
        "Found version:".dimmed(),
        release.tag_name.green()
    );

    // Download ZIP to temp file
    let temp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
    let zip_path = temp_dir.path().join("straymark.zip");

    utils::info("Downloading...");
    download::download_zip(&release.zip_url, &zip_path)?;

    // Extract files according to manifest
    utils::info("Extracting files...");
    let (manifest, templates) = extract_distribution(&zip_path, &target)?;

    // Create empty directory structure with .gitkeep
    create_empty_dirs(&target)?;

    // Inject into directive files
    utils::info("Configuring AI agent directives...");
    inject_directives(&target, &manifest, &templates)?;

    // Save manifest locally for future remove operations
    save_local_manifest(&target, &manifest)?;

    // Save checksums
    save_initial_checksums(&target, &release.tag_name)?;

    // Install pre-PR hook (opt-in via --hooks).
    if install_hooks {
        match install_pre_pr_hook(&target) {
            Ok(installed) => {
                if installed {
                    println!(
                        "  {} pre-PR hook installed at {}",
                        "".green().bold(),
                        ".git/hooks/pre-push".dimmed()
                    );
                }
            }
            Err(e) => {
                utils::warn(&format!(
                    "Failed to install pre-PR hook: {}. Continuing without it.",
                    e
                ));
            }
        }
    }

    // Print summary
    println!();
    utils::success("StrayMark initialized successfully!");
    println!();
    println!("  {}", "Next steps:".bold());
    println!("    1. Review .straymark/config.yml for language settings");
    println!("    2. Check STRAYMARK.md for governance rules");
    println!(
        "    3. Run {} to validate your setup",
        "straymark validate".cyan()
    );
    println!(
        "    4. Commit: {}",
        "git add .straymark/ STRAYMARK.md && git commit -m \"chore: adopt StrayMark\"".dimmed()
    );

    Ok(())
}

/// Extract distributable files from the release ZIP and read templates into memory
fn extract_distribution(
    zip_path: &Path,
    target: &Path,
) -> Result<(DistManifest, HashMap<String, String>)> {
    let file = std::fs::File::open(zip_path).context("Failed to open ZIP file")?;
    let mut archive = zip::ZipArchive::new(file).context("Failed to read ZIP archive")?;

    // Find the manifest inside the ZIP (it may be in a subdirectory like straymark-v2.0.0/)
    let mut manifest_content = None;
    let mut prefix = String::new();

    // First pass: find the manifest entry index
    let mut manifest_index = None;
    for i in 0..archive.len() {
        let entry = archive.by_index(i)?;
        let name = entry.name().to_string();
        if name.ends_with("dist-manifest.yml") {
            if let Some(pos) = name.find("dist-manifest.yml") {
                prefix = name[..pos].to_string();
            }
            manifest_index = Some(i);
            break;
        }
    }

    // Second pass: read manifest content
    if let Some(idx) = manifest_index {
        let mut content = String::new();
        let mut entry = archive.by_index(idx)?;
        std::io::Read::read_to_string(&mut entry, &mut content)?;
        manifest_content = Some(content);
    }

    let manifest_str = manifest_content.context("dist-manifest.yml not found in release ZIP")?;
    let manifest = DistManifest::from_str(&manifest_str)?;

    // Extract each file listed in manifest
    for pattern in &manifest.files {
        extract_matching_files(&mut archive, &prefix, pattern, target)?;
    }

    // Read template files from ZIP into memory
    let mut templates: HashMap<String, String> = HashMap::new();
    for injection in &manifest.injections {
        let zip_entry_name = format!("{}{}", prefix, injection.template);
        for i in 0..archive.len() {
            let mut entry = archive.by_index(i)?;
            if entry.name() == zip_entry_name {
                let mut content = String::new();
                std::io::Read::read_to_string(&mut entry, &mut content)?;
                templates.insert(injection.template.clone(), content);
                break;
            }
        }
    }

    Ok((manifest, templates))
}

/// Extract files from ZIP matching a manifest pattern
fn extract_matching_files(
    archive: &mut zip::ZipArchive<std::fs::File>,
    prefix: &str,
    pattern: &str,
    target: &Path,
) -> Result<()> {
    let pattern_with_prefix = format!("{}{}", prefix, pattern);

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let name = entry.name().to_string();

        // Check if this entry matches the pattern
        let matches = if pattern.ends_with('/') {
            // Directory pattern: match anything inside it
            name.starts_with(&pattern_with_prefix)
        } else {
            // Exact file match
            name == pattern_with_prefix
        };

        if matches && !entry.is_dir() {
            // Compute relative path (strip the prefix)
            let relative = &name[prefix.len()..];
            let dest = target.join(relative);

            // Create parent directories
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent)?;
            }

            // Write file
            let mut outfile = std::fs::File::create(&dest)?;
            std::io::copy(&mut entry, &mut outfile)?;
        }
    }

    Ok(())
}

/// Create the empty directory structure with .gitkeep files
fn create_empty_dirs(target: &Path) -> Result<()> {
    let dirs = [
        ".straymark/01-requirements",
        ".straymark/02-design/decisions",
        ".straymark/03-implementation",
        ".straymark/04-testing",
        ".straymark/05-operations/incidents",
        ".straymark/05-operations/runbooks",
        ".straymark/06-evolution/technical-debt",
        ".straymark/07-ai-audit/agent-logs",
        ".straymark/07-ai-audit/decisions",
        ".straymark/07-ai-audit/ethical-reviews",
        ".straymark/08-security",
        ".straymark/09-ai-models",
        ".straymark/00-governance/exceptions",
    ];

    for dir in &dirs {
        let dir_path = target.join(dir);
        utils::ensure_dir(&dir_path)?;
        let gitkeep = dir_path.join(".gitkeep");
        if !gitkeep.exists() {
            std::fs::write(&gitkeep, "")?;
        }
    }

    Ok(())
}

/// Inject StrayMark directives based on manifest and templates
fn inject_directives(
    target: &Path,
    manifest: &DistManifest,
    templates: &HashMap<String, String>,
) -> Result<()> {
    for injection in &manifest.injections {
        let template_content = match templates.get(&injection.template) {
            Some(content) => content,
            None => {
                utils::warn(&format!(
                    "Template not found in ZIP: {}",
                    injection.template
                ));
                continue;
            }
        };

        let embed_content = if let Some(embed_file) = &injection.embed {
            let embed_path = target.join(embed_file);
            if embed_path.exists() {
                Some(std::fs::read_to_string(&embed_path).with_context(|| {
                    format!("Failed to read embed file: {}", embed_path.display())
                })?)
            } else {
                utils::warn(&format!(
                    "Embed file not found: {} (skipping {})",
                    embed_file, injection.target
                ));
                continue;
            }
        } else {
            None
        };

        let target_path = target.join(&injection.target);
        inject::inject_directive(
            &target_path,
            template_content,
            embed_content.as_deref(),
        )?;
        utils::success(&format!("Configured {}", injection.target));
    }

    Ok(())
}

/// Save the manifest locally for future remove operations
fn save_local_manifest(target: &Path, manifest: &DistManifest) -> Result<()> {
    let manifest_path = target.join(".straymark/dist-manifest.yml");
    let content = manifest.to_yaml()?;
    std::fs::write(&manifest_path, content)
        .context("Failed to save local dist-manifest.yml")?;
    Ok(())
}

/// Save initial checksums for all framework files
fn save_initial_checksums(target: &Path, version: &str) -> Result<()> {
    let mut checksums = Checksums {
        version: version.to_string(),
        files: std::collections::HashMap::new(),
    };

    // Walk .straymark/ and hash all files
    if let Ok(entries) = walkdir(target.join(".straymark")) {
        for entry in entries {
            if let Some(hash) = utils::file_hash(&entry) {
                let relative = entry
                    .strip_prefix(target)
                    .unwrap_or(&entry)
                    .display()
                    .to_string();
                checksums.files.insert(relative, hash);
            }
        }
    }

    // Also hash STRAYMARK.md
    let straymark_path = target.join("STRAYMARK.md");
    if let Some(hash) = utils::file_hash(&straymark_path) {
        checksums.files.insert("STRAYMARK.md".to_string(), hash);
    }

    checksums.save(target)?;
    Ok(())
}

/// Install `.straymark/hooks/pre-pr.sh` as `.git/hooks/pre-push`. Returns
/// `Ok(true)` on success, `Ok(false)` if the project is not a git repo
/// (so the caller can skip silently). Errors only on actual filesystem
/// failures (the hook source is missing, the destination can't be written,
/// etc.).
fn install_pre_pr_hook(target: &Path) -> Result<bool> {
    let git_dir = target.join(".git");
    if !git_dir.exists() {
        utils::warn(
            "Skipping --hooks: not a git repository (no .git/ directory). Run 'git init' first.",
        );
        return Ok(false);
    }

    let source = target.join(".straymark/hooks/pre-pr.sh");
    if !source.exists() {
        bail!(
            "pre-PR hook source not found at {}. The framework distribution may be incomplete.",
            source.display()
        );
    }

    let hooks_dir = git_dir.join("hooks");
    std::fs::create_dir_all(&hooks_dir)
        .with_context(|| format!("Failed to create {}", hooks_dir.display()))?;

    let dest = hooks_dir.join("pre-push");
    if dest.exists() {
        utils::warn(&format!(
            "Refusing to overwrite existing hook at {}. Move or remove it, then re-run with --hooks.",
            dest.display()
        ));
        return Ok(false);
    }

    std::fs::copy(&source, &dest)
        .with_context(|| format!("Failed to copy hook to {}", dest.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&dest)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&dest, perms)?;
    }
    Ok(true)
}

#[cfg(test)]
mod hook_tests {
    use super::*;
    use tempfile::TempDir;

    fn setup_tempdir_with_hook_source(tmp: &Path) {
        std::fs::create_dir_all(tmp.join(".git/objects")).unwrap();
        std::fs::create_dir_all(tmp.join(".straymark/hooks")).unwrap();
        std::fs::write(
            tmp.join(".straymark/hooks/pre-pr.sh"),
            "#!/usr/bin/env bash\necho hook\n",
        )
        .unwrap();
    }

    #[test]
    fn install_pre_pr_hook_copies_and_makes_executable() {
        let tmp = TempDir::new().unwrap();
        setup_tempdir_with_hook_source(tmp.path());

        let installed = install_pre_pr_hook(tmp.path()).unwrap();
        assert!(installed);

        let dest = tmp.path().join(".git/hooks/pre-push");
        assert!(dest.exists());
        let body = std::fs::read_to_string(&dest).unwrap();
        assert!(body.contains("hook"));

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&dest).unwrap().permissions().mode();
            assert_eq!(mode & 0o111, 0o111, "hook must be executable");
        }
    }

    #[test]
    fn install_pre_pr_hook_skips_when_not_a_git_repo() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".straymark/hooks")).unwrap();
        std::fs::write(
            tmp.path().join(".straymark/hooks/pre-pr.sh"),
            "#!/usr/bin/env bash\nexit 0\n",
        )
        .unwrap();

        let installed = install_pre_pr_hook(tmp.path()).unwrap();
        assert!(!installed);
    }

    #[test]
    fn install_pre_pr_hook_refuses_to_overwrite_existing() {
        let tmp = TempDir::new().unwrap();
        setup_tempdir_with_hook_source(tmp.path());
        let dest = tmp.path().join(".git/hooks/pre-push");
        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
        std::fs::write(&dest, "#!/bin/sh\necho existing\n").unwrap();

        let installed = install_pre_pr_hook(tmp.path()).unwrap();
        assert!(!installed);

        // Original content is preserved.
        let body = std::fs::read_to_string(&dest).unwrap();
        assert!(body.contains("existing"));
    }

    #[test]
    fn install_pre_pr_hook_errors_when_source_missing() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".git/objects")).unwrap();
        // Note: no .straymark/hooks/pre-pr.sh

        let result = install_pre_pr_hook(tmp.path());
        assert!(result.is_err());
        let msg = format!("{:?}", result.unwrap_err());
        assert!(msg.contains("pre-PR hook source not found"));
    }
}

/// Simple recursive directory walker
fn walkdir(dir: PathBuf) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    if !dir.is_dir() {
        return Ok(files);
    }

    for entry in std::fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            files.extend(walkdir(path)?);
        } else {
            files.push(path);
        }
    }

    Ok(files)
}