homeboy 0.21.0

CLI for multi-component deployment and development workflow automation
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
use std::collections::HashSet;

use clap::Args;
use serde::Serialize;

use homeboy::component::{self, Component};
use homeboy::context::{self, ContextOutput};
use homeboy::module::{
    is_module_compatible, is_module_linked, load_all_modules, module_ready_status,
};
use homeboy::project::{self, Project};
use homeboy::server::{self, Server};
use homeboy::{changelog, git, version};
use std::fs;
use std::path::PathBuf;

use super::CmdResult;

#[derive(Args)]
pub struct InitArgs {
    /// Show all components, modules, projects, and servers
    #[arg(long, short = 'a')]
    pub all: bool,
}

#[derive(Debug, Serialize)]
pub struct InitOutput {
    pub command: &'static str,
    pub context: ContextOutput,
    pub next_steps: Vec<String>,
    pub servers: Vec<Server>,
    pub projects: Vec<ProjectListItem>,
    pub components: Vec<Component>,
    pub modules: Vec<ModuleEntry>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<VersionSnapshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git: Option<GitSnapshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_release: Option<ReleaseSnapshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub changelog: Option<ChangelogSnapshot>,
}

#[derive(Debug, Serialize)]
pub struct ProjectListItem {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}

impl From<Project> for ProjectListItem {
    fn from(p: Project) -> Self {
        Self {
            id: p.id,
            domain: p.domain,
        }
    }
}

#[derive(Debug, Serialize)]
pub struct ModuleEntry {
    pub id: String,
    pub name: String,
    pub version: String,
    pub description: String,
    pub runtime: String,
    pub compatible: bool,
    pub ready: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ready_reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ready_detail: Option<String>,
    pub linked: bool,
}

#[derive(Debug, Serialize)]
pub struct VersionSnapshot {
    pub component_id: String,
    pub version: String,
    pub targets: Vec<version::VersionTargetInfo>,
}

#[derive(Debug, Serialize)]
pub struct GitSnapshot {
    pub branch: String,
    pub clean: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ahead: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub behind: Option<u32>,
}

#[derive(Debug, Serialize)]
pub struct ReleaseSnapshot {
    pub tag: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ChangelogSnapshot {
    pub path: String,
    pub label: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<Vec<String>>,
}

pub fn run_json(args: InitArgs) -> CmdResult<InitOutput> {
    // Get context for current directory
    let (context_output, _) = context::run(None)?;

    // Collect relevant component IDs from context
    let relevant_ids: HashSet<String> = context_output
        .matched_components
        .iter()
        .chain(context_output.contained_components.iter())
        .cloned()
        .collect();

    // Load all data sources
    let all_components = component::list().unwrap_or_default();
    let all_projects = project::list().unwrap_or_default();
    let all_servers = server::list().unwrap_or_default();
    let all_modules = load_all_modules();

    // Determine if we should show focused output
    let show_all = args.all || relevant_ids.is_empty();

    // Filter components
    let components: Vec<Component> = if show_all {
        all_components
    } else {
        all_components
            .into_iter()
            .filter(|c| relevant_ids.contains(&c.id))
            .collect()
    };

    // Get module IDs linked to matched components
    let linked_module_ids: HashSet<String> = components
        .iter()
        .filter_map(|c| c.modules.as_ref())
        .flat_map(|m| m.keys().cloned())
        .collect();

    // Filter modules: linked modules + platform modules (runtime.is_none())
    let modules: Vec<ModuleEntry> = all_modules
        .iter()
        .filter(|m| show_all || linked_module_ids.contains(&m.id) || m.runtime.is_none())
        .map(|m| {
            let ready_status = module_ready_status(m);
            ModuleEntry {
                id: m.id.clone(),
                name: m.name.clone(),
                version: m.version.clone(),
                description: m
                    .description
                    .as_ref()
                    .and_then(|d| d.lines().next())
                    .unwrap_or("")
                    .to_string(),
                runtime: if m.runtime.is_some() {
                    "executable"
                } else {
                    "platform"
                }
                .to_string(),
                compatible: is_module_compatible(m, None),
                ready: ready_status.ready,
                ready_reason: ready_status.reason,
                ready_detail: ready_status.detail,
                linked: is_module_linked(&m.id),
            }
        })
        .collect();

    // Filter projects: those containing relevant components
    let filtered_projects: Vec<Project> = if show_all {
        all_projects
    } else {
        all_projects
            .into_iter()
            .filter(|p| p.component_ids.iter().any(|id| relevant_ids.contains(id)))
            .collect()
    };

    // Get server IDs from filtered projects
    let relevant_server_ids: HashSet<String> = filtered_projects
        .iter()
        .filter_map(|p| p.server_id.clone())
        .collect();

    // Convert projects to list items
    let projects: Vec<ProjectListItem> = filtered_projects
        .into_iter()
        .map(ProjectListItem::from)
        .collect();

    // Filter servers
    let servers: Vec<Server> = if show_all {
        all_servers
    } else {
        all_servers
            .into_iter()
            .filter(|s| relevant_server_ids.contains(&s.id))
            .collect()
    };

    let mut next_steps = vec![
        "Read CLAUDE.md and README.md for repo-specific guidance.".to_string(),
        "Run `homeboy docs documentation/index` for Homeboy documentation. Documentation workflows are self-directed—explore before asking.".to_string(),
        "Run `homeboy docs commands/commands-index` to browse available commands.".to_string(),
    ];

    if context_output.managed {
        next_steps.push("Run `homeboy context` to inspect local config state.".to_string());
        if !components.is_empty() {
            next_steps
                .push("Run `homeboy component show <id>` to inspect a component.".to_string());
        }
    } else if !context_output.contained_components.is_empty() {
        next_steps.push("Run `homeboy component show <id>` for a contained component.".to_string());
    } else {
        next_steps.push(
            "Create a project with `homeboy project create <name> <domain> --server <server_id> --module <module_id>`.".to_string(),
        );
        next_steps.push(
            "Create a component with `homeboy component create <name> --local-path . --remote-path <path> --project <project_id>`.".to_string(),
        );
    }

    // If agent context file exists, add documentation guidance
    if std::path::Path::new("CLAUDE.md").exists() || std::path::Path::new("AGENTS.md").exists() {
        next_steps.push(
            "For documentation tasks: Run `homeboy changes --cwd` first, then follow `homeboy docs documentation/alignment`. No clarification needed.".to_string(),
        );
    }

    if let Some(suggestion) = context_output.suggestion.as_ref() {
        next_steps.push(format!("Suggestion: {}", suggestion));
    }

    let version_snapshot = resolve_version_snapshot(&components);
    let git_snapshot = resolve_git_snapshot(context_output.git_root.as_ref());
    let (last_release, changelog_snapshot) = resolve_changelog_snapshots(&components);

    Ok((
        InitOutput {
            command: "init",
            context: context_output,
            next_steps,
            servers,
            projects,
            components,
            modules,
            version: version_snapshot,
            git: git_snapshot,
            last_release,
            changelog: changelog_snapshot,
        },
        0,
    ))
}

fn resolve_version_snapshot(components: &[Component]) -> Option<VersionSnapshot> {
    let component = components.first()?;
    let info = version::read_component_version(component).ok()?;
    Some(VersionSnapshot {
        component_id: component.id.clone(),
        version: info.version,
        targets: info.targets,
    })
}

fn resolve_git_snapshot(git_root: Option<&String>) -> Option<GitSnapshot> {
    let root = git_root?;
    let snapshot = git::get_repo_snapshot(root).ok()?;
    Some(GitSnapshot {
        branch: snapshot.branch,
        clean: snapshot.clean,
        ahead: snapshot.ahead,
        behind: snapshot.behind,
    })
}

fn resolve_changelog_snapshots(
    components: &[Component],
) -> (Option<ReleaseSnapshot>, Option<ChangelogSnapshot>) {
    let component = match components.first() {
        Some(c) => c,
        None => return (None, None),
    };

    let changelog_path = match changelog::resolve_changelog_path(component) {
        Ok(path) => path,
        Err(_) => return (None, None),
    };
    let content = match fs::read_to_string(&changelog_path) {
        Ok(content) => content,
        Err(_) => return (None, None),
    };
    let settings = changelog::resolve_effective_settings(Some(component));

    let changelog_snapshot = build_changelog_snapshot(&content, &changelog_path, &settings);
    let last_release = build_last_release_snapshot(&content);

    (last_release, changelog_snapshot)
}

fn build_changelog_snapshot(
    content: &str,
    changelog_path: &PathBuf,
    settings: &changelog::EffectiveChangelogSettings,
) -> Option<ChangelogSnapshot> {
    let items = extract_section_items(content, &settings.next_section_aliases);
    Some(ChangelogSnapshot {
        path: changelog_path.to_string_lossy().to_string(),
        label: settings.next_section_label.clone(),
        items: if items.is_empty() { None } else { Some(items) },
    })
}

fn build_last_release_snapshot(content: &str) -> Option<ReleaseSnapshot> {
    let lines: Vec<&str> = content.lines().collect();
    for (index, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if !trimmed.starts_with("## ") {
            continue;
        }

        let label = trimmed.trim_start_matches("## ").trim();
        if label.eq_ignore_ascii_case("unreleased")
            || label.starts_with("[Unreleased")
            || label.starts_with("[unreleased")
        {
            continue;
        }

        let Some(tag) = parse_version_label(label) else {
            continue;
        };

        let date = parse_date_label(label);
        let summary = extract_first_bullet(&lines, index + 1);

        return Some(ReleaseSnapshot {
            tag: format!("v{}", tag),
            date,
            summary,
        });
    }

    None
}

fn extract_section_items(content: &str, aliases: &[String]) -> Vec<String> {
    let lines: Vec<&str> = content.lines().collect();
    let start = find_section_start(&lines, aliases);
    let Some(start_index) = start else {
        return Vec::new();
    };
    let end_index = find_section_end(&lines, start_index);
    let mut items = Vec::new();

    for line in &lines[start_index + 1..end_index] {
        let trimmed = line.trim();
        if trimmed.starts_with('-') {
            items.push(trimmed.trim_start_matches('-').trim().to_string());
        }
    }

    items
}

fn find_section_start(lines: &[&str], aliases: &[String]) -> Option<usize> {
    lines.iter().position(|line| {
        let trimmed = line.trim();
        if !trimmed.starts_with("## ") {
            return false;
        }
        let label = trimmed.trim_start_matches("## ").trim();
        aliases.iter().any(|alias| {
            let alias_trim = alias.trim().trim_matches(['[', ']']);
            let label_trim = label.trim().trim_matches(['[', ']']);
            alias_trim == label_trim
        })
    })
}

fn find_section_end(lines: &[&str], start: usize) -> usize {
    let mut index = start + 1;
    while index < lines.len() {
        if lines[index].trim().starts_with("## ") {
            break;
        }
        index += 1;
    }
    index
}

fn extract_first_bullet(lines: &[&str], start: usize) -> Option<String> {
    for line in &lines[start..] {
        let trimmed = line.trim();
        if trimmed.starts_with("## ") {
            break;
        }
        if trimmed.starts_with('-') {
            return Some(trimmed.trim_start_matches('-').trim().to_string());
        }
    }
    None
}

fn parse_version_label(label: &str) -> Option<String> {
    let re = regex::Regex::new(r"\[?(\d+\.\d+\.\d+)\]?").ok()?;
    re.captures(label)
        .and_then(|caps| caps.get(1))
        .map(|m| m.as_str().to_string())
}

fn parse_date_label(label: &str) -> Option<String> {
    let re = regex::Regex::new(r"\d{4}-\d{2}-\d{2}").ok()?;
    re.find(label).map(|m| m.as_str().to_string())
}