blotter-cli 0.15.0

A tiny CLI for AI agents to log the cuts they hit during work.
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
pub mod cli;
pub mod commands;
pub mod error;
pub mod output;
pub mod store;

use crate::error::{AppError, AppResult};
use jiff::{SignedDuration, Timestamp, Unit};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fmt::Write as _;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Minor,
    Major,
    Blocker,
}

impl Severity {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Minor => "minor",
            Self::Major => "major",
            Self::Blocker => "blocker",
        }
    }

    pub fn rank(self) -> u8 {
        match self {
            Self::Minor => 0,
            Self::Major => 1,
            Self::Blocker => 2,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cmd: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum LogEvent {
    Cut {
        id: String,
        ts: String,
        agent: String,
        text: String,
        tags: Vec<String>,
        severity: Severity,
        cwd: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        source: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        evidence: Option<Evidence>,
    },
    Dogear {
        id: String,
        ts: String,
        agent: String,
        text: String,
        tags: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        evidence: Option<String>,
        cwd: String,
    },
    Resolve {
        id: String,
        ts: String,
        agent: String,
        note: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        task: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pr: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        commit: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        url: Option<String>,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        dropped: bool,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        amend: bool,
    },
    #[serde(other)]
    Unknown,
}

impl LogEvent {
    pub fn id(&self) -> Option<&str> {
        match self {
            Self::Cut { id, .. } | Self::Dogear { id, .. } | Self::Resolve { id, .. } => Some(id),
            Self::Unknown => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Resolution {
    pub ts: String,
    pub agent: String,
    pub note: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pr: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub dropped: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub amended: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListItem {
    pub kind: String,
    pub id: String,
    pub ts: String,
    pub agent: String,
    pub text: String,
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<Severity>,
    pub cwd: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<serde_json::Value>,
    pub status: ItemStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolution: Option<Resolution>,
}

impl ListItem {
    pub(crate) fn from_record(event: LogEvent, resolution: Option<Resolution>) -> Self {
        let status = if resolution.is_some() {
            ItemStatus::Resolved
        } else {
            ItemStatus::Open
        };
        match event {
            LogEvent::Cut {
                id,
                ts,
                agent,
                text,
                tags,
                severity,
                cwd,
                source,
                evidence,
            } => Self {
                kind: "cut".into(),
                id,
                ts,
                agent,
                text,
                tags,
                severity: Some(severity),
                cwd,
                source,
                evidence: evidence
                    .map(|evidence| serde_json::to_value(evidence).expect("evidence serializes")),
                status,
                resolution,
            },
            LogEvent::Dogear {
                id,
                ts,
                agent,
                text,
                tags,
                evidence,
                cwd,
            } => Self {
                kind: "dogear".into(),
                id,
                ts,
                agent,
                text,
                tags,
                severity: None,
                cwd,
                source: None,
                evidence: evidence.map(serde_json::Value::String),
                status,
                resolution,
            },
            LogEvent::Resolve { .. } | LogEvent::Unknown => {
                unreachable!("folded records are cut or dogear")
            }
        }
    }
}

pub fn is_auto_capture(tags: &[String]) -> bool {
    tags.iter().any(|tag| tag == "auto")
}

pub(crate) fn partition_auto_captures(
    items: Vec<ListItem>,
    include_auto: bool,
) -> (Vec<ListItem>, Vec<ListItem>) {
    if include_auto {
        (items, Vec::new())
    } else {
        items
            .into_iter()
            .partition(|item| !is_auto_capture(&item.tags))
    }
}

pub(crate) fn auto_capture_warning(count: usize) -> String {
    let noun = if count == 1 { "record" } else { "records" };
    format!("{count} auto-captured {noun} hidden; use --include-auto to include them")
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ItemStatus {
    Open,
    Resolved,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IdNamespace {
    Bl,
    Pc,
}

pub(crate) fn id_namespace(id: &str) -> Option<IdNamespace> {
    match id.get(..3) {
        Some(prefix) if prefix.eq_ignore_ascii_case("bl_") => Some(IdNamespace::Bl),
        Some(prefix) if prefix.eq_ignore_ascii_case("pc_") => Some(IdNamespace::Pc),
        _ => None,
    }
}

pub fn effective_now() -> AppResult<Timestamp> {
    let timestamp = match std::env::var("BLOTTER_NOW") {
        Ok(value) if !value.is_empty() => value.parse::<Timestamp>().map_err(|_| {
            AppError::config(
                "BLOTTER_NOW must be a full RFC3339 timestamp",
                "Set BLOTTER_NOW to a value like 2026-07-09T18:30:00Z or unset it.",
            )
        })?,
        Ok(_) | Err(std::env::VarError::NotPresent) => Timestamp::now(),
        Err(std::env::VarError::NotUnicode(_)) => {
            return Err(AppError::config(
                "BLOTTER_NOW is not valid UTF-8",
                "Set BLOTTER_NOW to a full RFC3339 timestamp or unset it.",
            ));
        }
    };
    timestamp
        .round(Unit::Millisecond)
        .map_err(|error| AppError::internal(error.to_string()))
}

pub fn format_timestamp(timestamp: Timestamp) -> String {
    format!("{timestamp:.3}")
}

pub fn parse_since(value: &str, now: Timestamp) -> AppResult<Timestamp> {
    parse_cutoff("--since", value, now)
}

pub fn parse_before(value: &str, now: Timestamp) -> AppResult<Timestamp> {
    parse_cutoff("--before", value, now)
}

fn parse_cutoff(flag_name: &str, value: &str, now: Timestamp) -> AppResult<Timestamp> {
    let is_since = flag_name == "--since";
    let relative_suggested_fix = || {
        if is_since {
            "Use a full RFC3339 timestamp, Nd, or Nh.".to_owned()
        } else {
            format!("Use {flag_name} with a full RFC3339 timestamp, Nd, or Nh.")
        }
    };
    let smaller_duration_suggested_fix = || {
        if is_since {
            "Use a smaller Nd or Nh duration.".to_owned()
        } else {
            format!("Use a smaller relative value for {flag_name}.")
        }
    };
    let absolute_suggested_fix = || {
        if is_since {
            "Use a full RFC3339 timestamp such as 2026-07-09T18:30:00Z, or a relative value such as 7d or 12h.".to_owned()
        } else {
            format!(
                "Use {flag_name} with a full RFC3339 timestamp such as 2026-07-09T18:30:00Z, or a relative value such as 7d or 12h."
            )
        }
    };
    if let Some((number, unit)) = value.split_at_checked(value.len().saturating_sub(1))
        && !number.is_empty()
        && number.bytes().all(|byte| byte.is_ascii_digit())
        && matches!(unit, "d" | "h")
    {
        let amount = number.parse::<i64>().map_err(|_| {
            AppError::invalid_argument(
                format!("invalid {flag_name} value '{value}'"),
                relative_suggested_fix(),
            )
        })?;
        let duration = if unit == "d" {
            amount.checked_mul(24)
        } else {
            Some(amount)
        }
        .and_then(SignedDuration::try_from_hours)
        .ok_or_else(|| {
            AppError::invalid_argument(
                format!("{flag_name} value '{value}' is too large"),
                smaller_duration_suggested_fix(),
            )
        })?;
        return now.checked_sub(duration).map_err(|_| {
            AppError::invalid_argument(
                format!("{flag_name} value '{value}' is outside the supported range"),
                smaller_duration_suggested_fix(),
            )
        });
    }

    value.parse::<Timestamp>().map_err(|_| {
        AppError::invalid_argument(
            format!("invalid {flag_name} value '{value}'"),
            absolute_suggested_fix(),
        )
    })
}

pub fn compute_id(
    ts: &str,
    agent: &str,
    text: &str,
    severity: Severity,
    tags: &[String],
) -> String {
    let mut tags = tags.to_vec();
    tags.sort();
    tags.dedup();
    let count = tags.len().to_string();
    let mut fields: Vec<&str> = vec![
        "bl1",
        "cut",
        ts,
        agent,
        text,
        severity.as_str(),
        count.as_str(),
    ];
    fields.extend(tags.iter().map(String::as_str));
    compute_id_fields_bytes(&fields, 6)
}

pub fn compute_dogear_id(ts: &str, agent: &str, text: &str, tags: &[String]) -> String {
    let mut tags = tags.to_vec();
    tags.sort();
    tags.dedup();
    let count = tags.len().to_string();
    // v1 dogear identity: a version literal and the kind provide domain
    // separation, and every tag is its own length-prefixed field (TupleHash
    // style) so tag-set boundaries cannot collide (`["a","b"]` != `["a,b"]`).
    // 80-bit digest; cut IDs use the matching framed scheme at 48 bits.
    let mut fields: Vec<&str> = vec!["bl1", "dogear", ts, agent, text, count.as_str()];
    fields.extend(tags.iter().map(String::as_str));
    compute_id_fields_bytes(&fields, 10)
}

fn compute_id_fields_bytes(fields: &[&str], bytes: usize) -> String {
    let mut hash = Sha256::new();
    for field in fields {
        hash.update((field.len() as u32).to_le_bytes());
        hash.update(field.as_bytes());
    }
    let digest = hash.finalize();
    let mut id = String::with_capacity(3 + bytes * 2);
    id.push_str("bl_");
    for byte in &digest[..bytes] {
        write!(&mut id, "{byte:02x}").expect("writing to a String cannot fail");
    }
    id
}

pub fn resolve_agent(flag: Option<String>) -> (String, &'static str) {
    if let Some(agent) = flag.filter(|value| !value.is_empty()) {
        return (agent, "flag");
    }
    if let Ok(agent) = std::env::var("BLOTTER_AGENT")
        && !agent.is_empty()
    {
        return (agent, "env");
    }
    if std::env::var_os("CLAUDECODE").is_some() {
        return ("claude-code".into(), "detected");
    }
    if std::env::vars_os().any(|(key, _)| key.to_string_lossy().starts_with("CODEX_")) {
        return ("codex".into(), "detected");
    }
    if std::env::vars_os().any(|(key, _)| key.to_string_lossy().starts_with("CURSOR_")) {
        return ("cursor".into(), "detected");
    }
    ("unknown".into(), "default")
}

pub(crate) fn resolve_agent_checked(
    flag: Option<String>,
    reject_resolved_whitespace: bool,
) -> AppResult<(String, &'static str)> {
    if flag.as_deref().is_some_and(|agent| agent.trim().is_empty()) {
        return Err(AppError::invalid_input(
            "agent name cannot be empty or whitespace-only",
            "Pass a non-empty --agent NAME or omit the flag.",
        ));
    }
    let (agent, source) = resolve_agent(flag);
    if reject_resolved_whitespace && agent.trim().is_empty() {
        return Err(AppError::invalid_input(
            "agent name cannot be whitespace-only",
            "Pass a non-empty --agent NAME or set BLOTTER_AGENT.",
        ));
    }
    Ok((agent, source))
}