godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
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
//! Release orchestration: version bumping, tagging, pushing, and changelog generation.

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result, bail};

#[path = "release_tag.rs"]
pub mod release_tag;
#[path = "release_version.rs"]
pub mod release_version;

pub use release_tag::{push, tag};
pub use release_version::{extract_cargo_workspace_version, latest_tag_version};

use release_version::{bump_patch, load_config, read_version_field, write_version_field};

// ── Public types ────────────────────────────────────────────────────

#[derive(Debug, serde::Serialize)]
pub struct ReleaseInfo {
    pub old_version: String,
    pub new_version: String,
    pub tag: String,
    pub pushed: bool,
}

// ── Public API ──────────────────────────────────────────────────────

/// Read the current semantic version from the Cargo workspace.
pub fn current_version(root: &Path) -> Result<String> {
    let cfg = load_config(root)?;
    let cargo_toml = root.join(&cfg.workspace_manifest);
    let version = if cargo_toml.exists() {
        let content = fs::read_to_string(&cargo_toml)?;
        extract_cargo_workspace_version(&content).with_context(|| {
            format!(
                "workspace.package.version missing from {}",
                cargo_toml.display()
            )
        })?
    } else {
        let target = cfg
            .files
            .first()
            .context("no files in .version-bump.json")?;
        read_version_field(root, target)?
    };
    validate_semver(&version)?;
    Ok(version)
}

fn semver_components(version: &str) -> Result<(u64, u64, u64)> {
    let parts: Vec<&str> = version.split(char::from(46)).collect();
    if parts.len() != 3 {
        bail!("version {version} is not semver (expected MAJOR.MINOR.PATCH)");
    }
    Ok((parts[0].parse()?, parts[1].parse()?, parts[2].parse()?))
}

fn validate_semver(version: &str) -> Result<()> {
    semver_components(version).map(|_| ())
}

fn write_cargo_workspace_version(root: &Path, manifest: &str, version: &str) -> Result<()> {
    let path = root.join(manifest);
    if !path.exists() {
        return Ok(());
    }
    let content = fs::read_to_string(&path)?;
    let mut in_workspace_package = false;
    let mut replaced = false;
    let mut lines = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed == "[workspace.package]" {
            in_workspace_package = true;
        } else if trimmed.starts_with(char::from(91)) {
            in_workspace_package = false;
        }
        if in_workspace_package && trimmed.starts_with("version") {
            lines.push(format!("version = \"{version}\""));
            replaced = true;
        } else {
            lines.push(line.to_string());
        }
    }
    if !replaced {
        bail!("workspace.package.version missing from Cargo.toml");
    }
    fs::write(path, format!("{}\n", lines.join("\n")))?;
    Ok(())
}

/// Increment the patch component across all files in `.version-bump.json`.
/// Pass `explicit` to set an exact version instead of auto-incrementing.
pub fn bump(root: &Path, explicit: Option<&str>) -> Result<ReleaseInfo> {
    let drift = validate_versions(root).unwrap_or_default();
    if !drift.is_empty() {
        eprintln!("Warning: version drift detected before bump:");
        for w in &drift {
            eprintln!("  - {w}");
        }
    }

    let cfg = load_config(root)?;
    if cfg.files.is_empty() {
        bail!("no files listed in .version-bump.json");
    }

    let old_version = current_version(root)?;
    let new_version = match explicit {
        Some(v) => {
            validate_semver(v)?;
            v.to_string()
        }
        None => bump_patch(&old_version)?,
    };

    for target in &cfg.files {
        write_version_field(root, target, &new_version)?;
    }
    write_cargo_workspace_version(root, &cfg.workspace_manifest, &new_version)?;

    let tag = format!("v{new_version}");
    Ok(ReleaseInfo {
        old_version,
        new_version,
        tag,
        pushed: false,
    })
}

// ── Changelog ───────────────────────────────────────────────────────

/// One versioned section in CHANGELOG.md.
#[derive(Debug)]
pub struct ChangelogEntry {
    pub version: String,
    pub date: String,
    pub sections: BTreeMap<String, Vec<String>>,
}

fn commit_type_heading(prefix: &str) -> &'static str {
    match prefix {
        "feat" => "Features",
        "fix" => "Bug Fixes",
        "chore" => "Chores",
        "docs" => "Documentation",
        "refactor" => "Refactoring",
        "test" => "Tests",
        _ => "Other",
    }
}

fn classify(subject: &str) -> (&'static str, String) {
    if let Some(colon) = subject.find(':') {
        let prefix = subject[..colon].split('(').next().unwrap_or("").trim();
        let msg = subject[colon + 1..].trim().to_string();
        let heading = commit_type_heading(prefix);
        if heading != "Other" || prefix.chars().all(|c| c.is_alphabetic()) {
            return (heading, msg);
        }
    }
    ("Other", subject.to_string())
}

/// Generate a changelog entry from commits since the latest tag.
pub fn generate_changelog(root: &Path) -> Result<ChangelogEntry> {
    let root_str = root.to_str().unwrap_or(".");

    let tag_out = Command::new("git")
        .args(["-C", root_str, "describe", "--tags", "--abbrev=0"])
        .output()
        .context("failed to run git describe")?;
    let since = if tag_out.status.success() {
        let tag = String::from_utf8_lossy(&tag_out.stdout).trim().to_string();
        format!("{}..HEAD", tag)
    } else {
        "HEAD".to_string()
    };

    let log_out = Command::new("git")
        .args(["-C", root_str, "log", &since, "--format=%s"])
        .output()
        .context("failed to run git log")?;
    if !log_out.status.success() {
        bail!(
            "git log failed: {}",
            String::from_utf8_lossy(&log_out.stderr)
        );
    }

    let mut sections: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for line in String::from_utf8_lossy(&log_out.stdout).lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let (heading, msg) = classify(line);
        sections.entry(heading.to_string()).or_default().push(msg);
    }

    let version = current_version(root)?;
    let date = Command::new("date")
        .args(["+%Y-%m-%d"])
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|_| "unknown".to_string());

    Ok(ChangelogEntry {
        version,
        date,
        sections,
    })
}

/// Prepend a new section to CHANGELOG.md (creates the file if absent).
pub fn write_changelog(root: &Path, entry: &ChangelogEntry) -> Result<()> {
    let path = root.join("CHANGELOG.md");
    let existing = if path.exists() {
        fs::read_to_string(&path).unwrap_or_default()
    } else {
        String::new()
    };

    let mut new_section = format!("## [{}] - {}\n", entry.version, entry.date);

    let order = [
        "Features",
        "Bug Fixes",
        "Refactoring",
        "Tests",
        "Documentation",
        "Chores",
        "Other",
    ];
    for heading in order {
        if let Some(items) = entry.sections.get(heading) {
            new_section.push_str(&format!("\n### {}\n", heading));
            for item in items {
                new_section.push_str(&format!("- {}\n", item));
            }
        }
    }
    for (heading, items) in &entry.sections {
        if !order.contains(&heading.as_str()) {
            new_section.push_str(&format!("\n### {}\n", heading));
            for item in items {
                new_section.push_str(&format!("- {}\n", item));
            }
        }
    }

    let content = if existing.is_empty() {
        format!("# Changelog\n\n{}\n", new_section)
    } else {
        if existing.starts_with("# Changelog") {
            let rest = existing
                .split_once('\n')
                .map(|x| x.1)
                .unwrap_or("")
                .trim_start_matches('\n');
            format!("# Changelog\n\n{}\n{}", new_section, rest)
        } else {
            format!("{}\n{}", new_section, existing)
        }
    };

    fs::write(&path, content).with_context(|| format!("failed to write {}", path.display()))?;
    Ok(())
}

// ── Version cross-validation ────────────────────────────────────────

/// Cross-check plugin.json version, Cargo.toml workspace version, and latest git tag.
pub fn validate_versions(root: &Path) -> Result<Vec<String>> {
    let mut warnings = Vec::new();

    let project_version = current_version(root)?;

    let cargo_toml = root.join("Cargo.toml");
    let cargo_version = if cargo_toml.exists() {
        let content = fs::read_to_string(&cargo_toml)?;
        extract_cargo_workspace_version(&content)
    } else {
        None
    };

    let tag_version = latest_tag_version(root);

    let config = load_config(root)?;
    for target in &config.files {
        let version = read_version_field(root, target)?;
        if let Some(ref cargo_version) = cargo_version
            && version != *cargo_version
        {
            warnings.push(format!(
                "version mismatch: {}={version}, Cargo.toml={cargo_version}",
                target.path
            ));
        }
    }

    if let Some(ref tag_version) = tag_version
        && semver_components(tag_version)? > semver_components(&project_version)?
    {
        warnings.push(format!(
            "version regression: workspace={project_version}, latest tag=v{tag_version}"
        ));
    }

    Ok(warnings)
}

// ── Tests ───────────────────────────────────────────────────────────

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

    fn make_fixture(version: &str) -> TempDir {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();

        fs::create_dir_all(root.join(".claude-plugin")).unwrap();
        fs::write(
            root.join(".claude-plugin/plugin.json"),
            format!(r#"{{"name":"godmode","version":"{version}","author":{{"name":"Joe"}},"description":"x"}}"#),
        )
        .unwrap();

        fs::write(
            root.join("Cargo.toml"),
            format!("[workspace]\n\n[workspace.package]\nversion = \"{version}\"\n"),
        )
        .unwrap();

        fs::write(
            root.join(".version-bump.json"),
            r#"{"files":[{"path":".claude-plugin/plugin.json","field":"version"}],"audit":{"exclude":["target"]}}"#,
        )
        .unwrap();

        tmp
    }

    #[test]
    fn current_version_reads_workspace_semver() {
        let tmp = make_fixture("1.2.3");
        assert_eq!(current_version(tmp.path()).unwrap(), "1.2.3");
    }

    #[test]
    fn bump_increments_patch() {
        let tmp = make_fixture("1.1.0");
        let info = bump(tmp.path(), None).unwrap();
        assert_eq!(info.old_version, "1.1.0");
        assert_eq!(info.new_version, "1.1.1");
        assert_eq!(info.tag, "v1.1.1");
        assert_eq!(current_version(tmp.path()).unwrap(), "1.1.1");
    }

    #[test]
    fn bump_accepts_explicit_version() {
        let tmp = make_fixture("1.0.0");
        let info = bump(tmp.path(), Some("2.0.0")).unwrap();
        assert_eq!(info.new_version, "2.0.0");
        assert_eq!(current_version(tmp.path()).unwrap(), "2.0.0");
    }

    #[test]
    fn bump_patch_arithmetic() {
        use release_version::bump_patch;
        assert_eq!(bump_patch("0.0.9").unwrap(), "0.0.10");
        assert_eq!(bump_patch("1.2.3").unwrap(), "1.2.4");
        assert!(bump_patch("1.0").is_err());
        assert!(bump_patch("bad").is_err());
    }

    #[test]
    fn bump_fails_on_missing_version_bump_json() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(bump(tmp.path(), None).is_err());
    }

    #[test]
    fn extract_cargo_workspace_version_parses() {
        let toml = r#"
[workspace]
members = ["crates/*"]

[workspace.package]
version = "0.6.0"
edition = "2024"
"#;
        assert_eq!(
            extract_cargo_workspace_version(toml),
            Some("0.6.0".to_string())
        );
    }

    #[test]
    fn extract_cargo_workspace_version_returns_none_if_missing() {
        let toml = "[workspace]\nmembers = [\"crates/*\"]\n";
        assert_eq!(extract_cargo_workspace_version(toml), None);
    }

    #[test]
    fn validate_versions_reports_no_warnings_when_consistent() {
        let tmp = make_fixture("1.0.0");
        let warnings = validate_versions(tmp.path()).unwrap();
        assert!(warnings.is_empty());
    }
    #[test]
    fn validate_versions_checks_every_configured_version_adapter() {
        let tmp = make_fixture("1.0.0");
        fs::create_dir_all(tmp.path().join("adapters/example")).unwrap();
        fs::write(
            tmp.path().join("adapters/example/manifest.json"),
            r#"{"version":"0.9.0"}"#,
        )
        .unwrap();
        fs::write(tmp.path().join(".version-bump.json"), r#"{"files":[{"path":".claude-plugin/plugin.json","field":"version"},{"path":"adapters/example/manifest.json","field":"version"}],"audit":{"exclude":["target"]}}"#).unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\n\n[workspace.package]\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        let warnings = validate_versions(tmp.path()).unwrap();
        assert!(
            warnings.iter().any(|warning| warning
                .contains("adapters/example/manifest.json=0.9.0, Cargo.toml=1.0.0")),
            "warnings: {warnings:?}"
        );
    }
    #[test]
    fn bump_rejects_non_semver_explicit_versions() {
        let tmp = make_fixture("1.0.0");
        assert!(bump(tmp.path(), Some("deadbeef")).is_err());
    }
}