Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,412 @@
use std::collections::VecDeque;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::time::SystemTime;
use super::HISTORY_READ_BUFFER_SIZE;
use super::HistoryConfig;
use super::HistoryEntry;
use super::MAX_RETRIES;
use super::RETRY_SLEEP;
use super::history_filepath;
use super::log_identity;
const MAX_BATCH_ROWS: usize = 128;
const MAX_BATCH_BYTES: usize = 64 * 1024;
/// Position of the newest record to include in a bounded history lookup.
///
/// The initial cursor identifies only an absolute row offset. Continuation cursors also retain a
/// byte position so older batches can scan backward from the previous batch instead of rescanning
/// the history prefix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HistoryBatchCursor {
end_offset: usize,
byte_anchor: Option<HistoryByteAnchor>,
}
impl HistoryBatchCursor {
/// Creates an initial cursor ending at the given absolute history offset.
pub fn new(end_offset: usize) -> Self {
Self {
end_offset,
byte_anchor: None,
}
}
/// Returns the absolute history offset covered first by this cursor.
pub fn end_offset(self) -> usize {
self.end_offset
}
}
/// Validated row boundary used to continue scanning one unchanged file revision.
///
/// Byte positions and file lengths use `u64` to match filesystem and seek APIs, while history row
/// offsets use `usize` to match collection indices.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct HistoryByteAnchor {
position: u64,
revision: HistoryFileRevision,
}
/// File metadata that must remain unchanged before a byte position can be reused.
///
/// Byte positions are only reused for uncapped histories, which Codex writes append-only. Capped
/// histories can be rewritten in place when they are trimmed, so their cursors always fall back to
/// an offset scan. Filesystems without a modification time also fall back to an offset scan.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct HistoryFileRevision {
len: u64,
modified: Option<SystemTime>,
}
/// One absolute history offset covered by a bounded lookup.
///
/// Malformed records retain their offset with `entry` set to `None`, allowing callers to continue
/// searching older valid records without changing offset semantics.
#[derive(Clone, Debug, PartialEq)]
pub struct HistoryBatchEntry {
/// Zero-based position in the history file, counted from the oldest record.
pub offset: usize,
/// Parsed record, or `None` when the row at `offset` is malformed.
pub entry: Option<HistoryEntry>,
}
/// A bounded newest-first suffix ending at a requested absolute history offset.
///
/// `next_older_cursor` identifies the next position a caller should request after exhausting
/// `entries`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HistoryBatch {
/// Covered records in newest-to-oldest order.
pub entries: Vec<HistoryBatchEntry>,
/// Next position to request after exhausting `entries`.
pub next_older_cursor: Option<HistoryBatchCursor>,
}
struct RawHistoryBatchEntry {
offset: usize,
byte_position: u64,
byte_len: usize,
/// Oversized rows remain unbuffered until the scan determines they belong in the result.
bytes: Option<Vec<u8>>,
}
/// Look up a bounded batch of history records ending at `cursor`.
///
/// The file is opened, identity-checked, and shared-locked once. Records are counted from the
/// oldest offset on the initial lookup. Continuation lookups scan backward from the byte position
/// returned with the previous batch. The result retains at most 128 rows and 64 KiB of raw JSONL,
/// except that one oversized newest row is returned alone so callers always make progress.
///
/// # Errors
///
/// Returns an I/O error when the history file cannot be opened, inspected, locked, or read.
pub fn lookup_batch(
log_id: u64,
cursor: HistoryBatchCursor,
config: &HistoryConfig,
) -> std::io::Result<HistoryBatch> {
let path = history_filepath(config);
let mut file = OpenOptions::new().read(true).open(path)?;
let current_log_id = log_identity(&file.metadata()?).unwrap_or(0);
if log_id != 0 && current_log_id != log_id {
return Ok(HistoryBatch::default());
}
for _ in 0..MAX_RETRIES {
match file.try_lock_shared() {
Ok(()) => return scan_batch(&mut file, cursor, config),
Err(std::fs::TryLockError::WouldBlock) => std::thread::sleep(RETRY_SLEEP),
Err(error) => return Err(error.into()),
}
}
Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
"could not acquire shared history lock after multiple attempts",
))
}
/// Selects the anchored backward scan only for an unchanged, uncapped history file.
///
/// Capped histories always use the forward scan because trimming rewrites them in place and a
/// same-size rewrite may not be distinguishable from metadata on filesystems with coarse
/// modification times. Falling back preserves absolute row semantics at the cost of rescanning
/// that request from the beginning.
fn scan_batch(
file: &mut File,
cursor: HistoryBatchCursor,
config: &HistoryConfig,
) -> std::io::Result<HistoryBatch> {
let metadata = file.metadata()?;
let revision = HistoryFileRevision {
len: metadata.len(),
modified: metadata.modified().ok(),
};
if config.max_bytes.is_none()
&& let Some(anchor) = cursor.byte_anchor
&& anchor.revision == revision
{
return scan_batch_backward(file, cursor.end_offset, anchor.position, revision);
}
file.seek(SeekFrom::Start(0))?;
let mut batch = scan_batch_forward(file, cursor.end_offset, revision)?;
if config.max_bytes.is_some()
&& let Some(next_older_cursor) = &mut batch.next_older_cursor
{
next_older_cursor.byte_anchor = None;
}
Ok(batch)
}
/// Streams from byte zero through `end_offset`, retaining only the bounded newest suffix.
///
/// This path establishes byte positions for later continuation cursors and is also the safe
/// fallback when an existing cursor belongs to an older file revision. Oversized rows are tracked
/// by position and length, then materialized only if they remain in the returned suffix.
fn scan_batch_forward(
file: &mut File,
end_offset: usize,
revision: HistoryFileRevision,
) -> std::io::Result<HistoryBatch> {
let mut suffix = VecDeque::new();
let mut suffix_bytes = 0usize;
{
let mut byte_position = 0u64;
let mut reader = BufReader::with_capacity(HISTORY_READ_BUFFER_SIZE, &mut *file);
'rows: for offset in 0..=end_offset {
let mut byte_len = 0usize;
let mut bytes = Some(Vec::new());
loop {
let buffer = reader.fill_buf()?;
if buffer.is_empty() {
if byte_len == 0 {
break 'rows;
}
break;
}
let newline = buffer.iter().position(|byte| *byte == b'\n');
let consumed = newline.map_or(buffer.len(), |index| index + 1);
byte_len = byte_len.saturating_add(consumed);
if let Some(buffered) = bytes.as_mut() {
if byte_len <= MAX_BATCH_BYTES {
buffered.extend_from_slice(&buffer[..consumed]);
} else {
bytes = None;
}
}
reader.consume(consumed);
if newline.is_some() {
break;
}
}
retain_row(
&mut suffix,
&mut suffix_bytes,
RawHistoryBatchEntry {
offset,
byte_position,
byte_len,
bytes,
},
);
byte_position += byte_len as u64;
}
}
finish_materialized_batch(file, suffix.into_iter().rev().collect(), revision)
}
/// Reads complete rows backward from a validated exclusive byte boundary.
///
/// `end_byte_position` must be the start of the row immediately newer than `end_offset`. Scanning
/// in reverse lets each continuation touch only its own rows while preserving absolute offsets.
fn scan_batch_backward(
file: &mut File,
end_offset: usize,
end_byte_position: u64,
revision: HistoryFileRevision,
) -> std::io::Result<HistoryBatch> {
let mut entries = Vec::new();
let mut entries_bytes = 0usize;
let mut reversed_row = Some(Vec::new());
let mut row_byte_len = 0usize;
let mut read_buffer = [0u8; HISTORY_READ_BUFFER_SIZE];
let mut read_end = end_byte_position;
let mut offset = end_offset;
while read_end > 0 {
let read_start = read_end.saturating_sub(HISTORY_READ_BUFFER_SIZE as u64);
let read_len = usize::try_from(read_end - read_start).unwrap_or(HISTORY_READ_BUFFER_SIZE);
file.seek(SeekFrom::Start(read_start))?;
file.read_exact(&mut read_buffer[..read_len])?;
for index in (0..read_len).rev() {
let byte = read_buffer[index];
if byte == b'\n' && row_byte_len > 0 {
if let Some(bytes) = reversed_row.as_mut() {
bytes.reverse();
}
let raw = RawHistoryBatchEntry {
offset,
byte_position: read_start + index as u64 + 1,
byte_len: row_byte_len,
bytes: reversed_row.take(),
};
if !retain_newest_row(&mut entries, &mut entries_bytes, raw) {
return finish_materialized_batch(file, entries, revision);
}
let Some(next_offset) = offset.checked_sub(1) else {
return finish_materialized_batch(file, entries, revision);
};
offset = next_offset;
reversed_row = Some(vec![b'\n']);
row_byte_len = 1;
} else {
row_byte_len = row_byte_len.saturating_add(1);
if let Some(bytes) = reversed_row.as_mut() {
if row_byte_len <= MAX_BATCH_BYTES {
bytes.push(byte);
} else {
reversed_row = None;
}
}
}
}
read_end = read_start;
}
if row_byte_len > 0 {
if let Some(bytes) = reversed_row.as_mut() {
bytes.reverse();
}
retain_newest_row(
&mut entries,
&mut entries_bytes,
RawHistoryBatchEntry {
offset,
byte_position: 0,
byte_len: row_byte_len,
bytes: reversed_row,
},
);
}
finish_materialized_batch(file, entries, revision)
}
fn finish_materialized_batch(
file: &mut File,
mut entries: Vec<RawHistoryBatchEntry>,
revision: HistoryFileRevision,
) -> std::io::Result<HistoryBatch> {
for entry in &mut entries {
if entry.bytes.is_none() {
file.seek(SeekFrom::Start(entry.byte_position))?;
let mut bytes = vec![0; entry.byte_len];
file.read_exact(&mut bytes)?;
entry.bytes = Some(bytes);
}
}
finish_batch(entries, revision)
}
/// Retains the newest suffix seen by a forward scan under both row and byte caps.
///
/// A single oversized row replaces the suffix so the newest requested record is always returned
/// and callers can continue to an older cursor.
fn retain_row(
suffix: &mut VecDeque<RawHistoryBatchEntry>,
suffix_bytes: &mut usize,
entry: RawHistoryBatchEntry,
) {
let row_bytes = entry.byte_len;
if row_bytes > MAX_BATCH_BYTES {
suffix.clear();
*suffix_bytes = row_bytes;
suffix.push_back(entry);
return;
}
*suffix_bytes += row_bytes;
suffix.push_back(entry);
while suffix.len() > MAX_BATCH_ROWS || *suffix_bytes > MAX_BATCH_BYTES {
if let Some(removed) = suffix.pop_front() {
*suffix_bytes -= removed.byte_len;
}
}
}
/// Appends one newest-to-oldest row and reports whether the backward scan should continue.
///
/// Returning `false` means the batch is complete. An oversized first row is retained alone;
/// otherwise the row that would exceed a cap is left for the next batch.
fn retain_newest_row(
entries: &mut Vec<RawHistoryBatchEntry>,
entries_bytes: &mut usize,
entry: RawHistoryBatchEntry,
) -> bool {
let row_bytes = entry.byte_len;
if entries.is_empty() && row_bytes > MAX_BATCH_BYTES {
entries.push(entry);
return false;
}
if entries.len() == MAX_BATCH_ROWS || entries_bytes.saturating_add(row_bytes) > MAX_BATCH_BYTES
{
return false;
}
*entries_bytes += row_bytes;
entries.push(entry);
true
}
/// Parses newest-first rows and anchors the continuation at the oldest retained row's start.
fn finish_batch(
entries: Vec<RawHistoryBatchEntry>,
revision: HistoryFileRevision,
) -> std::io::Result<HistoryBatch> {
let next_older_cursor = entries.last().and_then(|entry| {
entry
.offset
.checked_sub(1)
.map(|end_offset| HistoryBatchCursor {
end_offset,
byte_anchor: revision.modified.map(|_| HistoryByteAnchor {
position: entry.byte_position,
revision,
}),
})
});
let entries = entries
.into_iter()
.map(|raw| {
let bytes = raw.bytes.ok_or_else(|| {
std::io::Error::other("retained history row was not materialized")
})?;
Ok(HistoryBatchEntry {
offset: raw.offset,
entry: try_parse_entry(&bytes),
})
})
.collect::<std::io::Result<Vec<_>>>()?;
Ok(HistoryBatch {
entries,
next_older_cursor,
})
}
fn try_parse_entry(raw: &[u8]) -> Option<HistoryEntry> {
let raw = raw.strip_suffix(b"\n").unwrap_or(raw);
let raw = raw.strip_suffix(b"\r").unwrap_or(raw);
serde_json::from_slice(raw).ok()
}

View File

@@ -0,0 +1,359 @@
use std::fs::File;
use std::io::Write;
use akode_config::types::History;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use crate::*;
fn entry(offset: usize, text: impl Into<String>) -> HistoryEntry {
HistoryEntry {
session_id: "session".to_string(),
ts: offset as u64,
text: text.into(),
}
}
fn write_entries(home: &TempDir, entries: &[HistoryEntry]) -> HistoryConfig {
let mut file = File::create(home.path().join(HISTORY_FILENAME)).expect("create history");
for entry in entries {
serde_json::to_writer(&mut file, entry).expect("serialize entry");
writeln!(file).expect("write entry");
}
HistoryConfig::new(home.path(), &History::default())
}
async fn batch_for(entries: &[HistoryEntry], end_offset: usize) -> (TempDir, HistoryBatch) {
let home = TempDir::new().expect("temp dir");
let config = write_entries(&home, entries);
let (log_id, _) = history_metadata(&config).await;
let batch = lookup_batch(log_id, HistoryBatchCursor::new(end_offset), &config)
.expect("read history batch");
(home, batch)
}
#[tokio::test]
async fn search_batch_returns_bounded_newest_first_absolute_offsets() {
let entries: Vec<_> = (0..400)
.map(|offset| entry(offset, format!("row {offset}")))
.collect();
let (home, batch) = batch_for(&entries, /*end_offset*/ 399).await;
assert_eq!(batch.entries.len(), 128);
assert_eq!(batch.entries.first().map(|entry| entry.offset), Some(399));
assert_eq!(batch.entries.last().map(|entry| entry.offset), Some(272));
let next_cursor = batch.next_older_cursor.expect("older cursor");
assert_eq!(next_cursor.end_offset(), 271);
assert_eq!(batch.entries[0].entry, Some(entries[399].clone()));
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
let mut offsets: Vec<_> = batch.entries.iter().map(|entry| entry.offset).collect();
let mut cursor = Some(next_cursor);
while let Some(next_cursor) = cursor {
let older = lookup_batch(log_id, next_cursor, &config).expect("read older history batch");
offsets.extend(older.entries.iter().map(|entry| entry.offset));
cursor = older.next_older_cursor;
}
assert_eq!(offsets, (0..400).rev().collect::<Vec<_>>());
}
#[tokio::test]
async fn search_batch_invalidates_byte_cursor_after_in_place_rewrite() {
let original: Vec<_> = (0..400)
.map(|offset| entry(offset, format!("old row {offset}")))
.collect();
let (home, batch) = batch_for(&original, /*end_offset*/ 399).await;
let cursor = batch.next_older_cursor.expect("older cursor");
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
let original_len = std::fs::metadata(home.path().join(HISTORY_FILENAME))
.expect("history metadata")
.len();
let replacement: Vec<_> = (0..500)
.map(|offset| entry(offset, format!("replacement row {offset} with padding")))
.collect();
let replacement_config = write_entries(&home, &replacement);
let replacement_len = std::fs::metadata(home.path().join(HISTORY_FILENAME))
.expect("replacement history metadata")
.len();
assert!(replacement_len > original_len);
let (replacement_log_id, _) = history_metadata(&replacement_config).await;
assert_eq!(replacement_log_id, log_id);
let older =
lookup_batch(log_id, cursor, &replacement_config).expect("read rewritten history batch");
assert_eq!(older.entries.len(), 128);
assert_eq!(older.entries[0].offset, 271);
assert_eq!(older.entries[0].entry, Some(replacement[271].clone()));
assert_eq!(older.entries[127].offset, 144);
assert_eq!(older.entries[127].entry, Some(replacement[144].clone()));
}
#[tokio::test]
async fn search_batch_rescans_capped_history_after_same_size_rewrite() {
let home = TempDir::new().expect("temp dir");
let original: Vec<_> = (0..400)
.map(|offset| entry(offset, "a".repeat(20)))
.collect();
write_entries(&home, &original);
let path = home.path().join(HISTORY_FILENAME);
let original_metadata = std::fs::metadata(&path).expect("history metadata");
let original_modified = original_metadata.modified().expect("history modified time");
let history = History {
max_bytes: Some(original_metadata.len() as usize),
..History::default()
};
let config = HistoryConfig::new(home.path(), &history);
let (log_id, _) = history_metadata(&config).await;
let first = lookup_batch(log_id, HistoryBatchCursor::new(/*end_offset*/ 399), &config)
.expect("read history batch");
let cursor = first.next_older_cursor.expect("older cursor");
let mut replacement: Vec<_> = (0..400)
.map(|offset| entry(offset, "b".repeat(20)))
.collect();
replacement[0].text.push_str(&"b".repeat(10));
replacement[399].text.truncate(10);
write_entries(&home, &replacement);
let file = File::options()
.write(true)
.open(&path)
.expect("open replacement history");
file.set_times(std::fs::FileTimes::new().set_modified(original_modified))
.expect("restore history modified time");
let replacement_metadata = std::fs::metadata(&path).expect("replacement history metadata");
assert_eq!(replacement_metadata.len(), original_metadata.len());
assert_eq!(
replacement_metadata.modified().ok(),
Some(original_modified)
);
let older = lookup_batch(log_id, cursor, &config).expect("read rewritten history batch");
assert_eq!(
older,
HistoryBatch {
entries: (144..=271)
.rev()
.map(|offset| HistoryBatchEntry {
offset,
entry: Some(replacement[offset].clone()),
})
.collect(),
next_older_cursor: Some(HistoryBatchCursor::new(/*end_offset*/ 143)),
}
);
}
#[tokio::test]
async fn search_batch_stitches_chunks_and_keeps_malformed_offsets() {
let home = TempDir::new().expect("temp dir");
let first = entry(/*offset*/ 0, "a".repeat(HISTORY_READ_BUFFER_SIZE + 17));
let third = entry(/*offset*/ 2, "third");
let contents = format!(
"{}\nnot-json\n{}\n",
serde_json::to_string(&first).expect("serialize first"),
serde_json::to_string(&third).expect("serialize third")
);
std::fs::write(home.path().join(HISTORY_FILENAME), contents).expect("write history");
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
assert_eq!(
lookup_batch(log_id, HistoryBatchCursor::new(/*end_offset*/ 2), &config,)
.expect("read history batch"),
HistoryBatch {
entries: vec![
HistoryBatchEntry {
offset: 2,
entry: Some(third),
},
HistoryBatchEntry {
offset: 1,
entry: None,
},
HistoryBatchEntry {
offset: 0,
entry: Some(first),
},
],
next_older_cursor: None,
}
);
}
#[tokio::test]
async fn search_batch_preserves_identity_append_trim_and_short_file_semantics() {
let home = TempDir::new().expect("temp dir");
let initial = vec![entry(/*offset*/ 0, "zero"), entry(/*offset*/ 1, "one")];
let config = write_entries(&home, &initial);
let (log_id, _) = history_metadata(&config).await;
assert_eq!(
lookup_batch(
log_id.wrapping_add(1),
HistoryBatchCursor::new(/*end_offset*/ 1),
&config,
)
.expect("read history batch"),
HistoryBatch::default()
);
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(home.path().join(HISTORY_FILENAME))
.expect("open history");
serde_json::to_writer(&mut file, &entry(/*offset*/ 2, "appended")).expect("serialize append");
writeln!(file).expect("append entry");
let batch = lookup_batch(log_id, HistoryBatchCursor::new(/*end_offset*/ 1), &config)
.expect("read history batch");
assert_eq!(
batch.entries,
vec![
HistoryBatchEntry {
offset: 1,
entry: Some(initial[1].clone()),
},
HistoryBatchEntry {
offset: 0,
entry: Some(initial[0].clone()),
},
]
);
let newest = "c".repeat(200);
let history = History {
max_bytes: Some(newest.len() + 80),
..History::default()
};
let trimmed_config = HistoryConfig::new(home.path(), &history);
append_entry(&newest, "session", &trimmed_config)
.await
.expect("append and trim");
let trimmed = lookup_batch(
log_id,
HistoryBatchCursor::new(/*end_offset*/ 20),
&trimmed_config,
)
.expect("read trimmed history batch");
assert_eq!(trimmed.entries.len(), 1);
assert_eq!(trimmed.entries[0].offset, 0);
assert_eq!(
trimmed.entries[0].entry.as_ref().map(|entry| &entry.text),
Some(&newest)
);
assert_eq!(trimmed.next_older_cursor, None);
}
#[tokio::test]
async fn search_batch_enforces_byte_cap_and_oversized_row_progress() {
let entries: Vec<_> = (0..5)
.map(|offset| {
entry(
offset,
char::from(b'a' + offset as u8).to_string().repeat(20_000),
)
})
.collect();
let (_home, batch) = batch_for(&entries, /*end_offset*/ 4).await;
assert_eq!(batch.entries.len(), 3);
assert_eq!(batch.entries.first().map(|entry| entry.offset), Some(4));
assert_eq!(batch.entries.last().map(|entry| entry.offset), Some(2));
assert_eq!(
batch.next_older_cursor.expect("older cursor").end_offset(),
1
);
let entries = vec![
entry(/*offset*/ 0, "small"),
entry(/*offset*/ 1, "x".repeat(70_000)),
];
let (home, oversized) = batch_for(&entries, /*end_offset*/ 1).await;
assert_eq!(oversized.entries.len(), 1);
assert_eq!(oversized.entries[0].entry, Some(entries[1].clone()));
let next_cursor = oversized.next_older_cursor.expect("older cursor");
assert_eq!(next_cursor.end_offset(), 0);
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
let next = lookup_batch(log_id, next_cursor, &config).expect("read older history batch");
assert_eq!(next.entries[0].entry, Some(entries[0].clone()));
assert_eq!(next.next_older_cursor, None);
let entries = vec![
entry(/*offset*/ 0, "x".repeat(70_000)),
entry(/*offset*/ 1, "newest"),
];
let (home, newest) = batch_for(&entries, /*end_offset*/ 1).await;
assert_eq!(
newest.entries,
vec![HistoryBatchEntry {
offset: 1,
entry: Some(entries[1].clone()),
}]
);
let next_cursor = newest.next_older_cursor.expect("older cursor");
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
let oversized = lookup_batch(log_id, next_cursor, &config).expect("read oversized older row");
assert_eq!(
oversized,
HistoryBatch {
entries: vec![HistoryBatchEntry {
offset: 0,
entry: Some(entries[0].clone()),
}],
next_older_cursor: None,
}
);
}
#[tokio::test]
async fn search_batch_defers_oversized_row_during_backward_scan() {
let mut entries = vec![
entry(/*offset*/ 0, "oldest"),
entry(/*offset*/ 1, "x".repeat(70_000)),
];
entries.extend((2..8).map(|offset| entry(offset, "x".repeat(20_000))));
let (home, newest) = batch_for(&entries, /*end_offset*/ 7).await;
assert_eq!(
newest
.entries
.iter()
.map(|entry| entry.offset)
.collect::<Vec<_>>(),
vec![7, 6, 5]
);
let config = HistoryConfig::new(home.path(), &History::default());
let (log_id, _) = history_metadata(&config).await;
let middle = lookup_batch(
log_id,
newest.next_older_cursor.expect("middle cursor"),
&config,
)
.expect("read middle history batch");
assert_eq!(
middle
.entries
.iter()
.map(|entry| entry.offset)
.collect::<Vec<_>>(),
vec![4, 3, 2]
);
let oversized = lookup_batch(
log_id,
middle.next_older_cursor.expect("oversized cursor"),
&config,
)
.expect("read oversized history row");
assert_eq!(oversized.entries[0].entry, Some(entries[1].clone()));
assert_eq!(
oversized
.next_older_cursor
.expect("oldest cursor")
.end_offset(),
0
);
}

View File

@@ -0,0 +1,443 @@
//! Persistence layer for the global, append-only *message history* file.
//!
//! The history is stored at `~/.akode/history.jsonl` with **one JSON object per
//! line** so that it can be efficiently appended to and parsed with standard
//! JSON-Lines tooling. Each record has the following schema:
//!
//! ````text
//! {"session_id":"<uuid>","ts":<unix_seconds>,"text":"<message>"}
//! ````
//!
//! To minimize the chance of interleaved writes when multiple processes are
//! appending concurrently, callers should *prepare the full line* (record +
//! trailing `\n`) and write it with a **single `write(2)` system call** while
//! the file descriptor is opened with the `O_APPEND` flag. POSIX guarantees
//! that writes up to `PIPE_BUF` bytes are atomic in that case.
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use std::io::Result;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use memchr::memchr_iter;
use serde::Deserialize;
use serde::Serialize;
use std::time::Duration;
use tokio::fs;
use tokio::io::AsyncReadExt;
use akode_config::types::History;
use akode_config::types::HistoryPersistence;
mod batch;
pub use batch::HistoryBatch;
pub use batch::HistoryBatchCursor;
pub use batch::HistoryBatchEntry;
pub use batch::lookup_batch;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
/// Filename that stores the message history inside `~/.akode`.
const HISTORY_FILENAME: &str = "history.jsonl";
const HISTORY_READ_BUFFER_SIZE: usize = 8192;
/// When history exceeds the hard cap, trim it down to this fraction of `max_bytes`.
const HISTORY_SOFT_CAP_RATIO: f64 = 0.8;
const MAX_RETRIES: usize = 10;
const RETRY_SLEEP: Duration = Duration::from_millis(100);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct HistoryEntry {
pub session_id: String,
pub ts: u64,
pub text: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HistoryConfig {
pub codex_home: PathBuf,
pub persistence: HistoryPersistence,
pub max_bytes: Option<usize>,
}
impl HistoryConfig {
pub fn new(codex_home: impl Into<PathBuf>, history: &History) -> Self {
Self {
codex_home: codex_home.into(),
persistence: history.persistence,
max_bytes: history.max_bytes,
}
}
}
fn history_filepath(config: &HistoryConfig) -> PathBuf {
config.codex_home.join(HISTORY_FILENAME)
}
/// Append a `text` entry associated with `conversation_id` to the history file.
///
/// Uses advisory file locking (`File::try_lock`) with a retry loop to ensure
/// concurrent writes from multiple TUI processes do not interleave. The lock
/// acquisition and write are performed inside `spawn_blocking` so the caller's
/// async runtime is not blocked.
///
/// The entry is silently skipped when `config.history.persistence` is
/// [`HistoryPersistence::None`].
///
/// # Errors
///
/// Returns an I/O error if the history file cannot be opened/created, the
/// system clock is before the Unix epoch, or the exclusive lock cannot be
/// acquired after [`MAX_RETRIES`] attempts.
pub async fn append_entry(
text: &str,
conversation_id: impl std::fmt::Display,
config: &HistoryConfig,
) -> Result<()> {
match config.persistence {
HistoryPersistence::SaveAll => {
// Save everything: proceed.
}
HistoryPersistence::None => {
// No history persistence requested.
return Ok(());
}
}
// TODO: check `text` for sensitive patterns
// Resolve `~/.akode/history.jsonl` and ensure the parent directory exists.
let path = history_filepath(config);
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
// Compute timestamp (seconds since the Unix epoch).
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| std::io::Error::other(format!("system clock before Unix epoch: {e}")))?
.as_secs();
// Construct the JSON line first so we can write it in a single syscall.
let entry = HistoryEntry {
session_id: conversation_id.to_string(),
ts,
text: text.to_string(),
};
let mut line = serde_json::to_string(&entry)
.map_err(|e| std::io::Error::other(format!("failed to serialise history entry: {e}")))?;
line.push('\n');
// Open the history file for read/write access (append-only on Unix).
let mut options = OpenOptions::new();
options.read(true).write(true).create(true);
#[cfg(unix)]
{
options.append(true);
options.mode(0o600);
}
let mut history_file = options.open(&path)?;
// Ensure permissions.
ensure_owner_only_permissions(&history_file).await?;
let history_max_bytes = config.max_bytes;
// Perform a blocking write under an advisory write lock using std::fs.
tokio::task::spawn_blocking(move || -> Result<()> {
// Retry a few times to avoid indefinite blocking when contended.
for _ in 0..MAX_RETRIES {
match history_file.try_lock() {
Ok(()) => {
// While holding the exclusive lock, write the full line.
// We do not open the file with `append(true)` on Windows, so ensure the
// cursor is positioned at the end before writing.
history_file.seek(SeekFrom::End(0))?;
history_file.write_all(line.as_bytes())?;
history_file.flush()?;
enforce_history_limit(&mut history_file, history_max_bytes)?;
return Ok(());
}
Err(std::fs::TryLockError::WouldBlock) => {
std::thread::sleep(RETRY_SLEEP);
}
Err(e) => return Err(e.into()),
}
}
Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
"could not acquire exclusive lock on history file after multiple attempts",
))
})
.await??;
Ok(())
}
/// Trim the history file to honor `max_bytes`, dropping the oldest lines while holding
/// the write lock so the newest entry is always retained. When the file exceeds the
/// hard cap, it rewrites the remaining tail to a soft cap to avoid trimming again
/// immediately on the next write.
fn enforce_history_limit(file: &mut File, max_bytes: Option<usize>) -> Result<()> {
let Some(max_bytes) = max_bytes else {
return Ok(());
};
if max_bytes == 0 {
return Ok(());
}
let max_bytes = match u64::try_from(max_bytes) {
Ok(value) => value,
Err(_) => return Ok(()),
};
let mut current_len = file.metadata()?.len();
if current_len <= max_bytes {
return Ok(());
}
let mut reader_file = file.try_clone()?;
reader_file.seek(SeekFrom::Start(0))?;
let mut buf_reader = BufReader::new(reader_file);
let mut line_lengths = Vec::new();
let mut line_buf = String::new();
loop {
line_buf.clear();
let bytes = buf_reader.read_line(&mut line_buf)?;
if bytes == 0 {
break;
}
line_lengths.push(bytes as u64);
}
if line_lengths.is_empty() {
return Ok(());
}
let last_index = line_lengths.len() - 1;
let trim_target = trim_target_bytes(max_bytes, line_lengths[last_index]);
let mut drop_bytes = 0u64;
let mut idx = 0usize;
while current_len > trim_target && idx < last_index {
current_len = current_len.saturating_sub(line_lengths[idx]);
drop_bytes += line_lengths[idx];
idx += 1;
}
if drop_bytes == 0 {
return Ok(());
}
let mut reader = buf_reader.into_inner();
reader.seek(SeekFrom::Start(drop_bytes))?;
let capacity = usize::try_from(current_len).unwrap_or(0);
let mut tail = Vec::with_capacity(capacity);
reader.read_to_end(&mut tail)?;
file.set_len(0)?;
file.seek(SeekFrom::Start(0))?;
file.write_all(&tail)?;
file.flush()?;
Ok(())
}
fn trim_target_bytes(max_bytes: u64, newest_entry_len: u64) -> u64 {
let soft_cap_bytes = ((max_bytes as f64) * HISTORY_SOFT_CAP_RATIO)
.floor()
.clamp(1.0, max_bytes as f64) as u64;
soft_cap_bytes.max(newest_entry_len)
}
/// Asynchronously fetch the history file's *identifier* and current entry count.
///
/// The identifier is the file's inode on Unix or creation time on Windows.
/// The entry count is derived by counting newline bytes in the file. Returns
/// `(0, 0)` when the file does not exist or its metadata cannot be read. If
/// metadata succeeds but the file cannot be opened or scanned, returns
/// `(log_id, 0)` so callers can still detect that a history file exists.
pub async fn history_metadata(config: &HistoryConfig) -> (u64, usize) {
let path = history_filepath(config);
history_metadata_for_file(&path).await
}
/// Look up a single history entry by file identity and zero-based offset.
///
/// Returns `Some(entry)` when the current history file's identifier (inode on
/// Unix, creation time on Windows) matches `log_id` **and** a valid JSON
/// record exists at `offset`. Returns `None` on any mismatch, I/O error, or
/// parse failure, all of which are logged at `warn` level.
///
/// This function is synchronous because it acquires a shared advisory file lock
/// via `File::try_lock_shared`. Callers on an async runtime should wrap it in
/// `spawn_blocking`.
pub fn lookup(log_id: u64, offset: usize, config: &HistoryConfig) -> Option<HistoryEntry> {
let path = history_filepath(config);
lookup_history_entry(&path, log_id, offset)
}
/// On Unix systems, ensure the file permissions are `0o600` (rw-------). If the
/// permissions cannot be changed the error is propagated to the caller.
#[cfg(unix)]
async fn ensure_owner_only_permissions(file: &File) -> Result<()> {
let metadata = file.metadata()?;
let current_mode = metadata.permissions().mode() & 0o777;
if current_mode != 0o600 {
let mut perms = metadata.permissions();
perms.set_mode(0o600);
let perms_clone = perms.clone();
let file_clone = file.try_clone()?;
tokio::task::spawn_blocking(move || file_clone.set_permissions(perms_clone)).await??;
}
Ok(())
}
#[cfg(windows)]
// On Windows, simply succeed.
async fn ensure_owner_only_permissions(_file: &File) -> Result<()> {
Ok(())
}
async fn history_metadata_for_file(path: &Path) -> (u64, usize) {
let log_id = match fs::metadata(path).await {
Ok(metadata) => log_identity(&metadata).unwrap_or(0),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (0, 0),
Err(_) => return (0, 0),
};
// Open the file.
let mut file = match fs::File::open(path).await {
Ok(f) => f,
Err(_) => return (log_id, 0),
};
// Count newline bytes.
let mut buf = [0u8; HISTORY_READ_BUFFER_SIZE];
let mut count = 0usize;
loop {
match file.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
count += memchr_iter(b'\n', &buf[..n]).count();
}
Err(_) => return (log_id, 0),
}
}
(log_id, count)
}
fn lookup_history_entry(path: &Path, log_id: u64, offset: usize) -> Option<HistoryEntry> {
use std::io::BufRead;
use std::io::BufReader;
let file: File = match OpenOptions::new().read(true).open(path) {
Ok(f) => f,
Err(e) => {
tracing::warn!(error = %e, "failed to open history file");
return None;
}
};
let metadata = match file.metadata() {
Ok(m) => m,
Err(e) => {
tracing::warn!(error = %e, "failed to stat history file");
return None;
}
};
let current_log_id = log_identity(&metadata)?;
if log_id != 0 && current_log_id != log_id {
return None;
}
// Open & lock file for reading using a shared lock.
// Retry a few times to avoid indefinite blocking.
for _ in 0..MAX_RETRIES {
let lock_result = file.try_lock_shared();
match lock_result {
Ok(()) => {
let reader = BufReader::new(&file);
for (idx, line_res) in reader.lines().enumerate() {
let line = match line_res {
Ok(l) => l,
Err(e) => {
tracing::warn!(error = %e, "failed to read line from history file");
return None;
}
};
if idx == offset {
match serde_json::from_str::<HistoryEntry>(&line) {
Ok(entry) => return Some(entry),
Err(e) => {
tracing::warn!(error = %e, "failed to parse history entry");
return None;
}
}
}
}
// Not found at requested offset.
return None;
}
Err(std::fs::TryLockError::WouldBlock) => {
std::thread::sleep(RETRY_SLEEP);
}
Err(e) => {
tracing::warn!(error = %e, "failed to acquire shared lock on history file");
return None;
}
}
}
None
}
#[cfg(unix)]
fn log_identity(metadata: &std::fs::Metadata) -> Option<u64> {
use std::os::unix::fs::MetadataExt;
Some(metadata.ino())
}
#[cfg(windows)]
fn log_identity(metadata: &std::fs::Metadata) -> Option<u64> {
use std::os::windows::fs::MetadataExt;
Some(metadata.creation_time())
}
#[cfg(not(any(unix, windows)))]
fn log_identity(_metadata: &std::fs::Metadata) -> Option<u64> {
None
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,223 @@
use super::*;
use akode_config::types::History;
use pretty_assertions::assert_eq;
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
#[tokio::test]
async fn lookup_reads_history_entries() {
let temp_dir = TempDir::new().expect("create temp dir");
let history_path = temp_dir.path().join(HISTORY_FILENAME);
let entries = vec![
HistoryEntry {
session_id: "first-session".to_string(),
ts: 1,
text: "first".to_string(),
},
HistoryEntry {
session_id: "second-session".to_string(),
ts: 2,
text: "second".to_string(),
},
];
let mut file = File::create(&history_path).expect("create history file");
for entry in &entries {
writeln!(
file,
"{}",
serde_json::to_string(entry).expect("serialize history entry")
)
.expect("write history entry");
}
let (log_id, count) = history_metadata_for_file(&history_path).await;
assert_eq!(count, entries.len());
let second_entry = lookup_history_entry(&history_path, log_id, /*offset*/ 1)
.expect("fetch second history entry");
assert_eq!(second_entry, entries[1]);
}
#[tokio::test]
async fn history_metadata_counts_newlines_across_read_boundaries() {
let temp_dir = TempDir::new().expect("create temp dir");
let history_path = temp_dir.path().join(HISTORY_FILENAME);
let mut contents = vec![b'x'; 3 * HISTORY_READ_BUFFER_SIZE + 1];
let newline_offsets = [
0,
HISTORY_READ_BUFFER_SIZE - 1,
HISTORY_READ_BUFFER_SIZE,
2 * HISTORY_READ_BUFFER_SIZE,
contents.len() - 2,
];
for offset in newline_offsets {
contents[offset] = b'\n';
}
std::fs::write(&history_path, contents).expect("write history file");
let (_, count) = history_metadata_for_file(&history_path).await;
assert_eq!(count, newline_offsets.len());
}
#[tokio::test]
async fn lookup_uses_stable_log_id_after_appends() {
let temp_dir = TempDir::new().expect("create temp dir");
let history_path = temp_dir.path().join(HISTORY_FILENAME);
let initial = HistoryEntry {
session_id: "first-session".to_string(),
ts: 1,
text: "first".to_string(),
};
let appended = HistoryEntry {
session_id: "second-session".to_string(),
ts: 2,
text: "second".to_string(),
};
let mut file = File::create(&history_path).expect("create history file");
writeln!(
file,
"{}",
serde_json::to_string(&initial).expect("serialize initial entry")
)
.expect("write initial entry");
let (log_id, count) = history_metadata_for_file(&history_path).await;
assert_eq!(count, 1);
let mut append = std::fs::OpenOptions::new()
.append(true)
.open(&history_path)
.expect("open history file for append");
writeln!(
append,
"{}",
serde_json::to_string(&appended).expect("serialize appended entry")
)
.expect("append history entry");
let fetched = lookup_history_entry(&history_path, log_id, /*offset*/ 1)
.expect("lookup appended history entry");
assert_eq!(fetched, appended);
}
#[tokio::test]
async fn append_entry_trims_history_when_beyond_max_bytes() {
let codex_home = TempDir::new().expect("create temp dir");
let mut history = History::default();
let mut config = HistoryConfig::new(codex_home.path(), &history);
let conversation_id = "conversation-id";
let entry_one = "a".repeat(200);
let entry_two = "b".repeat(200);
let history_path = codex_home.path().join("history.jsonl");
append_entry(&entry_one, &conversation_id, &config)
.await
.expect("write first entry");
let first_len = std::fs::metadata(&history_path).expect("metadata").len();
let limit_bytes = first_len + 10;
history.max_bytes = Some(usize::try_from(limit_bytes).expect("limit should fit into usize"));
config = HistoryConfig::new(codex_home.path(), &history);
append_entry(&entry_two, &conversation_id, &config)
.await
.expect("write second entry");
let contents = std::fs::read_to_string(&history_path).expect("read history");
let entries = contents
.lines()
.map(|line| serde_json::from_str::<HistoryEntry>(line).expect("parse entry"))
.collect::<Vec<HistoryEntry>>();
assert_eq!(
entries.len(),
1,
"only one entry left because entry_one should be evicted"
);
assert_eq!(entries[0].text, entry_two);
assert!(std::fs::metadata(&history_path).expect("metadata").len() <= limit_bytes);
}
#[tokio::test]
async fn append_entry_trims_history_to_soft_cap() {
let codex_home = TempDir::new().expect("create temp dir");
let mut history = History::default();
let mut config = HistoryConfig::new(codex_home.path(), &history);
let conversation_id = "conversation-id";
let short_entry = "a".repeat(200);
let long_entry = "b".repeat(400);
let history_path = codex_home.path().join("history.jsonl");
append_entry(&short_entry, &conversation_id, &config)
.await
.expect("write first entry");
let short_entry_len = std::fs::metadata(&history_path).expect("metadata").len();
append_entry(&long_entry, &conversation_id, &config)
.await
.expect("write second entry");
let two_entry_len = std::fs::metadata(&history_path).expect("metadata").len();
let long_entry_len = two_entry_len
.checked_sub(short_entry_len)
.expect("second entry length should be larger than first entry length");
history.max_bytes = Some(
usize::try_from((2 * long_entry_len) + (short_entry_len / 2))
.expect("max bytes should fit into usize"),
);
config = HistoryConfig::new(codex_home.path(), &history);
append_entry(&long_entry, &conversation_id, &config)
.await
.expect("write third entry");
let contents = std::fs::read_to_string(&history_path).expect("read history");
let entries = contents
.lines()
.map(|line| serde_json::from_str::<HistoryEntry>(line).expect("parse entry"))
.collect::<Vec<HistoryEntry>>();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].text, long_entry);
let pruned_len = std::fs::metadata(&history_path).expect("metadata").len();
let max_bytes = config.max_bytes.expect("max bytes should be configured") as u64;
assert!(pruned_len <= max_bytes);
let soft_cap_bytes = ((max_bytes as f64) * HISTORY_SOFT_CAP_RATIO)
.floor()
.clamp(1.0, max_bytes as f64) as u64;
let len_without_first = 2 * long_entry_len;
assert!(
len_without_first <= max_bytes,
"dropping only the first entry would satisfy the hard cap"
);
assert!(
len_without_first > soft_cap_bytes,
"soft cap should require more aggressive trimming than the hard cap"
);
assert_eq!(pruned_len, long_entry_len);
assert!(pruned_len <= soft_cap_bytes.max(long_entry_len));
}
#[path = "batch_tests.rs"]
mod batch_tests;