use std::{collections::BTreeMap, fs, path::Path};
use super::{
DurableMemoryError,
paths::{MANIFEST_FILE, TOPICS_DIR},
state::atomic_write,
};
const MAX_BYTES: usize = 8 * 1024;
const MAX_ENTRIES: usize = 512;
const TITLE_SHARE_NUMERATOR: usize = 3;
const TITLE_SHARE_DENOMINATOR: usize = 4;
const OMITTED_NOTE_RESERVE: usize = 128;
const MAX_SOURCE_BYTES: u64 = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ManifestEntry {
pub(crate) relative_path: String,
pub(crate) title: String,
pub(crate) read_count: u64,
}
pub(crate) fn write_scope_manifest(
scope_dir: &Path,
heading: &str,
read_counts: &BTreeMap<String, u64>,
) -> Result<String, DurableMemoryError> {
let entries = collect_topics(scope_dir, read_counts)?;
let content = render_manifest(heading, scope_dir, &entries);
let path = scope_dir.join(MANIFEST_FILE);
atomic_write(&path, content.as_bytes())?;
Ok(content)
}
pub(crate) fn render_injected_context(
global_dir: &Path,
global_manifest: &str,
global_pending: &str,
workspace_dir: &Path,
workspace_manifest: &str,
workspace_pending: &str,
) -> String {
format!(
"## Global memory manifest\n**Scope root:** `{global}`\n\n{global_manifest}{global_pending}\n## Workspace memory manifest\n**Scope root:** `{workspace}`\n\n{workspace_manifest}{workspace_pending}",
global = global_dir.display(),
workspace = workspace_dir.display(),
)
}
pub(crate) fn observation_title(path: &Path) -> String {
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("observation.md");
topic_title(path, file_name)
}
fn render_manifest(heading: &str, scope_dir: &Path, entries: &[ManifestEntry]) -> String {
let header = format!(
"# {heading}\n\n> Generated by Merry. Do not edit this file directly.\n> Paths are relative to `{dir}`.\n",
dir = sanitize_inline(&scope_dir.display().to_string()),
);
if entries.is_empty() {
return truncate_utf8(
&format!("{header}\nNo topics have been recorded yet.\n"),
MAX_BYTES,
)
.to_owned();
}
let title_budget = MAX_BYTES * TITLE_SHARE_NUMERATOR / TITLE_SHARE_DENOMINATOR;
let mut ranked = entries.to_vec();
ranked.sort_by(|left, right| {
right
.read_count
.cmp(&left.read_count)
.then_with(|| left.relative_path.cmp(&right.relative_path))
});
ranked.truncate(MAX_ENTRIES);
let mut content = truncate_utf8(&header, MAX_BYTES).to_owned();
if content.len() < header.len() {
return content;
}
let mut untitled = Vec::new();
let mut included = 0usize;
let mut started_topics = false;
for entry in &ranked {
let mut addition = String::new();
if !started_topics {
addition.push_str("\n## Topics\n");
}
addition.push_str("\n- **");
addition.push_str(&sanitize_inline(&entry.title));
addition.push_str("** (`");
addition.push_str(&entry.relative_path);
addition.push_str("`)\n");
if content.len().saturating_add(addition.len()) > title_budget {
untitled.push(entry);
continue;
}
content.push_str(&addition);
started_topics = true;
included += 1;
}
if !untitled.is_empty() {
let tail_max = MAX_BYTES.saturating_sub(OMITTED_NOTE_RESERVE);
let tail_prefix = "\n## More topics\n\nBy file name under `topics/`:";
let mut slugs = Vec::new();
let mut tail_len = content.len() + tail_prefix.len() + 1;
for entry in untitled {
let slug = entry
.relative_path
.strip_prefix("topics/")
.unwrap_or(&entry.relative_path)
.strip_suffix(".md")
.unwrap_or(&entry.relative_path);
let separator_len = if slugs.is_empty() { 1 } else { 2 };
if tail_len + separator_len + slug.len() > tail_max {
break;
}
tail_len += separator_len + slug.len();
slugs.push(slug);
included += 1;
}
slugs.sort_unstable();
if !slugs.is_empty() {
content.push_str(tail_prefix);
for (index, slug) in slugs.iter().enumerate() {
content.push_str(if index == 0 { " " } else { ", " });
content.push_str(slug);
}
content.push('\n');
}
let omitted = entries.len().saturating_sub(included);
if omitted > 0 {
let note = format!("\n{omitted} more topics are not listed.\n");
if content.len().saturating_add(note.len()) <= MAX_BYTES {
content.push_str(¬e);
}
}
}
content
}
fn collect_topics(
scope_dir: &Path,
read_counts: &BTreeMap<String, u64>,
) -> Result<Vec<ManifestEntry>, DurableMemoryError> {
let directory = scope_dir.join(TOPICS_DIR);
let entries = match fs::read_dir(&directory) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(source) => {
return Err(DurableMemoryError::Io {
operation: "list memory topics",
path: directory,
source,
});
}
};
let mut topics = Vec::new();
for entry in entries {
let entry = entry.map_err(|source| DurableMemoryError::Io {
operation: "read memory topic entry",
path: directory.clone(),
source,
})?;
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
if !name.ends_with(".md") || name.starts_with('.') {
continue;
}
let path = entry.path();
let metadata = entry.metadata().map_err(|source| DurableMemoryError::Io {
operation: "inspect memory topic",
path: path.clone(),
source,
})?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
continue;
}
let relative_path = format!("{TOPICS_DIR}/{name}");
let title = topic_title(&path, name);
topics.push(ManifestEntry {
read_count: read_counts.get(&relative_path).copied().unwrap_or(0),
relative_path,
title,
});
}
topics.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
Ok(topics)
}
fn topic_title(path: &Path, file_name: &str) -> String {
let bytes = fs::read(path).unwrap_or_default();
let text = String::from_utf8_lossy(&bytes[..bytes.len().min(MAX_SOURCE_BYTES as usize)]);
for line in text.lines() {
let trimmed = line.trim();
if let Some(title) = trimmed.strip_prefix("# ") {
let title = title.trim();
if !title.is_empty() {
return sanitize_inline(title).to_owned();
}
}
}
file_name.trim_end_matches(".md").to_owned()
}
fn sanitize_inline(value: &str) -> String {
value
.chars()
.map(|character| {
if character.is_control() || character == '`' {
' '
} else {
character
}
})
.collect()
}
pub(crate) fn truncate_utf8(text: &str, max_bytes: usize) -> &str {
let mut end = text.len().min(max_bytes);
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
}