kazam 0.4.0

Beautiful static sites from simple YAML. One Rust binary, no framework, no npm, no runtime JS.
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
//! `kazam wish <name>` — point the agent at a workspace full of your real
//! context and get back a populated kazam YAML.
//!
//! kazam's job: scaffold the workspace and shell out to an agent. File
//! parsing, PDF handling, large-file chunking — all of that is the agent's
//! problem. kazam just sets the CWD to the workspace and tells the agent to
//! read whatever's there.
//!
//! Each wish (see `deck.rs`) declares:
//!   * a template `questions.md` written to the workspace on init
//!   * a template `README.md` explaining what to drop in
//!   * a static agent prompt that tells the agent how to turn the workspace
//!     into a valid kazam YAML for this wish type
//!   * a markdown spec for `--stdout` mode (portable, pipe into any agent)
//!
//! Flow:
//!   kazam wish deck              → scaffold ./wish-deck/ if missing, else
//!                                  shell out to the first agent on $PATH
//!                                  from inside the workspace to write deck.yaml
//!   kazam wish deck --agent X    → force a specific agent
//!   kazam wish deck --dry-run    → print the prompt that would be sent
//!   kazam wish deck --stdout     → print the portable wish markdown spec
//!   kazam wish list              → enumerate available wishes

use anyhow::{anyhow, bail, Context, Result};
use clap::ValueEnum;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

mod deck;

#[derive(Copy, Clone, Debug, ValueEnum)]
pub enum Agent {
    Claude,
    Gemini,
    Codex,
    Opencode,
}

impl Agent {
    fn label(&self) -> &'static str {
        match self {
            Agent::Claude => "Claude Code",
            Agent::Gemini => "Gemini CLI",
            Agent::Codex => "Codex",
            Agent::Opencode => "OpenCode",
        }
    }

    fn bin(&self) -> &'static str {
        match self {
            Agent::Claude => "claude",
            Agent::Gemini => "gemini",
            Agent::Codex => "codex",
            Agent::Opencode => "opencode",
        }
    }

    /// Build the `Command` that feeds `prompt` to the agent in non-interactive
    /// mode and prints the generated text to stdout.
    fn command(&self, prompt: &str) -> Command {
        let mut c = Command::new(self.bin());
        match self {
            Agent::Claude | Agent::Gemini => {
                c.arg("-p").arg(prompt);
            }
            Agent::Codex => {
                c.arg("exec").arg(prompt);
            }
            Agent::Opencode => {
                c.arg("run").arg(prompt);
            }
        }
        c
    }

    /// Order matters — first match on $PATH wins when `--agent` isn't given.
    const AUTO_DETECT_ORDER: &'static [Agent] =
        &[Agent::Claude, Agent::Gemini, Agent::Codex, Agent::Opencode];
}

/// A wish: workspace scaffolding + agent prompt + portable markdown.
pub struct Wish {
    pub name: &'static str,
    pub description: &'static str,
    /// Where the populated YAML is written (e.g. "deck.yaml"). Next to the
    /// workspace directory, not inside it.
    pub default_out: &'static str,
    /// Template written to `<workspace>/questions.md` on init.
    pub questions_md: &'static str,
    /// Template written to `<workspace>/README.md` on init.
    pub readme_md: &'static str,
    /// Reference material dropped into `<workspace>/reference/` on init —
    /// schema guide, example decks, anything the agent should consult for
    /// shape/validation. Pairs of (filename, contents).
    pub references: &'static [(&'static str, &'static str)],
    /// The single prompt shelled out to the agent. The agent is run with its
    /// CWD set to the workspace, so the prompt refers to files in "this
    /// directory" and lets the agent read them with its own tools.
    pub agent_prompt: &'static str,
    /// Builds the prompt for `--yolo` mode: no workspace, no questions —
    /// the agent invents the whole thing. Topic is optional; `None` means
    /// "surprise me." The prompt embeds the schema inline since there's no
    /// workspace `reference/` folder to read from.
    pub yolo_prompt: fn(Option<&str>) -> String,
    /// Portable spec printed by `--stdout`.
    pub stdout_markdown: &'static str,
}

fn all() -> &'static [&'static Wish] {
    const ALL: &[&Wish] = &[&deck::DECK];
    ALL
}

fn find(name: &str) -> Option<&'static Wish> {
    all().iter().copied().find(|w| w.name == name)
}

pub fn run(
    name: &str,
    out: Option<PathBuf>,
    agent: Option<Agent>,
    stdout_mode: bool,
    dry_run: bool,
    yolo: Option<String>,
) -> Result<()> {
    if name == "list" {
        return list();
    }

    let wish =
        find(name).ok_or_else(|| anyhow!("unknown wish '{}'. Try `kazam wish list`", name))?;

    if stdout_mode {
        print!("{}", wish.stdout_markdown);
        return Ok(());
    }

    if let Some(topic) = yolo {
        let topic = topic.trim();
        let topic = if topic.is_empty() { None } else { Some(topic) };
        return grant_yolo(wish, topic, out, agent, dry_run);
    }

    let workspace = PathBuf::from(format!("wish-{}", wish.name));
    if !workspace.exists() {
        scaffold(wish, &workspace)?;
        return Ok(());
    }

    // Workspace exists → grant.
    grant(wish, &workspace, out, agent, dry_run)
}

fn scaffold(wish: &Wish, workspace: &Path) -> Result<()> {
    fs::create_dir_all(workspace)
        .with_context(|| format!("creating workspace {}", workspace.display()))?;
    fs::write(workspace.join("questions.md"), wish.questions_md)?;
    fs::write(workspace.join("README.md"), wish.readme_md)?;

    // Reference material — version-matched to this binary. The agent reads
    // these during grant; the user can edit or inspect them too.
    if !wish.references.is_empty() {
        let ref_dir = workspace.join("reference");
        fs::create_dir_all(&ref_dir).with_context(|| format!("creating {}", ref_dir.display()))?;
        for (name, contents) in wish.references {
            fs::write(ref_dir.join(name), contents)
                .with_context(|| format!("writing reference/{}", name))?;
        }
    }

    println!();
    println!("  ✨ Making your {} wish — {}", wish.name, wish.description);
    println!();
    println!("  Created workspace: {}/", workspace.display());
    println!("    questions.md       structured prompts — fill in what you know");
    println!("    README.md          what to drop in this folder");
    if !wish.references.is_empty() {
        println!("    reference/         kazam schema + worked example (read-only to the agent)");
    }
    println!();
    println!("  Next:");
    println!(
        "    1. Fill in {}/questions.md with whatever you want to",
        workspace.display()
    );
    println!("       answer up front (blanks are fine — the agent will infer).");
    println!("    2. Drop any real context (docs, notes, transcripts, last");
    println!("       quarter's deck) into {}/.", workspace.display());
    println!("    3. Run `kazam wish {}` again to grant it.", wish.name);
    println!();

    Ok(())
}

fn grant(
    wish: &Wish,
    workspace: &Path,
    out: Option<PathBuf>,
    agent: Option<Agent>,
    dry_run: bool,
) -> Result<()> {
    if dry_run {
        print!("{}", wish.agent_prompt);
        return Ok(());
    }

    let out_path = out.unwrap_or_else(|| PathBuf::from(wish.default_out));
    if out_path.exists() {
        bail!(
            "'{}' already exists — pass `--out <path>` to write elsewhere",
            out_path.display()
        );
    }

    let agent = agent.or_else(detect_agent).ok_or_else(|| {
        anyhow!(
            "no agent found on $PATH (looked for claude, gemini, codex, opencode). \
             Install one, pass --agent explicitly, or use --dry-run to print the prompt."
        )
    })?;

    println!();
    println!(
        "  ✨ Granting your {} wish via {}",
        wish.name,
        agent.label()
    );
    println!();
    println!(
        "  Running {} in {} (can take 30-90s)…",
        agent.bin(),
        workspace.display()
    );
    println!();

    let yaml = run_agent(agent, wish.agent_prompt, workspace)?;
    fs::write(&out_path, &yaml).with_context(|| format!("writing {}", out_path.display()))?;

    let page_url = out_path
        .file_stem()
        .and_then(|s| s.to_str())
        .map(|stem| format!("http://localhost:3000/{}.html", stem))
        .unwrap_or_else(|| "http://localhost:3000/".to_string());

    println!();
    println!("  ✓ Wrote {}", out_path.display());
    println!();
    println!("  Next:");
    println!("    kazam dev .");
    println!("    → open {}", page_url);
    println!();

    Ok(())
}

fn grant_yolo(
    wish: &Wish,
    topic: Option<&str>,
    out: Option<PathBuf>,
    agent: Option<Agent>,
    dry_run: bool,
) -> Result<()> {
    let prompt = (wish.yolo_prompt)(topic);

    if dry_run {
        print!("{}", prompt);
        return Ok(());
    }

    let out_path = out.unwrap_or_else(|| PathBuf::from(wish.default_out));
    if out_path.exists() {
        bail!(
            "'{}' already exists — pass `--out <path>` to write elsewhere",
            out_path.display()
        );
    }

    let agent = agent.or_else(detect_agent).ok_or_else(|| {
        anyhow!(
            "no agent found on $PATH (looked for claude, gemini, codex, opencode). \
             Install one, pass --agent explicitly, or use --dry-run to print the prompt."
        )
    })?;

    let cwd = std::env::current_dir().context("reading current directory")?;
    println!();
    match topic {
        Some(t) => println!(
            "  🎲 Granting a YOLO {} wish via {} — topic: {}",
            wish.name,
            agent.label(),
            t
        ),
        None => println!(
            "  🎲 Granting a YOLO {} wish via {} — topic: surprise me",
            wish.name,
            agent.label()
        ),
    }
    println!();
    println!("  Running {} (can take 30-90s)…", agent.bin());
    println!();

    let yaml = run_agent(agent, &prompt, &cwd)?;
    fs::write(&out_path, &yaml).with_context(|| format!("writing {}", out_path.display()))?;

    let page_url = out_path
        .file_stem()
        .and_then(|s| s.to_str())
        .map(|stem| format!("http://localhost:3000/{}.html", stem))
        .unwrap_or_else(|| "http://localhost:3000/".to_string());

    println!();
    println!("  ✓ Wrote {}", out_path.display());
    println!();
    println!("  Next:");
    println!("    kazam dev .");
    println!("    → open {}", page_url);
    println!();

    Ok(())
}

fn detect_agent() -> Option<Agent> {
    Agent::AUTO_DETECT_ORDER
        .iter()
        .copied()
        .find(|a| cmd_on_path(a.bin()))
}

fn cmd_on_path(name: &str) -> bool {
    let path = match std::env::var_os("PATH") {
        Some(p) => p,
        None => return false,
    };
    for dir in std::env::split_paths(&path) {
        if dir.join(name).is_file() {
            return true;
        }
    }
    false
}

fn run_agent(agent: Agent, prompt: &str, cwd: &Path) -> Result<String> {
    let mut child = agent
        .command(prompt)
        .current_dir(cwd)
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .with_context(|| {
            format!(
                "could not start `{}` — is it installed and on your $PATH?",
                agent.bin()
            )
        })?;

    let mut stdout = child.stdout.take().expect("captured stdout");
    let mut raw = String::new();
    stdout.read_to_string(&mut raw)?;
    let status = child.wait()?;
    if !status.success() {
        bail!("{} exited with {}", agent.label(), status);
    }
    Ok(strip_code_fence(&raw))
}

/// Strip a fenced ```yaml ... ``` block if the agent wrapped its output. Falls
/// back to the raw string.
fn strip_code_fence(s: &str) -> String {
    let trimmed = s.trim();
    if let Some(rest) = trimmed.strip_prefix("```") {
        let after_lang = rest.find('\n').map(|i| &rest[i + 1..]).unwrap_or(rest);
        if let Some(body) = after_lang.rsplit_once("```") {
            return body.0.trim_end().to_string() + "\n";
        }
    }
    if !trimmed.ends_with('\n') {
        format!("{}\n", trimmed)
    } else {
        trimmed.to_string()
    }
}

fn list() -> Result<()> {
    println!();
    println!("  Available wishes:");
    println!();
    for w in all() {
        println!("    kazam wish {:<10}  {}", w.name, w.description);
    }
    println!();
    println!("  Flags:");
    println!("    --agent <claude|gemini|codex|opencode>   Force a specific agent");
    println!("    --yolo [topic]                           Skip workspace, let the agent invent everything");
    println!("    --dry-run                                Print the prompt instead of running the agent");
    println!("    --stdout                                 Print the portable wish markdown");
    println!("    --out <path>                             Where to write the populated YAML");
    println!();
    Ok(())
}

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

    #[test]
    fn strip_code_fence_removes_yaml_wrapper() {
        let raw = "```yaml\ntitle: hi\nshell: deck\n```\n";
        let s = strip_code_fence(raw);
        assert!(s.starts_with("title: hi"));
        assert!(!s.contains("```"));
    }

    #[test]
    fn strip_code_fence_passes_through_plain_yaml() {
        let raw = "title: hi\nshell: deck\n";
        let s = strip_code_fence(raw);
        assert!(s.starts_with("title: hi"));
    }

    #[test]
    fn all_wishes_have_unique_names() {
        let mut names: Vec<&str> = all().iter().map(|w| w.name).collect();
        names.sort();
        let before = names.len();
        names.dedup();
        assert_eq!(before, names.len(), "duplicate wish names");
    }
}