memory: add l3u-to-l4u current-state user model extraction #81

Merged
JakeHillion merged 1 commits from jj/oloknulwtzty into main 2026-05-15 16:21:06 +01:00
3 changed files with 704 additions and 0 deletions

No files matched your search

+30
View File
@@ -123,6 +123,26 @@ enum MemoryCmd {
#[arg(long)]
token_file: Option<PathBuf>,
},
/// Consolidate L3u period summaries into a single L4u current-state
/// user model file
/// (`l4u-{earliest_first}-{latest_last}.jsonl.zst`).
L3uToL4u {
/// Directory containing `l3u-{first}-{last}.jsonl.zst` L3u files.
#[arg(long)]
input: PathBuf,
/// Directory to write the L4u file into. Created if missing.
#[arg(long)]
output: PathBuf,
/// Base URL for the OpenAI-compatible chat completions endpoint.
#[arg(long)]
base_url: String,
/// Model id sent to the endpoint.
#[arg(long)]
model: String,
/// Optional bearer token file. Omit for unauthenticated endpoints.
#[arg(long)]
token_file: Option<PathBuf>,
},
}
#[tokio::main]
@@ -203,6 +223,16 @@ async fn run_internal(cmd: InternalCmd) -> Result<()> {
let llm = build_llm_from_endpoint(base_url, model, token_file)?;
memory::run_l2_to_l3u(&input, &output, llm).await
}
MemoryCmd::L3uToL4u {
input,
output,
base_url,
model,
token_file,
} => {
let llm = build_llm_from_endpoint(base_url, model, token_file)?;
memory::run_l3u_to_l4u(&input, &output, llm).await
}
},
}
}
+627
View File
@@ -0,0 +1,627 @@
//! L4u: consolidated *current* user model derived from one or more L3u
//! period summaries.
//!
//! L3u runs over a bounded window and emits one
//! `l3u-{first}-{last}.jsonl.zst` per run. Re-running L3u over later
//! windows accumulates multiple L3u files, each a snapshot of the user
//! model at a point in time. L4u folds those snapshots together into a
//! single current-state JSONL, treating later periods as more salient
//! while resisting one-off corrections to long-standing claims.
//!
//! Like L3u, L4u retains citations: each output claim cites the
//! `l3u-...` source ids it was derived from.
use std::collections::HashSet;
use std::fs;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context as _;
use anyhow::Result;
use anyhow::bail;
use chrono::NaiveDate;
use serde::Deserialize;
use serde::Serialize;
use sha2::Digest;
use sha2::Sha256;
use tracing::info;
use tracing::warn;
use crate::llm::ChatBackend;
use crate::llm::ChatMessage;
use crate::memory::l2::Confidence;
use crate::memory::l3u::L3uClaim;
use crate::tools::ToolContext;
use crate::tools::ToolRegistry;
/// Maximum rendered prompt size in characters. Matches L3u's budget —
/// well under Kimi K2.6's 256k token window. Exceeded → hard error
/// (not a warning): windowing isn't designed yet.
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,
}
/// A loaded L3u claim with its assigned L4u-input id.
#[derive(Debug, Clone)]
pub struct L3uEntry {
pub id: String,
pub claim: L3uClaim,
}
/// L4u output schema: a durable current-state claim with L3u citations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct L4uClaim {
pub claim: String,
pub confidence: Confidence,
pub sources: Vec<String>,
}
/// 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>)>> {
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()))?
{
let entry = entry?;
let path = entry.path();
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
let Some(period) = parse_period_from_filename(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"
);
}
continue;
};
period_files.push((period, path));
}
if period_files.is_empty() {
bail!(
"No L3u period files (l3u-YYYY-MM-DD-YYYY-MM-DD.jsonl.zst) found in {}",
input_dir.display()
);
}
period_files.sort_by_key(|(p, _)| *p);
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)?;
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>> {
let f = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
let mut dec = zstd::Decoder::new(f)
.with_context(|| format!("Failed to init zstd decoder for {}", path.display()))?;
let mut text = String::new();
dec.read_to_string(&mut text)
.with_context(|| format!("Failed to read {}", path.display()))?;
let mut entries = Vec::new();
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() {
continue;
}
let claim: L3uClaim = match serde_json::from_str(line) {
Ok(c) => c,
Err(err) => {
warn!(source = %path.display(), error = %err, "Skipping malformed L3u claim line");
continue;
}
};
let index = entries.len();
let id = compute_l3u_id(period, index, line);
entries.push(L3uEntry { id, claim });
}
Ok(entries)
}
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
/// final block as the most recent state.
pub fn render_corpus_for_prompt(by_period: &[(PeriodTag, Vec<L3uEntry>)]) -> String {
let mut out = String::new();
for (period, entries) in by_period {
if entries.is_empty() {
continue;
}
out.push_str("## Period ");
out.push_str(&period.first.to_string());
out.push_str(" to ");
out.push_str(&period.last.to_string());
out.push('\n');
for e in entries {
let conf = match e.claim.confidence {
Confidence::High => "high",
Confidence::Medium => "medium",
Confidence::Low => "low",
};
out.push_str(&e.id);
out.push_str(" [");
out.push_str(conf);
out.push_str("] ");
// L3u claims are single-sentence; collapse any stray newlines.
out.push_str(&e.claim.claim.replace('\n', " "));
out.push('\n');
}
out.push('\n');
}
out
}
/// Run the L3u → L4u extraction in a single LLM call. Errors if the
/// rendered corpus exceeds [`CORPUS_CHAR_LIMIT`].
pub async fn extract(
by_period: &[(PeriodTag, Vec<L3uEntry>)],
backend: &dyn ChatBackend,
) -> Result<Vec<L4uClaim>> {
let prompt = render_corpus_for_prompt(by_period);
if prompt.len() > CORPUS_CHAR_LIMIT {
bail!(
"L3u corpus is {} chars, exceeds limit of {}; windowing not yet supported",
prompt.len(),
CORPUS_CHAR_LIMIT
);
}
info!(
chars = prompt.len(),
periods = by_period.len(),
"Calling L4u extractor"
);
let messages = vec![
ChatMessage::system(SYSTEM_PROMPT),
ChatMessage::user(prompt),
];
let registry = ToolRegistry::new();
let ctx = ToolContext {
room_id: None,
tick: false,
};
let result = backend
.chat_completion_with_tools(&messages, &registry, &ctx)
.await
.context("LLM call failed during L4u extraction")?;
let parsed = parse_claims_jsonl(&result.reply);
let valid_ids: HashSet<&str> = by_period
.iter()
.flat_map(|(_, entries)| entries.iter().map(|e| e.id.as_str()))
.collect();
Ok(validate_sources(parsed, &valid_ids))
}
/// Parse a JSONL stream of `L4uClaim` objects. Malformed lines are skipped
/// with a warning. Tolerates an optional surrounding ```jsonl ... ``` fence.
pub fn parse_claims_jsonl(reply: &str) -> Vec<L4uClaim> {
let body = strip_code_fence(reply);
let mut claims = Vec::new();
for (i, raw) in body.lines().enumerate() {
let line = raw.trim();
if line.is_empty() {
continue;
}
match serde_json::from_str::<L4uClaim>(line) {
Ok(c) => claims.push(c),
Err(err) => {
warn!(line = i + 1, error = %err, "Skipping malformed L4u claim line");
}
}
}
claims
}
fn strip_code_fence(text: &str) -> &str {
let trimmed = text.trim();
let Some(rest) = trimmed.strip_prefix("```") else {
return trimmed;
};
let after_first_line = rest.split_once('\n').map(|(_, r)| r).unwrap_or(rest);
after_first_line
.trim_end()
.strip_suffix("```")
.map(str::trim)
.unwrap_or(after_first_line)
}
/// Drop claims with no sources or with any source not in `valid_ids`.
pub fn validate_sources(claims: Vec<L4uClaim>, valid_ids: &HashSet<&str>) -> Vec<L4uClaim> {
let mut out = Vec::with_capacity(claims.len());
for c in claims {
if c.sources.is_empty() {
warn!(claim = %c.claim, "Dropping L4u claim with no sources");
continue;
}
let bad: Vec<&str> = c
.sources
.iter()
.filter(|s| !valid_ids.contains(s.as_str()))
.map(|s| s.as_str())
.collect();
if !bad.is_empty() {
warn!(
claim = %c.claim,
bad = ?bad,
"Dropping L4u claim citing nonexistent source ids"
);
continue;
}
out.push(c);
}
out
}
/// Serialize claims as ZSTD-compressed JSONL at `path`.
pub fn write_output_file(path: &Path, claims: &[L4uClaim]) -> Result<()> {
let file =
File::create(path).with_context(|| format!("Failed to create {}", path.display()))?;
let mut enc = zstd::Encoder::new(file, 0)
.with_context(|| format!("Failed to init zstd encoder for {}", path.display()))?;
for c in claims {
let line = serde_json::to_string(c)?;
enc.write_all(line.as_bytes())?;
enc.write_all(b"\n")?;
}
enc.finish()
.with_context(|| format!("Failed to finalize zstd stream for {}", path.display()))?;
Ok(())
}
const SYSTEM_PROMPT: &str = "\
You are a memory consolidation agent producing the user's *current* model \
from a chronological series of consolidated period summaries (L3u files).
You will be given several periods, each containing claims about the user \
with confidence levels. Periods are presented in chronological order: the \
LAST period in the input is the most recent and the most salient.
Your job is to emit durable facts about the user's current state — their \
life, circumstances, explicit preferences, commitments, projects — as \
JSONL with citations back to the period claims.
Rules:
- Output valid JSONL, one object per line, no other text, no preamble.
- Later periods are more salient than earlier ones; when periods agree, \
cite all supporting periods.
- An explicit correction from the user (e.g. \"actually I prefer X\", \
\"stop doing Y\", \"I no longer do Z\") OVERRIDES earlier claims and must be \
reflected in the current-state output. Cite both the original and the \
correcting period(s).
- Track natural drift in circumstances, mood, projects, and stated \
preferences over time — emit the *current* state, not the historical one. \
Do not emit superseded states as separate claims.
- BUT: do NOT flip a long-standing claim (one supported across many \
earlier periods) on the basis of a single later event, complaint, or \
off-hand remark. Require either (a) corroboration across at least two \
later periods, or (b) an explicit user correction, before overturning a \
well-established claim. Otherwise keep the long-standing claim and lower \
its confidence if there is genuine tension.
- Preserve ambiguity rather than resolving it. Lower confidence rather \
than omitting a claim when periods disagree.
- Every claim must cite at least one l3u-* source id from the input.
- Confidence reflects support across periods, with weight given to recency.
- Begin output immediately with the first JSON object, no preamble.
Schema:
{\"claim\": \"<one-sentence current-state claim>\", \"confidence\": \"high|medium|low\", \"sources\": [\"l3u-...\"]}
Example output line:
{\"claim\": \"User supervises CS undergraduates at Cambridge\", \"confidence\": \"high\", \"sources\": [\"l3u-20260224-20260514-007-a1b2c3\"]}
";
#[cfg(test)]
mod tests {
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
use super::*;
use crate::llm::CompletionResult;
struct FixedBackend {
reply: String,
last_user: Mutex<Option<String>>,
}
impl ChatBackend for FixedBackend {
fn chat_completion_with_tools<'a>(
&'a self,
messages: &'a [ChatMessage],
_registry: &'a ToolRegistry,
_ctx: &'a ToolContext,
) -> Pin<Box<dyn Future<Output = Result<CompletionResult>> + Send + 'a>> {
let last_user = messages
.iter()
.rev()
.find(|m| m.role == "user")
.and_then(|m| m.content.clone());
*self.last_user.lock().unwrap() = last_user;
let reply = self.reply.clone();
Box::pin(async move {
Ok(CompletionResult {
reply,
intermediate_messages: Vec::new(),
prompt_tokens: None,
})
})
}
}
fn day(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
fn period(f: NaiveDate, l: NaiveDate) -> PeriodTag {
PeriodTag { first: f, last: l }
}
fn l3u_claim(text: &str) -> L3uClaim {
L3uClaim {
claim: text.to_owned(),
confidence: Confidence::High,
sources: vec!["l2-20260224-000-aaaaaa".to_owned()],
}
}
fn write_l3u_period(dir: &Path, p: PeriodTag, claims: &[L3uClaim]) {
let path = dir.join(format!("l3u-{}-{}.jsonl.zst", p.first, p.last));
let f = File::create(&path).unwrap();
let mut enc = zstd::Encoder::new(f, 0).unwrap();
for c in claims {
let line = serde_json::to_string(c).unwrap();
enc.write_all(line.as_bytes()).unwrap();
enc.write_all(b"\n").unwrap();
}
enc.finish().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();
let p_old = period(day(2025, 12, 1), day(2026, 2, 23));
let p_new = period(day(2026, 2, 24), day(2026, 5, 14));
// Write newer first to verify sort.
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();
assert_eq!(corpus.len(), 2);
assert_eq!(corpus[0].0, p_old);
assert_eq!(corpus[1].0, p_new);
assert_eq!(corpus[0].1.len(), 1);
assert!(corpus[0].1[0].id.starts_with("l3u-20251201-20260223-000-"));
assert!(corpus[1].1[0].id.starts_with("l3u-20260224-20260514-000-"));
assert!(corpus[1].1[1].id.starts_with("l3u-20260224-20260514-001-"));
}
#[test]
fn load_corpus_skips_l4u_files() {
let tmp = tempfile::tempdir().unwrap();
let p = period(day(2026, 2, 24), day(2026, 5, 14));
write_l3u_period(tmp.path(), p, &[l3u_claim("alpha")]);
// Drop an l4u-named file in the same dir — must be ignored.
File::create(tmp.path().join("l4u-2026-02-24-2026-05-14.jsonl.zst")).unwrap();
let corpus = load_l3u_corpus(tmp.path()).unwrap();
assert_eq!(corpus.len(), 1);
assert_eq!(corpus[0].0, p);
}
#[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"));
}
#[test]
fn render_prompt_includes_period_headers_and_ids() {
let entries = vec![L3uEntry {
id: "l3u-20260224-20260514-000-aaaaaa".to_owned(),
claim: l3u_claim("user lives in London"),
}];
let p = period(day(2026, 2, 24), day(2026, 5, 14));
let rendered = render_corpus_for_prompt(&[(p, entries)]);
assert!(rendered.contains("## Period 2026-02-24 to 2026-05-14"));
assert!(rendered.contains("l3u-20260224-20260514-000-aaaaaa [high] user lives in London"));
}
#[test]
fn parse_claims_skips_malformed() {
let reply = "garbage\n\
{\"claim\":\"a\",\"confidence\":\"high\",\"sources\":[\"l3u-20260224-20260514-000-aaaaaa\"]}\n\
{\"no\":\"keys\"}";
let claims = parse_claims_jsonl(reply);
assert_eq!(claims.len(), 1);
assert_eq!(claims[0].claim, "a");
}
#[test]
fn parse_claims_strips_code_fence() {
let reply = "```jsonl\n{\"claim\":\"a\",\"confidence\":\"low\",\"sources\":[\"l3u-20260224-20260514-000-aaaaaa\"]}\n```";
let claims = parse_claims_jsonl(reply);
assert_eq!(claims.len(), 1);
assert_eq!(claims[0].confidence, Confidence::Low);
}
#[test]
fn validate_drops_bogus_and_empty_sources() {
let valid: HashSet<&str> = ["l3u-20260224-20260514-000-aaaaaa"].into_iter().collect();
let claims = vec![
L4uClaim {
claim: "good".to_owned(),
confidence: Confidence::High,
sources: vec!["l3u-20260224-20260514-000-aaaaaa".to_owned()],
},
L4uClaim {
claim: "bad".to_owned(),
confidence: Confidence::Medium,
sources: vec!["l3u-99999999-99999999-000-ffffff".to_owned()],
},
L4uClaim {
claim: "empty".to_owned(),
confidence: Confidence::Low,
sources: vec![],
},
];
let out = validate_sources(claims, &valid);
assert_eq!(out.len(), 1);
assert_eq!(out[0].claim, "good");
}
#[test]
fn zstd_jsonl_roundtrip() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("l4u-2025-12-01-2026-05-14.jsonl.zst");
let claims = vec![
L4uClaim {
claim: "user lives in London".to_owned(),
confidence: Confidence::High,
sources: vec!["l3u-20260224-20260514-000-aaaaaa".to_owned()],
},
L4uClaim {
claim: "user supervises CS students at Cambridge".to_owned(),
confidence: Confidence::Medium,
sources: vec![
"l3u-20251201-20260223-000-bbbbbb".to_owned(),
"l3u-20260224-20260514-001-cccccc".to_owned(),
],
},
];
write_output_file(&path, &claims).unwrap();
let f = File::open(&path).unwrap();
let mut dec = zstd::Decoder::new(f).unwrap();
let mut text = String::new();
dec.read_to_string(&mut text).unwrap();
let parsed: Vec<L4uClaim> = text
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(parsed, claims);
}
#[tokio::test]
async fn extract_end_to_end() {
let p = period(day(2026, 2, 24), day(2026, 5, 14));
let entries = vec![(
p,
vec![L3uEntry {
id: "l3u-20260224-20260514-000-aaaaaa".to_owned(),
claim: l3u_claim("user lives in London"),
}],
)];
let reply = "{\"claim\":\"user lives in London\",\"confidence\":\"high\",\"sources\":[\"l3u-20260224-20260514-000-aaaaaa\"]}\n\
{\"claim\":\"bogus src\",\"confidence\":\"low\",\"sources\":[\"l3u-99999999-99999999-000-ffffff\"]}\n";
let backend = FixedBackend {
reply: reply.to_owned(),
last_user: Mutex::new(None),
};
let claims = extract(&entries, &backend).await.unwrap();
assert_eq!(claims.len(), 1);
assert_eq!(claims[0].claim, "user lives in London");
let prompt = backend.last_user.lock().unwrap().clone().unwrap();
assert!(prompt.contains("## Period 2026-02-24 to 2026-05-14"));
assert!(prompt.contains("l3u-20260224-20260514-000-aaaaaa"));
}
#[tokio::test]
async fn extract_errors_on_oversized_corpus() {
let big = "x".repeat(CORPUS_CHAR_LIMIT + 1);
let p = period(day(2026, 2, 24), day(2026, 5, 14));
let entries = vec![(
p,
vec![L3uEntry {
id: "l3u-20260224-20260514-000-aaaaaa".to_owned(),
claim: l3u_claim(&big),
}],
)];
let backend = FixedBackend {
reply: "unused".to_owned(),
last_user: Mutex::new(None),
};
let err = extract(&entries, &backend).await.unwrap_err();
assert!(err.to_string().contains("exceeds limit"));
}
}
+47
View File
@@ -22,6 +22,7 @@ use crate::llm::ChatBackend;
pub mod l1;
pub mod l2;
pub mod l3u;
pub mod l4u;
/// Run the L1 → L2 extraction pipeline.
///
@@ -110,3 +111,49 @@ pub async fn run_l2_to_l3u(
);
Ok(())
}
/// Run the L3u → L4u extraction pipeline.
///
/// Loads every `l3u-{first}-{last}.jsonl.zst` period file from
/// `input_dir`, sends the entire chronologically-ordered corpus to the
/// LLM in one call, validates citations against the assembled L3u id
/// set, and writes a single `l4u-{earliest_first}-{latest_last}.jsonl.zst`
/// file to `output_dir`. The output range spans every input period —
/// `latest_last` uses `max(period.last)` to handle nested or overlapping
/// periods correctly.
pub async fn run_l3u_to_l4u(
input_dir: &Path,
output_dir: &Path,
backend: Arc<dyn ChatBackend>,
) -> Result<()> {
let corpus = l4u::load_l3u_corpus(input_dir)?;
let earliest_first = corpus.first().expect("non-empty after load").0.first;
let latest_last = corpus
.iter()
.map(|(p, _)| p.last)
.max()
.expect("non-empty after load");
let total_l3u: usize = corpus.iter().map(|(_, e)| e.len()).sum();
info!(
periods = corpus.len(),
earliest = %earliest_first,
latest = %latest_last,
l3u_claims = total_l3u,
"Loaded L3u corpus"
);
let claims = l4u::extract(&corpus, backend.as_ref()).await?;
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"));
l4u::write_output_file(&out_path, &claims)?;
info!(
claims = claims.len(),
out = %out_path.display(),
"Wrote L4u file"
);
Ok(())
}