memory: derive the L3 and L4 paths and citation ids from a track tag #108

Merged
JakeHillion merged 1 commits from jj/pxqtwqrulmxp into main 2026-07-28 18:25:49 +01:00
8 changed files with 319 additions and 166 deletions
Showing only changes of commit 7530203346 - Show all commits

No files matched your search

+13 -4
View File
@@ -10,6 +10,8 @@ use tracing::info;
use tracing::warn;
use tracing_subscriber::EnvFilter;
use crate::personality::PersonalityFile;
mod command;
mod config;
mod conversation;
@@ -246,7 +248,7 @@ async fn run_internal(cmd: InternalCmd) -> Result<()> {
token_file,
} => {
let llm = build_llm_from_endpoint(base_url, model, token_file)?;
memory::run_l2_to_l3u(&input, &output, llm).await
memory::run_l2_to_l3u(&input, &output, PersonalityFile::User.track_tag(), llm).await
}
MemoryCmd::L3uToL4u {
input,
@@ -256,7 +258,8 @@ async fn run_internal(cmd: InternalCmd) -> Result<()> {
token_file,
} => {
let llm = build_llm_from_endpoint(base_url, model, token_file)?;
memory::run_l3u_to_l4u(&input, &output, llm).await
memory::run_l3u_to_l4u(&input, &output, PersonalityFile::User.track_tag(), llm)
.await
}
MemoryCmd::L4uToUserMd {
input,
@@ -267,8 +270,14 @@ async fn run_internal(cmd: InternalCmd) -> Result<()> {
token_file,
} => {
let llm = build_llm_from_endpoint(base_url, model, token_file)?;
let report =
memory::run_l4u_to_user_md(&input, &output, previous.as_deref(), llm).await?;
let report = memory::run_l4u_to_user_md(
&input,
&output,
PersonalityFile::User.track_tag(),
previous.as_deref(),
llm,
)
.await?;
info!(action = ?report.action, "L4u → USER.md done");
Ok(())
}
+25 -51
View File
@@ -25,7 +25,6 @@ use std::path::PathBuf;
use anyhow::Context as _;
use anyhow::Result;
use anyhow::bail;
use chrono::NaiveDate;
use serde::Deserialize;
use tracing::info;
use tracing::warn;
@@ -34,7 +33,10 @@ use crate::llm::ChatBackend;
use crate::llm::ChatMessage;
use crate::memory::claim;
use crate::memory::l4::L4uClaim;
use crate::memory::layout;
use crate::memory::layout::Span;
use crate::memory::store;
use crate::personality::PersonalityFile;
use crate::tools::ToolContext;
use crate::tools::ToolRegistry;
@@ -43,11 +45,7 @@ use crate::tools::ToolRegistry;
const CORPUS_CHAR_LIMIT: usize = 800_000;
/// The date range covered by the chosen L4u file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PeriodSpan {
pub first: NaiveDate,
pub last: NaiveDate,
}
pub type PeriodSpan = Span;
/// What the run did to USER.md on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -73,7 +71,7 @@ pub struct RunReport {
/// Pick the most-recent `l4u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst` file from
/// `input_dir` (greatest `last`, tiebreak greatest `first`) and load its
/// claims.
pub fn load_latest_l4u(input_dir: &Path) -> Result<(PeriodSpan, Vec<L4uClaim>)> {
pub fn load_latest_l4u(input_dir: &Path, tag: &str) -> Result<(PeriodSpan, Vec<L4uClaim>)> {
let mut files: BTreeMap<PeriodSpan, PathBuf> = BTreeMap::new();
for entry in fs::read_dir(input_dir)
.with_context(|| format!("Failed to read input dir {}", input_dir.display()))?
@@ -83,9 +81,9 @@ pub fn load_latest_l4u(input_dir: &Path) -> Result<(PeriodSpan, Vec<L4uClaim>)>
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
if let Some(span) = parse_l4u_filename(name) {
if let Some(span) = layout::parse_l4_filename(tag, name) {
files.insert(span, path);
} else if name.starts_with("l4u-") {
} else if layout::has_l4_prefix(tag, name) {
warn!(
name,
"Skipping L4u file with unparseable period in filename"
@@ -101,18 +99,6 @@ pub fn load_latest_l4u(input_dir: &Path) -> Result<(PeriodSpan, Vec<L4uClaim>)>
Ok((span, claims))
}
/// Parse `l4u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst`. Returns `None` for
/// anything else.
fn parse_l4u_filename(name: &str) -> Option<PeriodSpan> {
let rest = name.strip_prefix("l4u-")?.strip_suffix(".jsonl.zst")?;
if rest.len() != 21 || rest.as_bytes().get(10) != Some(&b'-') {
return None;
}
let first = NaiveDate::parse_from_str(&rest[..10], "%Y-%m-%d").ok()?;
let last = NaiveDate::parse_from_str(&rest[11..], "%Y-%m-%d").ok()?;
Some(PeriodSpan { first, last })
}
fn load_l4u_file(path: &Path) -> Result<Vec<L4uClaim>> {
// USER.md does not cite, so the raw lines behind these claims are of no
// interest here — unlike the levels that derive ids from them.
@@ -146,10 +132,11 @@ pub fn render_l4u_for_prompt(claims: &[L4uClaim]) -> String {
pub async fn run(
input_dir: &Path,
output_dir: &Path,
tag: &str,
previous_path: Option<&Path>,
backend: &dyn ChatBackend,
) -> Result<RunReport> {
let (period, claims) = load_latest_l4u(input_dir)?;
let (period, claims) = load_latest_l4u(input_dir, tag)?;
let previous_text = match previous_path {
Some(p) => {
@@ -269,12 +256,13 @@ pub(crate) async fn decide_and_render(
/// `log/` (LogOnly).
pub async fn run_with_mode(
input_dir: &Path,
tag: &str,
personality: &crate::personality::Personality,
log_dir: &Path,
mode: WriteMode,
backend: &dyn ChatBackend,
) -> Result<RunReport> {
let (period, claims) = load_latest_l4u(input_dir)?;
let (period, claims) = load_latest_l4u(input_dir, tag)?;
let previous_text = personality
.read(crate::personality::PersonalityFile::User)
@@ -300,7 +288,11 @@ pub async fn run_with_mode(
if let Some(prev) = &previous_text {
fs::create_dir_all(log_dir)
.with_context(|| format!("Failed to create log dir {}", log_dir.display()))?;
let log_path = log_dir.join(archived_filename(period, "replaced"));
let log_path = log_dir.join(archived_filename(
PersonalityFile::User.stem(),
period,
"replaced",
));
fs::write(&log_path, prev.as_bytes()).with_context(|| {
format!(
"Failed to archive previous USER.md to {}",
@@ -317,7 +309,11 @@ pub async fn run_with_mode(
| (WriteMode::LogOnly, ReportAction::ReplacedPrevious) => {
fs::create_dir_all(log_dir)
.with_context(|| format!("Failed to create log dir {}", log_dir.display()))?;
let log_path = log_dir.join(archived_filename(period, "candidate"));
let log_path = log_dir.join(archived_filename(
PersonalityFile::User.stem(),
period,
"candidate",
));
fs::write(&log_path, outcome_str.as_bytes()).with_context(|| {
format!(
"Failed to write USER.md candidate to {}",
@@ -348,11 +344,11 @@ pub async fn run_with_mode(
})
}
fn archived_filename(period: PeriodSpan, suffix: &str) -> String {
fn archived_filename(stem: &str, period: PeriodSpan, suffix: &str) -> String {
let run_ts = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
format!(
"USER-{}-{}-{}-{}.md",
period.first, period.last, run_ts, suffix
"{}-{}-{}-{}-{}.md",
stem, period.first, period.last, run_ts, suffix
)
}
@@ -495,32 +491,10 @@ facts already present; remaining differences are wording only\").
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::claim::Confidence;
fn day(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
#[test]
fn parse_l4u_filename_accepts_well_formed() {
let p = parse_l4u_filename("l4u-2026-02-24-2026-05-14.jsonl.zst").unwrap();
assert_eq!(p.first, day(2026, 2, 24));
assert_eq!(p.last, day(2026, 5, 14));
}
#[test]
fn parse_l4u_filename_rejects_l3u_prefix() {
assert!(parse_l4u_filename("l3u-2026-02-24-2026-05-14.jsonl.zst").is_none());
}
#[test]
fn parse_l4u_filename_rejects_malformed() {
assert!(parse_l4u_filename("l4u-broken.jsonl.zst").is_none());
assert!(parse_l4u_filename("l4u-2026-02-24.jsonl.zst").is_none());
assert!(parse_l4u_filename("readme.md").is_none());
}
#[test]
fn parse_comparator_keep() {
let r = parse_comparator_response("{\"decision\":\"keep\",\"reason\":\"only reordering\"}")
+3 -20
View File
@@ -16,8 +16,6 @@ use anyhow::Context as _;
use anyhow::Result;
use anyhow::bail;
use chrono::NaiveDate;
use sha2::Digest;
use sha2::Sha256;
use tracing::info;
use tracing::warn;
@@ -26,6 +24,7 @@ use crate::llm::ChatMessage;
use crate::memory::claim;
use crate::memory::claim::Claim;
use crate::memory::l2::L2Claim;
use crate::memory::layout;
use crate::memory::store;
use crate::tools::ToolContext;
use crate::tools::ToolRegistry;
@@ -43,7 +42,7 @@ pub struct L2Entry {
}
/// An L3u claim: citations point at the `l2-YYYYMMDD-NNN-HHHHHH` ids
/// assigned to the L2 corpus by [`compute_l2_id`].
/// assigned to the L2 corpus by [`layout::l2_claim_id`].
pub type L3uClaim = Claim;
/// Load every `YYYY-MM-DD.jsonl.zst` file in `input_dir` and return its
@@ -89,19 +88,12 @@ fn load_day_file(date: NaiveDate, path: &Path) -> Result<Vec<L2Entry>> {
.into_iter()
.enumerate()
.map(|(index, (raw_line, claim))| L2Entry {
id: compute_l2_id(date, index, &raw_line),
id: layout::l2_claim_id(date, index, &raw_line),
claim,
})
.collect())
}
fn compute_l2_id(date: NaiveDate, index: usize, raw_line: &str) -> String {
let mut h = Sha256::new();
h.update(raw_line.as_bytes());
let hex = format!("{:x}", h.finalize());
format!("l2-{}-{:03}-{}", date.format("%Y%m%d"), index, &hex[..6])
}
/// Render the day-grouped corpus for the LLM. Each day gets a header and
/// each claim a single line: `{id} [{confidence}] {claim_text}`. The L1
/// sources from each L2 claim are deliberately omitted — L3u cites L2,
@@ -268,15 +260,6 @@ mod tests {
store::write_claims(&path, claims).unwrap();
}
#[test]
fn id_format_is_stable_and_zero_padded() {
let a = compute_l2_id(day(2026, 5, 9), 7, "the line");
let b = compute_l2_id(day(2026, 5, 9), 7, "the line");
assert_eq!(a, b);
assert!(a.starts_with("l2-20260509-007-"));
assert_eq!(a.len(), "l2-".len() + 8 + 1 + 3 + 1 + 6);
}
#[test]
fn load_corpus_sorts_by_date_and_assigns_ids() {
let tmp = tempfile::tempdir().unwrap();
+21 -82
View File
@@ -19,9 +19,6 @@ use std::path::PathBuf;
use anyhow::Context as _;
use anyhow::Result;
use anyhow::bail;
use chrono::NaiveDate;
use sha2::Digest;
use sha2::Sha256;
use tracing::info;
use tracing::warn;
@@ -30,6 +27,8 @@ use crate::llm::ChatMessage;
use crate::memory::claim;
use crate::memory::claim::Claim;
use crate::memory::l3::L3uClaim;
use crate::memory::layout;
use crate::memory::layout::Span;
use crate::memory::store;
use crate::tools::ToolContext;
use crate::tools::ToolRegistry;
@@ -40,11 +39,7 @@ use crate::tools::ToolRegistry;
const CORPUS_CHAR_LIMIT: usize = 800_000;
/// The date range covered by a single L3u file, parsed from its filename.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PeriodTag {
pub first: NaiveDate,
pub last: NaiveDate,
}
pub type PeriodTag = Span;
/// A loaded L3u claim with its assigned L4u-input id.
#[derive(Debug, Clone)]
@@ -55,14 +50,14 @@ pub struct L3uEntry {
/// An L4u claim: citations point at the
/// `l3u-YYYYMMDD-YYYYMMDD-NNN-HHHHHH` ids assigned to the L3u corpus by
/// [`compute_l3u_id`].
/// [`layout::l3_claim_id`].
pub type L4uClaim = Claim;
/// Load every `l3u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst` file in `input_dir`
/// and return its claims grouped by period in chronological order. Each
/// claim is tagged with an `l3u-YYYYMMDD-YYYYMMDD-NNN-HHHHHH` id derived
/// from the period and its on-disk line.
pub fn load_l3u_corpus(input_dir: &Path) -> Result<Vec<(PeriodTag, Vec<L3uEntry>)>> {
pub fn load_l3u_corpus(input_dir: &Path, tag: &str) -> Result<Vec<(PeriodTag, Vec<L3uEntry>)>> {
let mut period_files: Vec<(PeriodTag, PathBuf)> = Vec::new();
for entry in fs::read_dir(input_dir)
.with_context(|| format!("Failed to read input dir {}", input_dir.display()))?
@@ -72,14 +67,12 @@ pub fn load_l3u_corpus(input_dir: &Path) -> Result<Vec<(PeriodTag, Vec<L3uEntry>
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
let Some(period) = parse_period_from_filename(name) else {
let Some(period) = layout::parse_l3_filename(tag, name) else {
// Don't warn on the recognised output prefix or other unrelated files;
// anything starting with `l3u-` that fails to parse is suspicious.
if name.starts_with("l3u-") {
warn!(
name,
"Skipping L3u file with unparseable period in filename"
);
// anything claiming to be this track's L3 that fails to parse is
// suspicious.
if layout::has_l3_prefix(tag, name) {
warn!(name, "Skipping L3 file with unparseable period in filename");
}
continue;
};
@@ -88,7 +81,8 @@ pub fn load_l3u_corpus(input_dir: &Path) -> Result<Vec<(PeriodTag, Vec<L3uEntry>
if period_files.is_empty() {
bail!(
"No L3u period files (l3u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst) found in {}",
"No L3 period files (l3{}-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst) found in {}",
tag,
input_dir.display()
);
}
@@ -97,49 +91,23 @@ pub fn load_l3u_corpus(input_dir: &Path) -> Result<Vec<(PeriodTag, Vec<L3uEntry>
let mut out: Vec<(PeriodTag, Vec<L3uEntry>)> = Vec::with_capacity(period_files.len());
for (period, path) in period_files {
let entries = load_period_file(&period, &path)?;
let entries = load_period_file(tag, period, &path)?;
out.push((period, entries));
}
Ok(out)
}
/// Parse `l3u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst` into a `PeriodTag`.
/// Returns `None` for any other shape, including `l4u-*` files.
fn parse_period_from_filename(name: &str) -> Option<PeriodTag> {
let rest = name.strip_prefix("l3u-")?.strip_suffix(".jsonl.zst")?;
// Expect exactly: YYYY-MM-DD-YYYY-MM-DD (10 + 1 + 10 = 21 chars).
if rest.len() != 21 || rest.as_bytes().get(10) != Some(&b'-') {
return None;
}
let first = NaiveDate::parse_from_str(&rest[..10], "%Y-%m-%d").ok()?;
let last = NaiveDate::parse_from_str(&rest[11..], "%Y-%m-%d").ok()?;
Some(PeriodTag { first, last })
}
fn load_period_file(period: &PeriodTag, path: &Path) -> Result<Vec<L3uEntry>> {
fn load_period_file(tag: &str, period: PeriodTag, path: &Path) -> Result<Vec<L3uEntry>> {
Ok(store::read_claims(path)?
.into_iter()
.enumerate()
.map(|(index, (raw_line, claim))| L3uEntry {
id: compute_l3u_id(period, index, &raw_line),
id: layout::l3_claim_id(tag, period, index, &raw_line),
claim,
})
.collect())
}
fn compute_l3u_id(period: &PeriodTag, index: usize, raw_line: &str) -> String {
let mut h = Sha256::new();
h.update(raw_line.as_bytes());
let hex = format!("{:x}", h.finalize());
format!(
"l3u-{}-{}-{:03}-{}",
period.first.format("%Y%m%d"),
period.last.format("%Y%m%d"),
index,
&hex[..6]
)
}
/// Render the period-grouped corpus for the LLM. Each period gets a
/// header and each claim a single line: `{id} [{confidence}] {claim_text}`.
/// Periods are rendered in chronological order so the LLM can treat the
@@ -267,6 +235,8 @@ mod tests {
use std::pin::Pin;
use std::sync::Mutex;
use chrono::NaiveDate;
use super::*;
use crate::llm::CompletionResult;
use crate::memory::claim::Confidence;
@@ -321,37 +291,6 @@ mod tests {
store::write_claims(&path, claims).unwrap();
}
#[test]
fn id_format_is_stable_and_zero_padded() {
let p = period(day(2026, 2, 24), day(2026, 5, 14));
let a = compute_l3u_id(&p, 7, "the line");
let b = compute_l3u_id(&p, 7, "the line");
assert_eq!(a, b);
assert!(a.starts_with("l3u-20260224-20260514-007-"));
// l3u- + 8 + - + 8 + - + 3 + - + 6
assert_eq!(a.len(), "l3u-".len() + 8 + 1 + 8 + 1 + 3 + 1 + 6);
}
#[test]
fn parse_period_accepts_well_formed_name() {
let p = parse_period_from_filename("l3u-2026-02-24-2026-05-14.jsonl.zst").unwrap();
assert_eq!(p.first, day(2026, 2, 24));
assert_eq!(p.last, day(2026, 5, 14));
}
#[test]
fn parse_period_rejects_l4u_prefix() {
assert!(parse_period_from_filename("l4u-2026-02-24-2026-05-14.jsonl.zst").is_none());
}
#[test]
fn parse_period_rejects_malformed_names() {
assert!(parse_period_from_filename("l3u-broken.jsonl.zst").is_none());
assert!(parse_period_from_filename("l3u-2026-02-24.jsonl.zst").is_none());
assert!(parse_period_from_filename("l3u-2026-13-24-2026-05-14.jsonl.zst").is_none());
assert!(parse_period_from_filename("readme.md").is_none());
}
#[test]
fn load_corpus_sorts_by_period_and_assigns_ids() {
let tmp = tempfile::tempdir().unwrap();
@@ -361,7 +300,7 @@ mod tests {
write_l3u_period(tmp.path(), p_new, &[l3u_claim("alpha"), l3u_claim("beta")]);
write_l3u_period(tmp.path(), p_old, &[l3u_claim("gamma")]);
let corpus = load_l3u_corpus(tmp.path()).unwrap();
let corpus = load_l3u_corpus(tmp.path(), "u").unwrap();
assert_eq!(corpus.len(), 2);
assert_eq!(corpus[0].0, p_old);
assert_eq!(corpus[1].0, p_new);
@@ -379,7 +318,7 @@ mod tests {
// Drop an l4u-named file in the same dir — must be ignored.
std::fs::File::create(tmp.path().join("l4u-2026-02-24-2026-05-14.jsonl.zst")).unwrap();
let corpus = load_l3u_corpus(tmp.path()).unwrap();
let corpus = load_l3u_corpus(tmp.path(), "u").unwrap();
assert_eq!(corpus.len(), 1);
assert_eq!(corpus[0].0, p);
}
@@ -387,8 +326,8 @@ mod tests {
#[test]
fn load_corpus_errors_on_empty_input() {
let tmp = tempfile::tempdir().unwrap();
let err = load_l3u_corpus(tmp.path()).unwrap_err();
assert!(err.to_string().contains("No L3u period files"));
let err = load_l3u_corpus(tmp.path(), "u").unwrap_err();
assert!(err.to_string().contains("No L3 period files (l3u-"));
}
#[test]
+202
View File
@@ -0,0 +1,202 @@
//! Naming conventions for the per-track levels of the hierarchy.
//!
//! Everything above L2 is per-track: the L3 and L4 directories, the
//! filenames inside them, and the citation ids that reference those files
//! all embed a short track tag (`u` for `USER.md`). L2 is shared by every
//! track and so is not tagged.
//!
//! These are the only places the tag is spelled out. Keeping them here
//! rather than inline at each site means a track is added by registering a
//! tag, not by finding every `format!` that needs one.
use std::path::Path;
use std::path::PathBuf;
use chrono::NaiveDate;
use sha2::Digest as _;
use sha2::Sha256;
/// The `YYYY-MM-DD-YYYY-MM-DD` span a level file covers, as parsed from or
/// rendered into its filename.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Span {
pub first: NaiveDate,
pub last: NaiveDate,
}
/// Directory holding the L3 files for `tag`, e.g. `{memory}/l3u`.
pub fn l3_dir(memory_path: &Path, tag: &str) -> PathBuf {
memory_path.join(format!("l3{tag}"))
}
/// Directory holding the L4 files for `tag`, e.g. `{memory}/l4u`.
pub fn l4_dir(memory_path: &Path, tag: &str) -> PathBuf {
memory_path.join(format!("l4{tag}"))
}
/// Filename for an L3 file, e.g. `l3u-2026-02-24-2026-05-14.jsonl.zst`.
pub fn l3_filename(tag: &str, span: Span) -> String {
format!("l3{}-{}-{}.jsonl.zst", tag, span.first, span.last)
}
/// Filename for an L4 file, e.g. `l4u-2026-02-24-2026-05-14.jsonl.zst`.
pub fn l4_filename(tag: &str, span: Span) -> String {
format!("l4{}-{}-{}.jsonl.zst", tag, span.first, span.last)
}
/// Parse an L3 filename for `tag`. Returns `None` for anything else,
/// including the `l4{tag}-` files that share the directory tree.
pub fn parse_l3_filename(tag: &str, name: &str) -> Option<Span> {
parse_spanned_filename(&format!("l3{tag}-"), name)
}
/// Parse an L4 filename for `tag`. Returns `None` for anything else.
pub fn parse_l4_filename(tag: &str, name: &str) -> Option<Span> {
parse_spanned_filename(&format!("l4{tag}-"), name)
}
/// True if `name` claims to be an L3 file for `tag` — used to decide
/// whether an unparseable filename is suspicious or simply unrelated.
pub fn has_l3_prefix(tag: &str, name: &str) -> bool {
name.starts_with(&format!("l3{tag}-"))
}
/// True if `name` claims to be an L4 file for `tag`.
pub fn has_l4_prefix(tag: &str, name: &str) -> bool {
name.starts_with(&format!("l4{tag}-"))
}
fn parse_spanned_filename(prefix: &str, name: &str) -> Option<Span> {
let rest = name.strip_prefix(prefix)?.strip_suffix(".jsonl.zst")?;
// Expect exactly: YYYY-MM-DD-YYYY-MM-DD (10 + 1 + 10 = 21 chars).
if rest.len() != 21 || rest.as_bytes().get(10) != Some(&b'-') {
return None;
}
let first = NaiveDate::parse_from_str(&rest[..10], "%Y-%m-%d").ok()?;
let last = NaiveDate::parse_from_str(&rest[11..], "%Y-%m-%d").ok()?;
Some(Span { first, last })
}
/// Citation id for one claim in an L2 day file, e.g.
/// `l2-20260509-007-a3f2c1`. L2 is shared across tracks, so this carries
/// no tag.
pub fn l2_claim_id(date: NaiveDate, index: usize, raw_line: &str) -> String {
format!(
"l2-{}-{:03}-{}",
date.format("%Y%m%d"),
index,
short_hash(raw_line)
)
}
/// Citation id for one claim in an L3 period file, e.g.
/// `l3u-20260224-20260514-007-a3f2c1`. The period is embedded so the model
/// consuming it has temporal context without a separate lookup.
pub fn l3_claim_id(tag: &str, span: Span, index: usize, raw_line: &str) -> String {
format!(
"l3{}-{}-{}-{:03}-{}",
tag,
span.first.format("%Y%m%d"),
span.last.format("%Y%m%d"),
index,
short_hash(raw_line)
)
}
/// The first 6 hex characters of the line's SHA-256. Short enough to stay
/// readable in a prompt, long enough that a model cannot plausibly guess
/// one — which is what makes a fabricated citation detectable.
fn short_hash(raw_line: &str) -> String {
let mut h = Sha256::new();
h.update(raw_line.as_bytes());
format!("{:x}", h.finalize())[..6].to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn day(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
fn span(a: NaiveDate, b: NaiveDate) -> Span {
Span { first: a, last: b }
}
#[test]
fn user_track_names_match_the_established_layout() {
// These are the names already on disk for the user track; they must
// not move.
let s = span(day(2026, 2, 24), day(2026, 5, 14));
assert_eq!(
l3_dir(Path::new("/m"), "u"),
PathBuf::from("/m/l3u"),
"L3u directory"
);
assert_eq!(l4_dir(Path::new("/m"), "u"), PathBuf::from("/m/l4u"));
assert_eq!(l3_filename("u", s), "l3u-2026-02-24-2026-05-14.jsonl.zst");
assert_eq!(l4_filename("u", s), "l4u-2026-02-24-2026-05-14.jsonl.zst");
}
#[test]
fn filenames_roundtrip_through_their_parsers() {
let s = span(day(2026, 2, 24), day(2026, 5, 14));
for tag in ["u", "t", "a"] {
assert_eq!(parse_l3_filename(tag, &l3_filename(tag, s)), Some(s));
assert_eq!(parse_l4_filename(tag, &l4_filename(tag, s)), Some(s));
}
}
#[test]
fn parsers_reject_the_neighbouring_level_and_other_tracks() {
let s = span(day(2026, 2, 24), day(2026, 5, 14));
// L4 files share a tree with L3 files; neither parser may claim the
// other's.
assert!(parse_l3_filename("u", &l4_filename("u", s)).is_none());
assert!(parse_l4_filename("u", &l3_filename("u", s)).is_none());
// A tag is not a prefix match: track `t` must not eat track `u`.
assert!(parse_l3_filename("t", &l3_filename("u", s)).is_none());
}
#[test]
fn parsers_reject_malformed_names() {
assert!(parse_l3_filename("u", "l3u-broken.jsonl.zst").is_none());
assert!(parse_l3_filename("u", "l3u-2026-02-24.jsonl.zst").is_none());
assert!(parse_l4_filename("u", "readme.md").is_none());
assert!(parse_l4_filename("u", "l4u-2026-13-45-2026-05-14.jsonl.zst").is_none());
}
#[test]
fn prefix_checks_distinguish_levels_and_tracks() {
assert!(has_l3_prefix("u", "l3u-whatever"));
assert!(!has_l3_prefix("u", "l4u-whatever"));
assert!(!has_l3_prefix("u", "l3t-whatever"));
assert!(has_l4_prefix("t", "l4t-whatever"));
}
#[test]
fn claim_ids_are_stable_and_zero_padded() {
let a = l2_claim_id(day(2026, 5, 9), 7, "the line");
assert_eq!(a, l2_claim_id(day(2026, 5, 9), 7, "the line"));
assert!(a.starts_with("l2-20260509-007-"));
assert_eq!(a.len(), "l2-".len() + 8 + 1 + 3 + 1 + 6);
let s = span(day(2026, 2, 24), day(2026, 5, 14));
let b = l3_claim_id("u", s, 7, "the line");
assert_eq!(b, l3_claim_id("u", s, 7, "the line"));
assert!(b.starts_with("l3u-20260224-20260514-007-"));
// Same line, different track: the hash suffix is shared, the prefix
// is not, so ids never collide across tracks.
assert_ne!(b, l3_claim_id("t", s, 7, "the line"));
}
#[test]
fn claim_id_hash_depends_on_the_line() {
let s = span(day(2026, 2, 24), day(2026, 5, 14));
assert_ne!(
l3_claim_id("u", s, 0, "one"),
l3_claim_id("u", s, 0, "another")
);
}
}
+14 -5
View File
@@ -34,6 +34,7 @@ pub mod l1;
pub mod l2;
pub mod l3;
pub mod l4;
pub mod layout;
pub mod nightly;
pub mod store;
@@ -276,6 +277,7 @@ async fn extract_with_retries(
pub async fn run_l2_to_l3u(
input_dir: &Path,
output_dir: &Path,
tag: &str,
backend: Arc<dyn ChatBackend>,
) -> Result<()> {
let corpus = l3::load_l2_corpus(input_dir)?;
@@ -295,7 +297,7 @@ pub async fn run_l2_to_l3u(
std::fs::create_dir_all(output_dir)
.with_context(|| format!("Failed to create output directory {}", output_dir.display()))?;
let out_path: PathBuf = output_dir.join(format!("l3u-{first}-{last}.jsonl.zst"));
let out_path: PathBuf = output_dir.join(layout::l3_filename(tag, layout::Span { first, last }));
store::write_claims(&out_path, &claims)?;
info!(
claims = claims.len(),
@@ -317,9 +319,10 @@ pub async fn run_l2_to_l3u(
pub async fn run_l3u_to_l4u(
input_dir: &Path,
output_dir: &Path,
tag: &str,
backend: Arc<dyn ChatBackend>,
) -> Result<()> {
let corpus = l4::load_l3u_corpus(input_dir)?;
let corpus = l4::load_l3u_corpus(input_dir, tag)?;
let earliest_first = corpus.first().expect("non-empty after load").0.first;
let latest_last = corpus
.iter()
@@ -340,8 +343,13 @@ pub async fn run_l3u_to_l4u(
std::fs::create_dir_all(output_dir)
.with_context(|| format!("Failed to create output directory {}", output_dir.display()))?;
let out_path: PathBuf =
output_dir.join(format!("l4u-{earliest_first}-{latest_last}.jsonl.zst"));
let out_path: PathBuf = output_dir.join(layout::l4_filename(
tag,
layout::Span {
first: earliest_first,
last: latest_last,
},
));
store::write_claims(&out_path, &claims)?;
info!(
claims = claims.len(),
@@ -361,10 +369,11 @@ pub async fn run_l3u_to_l4u(
pub async fn run_l4u_to_user_md(
input_dir: &Path,
output_dir: &Path,
tag: &str,
previous: Option<&Path>,
backend: Arc<dyn ChatBackend>,
) -> Result<doc::RunReport> {
let report = doc::run(input_dir, output_dir, previous, backend.as_ref()).await?;
let report = doc::run(input_dir, output_dir, tag, previous, backend.as_ref()).await?;
info!(
action = ?report.action,
bytes = report.bytes_written,
+11 -4
View File
@@ -26,7 +26,9 @@ use crate::config::NightlyMode;
use crate::llm::ChatBackend;
use crate::memory;
use crate::memory::doc;
use crate::memory::layout;
use crate::personality::Personality;
use crate::personality::PersonalityFile;
/// Run a single nightly pass through all four stages. Returns `Ok(())` even
/// when an internal stage failed — the per-stage error has already been
@@ -48,10 +50,14 @@ pub async fn run_once(
NightlyMode::Enabled => doc::WriteMode::Enabled,
};
// Only the user track exists so far; the tag is what makes these
// `l3u`/`l4u` rather than any other track's directories.
let tag = PersonalityFile::User.track_tag();
let conversations_dir = state_dir.join("conversations");
let l2_dir = memory_path.join("l2");
let l3u_dir = memory_path.join("l3u");
let l4u_dir = memory_path.join("l4u");
let l3u_dir = layout::l3_dir(memory_path, tag);
let l4u_dir = layout::l4_dir(memory_path, tag);
let log_dir = memory_path.join("log");
info!(
@@ -90,13 +96,13 @@ pub async fn run_once(
};
let _ = l2_summary;
if let Err(err) = memory::run_l2_to_l3u(&l2_dir, &l3u_dir, Arc::clone(&backend)).await {
if let Err(err) = memory::run_l2_to_l3u(&l2_dir, &l3u_dir, tag, Arc::clone(&backend)).await {
error!(error = %err, "Stage L2->L3u failed; aborting nightly run");
return Ok(());
}
info!("Stage L2->L3u done");
if let Err(err) = memory::run_l3u_to_l4u(&l3u_dir, &l4u_dir, Arc::clone(&backend)).await {
if let Err(err) = memory::run_l3u_to_l4u(&l3u_dir, &l4u_dir, tag, Arc::clone(&backend)).await {
error!(error = %err, "Stage L3u->L4u failed; aborting nightly run");
return Ok(());
}
@@ -104,6 +110,7 @@ pub async fn run_once(
match doc::run_with_mode(
&l4u_dir,
tag,
personality,
&log_dir,
write_mode,
+30
View File
@@ -36,6 +36,36 @@ impl PersonalityFile {
}
}
/// The filename without its `.md` extension. Names archived copies of
/// this file in the memory log directory.
pub const fn stem(self) -> &'static str {
match self {
Self::Soul => "SOUL",
Self::Identity => "IDENTITY",
Self::User => "USER",
Self::Agents => "AGENTS",
Self::Tools => "TOOLS",
Self::Bootstrap => "BOOTSTRAP",
}
}
/// Short tag identifying this file's track in the memory hierarchy. It
/// appears in the per-track directory names (`l3u`, `l4u`) and in the
/// citation ids that reference those files.
///
/// The match is exhaustive rather than a lookup, so two tracks cannot
/// collide on a tag by construction.
pub const fn track_tag(self) -> &'static str {
match self {
Self::Soul => "s",
Self::Identity => "i",
Self::User => "u",
Self::Agents => "a",
Self::Tools => "t",
Self::Bootstrap => "b",
}
}
/// Default template content used to seed the file on first run.
pub const fn template(self) -> &'static str {
match self {