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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
use crate::cli::DoctorArgs;
use crate::error::{AppError, AppResult};
use crate::output::{self, Meta};
use crate::store;
use crate::{LogEvent, compute_dogear_id, compute_id};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

const EMPTY_WARNING: &str = "no blotter file yet; healthy empty state";
const EMPTY_FIX: &str = "Pass an existing --file PATH or omit --file to inspect discovered state.";
// Byte mirror of `commands::add::EVIDENCE_DELIMITERS` for raw leak scans.
// A slash is a path parent, not a delimiter.
const EVIDENCE_DELIMITERS: &[u8] = b",;)]}&#\"'";
// Byte mirror of `commands::add::HOME_PREFIXES`.
const HOME_PREFIXES: [&[u8]; 4] = [b"/Users/", b"/home/", b"-Users-", b"-home-"];

struct LeakScan<'a> {
    home: Option<Vec<u8>>,
    dash_home: Option<Vec<u8>>,
    deny: &'a [String],
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DoctorData {
    pub healthy: bool,
    pub findings: Vec<Finding>,
    pub checked_lines: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fix: Option<FixData>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Finding {
    pub line: usize,
    pub kind: String,
    pub message: String,
    #[serde(default)]
    pub fixable: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FixData {
    pub changed: bool,
    pub applied: Vec<AppliedFix>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quarantine: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restore_hint: Option<String>,
    pub dry_run: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AppliedFix {
    pub line: usize,
    pub kind: String,
    pub action: String,
}

pub fn run(
    args: DoctorArgs,
    file: Option<PathBuf>,
    pretty: bool,
    now: Timestamp,
) -> AppResult<i32> {
    if args.dry_run && !args.fix {
        return Err(AppError::invalid_argument(
            "--dry-run requires --fix for doctor",
            "Run `blotter doctor --fix --dry-run` to preview repairs.",
        ));
    }
    if args.leaks && args.fix {
        return Err(AppError::invalid_argument(
            "--leaks conflicts with --fix for doctor",
            "Run `blotter doctor --leaks` without --fix; the gate is read-only.",
        ));
    }
    if !args.deny.is_empty() && !args.leaks {
        return Err(AppError::invalid_argument(
            "--deny requires --leaks for doctor",
            "Run `blotter doctor --leaks --deny LITERAL` to scan a literal deny pattern.",
        ));
    }
    if args.deny.iter().any(|pattern| pattern.is_empty()) {
        return Err(AppError::invalid_argument(
            "--deny requires a non-empty literal",
            "Run `blotter doctor --leaks --deny LITERAL` with a non-empty literal.",
        ));
    }
    let leak_scan = args.leaks.then(|| {
        let home = current_home_path();
        let dash_home = home.as_ref().map(|home| {
            home.iter()
                .map(|byte| if *byte == b'/' { b'-' } else { *byte })
                .collect()
        });
        LeakScan {
            home,
            dash_home,
            deny: &args.deny,
        }
    });
    let resolved = store::discover(file)?;
    let mut warnings = resolved.warnings.clone();
    let (mut data, file_existed) = match (args.fix, args.dry_run) {
        (false, _) => diagnose_shared(&resolved, &mut warnings, leak_scan.as_ref())?,
        (true, true) => {
            let (mut data, file_existed) =
                diagnose_shared(&resolved, &mut warnings, leak_scan.as_ref())?;
            data.fix = Some(FixData {
                changed: false,
                applied: planned_fixes(&data.findings),
                backup: None,
                quarantine: None,
                restore_hint: None,
                dry_run: true,
            });
            (data, file_existed)
        }
        (true, false) => diagnose_and_fix(&resolved, &mut warnings, now)?,
    };
    add_gitignored_finding(&mut data, &resolved, file_existed);
    let exit = i32::from(!data.healthy);
    let mut meta = Meta::new();
    meta.file = Some(resolved.path.to_string_lossy().into_owned());
    meta.warnings = warnings;
    output::write_success(data, pretty, meta)
        .map_err(|error| AppError::from_io(error, Path::new("stdout")))?;
    Ok(exit)
}

fn diagnose_shared(
    resolved: &store::ResolvedFile,
    warnings: &mut Vec<String>,
    leak_scan: Option<&LeakScan<'_>>,
) -> AppResult<(DoctorData, bool)> {
    store::read_or_empty(
        &resolved.path,
        resolved.explicit,
        warnings,
        EMPTY_WARNING,
        EMPTY_FIX,
        empty_data,
        |log| {
            let bytes = store::read_bytes(log, &resolved.path)?;
            Ok(inspect(&bytes, leak_scan))
        },
    )
}

fn diagnose_and_fix(
    resolved: &store::ResolvedFile,
    warnings: &mut Vec<String>,
    now: Timestamp,
) -> AppResult<(DoctorData, bool)> {
    match store::with_exclusive(&resolved.path, false, |log| {
        apply_fixes(log, &resolved.path, now)
    }) {
        Ok(data) => Ok((data, true)),
        Err(error) if error.code == "not_found" && error.exit_code == 66 && !resolved.explicit => {
            warnings.push(EMPTY_WARNING.into());
            let mut data = empty_data();
            data.fix = Some(FixData {
                changed: false,
                applied: Vec::new(),
                backup: None,
                quarantine: None,
                restore_hint: None,
                dry_run: false,
            });
            Ok((data, false))
        }
        Err(error) if error.code == "not_found" && error.exit_code == 66 => {
            Err(AppError::not_found(
                format!("blotter file not found: {}", resolved.path.display()),
                EMPTY_FIX,
            ))
        }
        Err(error) => Err(error),
    }
}

fn apply_fixes(log: &mut File, path: &Path, now: Timestamp) -> AppResult<DoctorData> {
    let original = store::read_bytes(log, path)?;
    let before = inspect(&original, None);
    let applied = planned_fixes(&before.findings);
    if applied.is_empty() {
        return Ok(with_fix(
            before,
            FixData {
                changed: false,
                applied,
                backup: None,
                quarantine: None,
                restore_hint: None,
                dry_run: false,
            },
        ));
    }

    let permissions = log
        .metadata()
        .map_err(|error| AppError::from_io(error, path))?
        .permissions();
    // A symlinked log is locked and read through the link; the swap must land
    // on the target, not replace the link with a regular file.
    let path = &store::resolve_symlinked_log(path)?;
    let backup = store::write_new_file(
        &store::suffixed_path(path, &format!(".bak-{}", store::backup_timestamp(now))),
        &original,
        &permissions,
    )?;
    let quarantined = quarantined_bytes(&original, &applied);
    let quarantine = store::append_file(
        &store::suffixed_path(path, ".quarantine.jsonl"),
        &quarantined,
        &permissions,
    )?;
    let repaired = repaired_bytes(&original, &applied);
    store::replace_log(
        path,
        &repaired,
        &permissions,
        &format!(".tmp-fix-{}", std::process::id()),
    )?;
    let repaired = fs::read(path).map_err(|error| AppError::from_io(error, path))?;
    Ok(with_fix(
        inspect(&repaired, None),
        FixData {
            changed: true,
            applied,
            backup: Some(backup.to_string_lossy().into_owned()),
            quarantine: Some(quarantine.to_string_lossy().into_owned()),
            restore_hint: Some(store::restore_hint(&backup, path)),
            dry_run: false,
        },
    ))
}

fn with_fix(mut data: DoctorData, fix: FixData) -> DoctorData {
    data.fix = Some(fix);
    data
}

fn repaired_bytes(bytes: &[u8], applied: &[AppliedFix]) -> Vec<u8> {
    let remove_lines: HashSet<_> = applied
        .iter()
        .filter(|fix| fix.action == "quarantined")
        .map(|fix| fix.line)
        .collect();
    let mut repaired = Vec::new();
    for (index, raw) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() {
        if !remove_lines.contains(&(index + 1)) {
            repaired.extend_from_slice(raw);
        }
    }
    repaired
}

fn quarantined_bytes(bytes: &[u8], applied: &[AppliedFix]) -> Vec<u8> {
    let remove_lines: HashSet<_> = applied
        .iter()
        .filter(|fix| fix.action == "quarantined")
        .map(|fix| fix.line)
        .collect();
    let mut quarantined = Vec::new();
    for (index, raw) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() {
        if remove_lines.contains(&(index + 1)) {
            quarantined.extend_from_slice(raw);
            if !raw.ends_with(b"\n") {
                quarantined.push(b'\n');
            }
        }
    }
    quarantined
}

fn planned_fixes(findings: &[Finding]) -> Vec<AppliedFix> {
    findings
        .iter()
        .filter(|finding| finding.fixable)
        .map(|finding| AppliedFix {
            line: finding.line,
            kind: finding.kind.clone(),
            action: "quarantined".into(),
        })
        .collect()
}

fn add_gitignored_finding(
    data: &mut DoctorData,
    resolved: &store::ResolvedFile,
    file_existed: bool,
) {
    if file_existed
        && let Some(repo) = resolved.repo.as_ref()
        && resolved.path.starts_with(repo)
        && Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(["check-ignore", "-q", "--"])
            .arg(&resolved.path)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    {
        data.findings.push(finding(
            0,
            "gitignored",
            "blotter file is gitignored; blotter will not appear in diffs",
        ));
        data.healthy = false;
    }
}

fn empty_data() -> DoctorData {
    DoctorData {
        healthy: true,
        findings: Vec::new(),
        checked_lines: 0,
        fix: None,
    }
}

fn finding(line: usize, kind: impl Into<String>, message: impl Into<String>) -> Finding {
    let kind = kind.into();
    Finding {
        line,
        fixable: matches!(kind.as_str(), "torn_line" | "malformed" | "conflict_marker"),
        kind,
        message: message.into(),
    }
}

fn inspect(bytes: &[u8], leak_scan: Option<&LeakScan<'_>>) -> DoctorData {
    let mut findings = Vec::new();
    let mut leak_findings = Vec::new();
    let mut records = HashMap::<String, Vec<u8>>::new();
    let mut record_ids = HashSet::new();
    let mut resolves = Vec::<(usize, String)>::new();
    let mut checked_lines = 0;
    for scanned in store::scan(bytes) {
        checked_lines += 1;
        let line = scanned.line;
        if let Some(leak_scan) = leak_scan {
            add_leak_findings(&mut leak_findings, line, scanned.raw, leak_scan);
        }
        match scanned.event {
            Err(store::ScanIssue::Torn) => findings.push(finding(
                line,
                "torn_line",
                "final physical line is not newline-terminated",
            )),
            Err(store::ScanIssue::Malformed(message)) => {
                if scanned.raw.starts_with(b"<<<<<<< ") || scanned.raw.starts_with(b">>>>>>> ") {
                    findings.push(finding(
                        line,
                        "conflict_marker",
                        "complete git conflict-marker line found",
                    ));
                } else {
                    findings.push(finding(line, "malformed", message));
                }
            }
            Err(store::ScanIssue::Unknown(kind)) => findings.push(finding(
                line,
                "unknown_kind",
                kind.map_or_else(
                    || "event has no string kind field".into(),
                    |kind| format!("unknown event kind '{kind}'"),
                ),
            )),
            Ok(event) => match event {
                LogEvent::Cut {
                    id,
                    ts,
                    agent,
                    text,
                    tags,
                    severity,
                    ..
                } => {
                    if id
                        .get(..3)
                        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("bl_"))
                    {
                        let expected = compute_id(&ts, &agent, &text, severity, &tags);
                        if id != expected {
                            findings.push(finding(
                                line,
                                "id_conflict",
                                format!("cut ID {id} does not recompute to {expected}"),
                            ));
                        }
                    }
                    if let Some(first) = records.get(&id) {
                        let (kind, message) = if first == scanned.raw {
                            (
                                "duplicate_cut",
                                format!("byte-identical duplicate cut {id}"),
                            )
                        } else {
                            (
                                "id_conflict",
                                format!(
                                    "cut {id} has a different payload than its first occurrence"
                                ),
                            )
                        };
                        findings.push(finding(line, kind, message));
                    } else {
                        records.insert(id.clone(), scanned.raw.to_vec());
                    }
                    record_ids.insert(id);
                }
                LogEvent::Dogear {
                    id,
                    ts,
                    agent,
                    text,
                    tags,
                    ..
                } => {
                    if id
                        .get(..3)
                        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("bl_"))
                    {
                        let mut tags = tags;
                        tags.sort();
                        let expected = compute_dogear_id(&ts, &agent, &text, &tags);
                        if id != expected {
                            findings.push(finding(
                                line,
                                "id_conflict",
                                format!("dogear ID {id} does not recompute to {expected}"),
                            ));
                        }
                    }
                    if let Some(first) = records.get(&id) {
                        let (kind, message) = if first == scanned.raw {
                            (
                                "duplicate_dogear",
                                format!("byte-identical duplicate dogear {id}"),
                            )
                        } else {
                            (
                                "id_conflict",
                                format!(
                                    "dogear {id} has a different payload than its first occurrence"
                                ),
                            )
                        };
                        findings.push(finding(line, kind, message));
                    } else {
                        records.insert(id.clone(), scanned.raw.to_vec());
                    }
                    record_ids.insert(id);
                }
                LogEvent::Resolve { id, .. } => {
                    resolves.push((line, id));
                }
                LogEvent::Unknown => unreachable!("scanner classifies unknown events"),
            },
        }
    }
    for (line, id) in resolves {
        if !record_ids.contains(&id) {
            findings.push(finding(
                line,
                "orphan_resolve",
                format!("resolve references unknown record {id}"),
            ));
        }
    }
    findings.extend(leak_findings);
    DoctorData {
        healthy: findings.is_empty(),
        findings,
        checked_lines,
        fix: None,
    }
}

fn current_home_path() -> Option<Vec<u8>> {
    let cwd = std::env::current_dir().ok()?;
    store::home_dir(&cwd)
        .filter(|home| home.is_absolute())
        .and_then(|home| home.to_str().map(|home| home.as_bytes().to_vec()))
}

fn evidence_delimiter(byte: u8) -> bool {
    byte.is_ascii_whitespace() || EVIDENCE_DELIMITERS.contains(&byte)
}

fn path_prefix_boundary(bytes: &[u8], end: usize, separator: u8) -> bool {
    bytes
        .get(end)
        .is_none_or(|byte| *byte == b'/' || *byte == separator || evidence_delimiter(*byte))
}

fn dash_start_boundary(bytes: &[u8], start: usize) -> bool {
    start == 0
        || bytes
            .get(start - 1)
            .is_some_and(|byte| evidence_delimiter(*byte) || *byte == b'/')
}

fn generic_home_path_end(bytes: &[u8], start: usize) -> Option<usize> {
    let prefix = HOME_PREFIXES
        .into_iter()
        .find(|prefix| bytes[start..].starts_with(prefix))?;
    let separator = prefix[0];
    // Generic aliases only start a token. Unlike exact $HOME matching, a
    // preceding slash makes the slash form a nested path such as
    // /mnt/home/shared; a dash-encoded slug normally does follow a slash.
    if start != 0
        && !bytes
            .get(start - 1)
            .is_some_and(|byte| evidence_delimiter(*byte) || (separator == b'-' && *byte == b'/'))
    {
        return None;
    }
    let component_start = start + prefix.len();
    let mut component_end = component_start;
    while let Some(byte) = bytes.get(component_end) {
        if *byte == b'/' || *byte == separator || evidence_delimiter(*byte) {
            break;
        }
        component_end += 1;
    }
    (component_end > component_start && path_prefix_boundary(bytes, component_end, separator))
        .then_some(component_end)
}

fn contains_home_path(bytes: &[u8], home: Option<&[u8]>, dash_home: Option<&[u8]>) -> bool {
    let mut start = 0;
    while start < bytes.len() {
        let home_end = home
            .filter(|home| bytes[start..].starts_with(home))
            .map(|home| start + home.len())
            .filter(|end| path_prefix_boundary(bytes, *end, b'/'));
        // Exact current home in dash-encoded form; mirrors the redaction-side
        // precedence so dashed usernames and non-generic homes are caught.
        let dash_home_end = dash_home
            .filter(|_| dash_start_boundary(bytes, start))
            .filter(|dash| bytes[start..].starts_with(dash))
            .map(|dash| start + dash.len())
            .filter(|end| path_prefix_boundary(bytes, *end, b'-'));
        if home_end.is_some()
            || dash_home_end.is_some()
            || generic_home_path_end(bytes, start).is_some()
        {
            return true;
        }
        start += 1;
    }
    false
}

fn add_leak_findings(
    findings: &mut Vec<Finding>,
    line: usize,
    raw: &[u8],
    leak_scan: &LeakScan<'_>,
) {
    if contains_home_path(
        raw,
        leak_scan.home.as_deref(),
        leak_scan.dash_home.as_deref(),
    ) {
        findings.push(finding(
            line,
            "leak",
            format!("line {line} contains home path"),
        ));
    }
    for pattern in leak_scan.deny {
        let matches = raw
            .windows(pattern.len())
            .any(|candidate| candidate == pattern.as_bytes());
        if matches {
            findings.push(finding(
                line,
                "leak",
                format!("line {line} contains deny pattern {pattern:?}"),
            ));
        }
    }
}