second-brain-cli 0.12.0

Memory layer for AI coding agents: ingest, recall, and sync across machines
use anyhow::{Context, Result, bail};

pub fn cmd_redact(dry_run: bool) -> Result<()> {
    if !dry_run {
        bail!(
            "usage: sb redact --dry-run (the daemon redacts stored content by itself when it starts)"
        );
    }
    let api = crate::api::base_url();
    let client = crate::api::client(std::time::Duration::from_secs(3600))?;
    let report: serde_json::Value = crate::api::daemon_ok(
        client
            .get(format!("{api}/v1/redaction"))
            .send()
            .context("calling redaction on daemon")?,
    )?
    .json()?;
    print!("{}", render(&report));
    Ok(())
}

fn render(report: &serde_json::Value) -> String {
    let state = &report["state"];
    let mut out = match (state["phase"].as_str(), state["after"].as_i64()) {
        (Some("done"), _) => "migration: done\n".to_string(),
        (Some(phase), Some(after)) => format!("migration: in progress ({phase} after {after})\n"),
        (Some(phase), None) => format!("migration: in progress ({phase})\n"),
        _ => format!("migration: {state}\n"),
    };
    out.push_str("would redact (dry run, nothing changed):\n");
    for location in ["memories", "chunks", "entities", "relations", "sync_log"] {
        let counts = &report[location];
        out.push_str(&format!(
            "  {location:<9} {} rows\n",
            counts["rows"].as_u64().unwrap_or(0)
        ));
        for (kind, n) in counts["findings"].as_object().into_iter().flatten() {
            out.push_str(&format!("    {kind:<24} {n}\n"));
        }
    }
    out.push_str(&render_skipped(report));
    out
}

fn render_skipped(report: &serde_json::Value) -> String {
    let rows = report["skipped"].as_array().map_or(&[][..], Vec::as_slice);
    let omitted = report["skipped_omitted"].as_u64().unwrap_or(0);
    if rows.is_empty() && omitted == 0 {
        return String::new();
    }
    let mut out = "skipped (could not parse; text redacted in place, not synced):\n".to_string();
    for row in rows {
        out.push_str(&format!(
            "  {} {}: {}\n",
            row["table"].as_str().unwrap_or("?"),
            row["row"].as_str().unwrap_or("?"),
            row["reason"].as_str().unwrap_or("")
        ));
    }
    if omitted > 0 {
        out.push_str(&format!("  ... and {omitted} more\n"));
    }
    out
}

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

    #[test]
    fn renders_counts_by_location_and_kind() {
        let report = serde_json::json!({
            "state": {"phase": "memories", "after": 512},
            "memories": {"rows": 2, "findings": {"github_token": 3}},
            "chunks": {"rows": 0, "findings": {}},
            "entities": {"rows": 1, "findings": {"github_token": 1}},
            "relations": {"rows": 0, "findings": {}},
            "sync_log": {"rows": 5, "findings": {"aws_access_key_id": 1, "jwt": 4}},
        });
        assert_eq!(
            render(&report),
            "migration: in progress (memories after 512)\n\
             would redact (dry run, nothing changed):\n  \
             memories  2 rows\n    \
             github_token             3\n  \
             chunks    0 rows\n  \
             entities  1 rows\n    \
             github_token             1\n  \
             relations 0 rows\n  \
             sync_log  5 rows\n    \
             aws_access_key_id        1\n    \
             jwt                      4\n"
        );
    }

    #[test]
    fn skipped_rows_are_listed_after_the_counts() {
        let report = serde_json::json!({
            "state": {"phase": "done"},
            "memories": {"rows": 0, "findings": {}},
            "skipped": [
                {"table": "memories", "row": "rowid 42", "reason": "invalid uuid"},
                {"table": "relations", "row": "a/b/bogus", "reason": "unknown relation_type"},
            ],
            "skipped_omitted": 3,
        });
        assert_eq!(
            render(&report),
            "migration: done\n\
             would redact (dry run, nothing changed):\n  \
             memories  0 rows\n  \
             chunks    0 rows\n  \
             entities  0 rows\n  \
             relations 0 rows\n  \
             sync_log  0 rows\n\
             skipped (could not parse; text redacted in place, not synced):\n  \
             memories rowid 42: invalid uuid\n  \
             relations a/b/bogus: unknown relation_type\n  \
             ... and 3 more\n"
        );
    }

    #[test]
    fn a_report_without_skipped_rows_prints_no_skipped_section() {
        for report in [
            serde_json::json!({"state": {"phase": "done"}}),
            serde_json::json!({"state": {"phase": "done"}, "skipped": [], "skipped_omitted": 0}),
        ] {
            assert!(!render(&report).contains("skipped"));
        }
    }

    #[test]
    fn a_phase_without_a_cursor_reads_as_in_progress() {
        let report = serde_json::json!({"state": {"phase": "relations"}});
        assert!(render(&report).starts_with("migration: in progress (relations)\n"));
    }

    #[test]
    fn a_finished_migration_says_done() {
        let report = serde_json::json!({"state": {"phase": "done"}});
        assert!(render(&report).starts_with("migration: done\n"));
    }
}