nippo 0.1.1

Claude Code session collector for daily reports and reflection
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Claude Code JSONL セッションファイルのパーサ。
//!
//! ~/.claude/projects/ 以下に保存される JSONL ファイルを読み取り、
//! ユーザーのプロンプト・アシスタントの応答・ツール使用状況を抽出する。
//! rayon による並列パースと、2パスデシリアライズによる高速化を行う。

use anyhow::{Context, Result};
use rayon::prelude::*;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::filter::DateFilter;
use crate::output::{DateRange, MessageCounts, PromptSummary, SessionSummary};

// ---------------------------------------------------------------------------
// JSONL エントリ型(実データの構造に基づく)
//
// トップレベル type: user, assistant, queue-operation, progress,
//                    file-history-snapshot, system, last-prompt
// このうち日報生成に必要なのは user と assistant のみ。
// ---------------------------------------------------------------------------

/// JSONL 1行ごとのエントリ。type フィールドで判別する。
#[derive(Deserialize)]
#[serde(tag = "type")]
enum JournalEntry {
    #[serde(rename = "user")]
    User(UserEntry),
    #[serde(rename = "assistant")]
    Assistant(AssistantEntry),
    /// queue-operation, progress 等は構造を見ないため unit で受ける
    #[serde(other)]
    Other,
}

/// ユーザーメッセージ
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct UserEntry {
    timestamp: Option<String>,
    session_id: Option<String>,
    cwd: Option<String>,
    git_branch: Option<String>,
    #[serde(default)]
    is_sidechain: Option<bool>,
    message: Option<UserMessage>,
}

#[derive(Deserialize)]
struct UserMessage {
    content: MessageContent,
}

/// message.content は文字列またはブロック配列のどちらかが来る
#[derive(Deserialize)]
#[serde(untagged)]
enum MessageContent {
    Text(String),
    Blocks(Vec<ContentBlock>),
}

/// コンテンツブロックの種別
#[derive(Deserialize)]
#[serde(tag = "type")]
enum ContentBlock {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "tool_use")]
    ToolUse {
        name: Option<String>,
        input: Option<serde_json::Value>,
    },
    /// tool_result, thinking 等は中身を使わない
    #[serde(other)]
    Unknown,
}

/// アシスタントメッセージ
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AssistantEntry {
    timestamp: Option<String>,
    session_id: Option<String>,
    cwd: Option<String>,
    git_branch: Option<String>,
    message: Option<AssistantMessage>,
}

#[derive(Deserialize)]
struct AssistantMessage {
    content: Option<Vec<ContentBlock>>,
    usage: Option<TokenUsage>,
}

#[derive(Deserialize)]
struct TokenUsage {
    input_tokens: Option<u64>,
    output_tokens: Option<u64>,
}

/// 2パスデシリアライズ用の軽量ヘッダ。
/// 1パス目で type と timestamp だけ読み、フィルタを通過したものだけ2パス目でフル展開する。
#[derive(Deserialize)]
struct EntryHeader {
    #[serde(rename = "type")]
    entry_type: Option<String>,
    timestamp: Option<String>,
}

// ---------------------------------------------------------------------------
// パース結果の中間表現
// ---------------------------------------------------------------------------

/// 1セッション分のパース結果
pub struct RawSession {
    pub session_id: String,
    pub project: String,
    pub project_path: String,
    pub git_branch: Option<String>,
    pub user_entries: Vec<ParsedUserEntry>,
    pub assistant_entries: Vec<ParsedAssistantEntry>,
}

pub struct ParsedUserEntry {
    pub timestamp: String,
    pub text: String,
}

pub struct ParsedAssistantEntry {
    pub timestamp: String,
    pub tool_uses: Vec<String>,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub file_paths: Vec<String>,
}

// ---------------------------------------------------------------------------
// セッションファイルの探索
// ---------------------------------------------------------------------------

pub struct SessionFile {
    pub path: PathBuf,
    pub mtime: SystemTime,
}

/// ~/.claude/projects/ 以下の全 JSONL ファイルを探索する
pub fn discover_session_files(claude_dir: &Path) -> Result<Vec<SessionFile>> {
    let projects_dir = claude_dir.join("projects");
    if !projects_dir.exists() {
        anyhow::bail!(
            "Claude Code のセッションデータが見つかりません: {}\n\n\
             Claude Code(CLI または VS Code 拡張)を使用すると、\n\
             セッションデータが自動的にこのディレクトリに保存されます。\n\
             カスタムディレクトリを指定する場合は --claude-dir オプションを使用してください。",
            projects_dir.display()
        );
    }

    let pattern = format!("{}/**/*.jsonl", projects_dir.display());
    let mut files = Vec::new();

    for entry in glob::glob(&pattern).context("Failed to read glob pattern")? {
        let path = match entry {
            Ok(p) => p,
            Err(_) => continue,
        };
        let metadata = match fs::metadata(&path) {
            Ok(m) => m,
            Err(_) => continue,
        };
        if !metadata.is_file() {
            continue;
        }
        let mtime = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);
        files.push(SessionFile { path, mtime });
    }

    Ok(files)
}

// ---------------------------------------------------------------------------
// JSONL パース
// ---------------------------------------------------------------------------

/// ユーザープロンプトの最大文字数(超過分は省略)
const MAX_PROMPT_LEN: usize = 500;

fn truncate(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max).collect();
        format!("{truncated}...")
    }
}

/// ユーザーメッセージからテキスト部分を抽出する
fn extract_user_text(content: &MessageContent) -> Option<String> {
    match content {
        MessageContent::Text(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(truncate(trimmed, MAX_PROMPT_LEN))
            }
        }
        MessageContent::Blocks(blocks) => {
            let texts: Vec<&str> = blocks
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect();
            if texts.is_empty() {
                None
            } else {
                Some(truncate(&texts.join("\n"), MAX_PROMPT_LEN))
            }
        }
    }
}

/// アシスタント応答からツール名とファイルパスを抽出する
fn extract_tool_info(blocks: &[ContentBlock]) -> (Vec<String>, Vec<String>) {
    let mut tool_names = Vec::new();
    let mut file_paths = Vec::new();

    for block in blocks {
        if let ContentBlock::ToolUse {
            name: Some(n),
            input,
        } = block
        {
            tool_names.push(n.clone());

            // ファイル操作系ツールからパスを抽出
            if let Some(input_val) = input
                && matches!(n.as_str(), "Read" | "Write" | "Edit" | "Glob" | "Grep")
            {
                if let Some(fp) = input_val.get("file_path").and_then(|v| v.as_str()) {
                    file_paths.push(fp.to_string());
                }
                if let Some(fp) = input_val.get("path").and_then(|v| v.as_str()) {
                    file_paths.push(fp.to_string());
                }
            }
        }
    }

    (tool_names, file_paths)
}

/// cwd からプロジェクト名(ディレクトリ末尾)を取得する
fn extract_project_from_cwd(cwd: &str) -> String {
    Path::new(cwd)
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_else(|| cwd.to_string())
}

/// 1つの JSONL ファイルをパースし、RawSession を返す。
/// エントリが1件もフィルタを通過しなければ None。
pub fn parse_session_file(path: &Path, filter: &DateFilter) -> Result<Option<RawSession>> {
    let file = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
    let reader = BufReader::new(file);

    let mut user_entries = Vec::new();
    let mut assistant_entries = Vec::new();
    let mut session_id = String::new();
    let mut project = String::new();
    let mut project_path = String::new();
    let mut git_branch: Option<String> = None;

    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => continue,
        };

        if line.trim().is_empty() {
            continue;
        }

        // 1パス目: type と timestamp だけ確認してフィルタ
        let header: EntryHeader = match serde_json::from_str(&line) {
            Ok(h) => h,
            Err(_) => continue,
        };

        let entry_type = match &header.entry_type {
            Some(t) => t.as_str(),
            None => continue,
        };

        if !matches!(entry_type, "user" | "assistant") {
            continue;
        }

        if let Some(ts) = &header.timestamp {
            if !filter.matches(ts) {
                continue;
            }
        } else {
            continue;
        }

        // 2パス目: フィルタを通過したエントリのみフルデシリアライズ
        let entry: JournalEntry = match serde_json::from_str(&line) {
            Ok(e) => e,
            Err(_) => continue,
        };

        match entry {
            JournalEntry::User(user) => {
                // サブエージェントの内部メッセージはスキップ
                if user.is_sidechain.unwrap_or(false) {
                    continue;
                }

                if session_id.is_empty()
                    && let Some(sid) = &user.session_id
                {
                    session_id = sid.clone();
                }
                if project.is_empty()
                    && let Some(cwd) = &user.cwd
                {
                    project = extract_project_from_cwd(cwd);
                    project_path = cwd.clone();
                }
                if git_branch.is_none() {
                    git_branch = user.git_branch.clone();
                }

                if let Some(msg) = &user.message
                    && let Some(text) = extract_user_text(&msg.content)
                {
                    user_entries.push(ParsedUserEntry {
                        timestamp: user.timestamp.unwrap_or_default(),
                        text,
                    });
                }
            }
            JournalEntry::Assistant(assistant) => {
                if session_id.is_empty()
                    && let Some(sid) = &assistant.session_id
                {
                    session_id = sid.clone();
                }
                if project.is_empty()
                    && let Some(cwd) = &assistant.cwd
                {
                    project = extract_project_from_cwd(cwd);
                    project_path = cwd.clone();
                }
                if git_branch.is_none() {
                    git_branch = assistant.git_branch.clone();
                }

                if let Some(msg) = &assistant.message {
                    let blocks = msg.content.as_deref().unwrap_or(&[]);
                    let (tool_uses, file_paths) = extract_tool_info(blocks);
                    let (input_tokens, output_tokens) = msg
                        .usage
                        .as_ref()
                        .map(|u| (u.input_tokens.unwrap_or(0), u.output_tokens.unwrap_or(0)))
                        .unwrap_or((0, 0));

                    assistant_entries.push(ParsedAssistantEntry {
                        timestamp: assistant.timestamp.unwrap_or_default(),
                        tool_uses,
                        input_tokens,
                        output_tokens,
                        file_paths,
                    });
                }
            }
            JournalEntry::Other => {}
        }
    }

    if user_entries.is_empty() && assistant_entries.is_empty() {
        return Ok(None);
    }

    // ファイル名をセッションIDのフォールバックに使う
    if session_id.is_empty() {
        session_id = path
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();
    }

    Ok(Some(RawSession {
        session_id,
        project,
        project_path,
        git_branch,
        user_entries,
        assistant_entries,
    }))
}

// ---------------------------------------------------------------------------
// 並列収集
// ---------------------------------------------------------------------------

/// 全セッションファイルを並列でパースし、フィルタ済みの RawSession を返す
pub fn collect_sessions(claude_dir: &Path, filter: &DateFilter) -> Result<Vec<RawSession>> {
    let files = discover_session_files(claude_dir)?;

    // ファイルの更新日時で大半をスキップ(mtime プレフィルタ)
    let cutoff = filter.mtime_cutoff();
    let candidates: Vec<&SessionFile> = files
        .iter()
        .filter(|f| cutoff.map(|c| f.mtime >= c).unwrap_or(true))
        .collect();

    let sessions: Vec<RawSession> = candidates
        .par_iter()
        .filter_map(|sf| parse_session_file(&sf.path, filter).ok().flatten())
        .collect();

    Ok(sessions)
}

// ---------------------------------------------------------------------------
// セッションサマリーの構築
// ---------------------------------------------------------------------------

/// RawSession から出力用の SessionSummary を構築する
pub fn summarize_session(session: &RawSession) -> SessionSummary {
    let mut tool_usage: HashMap<String, u32> = HashMap::new();
    let mut total_input_tokens: u64 = 0;
    let mut total_output_tokens: u64 = 0;
    let mut all_file_paths: Vec<String> = Vec::new();

    for entry in &session.assistant_entries {
        for tool in &entry.tool_uses {
            *tool_usage.entry(tool.clone()).or_insert(0) += 1;
        }
        total_input_tokens += entry.input_tokens;
        total_output_tokens += entry.output_tokens;
        all_file_paths.extend(entry.file_paths.iter().cloned());
    }

    all_file_paths.sort();
    all_file_paths.dedup();

    let user_prompts: Vec<PromptSummary> = session
        .user_entries
        .iter()
        .map(|e| PromptSummary {
            text: e.text.clone(),
            timestamp: e.timestamp.clone(),
        })
        .collect();

    // タイムスタンプから時間範囲を計算
    let mut timestamps: Vec<&str> = Vec::new();
    for e in &session.user_entries {
        timestamps.push(&e.timestamp);
    }
    for e in &session.assistant_entries {
        timestamps.push(&e.timestamp);
    }
    timestamps.sort();

    let time_range = DateRange {
        start: timestamps.first().map(|s| s.to_string()),
        end: timestamps.last().map(|s| s.to_string()),
    };

    SessionSummary {
        session_id: session.session_id.clone(),
        project: session.project.clone(),
        project_path: session.project_path.clone(),
        git_branch: session.git_branch.clone(),
        time_range,
        user_prompts,
        tool_usage,
        message_counts: MessageCounts {
            user: session.user_entries.len(),
            assistant: session.assistant_entries.len(),
        },
        total_input_tokens,
        total_output_tokens,
        files_touched: all_file_paths,
    }
}