second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::SystemTime;

use second_brain_core::sqlite_store::NoteKind;
use second_brain_core::{machine, write_queue};
use serde_json::{Value, json};

use super::asked::Asked;
use super::daemon;

const SUBSTANTIVE_TOOL_CALLS: usize = 10;

const EDIT_TOOLS: [&str; 4] = ["Edit", "Write", "MultiEdit", "NotebookEdit"];

const NOTE_TOOL: &str = "note";

/// Asks the agent for a session-end note, once per session, when it did real
/// work and none is stored or queued; every doubt allows the stop.
pub(super) fn run(_event: &'static str, input: &Value) -> Option<Value> {
    if input["stop_hook_active"].as_bool() == Some(true) {
        return None;
    }
    let session_id = input["session_id"].as_str().filter(|id| !id.is_empty())?;
    let data_dir = machine::data_dir().ok()?;
    let asked = Asked::new(&data_dir, "stop");
    if asked.already(session_id) {
        return None;
    }
    let transcript = input["transcript_path"].as_str()?;
    if !shows_substantive_work(Path::new(transcript)) {
        return None;
    }
    if note_is_queued(&data_dir.join(write_queue::DIR_NAME), session_id) {
        return None;
    }
    let unnoted = stored_notes(session_id)? == 0;
    (unnoted && asked.record(session_id, SystemTime::now())).then(|| block(session_id))
}

/// Counts only the main agent's calls: subagent work is on `isSidechain`
/// lines.
fn shows_substantive_work(transcript: &Path) -> bool {
    let Ok(file) = File::open(transcript) else {
        return false;
    };
    let mut calls = HashSet::new();
    for line in BufReader::new(file).split(b'\n') {
        let Ok(line) = line else {
            break;
        };
        if !line.windows(b"tool_use".len()).any(|w| w == b"tool_use") {
            continue;
        }
        let Ok(entry) = serde_json::from_slice::<Value>(&line) else {
            continue;
        };
        if entry["type"] != "assistant" || entry["isSidechain"] == true {
            continue;
        }
        let Some(content) = entry["message"]["content"].as_array() else {
            continue;
        };
        for call in content.iter().filter(|item| item["type"] == "tool_use") {
            if call["name"]
                .as_str()
                .is_some_and(|name| EDIT_TOOLS.contains(&name))
            {
                return true;
            }
            if let Some(id) = call["id"].as_str() {
                calls.insert(id.to_string());
            }
            if calls.len() >= SUBSTANTIVE_TOOL_CALLS {
                return true;
            }
        }
    }
    false
}

fn note_is_queued(queue: &Path, session_id: &str) -> bool {
    let Ok(entries) = std::fs::read_dir(queue) else {
        return false;
    };
    entries
        .flatten()
        .filter(|entry| {
            entry
                .file_name()
                .to_str()
                .is_some_and(write_queue::is_entry_name)
        })
        .any(|entry| holds_session_end_note(&entry.path(), session_id))
}

/// Reads only the entry's label, which a sealed entry keeps in plaintext.
fn holds_session_end_note(path: &Path, session_id: &str) -> bool {
    let Ok(bytes) = std::fs::read(path) else {
        return false;
    };
    let Ok(label) = write_queue::read_label(&bytes) else {
        return false;
    };
    label.tool == NOTE_TOOL
        && label.session_id.as_deref() == Some(session_id)
        && label
            .kind
            .as_deref()
            .is_none_or(|kind| kind == NoteKind::SessionEnd.as_str())
}

fn stored_notes(session_id: &str) -> Option<usize> {
    let reply = daemon::get(
        "/v1/notes",
        &[
            ("session_id", session_id),
            ("kind", NoteKind::SessionEnd.as_str()),
        ],
    )?;
    reply["notes"].as_array().map(Vec::len)
}

fn block(session_id: &str) -> Value {
    let kind = NoteKind::SessionEnd.as_str();
    json!({
        "decision": "block",
        "reason": format!(
            "Before stopping, record this session for the next agent: call the second-brain \
             MCP tool `{NOTE_TOOL}` with session_id \"{session_id}\" and kind \"{kind}\", giving \
             the decision you reached and why, the dead ends you ruled out, the open items left, \
             and anything blocked on the user. Then stop."
        ),
    })
}