use super::bounded;
use serde_json::Value;
use std::path::{Path, PathBuf};
pub const CAP: u64 = 16 << 20;
const SMALL: u64 = 1 << 20;
pub fn canonical(vibe_home: &Path, native: &str) -> PathBuf {
vibe_home.join("logs/session/unified").join(native)
}
fn whole(vibe_home: &Path, path: &Path) -> Result<Value, String> {
let checked = bounded::plain(vibe_home, path)?;
let bytes = bounded::tail(path, &checked, SMALL, |_| false)?;
serde_json::from_slice(&bytes).map_err(|_| format!("{} is not JSON", path.display()))
}
fn digits(text: &str) -> bool {
!text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
}
fn texts(parts: &Value) -> String {
let parts = parts.as_array().into_iter().flatten();
let texts: Vec<&str> = parts
.filter(|p| p["type"] == "text")
.filter_map(|p| p["text"].as_str())
.collect();
texts.join("\n")
}
pub fn committed(
vibe_home: &Path,
native: &str,
given: &str,
turn: &str,
) -> Result<Option<String>, String> {
let directory = canonical(vibe_home, native);
if Path::new(given) != directory {
return Err("the hook named a session directory other than this session's own".into());
}
let current = whole(vibe_home, &directory.join("CURRENT"))?;
if current["session_id"] != native {
return Err("the session directory's CURRENT names another session".into());
}
let generation = current["generation"]
.as_str()
.filter(|g| digits(g))
.ok_or("the session directory's CURRENT names no generation")?;
let at = directory.join("generations").join(generation);
let finished = &whole(vibe_home, &at.join("checkpoint.json"))?["turn"];
let own = finished["turn_id"] == turn && finished["type"] == "terminal";
if own && finished["outcome"]["type"] != "completed" {
return Err("the turn ended without completing".into());
}
if own {
let answer = texts(&finished["outcome"]["output"]);
return match answer.is_empty() {
true => Err("the turn finished without an answer".into()),
false => Ok(Some(answer)),
};
}
let manifest = whole(vibe_home, &at.join("manifest.json"))?;
let segment = manifest["recovery_journal_segment"]["path"]
.as_str()
.filter(|p| {
p.strip_prefix("journal/")
.and_then(|name| name.strip_suffix(".jsonl"))
.is_some_and(digits)
})
.ok_or("the generation names no journal segment")?;
let path = directory.join(segment);
if !path.exists() {
return Ok(None);
}
let checked = bounded::plain(vibe_home, &path)?;
let window = bounded::tail(&path, &checked, CAP, |lines| {
lines
.split(|b| *b == b'\n')
.any(|line| reserves(line, turn))
})?;
journal(&window, turn)
}
fn reserves(line: &[u8], turn: &str) -> bool {
let named = std::str::from_utf8(line).is_ok_and(|l| l.contains(turn));
named
&& serde_json::from_slice::<Value>(line).is_ok_and(|record| {
record["type"] == "command_reserved" && record["payload"]["client_command_id"] == turn
})
}
fn appended<'a>(record: &'a Value, turn: &str) -> Option<&'a Value> {
let ops = record["payload"]["delta"].as_array()?;
ops.iter()
.rev()
.filter(|op| op["op"] == "append_entry")
.map(|op| &op["entry"])
.find(|entry| {
entry["type"] == "message"
&& entry["role"] == "assistant"
&& entry["turnId"] == turn
&& entry["outcome"]["type"] == "committed"
&& entry["generationStatus"] == "completed"
})
}
fn journal(window: &[u8], turn: &str) -> Result<Option<String>, String> {
let text = std::str::from_utf8(window).map_err(|_| "the journal is not UTF-8")?;
let lines: Vec<&str> = text.split('\n').filter(|l| !l.trim().is_empty()).collect();
let (mut answer, mut done) = (None, false);
for (index, line) in lines.iter().enumerate() {
let Ok(record) = serde_json::from_str::<Value>(line) else {
if index + 1 == lines.len() && !text.ends_with('\n') {
break;
}
return Err("a journal record is not whole JSON".into());
};
match record["type"].as_str() {
Some("receipt_succeeded") if record["payload"]["client_command_id"] == turn => {
done = true;
}
Some("projection_delta") => {
if let Some(entry) = appended(&record, turn) {
answer = Some(texts(&entry["content"]));
}
}
_ => {}
}
}
match (done, answer) {
(true, Some(answer)) if !answer.is_empty() => Ok(Some(answer)),
(true, _) => Err("the turn completed without a committed answer".into()),
(false, _) => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn record(kind: &str, payload: Value) -> String {
format!(
"{}\n",
serde_json::json!({"type": kind, "payload": payload})
)
}
fn message(turn: &str, outcome: &str, text: &str) -> String {
let entry = serde_json::json!({"type": "message", "role": "assistant", "turnId": turn,
"outcome": {"type": outcome}, "generationStatus": "completed",
"content": [{"type": "text", "text": text}]});
record(
"projection_delta",
serde_json::json!({"delta": [{"op": "append_entry", "entry": entry}]}),
)
}
#[test]
fn only_this_turns_committed_message_and_receipt_close_it() {
let reserved = record(
"command_reserved",
serde_json::json!({"client_command_id": "t2"}),
);
let receipt = record(
"receipt_succeeded",
serde_json::json!({"client_command_id": "t2"}),
);
let window = [
reserved.clone(),
message("t2", "committed", "banana"),
receipt.clone(),
]
.concat();
assert_eq!(journal(window.as_bytes(), "t2").unwrap().unwrap(), "banana");
assert!(reserves(reserved.trim().as_bytes(), "t2") && !reserves(reserved.as_bytes(), "t1"));
let early = [reserved.clone(), message("t2", "committed", "banana")].concat();
assert_eq!(journal(early.as_bytes(), "t2").unwrap(), None);
let other = [message("t1", "committed", "OLD"), receipt.clone()].concat();
assert!(journal(other.as_bytes(), "t2").is_err());
let candidate = [message("t2", "candidate", "maybe"), receipt.clone()].concat();
assert!(journal(candidate.as_bytes(), "t2").is_err());
let writing = format!("{}{{\"type\": \"proj", early);
assert_eq!(journal(writing.as_bytes(), "t2").unwrap(), None);
}
}