render-session 0.1.0

CLI for render-session: HTTP viewer with optional auto-watcher, MCP server alias, config-driven gen, session/recent capture.
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
use clap::{Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(
    name = "render-session",
    about = "render-session: MCP server + HTTP viewer for AI session output",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Run the MCP stdio server (default entry point from .mcp.json).
    /// Delegates to the render-session-mcp binary found next to this executable.
    Mcp,

    /// Start the HTTP viewer server
    Serve {
        /// Port to listen on
        #[arg(long, default_value = "8000")]
        port: u16,

        /// Project directory to serve content from
        #[arg(long)]
        dir: String,

        /// Phase 4 (c): viewer-internal watcher tick (seconds). When set, the viewer
        /// runs `auto_capture_once` every <tick> seconds in the background. None
        /// disables the watcher (Phase 1+ default behavior preserved).
        #[arg(long)]
        watch_tick: Option<u64>,
    },

    /// Generate list.json and render-lanes.md from config
    Gen {
        /// Project directory containing .render-session.yaml
        #[arg(long)]
        project: String,
    },

    /// Write a report from stdin
    Report {
        /// Directory to write the report into
        #[arg(long)]
        dir: String,

        /// Report title
        #[arg(long)]
        title: String,
    },

    /// Capture session jsonl from Claude Code projects and emit to render-site/.
    Capture {
        /// Project directory (where render-site/ lives)
        #[arg(long)]
        project: std::path::PathBuf,

        /// Capture mode: session | recent | both (default: both)
        #[arg(long, default_value = "both")]
        mode: String,

        /// Claude Code project slug (default: derived from project path via canonicalize + replace('/', "-"))
        #[arg(long)]
        slug: Option<String>,

        /// Recent mode: number of turns to emit (default: 5)
        #[arg(long, default_value_t = 5)]
        n: usize,

        /// Recent mode: include turns without visual artifact (default: false)
        #[arg(long, default_value_t = false)]
        all: bool,
    },
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::Subscriber::builder()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();
    let cli = Cli::parse();
    match cli.command {
        Commands::Mcp => {
            // B-plan: delegate to render-session-mcp binary.
            // Prefer the sibling binary in the same install directory; fall back to PATH.
            let exe_dir = std::env::current_exe()
                .ok()
                .and_then(|p| p.parent().map(|d| d.to_path_buf()));
            let mcp_path = exe_dir
                .map(|d| d.join("render-session-mcp"))
                .filter(|p| p.exists())
                .unwrap_or_else(|| std::path::PathBuf::from("render-session-mcp"));

            let status = tokio::process::Command::new(&mcp_path)
                .stdin(std::process::Stdio::inherit())
                .stdout(std::process::Stdio::inherit())
                .stderr(std::process::Stdio::inherit())
                .status()
                .await
                .map_err(|e| {
                    tracing::error!(
                        error = %e,
                        path = %mcp_path.display(),
                        "failed to spawn render-session-mcp"
                    );
                    e
                })?;

            if !status.success() {
                let code = status.code().unwrap_or(-1);
                tracing::error!(exit_code = code, "render-session-mcp exited non-zero");
                anyhow::bail!("render-session-mcp exited with {}", status);
            }
        }
        Commands::Serve {
            port,
            dir,
            watch_tick,
        } => {
            // Spawn the parent-death watch loop so that if the MCP server (our parent)
            // dies, this serve process self-exits within ~5 seconds.
            tokio::spawn(render_session_core::child::watch_parent_death());
            let watch_tick_dur = watch_tick.map(|t| {
                let clamped = if t == 0 {
                    tracing::warn!("watch_tick=0 not allowed, clamping to 1");
                    1
                } else {
                    t
                };
                std::time::Duration::from_secs(clamped)
            });
            render_session_core::serve::run(port, std::path::PathBuf::from(dir), watch_tick_dur)
                .await?;
        }
        Commands::Gen { project } => {
            let project_path = std::path::PathBuf::from(&project);

            let mut layers: Vec<render_session_core::config::Config> = Vec::new();
            if let Some(c) = render_session_core::config::load_user_global().map_err(|e| {
                tracing::error!(
                    error = %e,
                    project = %project,
                    layer = "user-global",
                    "config load failed"
                );
                e
            })? {
                layers.push(c);
            }
            if let Some(c) =
                render_session_core::config::load_project(&project_path).map_err(|e| {
                    tracing::error!(
                        error = %e,
                        project = %project,
                        layer = "project",
                        "config load failed"
                    );
                    e
                })?
            {
                layers.push(c);
            }
            if let Some(c) = render_session_core::config::load_lane(&project_path).map_err(|e| {
                tracing::error!(
                    error = %e,
                    project = %project,
                    layer = "lane",
                    "config load failed"
                );
                e
            })? {
                layers.push(c);
            }

            let merged = render_session_core::config::merge(layers);

            let list_path = render_session_core::gen::emit_list_json(&merged, &project_path)
                .map_err(|e| {
                    tracing::error!(error = %e, project = %project, "emit_list_json failed");
                    e
                })?;
            tracing::info!(file = %list_path.display(), "list.json emitted");
            println!("{}", list_path.display());

            let rules_path = render_session_core::gen::emit_rules_md(&merged, &project_path)
                .map_err(|e| {
                    tracing::error!(error = %e, project = %project, "emit_rules_md failed");
                    e
                })?;
            tracing::info!(file = %rules_path.display(), "render-lanes.md emitted");
            println!("{}", rules_path.display());
        }
        Commands::Report { dir, title } => {
            use tokio::io::AsyncReadExt as _;
            let mut body = String::new();
            tokio::io::stdin()
                .read_to_string(&mut body)
                .await
                .map_err(|e| {
                    tracing::error!(error = %e, "failed to read stdin for report");
                    e
                })?;
            let path = render_session_core::writer::write_report(
                std::path::Path::new(&dir),
                &title,
                &body,
            )
            .await
            .map_err(|e| {
                tracing::error!(error = %e, dir = %dir, title = %title, "write_report failed");
                e
            })?;
            println!("{}", path.display());
        }
        Commands::Capture {
            project,
            mode,
            slug,
            n,
            all,
        } => {
            let claude_slug = match slug {
                Some(s) => s,
                None => derive_slug(&project).map_err(|e| {
                    tracing::error!(project = %project.display(), error = %e, "derive_slug failed");
                    e
                })?,
            };
            let only_with_visual = !all;

            // Phase 4 (b): load project config, extract recent.filter if present.
            // yaml absent → Ok(None) → legacy path. yaml parse error → warn + legacy path.
            let project_config = match render_session_core::config::load_project(&project) {
                Ok(Some(cfg)) => Some(cfg),
                Ok(None) => None,
                Err(e) => {
                    tracing::warn!(
                        project = %project.display(),
                        error = %e,
                        "yaml parse failed, falling back to legacy path"
                    );
                    None
                }
            };
            let merged = match project_config {
                Some(cfg) => render_session_core::config::merge(vec![cfg]),
                None => render_session_core::config::Config::default(),
            };
            let filter_chain_cfg = merged
                .categories
                .get("recent")
                .and_then(|c| c.filter.as_ref());
            let filter_registry: Option<render_session_core::filters::FilterRegistry> =
                filter_chain_cfg
                    .map(|_| render_session_core::filters::FilterRegistry::with_builtins());
            let filter_arg = match (filter_registry.as_ref(), filter_chain_cfg) {
                (Some(reg), Some(cfg)) => Some((reg, cfg)),
                _ => None,
            };

            match mode.as_str() {
                "session" => {
                    // session mode: filter not applied (single-item capture).
                    if let Some(p) = render_session_core::sources::session::capture_session(
                        &project,
                        &claude_slug,
                    )
                    .map_err(|e| {
                        tracing::error!(error = %e, "capture_session failed");
                        e
                    })? {
                        println!("{}", p.display());
                    }
                }
                "recent" => {
                    for p in render_session_core::sources::session::capture_recent(
                        &project,
                        &claude_slug,
                        n,
                        only_with_visual,
                        filter_arg,
                    )
                    .map_err(|e| {
                        tracing::error!(error = %e, "capture_recent failed");
                        e
                    })? {
                        println!("{}", p.display());
                    }
                }
                "both" => {
                    // session: filter not applied
                    if let Some(p) = render_session_core::sources::session::capture_session(
                        &project,
                        &claude_slug,
                    )
                    .map_err(|e| {
                        tracing::error!(error = %e, "capture_session failed");
                        e
                    })? {
                        println!("{}", p.display());
                    }
                    // recent: filter applied if configured
                    for p in render_session_core::sources::session::capture_recent(
                        &project,
                        &claude_slug,
                        n,
                        only_with_visual,
                        filter_arg,
                    )
                    .map_err(|e| {
                        tracing::error!(error = %e, "capture_recent failed");
                        e
                    })? {
                        println!("{}", p.display());
                    }
                }
                other => {
                    anyhow::bail!("invalid mode {:?}, expected session|recent|both", other);
                }
            }
        }
    }
    Ok(())
}

/// Derive the Claude Code project slug from a project directory path.
///
/// Canonicalizes the path and replaces every `/` with `-`, matching legacy
/// `render-session.py:41`.  Intended for macOS/Linux only; Windows path
/// separator handling is deferred to Phase 6+.
fn derive_slug(project: &std::path::Path) -> anyhow::Result<String> {
    let canonical = project.canonicalize().map_err(|e| {
        tracing::error!(project = %project.display(), error = %e, "canonicalize failed");
        e
    })?;
    Ok(canonical.to_string_lossy().replace('/', "-"))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    /// Verify that spawning a short-lived process and awaiting its status works correctly.
    ///
    /// We spawn `true` (exits 0) and verify status.success() == true.
    /// We also verify that dropping the Future before poll does NOT kill the child
    /// (kill_on_drop defaults to false for tokio::process::Command).
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_mcp_commands_status_await() {
        // Spawn a process that exits immediately with success.
        // Use `/bin/true` on Unix (always exits 0).
        let true_bin = if cfg!(target_os = "macos") || cfg!(target_os = "linux") {
            "true"
        } else {
            "cmd"
        };

        let status = tokio::process::Command::new(true_bin)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .await
            .expect("spawn `true`");

        assert!(status.success(), "`true` must exit with success");

        // Now verify kill_on_drop=false behaviour: spawn a long-running process,
        // drop the Child handle before it exits, then verify the process is still alive.
        let child = tokio::process::Command::new("sleep")
            .arg("30")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(false)
            .spawn()
            .expect("spawn `sleep 30`");

        let pid = child.id().expect("child has pid") as libc::pid_t;

        // Drop the Child handle — with kill_on_drop=false the process keeps running.
        drop(child);

        // Give the OS a moment to process.
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        // kill(pid, 0) == 0 means process exists.
        #[allow(unsafe_code)]
        let probe = unsafe { libc::kill(pid, 0) };
        assert_eq!(
            probe, 0,
            "child should still be alive after handle drop (kill_on_drop=false)"
        );

        // Clean up.
        #[allow(unsafe_code)]
        unsafe {
            libc::kill(pid, libc::SIGTERM);
        }
    }
}