memd 1.5.2

Local memory CLI for AI agents with hybrid retrieval
Documentation
use super::action::*;
use super::rank::*;
use super::state::*;
use super::*;

pub(super) fn render_memory_md(
    project_state: &ProjectState,
    health_lines: &[String],
    project_takeaways: &[Takeaway],
    global_takeaways: &[Takeaway],
) -> String {
    let mut out = String::new();
    out.push_str("# memory.md\n\n");
    out.push_str("Generated by `memd memory-md`.\n\n");
    render_latest_project_state(&mut out, project_state);
    if !health_lines.is_empty() {
        out.push_str("## Memory health\n\n");
        for line in health_lines {
            out.push_str(&format!("- {line}\n"));
        }
        out.push('\n');
    }
    out.push_str("## Session-Start Use\n\n");
    out.push_str("- Read this file before task-specific retrieval.\n");
    out.push_str("- Refresh it at the start of substantive sessions with `memd memory-md`.\n");
    out.push_str("- Then run task-specific `memd agent-context` or `memd search`.\n\n");
    out.push_str("## Agent Guidance\n\n");
    out.push_str("- Treat fact-library items as durable memory to verify against current files, logs, or tests before applying.\n");
    out.push_str("- Use `Latest Project State` for the first resume pass; use `memd agent-context` for task-specific retrieval.\n\n");
    out.push_str("## Scoring\n\n");
    out.push_str("- Explicit `priority:N` or `importance:N` tags dominate when present.\n");
    out.push_str("- Decisions, finishes, evidence, recurring tags, multi-query matches, and search score increase priority.\n");
    out.push_str("- Repeated lessons should be recorded again with a higher `priority:N` tag when they keep mattering.\n\n");

    render_section(&mut out, "Project Fact Library", project_takeaways);
    if !global_takeaways.is_empty() {
        render_section(&mut out, "Machine-Wide Fact Library", global_takeaways);
    }
    out
}

pub(super) fn render_latest_project_state(out: &mut String, state: &ProjectState) {
    out.push_str("## Latest Project State\n\n");
    out.push_str("### Scope & Freshness\n\n");
    out.push_str(&format!("- tenant_id: `{}`\n", state.tenant_id));
    out.push_str(&format!(
        "- project_id: `{}`\n",
        state.project_id.as_deref().unwrap_or("<none>")
    ));
    if let Some(configured) = state.configured_project_dir.as_deref() {
        out.push_str(&format!("- configured_project_dir: `{configured}`\n"));
    } else {
        out.push_str("- configured_project_dir: `<none>`\n");
    }
    out.push_str(&format!(
        "- resolved_project_dir: `{}`\n",
        state.resolved_project_dir
    ));
    out.push_str(&format!(
        "- generated_unix_ms: `{}`\n\n",
        state.generated_unix_ms
    ));

    out.push_str("### Worktree\n\n");
    out.push_str(&format!("- git: {}\n\n", state.git.summary));

    out.push_str("### Latest Work\n\n");
    if let Some(task) = &state.latest_task {
        out.push_str(&format!("- task: {}\n", render_state_signal(task)));
    } else {
        out.push_str("- task: none detected in `tasks/todo.md`\n");
    }
    if let Some(handoff) = &state.latest_handoff {
        out.push_str(&format!("- handoff: {}\n", render_state_signal(handoff)));
    } else {
        out.push_str("- handoff: none detected under `docs/handoffs/`\n");
    }
    if let Some(vcs) = &state.latest_vcs {
        out.push_str(&format!("- vcs: {}\n", render_state_signal(vcs)));
    }
    out.push('\n');

    out.push_str("### Next Actions\n\n");
    match state.task_source_state {
        TaskSourceState::Missing => {
            out.push_str(
                "- Task source `tasks/todo.md` is missing; open-task state is unknown.\n\n",
            );
        }
        TaskSourceState::ParseFailed => {
            out.push_str(
                "- Task source `tasks/todo.md` could not be parsed; open-task state is unknown.\n\n",
            );
        }
        TaskSourceState::ParsedNoOpenTasks => {
            out.push_str("- No open next actions detected from `tasks/todo.md`.\n\n");
        }
        TaskSourceState::ParsedOpenTasks => {
            for (idx, action) in state.next_actions.iter().take(3).enumerate() {
                out.push_str(&format!(
                    "{}. {} ([{}:{}])\n",
                    idx + 1,
                    inline_code_text(&action.text),
                    action.source_path,
                    action.line
                ));
            }
            out.push('\n');
        }
    }

    out.push_str("### Memory Warnings\n\n");
    let warnings = project_state_warnings(state);
    if warnings.is_empty() {
        out.push_str("- none detected\n\n");
    } else {
        for warning in warnings {
            out.push_str(&format!("- {warning}\n"));
        }
        out.push('\n');
    }
}

pub(super) fn render_state_signal(signal: &StateSignal) -> String {
    let source = match signal.line {
        Some(line) => format!("{}:{}", signal.source_path, line),
        None => signal.source_path.clone(),
    };
    match signal.heading.as_deref() {
        Some(heading) if !heading.is_empty() => {
            format!(
                "{} - {} ([{}])",
                heading,
                inline_code_text(&signal.text),
                source
            )
        }
        _ => format!("{} ([{}])", inline_code_text(&signal.text), source),
    }
}

pub(super) fn project_state_warnings(state: &ProjectState) -> Vec<String> {
    let mut warnings = Vec::new();
    warnings.extend(state.scope_warnings.iter().cloned());
    if let Some(warning) = &state.git.warning {
        warnings.push(warning.clone());
    }
    if let Some(unreadable) = state.memory.unreadable_active_chunks {
        if unreadable > 0 {
            warnings.push(format!(
                "memory degraded: {unreadable} active chunks could not be read from payload segments"
            ));
        }
    }
    if let Some(warning) = &state.memory.scan_warning {
        warnings.push(warning.clone());
    }
    warnings.extend(state.collection_warnings.iter().cloned());
    warnings
}

pub(super) fn render_section(out: &mut String, title: &str, takeaways: &[Takeaway]) {
    out.push_str(&format!("## {title}\n\n"));
    if takeaways.is_empty() {
        out.push_str("- No takeaways found yet.\n\n");
        return;
    }

    let mut categorized = takeaways
        .iter()
        .map(|takeaway| (takeaway_category(takeaway), takeaway))
        .collect::<Vec<_>>();
    categorized.sort_by(|(left_category, left), (right_category, right)| {
        left_category
            .order
            .cmp(&right_category.order)
            .then_with(|| {
                right
                    .priority
                    .partial_cmp(&left.priority)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .then_with(|| right.timestamp_created.cmp(&left.timestamp_created))
    });

    for (heading, _) in TAKEAWAY_CATEGORIES {
        let group = categorized
            .iter()
            .filter(|(category, _)| category.heading == *heading)
            .collect::<Vec<_>>();
        if group.is_empty() {
            continue;
        }
        out.push_str(&format!("### {heading}\n\n"));
        for (idx, (category, takeaway)) in group.iter().enumerate() {
            render_takeaway(out, idx + 1, takeaway, category.reason);
        }
        out.push('\n');
    }
}

pub(super) fn render_takeaway(out: &mut String, idx: usize, takeaway: &Takeaway, reason: &str) {
    out.push_str(&format!(
        "{}. {}\n",
        idx,
        summarize_text(&takeaway.text, 320)
    ));
    out.push_str(&format!(
        "   - priority: `{:.1}`; chunk: `{}`; type: `{}`; tenant: `{}`",
        takeaway.priority, takeaway.chunk_id, takeaway.chunk_type, takeaway.tenant_id
    ));
    if let Some(project_id) = takeaway.project_id.as_deref() {
        out.push_str(&format!("; project: `{project_id}`"));
    }
    if takeaway.timestamp_created > 0 {
        out.push_str(&format!(
            "; created_unix_ms: `{}`",
            takeaway.timestamp_created
        ));
    }
    out.push('\n');
    out.push_str(&format!("   - reason: `{reason}`\n"));
    out.push_str(&format!(
        "   - agent action: `{}`\n",
        inline_code_text(&agent_action_for_takeaway(takeaway, reason))
    ));
    if !takeaway.tags.is_empty() {
        out.push_str(&format!(
            "   - tags: `{}`\n",
            takeaway
                .tags
                .iter()
                .take(8)
                .cloned()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if !takeaway.sources.is_empty() {
        out.push_str(&format!(
            "   - matched: `{}`\n",
            takeaway
                .sources
                .iter()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
}

pub(super) fn agent_action_for_takeaway(takeaway: &Takeaway, reason: &str) -> String {
    if let Some(action) = explicit_agent_action(&takeaway.text) {
        return summarize_text(&action, 240);
    }

    let evidence = summarize_text(&takeaway.text, 180);
    match reason {
        "decision or rationale" => {
            format!("Apply this decision when the same scope appears: {evidence}")
        }
        "validated fix or result" => {
            format!("Reuse this validated fix when the same failure appears: {evidence}")
        }
        "failure or root-cause evidence" => {
            format!(
                "Check for this known failure before retrying and avoid repeating it: {evidence}"
            )
        }
        "command, path, or parameter evidence" => {
            format!("Use or verify this command/path exactly when relevant: {evidence}")
        }
        "explicit follow-up" => {
            format!(
                "Treat this as pending work and resolve it before claiming completion: {evidence}"
            )
        }
        "evidence or run result" => {
            format!("Use this as evidence only after confirming it still matches current files or tests: {evidence}")
        }
        _ => format!("Translate this takeaway into a task-specific rule before acting: {evidence}"),
    }
}