aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
117
akode-rs/memories/write/src/control.rs
Normal file
117
akode-rs/memories/write/src/control.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use std::path::Path;
|
||||
|
||||
pub async fn clear_memory_roots_contents(codex_home: &Path) -> std::io::Result<()> {
|
||||
for memory_root in [
|
||||
codex_home.join("memories"),
|
||||
codex_home.join("memories_v2"),
|
||||
codex_home.join("memories_extensions"),
|
||||
] {
|
||||
clear_memory_root_contents(memory_root.as_path()).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn clear_memory_root_contents(memory_root: &Path) -> std::io::Result<()> {
|
||||
match tokio::fs::symlink_metadata(memory_root).await {
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"refusing to clear symlinked memory root {}",
|
||||
memory_root.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
|
||||
tokio::fs::create_dir_all(memory_root).await?;
|
||||
|
||||
let mut entries = tokio::fs::read_dir(memory_root).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
let file_type = entry.file_type().await?;
|
||||
if file_type.is_dir() {
|
||||
tokio::fs::remove_dir_all(path).await?;
|
||||
} else {
|
||||
tokio::fs::remove_file(path).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn clear_memory_root_contents_preserves_root_directory() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let root = dir.path().join("memories");
|
||||
let nested_dir = root.join("rollout_summaries");
|
||||
tokio::fs::create_dir_all(&nested_dir)
|
||||
.await
|
||||
.expect("create rollout summaries dir");
|
||||
tokio::fs::write(root.join("MEMORY.md"), "stale memory index\n")
|
||||
.await
|
||||
.expect("write memory index");
|
||||
tokio::fs::write(nested_dir.join("rollout.md"), "stale rollout\n")
|
||||
.await
|
||||
.expect("write rollout summary");
|
||||
|
||||
clear_memory_root_contents(&root)
|
||||
.await
|
||||
.expect("clear memory root contents");
|
||||
|
||||
assert!(
|
||||
tokio::fs::try_exists(&root)
|
||||
.await
|
||||
.expect("check memory root existence"),
|
||||
"memory root should still exist after clearing contents"
|
||||
);
|
||||
let mut entries = tokio::fs::read_dir(&root)
|
||||
.await
|
||||
.expect("read memory root after clear");
|
||||
assert!(
|
||||
entries
|
||||
.next_entry()
|
||||
.await
|
||||
.expect("read next entry")
|
||||
.is_none(),
|
||||
"memory root should be empty after clearing contents"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn clear_memory_root_contents_rejects_symlinked_root() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let target = dir.path().join("outside");
|
||||
tokio::fs::create_dir_all(&target)
|
||||
.await
|
||||
.expect("create symlink target dir");
|
||||
let target_file = target.join("keep.txt");
|
||||
tokio::fs::write(&target_file, "keep\n")
|
||||
.await
|
||||
.expect("write target file");
|
||||
|
||||
let root = dir.path().join("memories");
|
||||
std::os::unix::fs::symlink(&target, &root).expect("create memory root symlink");
|
||||
|
||||
let err = clear_memory_root_contents(&root)
|
||||
.await
|
||||
.expect_err("symlinked memory root should be rejected");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert!(
|
||||
tokio::fs::try_exists(&target_file)
|
||||
.await
|
||||
.expect("check target file existence"),
|
||||
"rejecting a symlinked memory root should not delete the symlink target"
|
||||
);
|
||||
}
|
||||
}
|
||||
30
akode-rs/memories/write/src/extensions/ad_hoc.rs
Normal file
30
akode-rs/memories/write/src/extensions/ad_hoc.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use crate::memory_extensions_root;
|
||||
use std::path::Path;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
pub(super) const INSTRUCTIONS: &str =
|
||||
include_str!("../../templates/extensions/ad_hoc/instructions.md");
|
||||
|
||||
pub(super) async fn seed_instructions(memory_root: &Path) -> std::io::Result<()> {
|
||||
let extension_root = memory_extensions_root(memory_root).join("ad_hoc");
|
||||
let instructions_path = extension_root.join("instructions.md");
|
||||
|
||||
tokio::fs::create_dir_all(&extension_root).await?;
|
||||
match tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&instructions_path)
|
||||
.await
|
||||
{
|
||||
Ok(mut file) => {
|
||||
file.write_all(INSTRUCTIONS.as_bytes()).await?;
|
||||
file.flush().await
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ad_hoc_tests.rs"]
|
||||
mod tests;
|
||||
36
akode-rs/memories/write/src/extensions/ad_hoc_tests.rs
Normal file
36
akode-rs/memories/write/src/extensions/ad_hoc_tests.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use super::*;
|
||||
use crate::memory_extensions_root;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn seeds_instructions_without_overwriting_existing_file() {
|
||||
let codex_home = TempDir::new().expect("create temp codex home");
|
||||
let memory_root = codex_home.path().join("memories");
|
||||
let instructions_path = memory_extensions_root(&memory_root).join("ad_hoc/instructions.md");
|
||||
|
||||
seed_instructions(&memory_root)
|
||||
.await
|
||||
.expect("seed ad-hoc instructions");
|
||||
|
||||
assert_eq!(
|
||||
tokio::fs::read_to_string(&instructions_path)
|
||||
.await
|
||||
.expect("read seeded ad-hoc instructions"),
|
||||
INSTRUCTIONS
|
||||
);
|
||||
|
||||
tokio::fs::write(&instructions_path, "custom instructions")
|
||||
.await
|
||||
.expect("write custom instructions");
|
||||
seed_instructions(&memory_root)
|
||||
.await
|
||||
.expect("seed ad-hoc instructions again");
|
||||
|
||||
assert_eq!(
|
||||
tokio::fs::read_to_string(&instructions_path)
|
||||
.await
|
||||
.expect("read custom ad-hoc instructions"),
|
||||
"custom instructions"
|
||||
);
|
||||
}
|
||||
10
akode-rs/memories/write/src/extensions/mod.rs
Normal file
10
akode-rs/memories/write/src/extensions/mod.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
mod ad_hoc;
|
||||
mod prune;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) async fn seed_extension_instructions(memory_root: &Path) -> std::io::Result<()> {
|
||||
ad_hoc::seed_instructions(memory_root).await
|
||||
}
|
||||
|
||||
pub use prune::prune_old_extension_resources;
|
||||
100
akode-rs/memories/write/src/extensions/prune.rs
Normal file
100
akode-rs/memories/write/src/extensions/prune.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use crate::memory_extensions_root;
|
||||
use chrono::DateTime;
|
||||
use chrono::Duration;
|
||||
use chrono::NaiveDateTime;
|
||||
use chrono::Utc;
|
||||
use std::path::Path;
|
||||
use tracing::warn;
|
||||
|
||||
pub async fn prune_old_extension_resources(memory_root: &Path) {
|
||||
prune_old_extension_resources_with_now(memory_root, Utc::now()).await
|
||||
}
|
||||
|
||||
async fn prune_old_extension_resources_with_now(memory_root: &Path, now: DateTime<Utc>) {
|
||||
let cutoff = now - Duration::days(crate::extension_resources::RETENTION_DAYS);
|
||||
let extensions_root = memory_extensions_root(memory_root);
|
||||
let mut extensions = match tokio::fs::read_dir(&extensions_root).await {
|
||||
Ok(extensions) => extensions,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed reading memory extensions root {}: {err}",
|
||||
extensions_root.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
while let Ok(Some(extension_entry)) = extensions.next_entry().await {
|
||||
let extension_path = extension_entry.path();
|
||||
let Ok(file_type) = extension_entry.file_type().await else {
|
||||
continue;
|
||||
};
|
||||
if !file_type.is_dir()
|
||||
|| !tokio::fs::try_exists(extension_path.join("instructions.md"))
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let resources_path = extension_path.join("resources");
|
||||
let mut resources = match tokio::fs::read_dir(&resources_path).await {
|
||||
Ok(resources) => resources,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed reading memory extension resources {}: {err}",
|
||||
resources_path.display()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
while let Ok(Some(resource_entry)) = resources.next_entry().await {
|
||||
let resource_file_path = resource_entry.path();
|
||||
let Ok(file_type) = resource_entry.file_type().await else {
|
||||
continue;
|
||||
};
|
||||
if !file_type.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Some(file_name) = resource_file_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !file_name.ends_with(".md") {
|
||||
continue;
|
||||
}
|
||||
let Some(resource_timestamp) = resource_timestamp(file_name) else {
|
||||
continue;
|
||||
};
|
||||
if resource_timestamp > cutoff {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(err) = tokio::fs::remove_file(&resource_file_path).await
|
||||
&& err.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(
|
||||
"failed pruning old memory extension resource {}: {err}",
|
||||
resource_file_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resource_timestamp(file_name: &str) -> Option<DateTime<Utc>> {
|
||||
let timestamp = file_name.get(..19)?;
|
||||
let naive =
|
||||
NaiveDateTime::parse_from_str(timestamp, crate::extension_resources::FILENAME_TS_FORMAT)
|
||||
.ok()?;
|
||||
Some(DateTime::from_naive_utc_and_offset(naive, Utc))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "prune_tests.rs"]
|
||||
mod tests;
|
||||
85
akode-rs/memories/write/src/extensions/prune_tests.rs
Normal file
85
akode-rs/memories/write/src/extensions/prune_tests.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use super::*;
|
||||
use crate::memory_extensions_root;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn prunes_only_old_resources_from_extensions_with_instructions() {
|
||||
let codex_home = TempDir::new().expect("create temp codex home");
|
||||
let memory_root = codex_home.path().join("memories");
|
||||
let extensions_root = memory_extensions_root(&memory_root);
|
||||
let chronicle_resources = extensions_root.join("chronicle/resources");
|
||||
tokio::fs::create_dir_all(&chronicle_resources)
|
||||
.await
|
||||
.expect("create chronicle resources");
|
||||
tokio::fs::write(
|
||||
extensions_root.join("chronicle/instructions.md"),
|
||||
"instructions",
|
||||
)
|
||||
.await
|
||||
.expect("write chronicle instructions");
|
||||
|
||||
let now = DateTime::from_naive_utc_and_offset(
|
||||
NaiveDateTime::parse_from_str(
|
||||
"2026-04-14T12-00-00",
|
||||
crate::extension_resources::FILENAME_TS_FORMAT,
|
||||
)
|
||||
.expect("parse now"),
|
||||
Utc,
|
||||
);
|
||||
let old_file = chronicle_resources.join("2026-03-30T11-59-59-abcd-10min-old.md");
|
||||
let exact_cutoff_file = chronicle_resources.join("2026-03-31T12-00-00-abcd-10min-cutoff.md");
|
||||
let recent_file = chronicle_resources.join("2026-04-01T12-00-00-abcd-10min-recent.md");
|
||||
let invalid_file = chronicle_resources.join("not-a-timestamp.md");
|
||||
for file in [&old_file, &exact_cutoff_file, &recent_file, &invalid_file] {
|
||||
tokio::fs::write(file, "resource")
|
||||
.await
|
||||
.expect("write chronicle resource");
|
||||
}
|
||||
|
||||
let ignored_resources = extensions_root.join("ignored/resources");
|
||||
tokio::fs::create_dir_all(&ignored_resources)
|
||||
.await
|
||||
.expect("create ignored resources");
|
||||
let ignored_old_file = ignored_resources.join("2026-03-30T11-59-59-abcd-10min-old.md");
|
||||
tokio::fs::write(&ignored_old_file, "ignored")
|
||||
.await
|
||||
.expect("write ignored resource");
|
||||
|
||||
prune_old_extension_resources_with_now(&memory_root, now).await;
|
||||
|
||||
assert!(
|
||||
!tokio::fs::try_exists(&old_file)
|
||||
.await
|
||||
.expect("check old file")
|
||||
);
|
||||
assert!(
|
||||
!tokio::fs::try_exists(&exact_cutoff_file)
|
||||
.await
|
||||
.expect("check cutoff file")
|
||||
);
|
||||
assert!(
|
||||
tokio::fs::try_exists(&recent_file)
|
||||
.await
|
||||
.expect("check recent file")
|
||||
);
|
||||
assert!(
|
||||
tokio::fs::try_exists(&invalid_file)
|
||||
.await
|
||||
.expect("check invalid file")
|
||||
);
|
||||
assert!(
|
||||
tokio::fs::try_exists(&ignored_old_file)
|
||||
.await
|
||||
.expect("check ignored file")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_timestamp_prefix_from_resource_file_name() {
|
||||
let parsed = resource_timestamp("2026-04-06T11-59-59-abcd-10min-old.md")
|
||||
.expect("timestamp should parse");
|
||||
|
||||
assert_eq!(parsed.timestamp(), 1_775_476_799);
|
||||
assert!(resource_timestamp("not-a-timestamp.md").is_none());
|
||||
}
|
||||
146
akode-rs/memories/write/src/lib.rs
Normal file
146
akode-rs/memories/write/src/lib.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
//! Write-path implementation for Codex memories.
|
||||
//!
|
||||
//! This crate owns the startup memory pipeline, file-backed memory artifact
|
||||
//! helpers, Phase 1 and Phase 2 prompt rendering, extension pruning, and
|
||||
//! workspace diffing.
|
||||
|
||||
mod control;
|
||||
mod extensions;
|
||||
mod metrics;
|
||||
mod phase1;
|
||||
mod phase1_output;
|
||||
mod phase2;
|
||||
mod prompts;
|
||||
mod rollout_input;
|
||||
mod runtime;
|
||||
mod start;
|
||||
mod storage;
|
||||
pub mod workspace;
|
||||
mod workspace_lock;
|
||||
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use control::clear_memory_roots_contents;
|
||||
pub use extensions::prune_old_extension_resources;
|
||||
pub use prompts::build_consolidation_prompt;
|
||||
pub use prompts::build_stage_one_input_message;
|
||||
pub use start::start_memories_startup_task;
|
||||
pub use storage::rebuild_raw_memories_file_from_memories;
|
||||
pub use storage::rollout_summary_file_stem;
|
||||
pub use storage::sync_rollout_summaries_from_memories;
|
||||
pub use workspace_lock::MemoryWorkspaceLock;
|
||||
|
||||
#[cfg(test)]
|
||||
mod startup_tests;
|
||||
|
||||
mod artifacts {
|
||||
pub(super) const EXTENSIONS_SUBDIR: &str = "extensions";
|
||||
pub(super) const ROLLOUT_SUMMARIES_SUBDIR: &str = "rollout_summaries";
|
||||
pub(super) const RAW_MEMORIES_FILENAME: &str = "raw_memories.md";
|
||||
}
|
||||
|
||||
mod extension_resources {
|
||||
pub(super) const FILENAME_TS_FORMAT: &str = "%Y-%m-%dT%H-%M-%S";
|
||||
pub(super) const RETENTION_DAYS: i64 = 14;
|
||||
}
|
||||
|
||||
mod prompt_blocks {
|
||||
pub(super) const EXTENSIONS_FOLDER_STRUCTURE: &str = r#"
|
||||
Memory extensions (under {{ memory_extensions_root }}/):
|
||||
|
||||
- <extension_name>/instructions.md
|
||||
- Source-specific guidance for interpreting additional memory signals. If an
|
||||
extension folder exists, you must read its instructions.md to determine how to use this memory
|
||||
source.
|
||||
|
||||
If the user has any memory extensions, you MUST read the instructions for each extension to
|
||||
determine how to use the memory source. If the workspace diff shows deleted extension resource files,
|
||||
remove stale memories derived only from those resources. If it has no extension folders, continue
|
||||
with the standard memory inputs only.
|
||||
"#;
|
||||
|
||||
pub(super) const EXTENSIONS_PRIMARY_INPUTS: &str = r#"
|
||||
Optional source-specific inputs:
|
||||
Under `{{ memory_extensions_root }}/`:
|
||||
|
||||
- `<extension_name>/instructions.md`
|
||||
- If extension folders exist, read each instructions.md first and follow it when interpreting
|
||||
that extension's memory source.
|
||||
|
||||
If the workspace diff shows deleted memory extension resources, use that extension-specific deletion
|
||||
signal to remove stale memories derived only from those resources.
|
||||
"#;
|
||||
}
|
||||
|
||||
mod stage_one {
|
||||
pub(super) const REASONING_EFFORT: akode_protocol::openai_models::ReasoningEffort =
|
||||
akode_protocol::openai_models::ReasoningEffort::Low;
|
||||
pub(super) const CONCURRENCY_LIMIT: usize = 8;
|
||||
pub(super) const JOB_LEASE_SECONDS: i64 = 3_600;
|
||||
pub(super) const JOB_RETRY_DELAY_SECONDS: i64 = 3_600;
|
||||
pub(super) const THREAD_SCAN_LIMIT: usize = 5_000;
|
||||
pub(super) const PRUNE_BATCH_SIZE: usize = 200;
|
||||
|
||||
/// Prompt used for phase 1 extraction.
|
||||
pub(super) const PROMPT: &str = include_str!("../templates/memories/stage_one_system.md");
|
||||
|
||||
/// Fallback stage-1 rollout truncation limit (tokens) when model metadata
|
||||
/// does not include a valid context window.
|
||||
pub(super) const DEFAULT_ROLLOUT_TOKEN_LIMIT: usize = 150_000;
|
||||
|
||||
/// Portion of the model effective input window reserved for the stage-1
|
||||
/// rollout input.
|
||||
///
|
||||
/// Keeping this below 100% leaves room for system instructions, prompt framing,
|
||||
/// and model output.
|
||||
pub(super) const CONTEXT_WINDOW_PERCENT: i64 = 70;
|
||||
}
|
||||
|
||||
mod stage_two {
|
||||
pub(super) const REASONING_EFFORT: akode_protocol::openai_models::ReasoningEffort =
|
||||
akode_protocol::openai_models::ReasoningEffort::Medium;
|
||||
pub(super) const JOB_LEASE_SECONDS: i64 = 3_600;
|
||||
pub(super) const JOB_RETRY_DELAY_SECONDS: i64 = 3_600;
|
||||
pub(super) const JOB_HEARTBEAT_SECONDS: u64 = 90;
|
||||
}
|
||||
|
||||
mod workspace_diff {
|
||||
/// Generated diff file the Phase 2 consolidation agent reads before editing memories.
|
||||
pub(super) const FILENAME: &str = "phase2_workspace_diff.md";
|
||||
pub(super) const MAX_BYTES: usize = 4 * 1024 * 1024;
|
||||
}
|
||||
|
||||
pub fn memory_root(codex_home: &AbsolutePathBuf) -> AbsolutePathBuf {
|
||||
codex_home.join("memories")
|
||||
}
|
||||
|
||||
pub fn rollout_summaries_dir(root: &Path) -> PathBuf {
|
||||
root.join(artifacts::ROLLOUT_SUMMARIES_SUBDIR)
|
||||
}
|
||||
|
||||
pub fn memory_extensions_root(root: &Path) -> PathBuf {
|
||||
root.join(artifacts::EXTENSIONS_SUBDIR)
|
||||
}
|
||||
|
||||
pub fn raw_memories_file(root: &Path) -> PathBuf {
|
||||
root.join(artifacts::RAW_MEMORIES_FILENAME)
|
||||
}
|
||||
|
||||
pub async fn ensure_layout(root: &Path) -> std::io::Result<()> {
|
||||
tokio::fs::create_dir_all(root).await?;
|
||||
if tokio::fs::symlink_metadata(root)
|
||||
.await?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("memory root cannot be a symbolic link: {}", root.display()),
|
||||
));
|
||||
}
|
||||
|
||||
workspace::remove_memory_symlinks(root).await?;
|
||||
tokio::fs::create_dir_all(rollout_summaries_dir(root)).await
|
||||
}
|
||||
11
akode-rs/memories/write/src/metrics.rs
Normal file
11
akode-rs/memories/write/src/metrics.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
pub(crate) const MEMORY_STORAGE_BYTES: &str = "codex.memory.storage_bytes";
|
||||
|
||||
pub(crate) const MEMORY_PHASE_ONE_JOBS: &str = "codex.memory.phase1";
|
||||
pub(crate) const MEMORY_PHASE_ONE_E2E_MS: &str = "codex.memory.phase1.e2e_ms";
|
||||
pub(crate) const MEMORY_PHASE_ONE_OUTPUT: &str = "codex.memory.phase1.output";
|
||||
pub(crate) const MEMORY_PHASE_ONE_TOKEN_USAGE: &str = "codex.memory.phase1.token_usage";
|
||||
|
||||
pub(crate) const MEMORY_PHASE_TWO_JOBS: &str = "codex.memory.phase2";
|
||||
pub(crate) const MEMORY_PHASE_TWO_E2E_MS: &str = "codex.memory.phase2.e2e_ms";
|
||||
pub(crate) const MEMORY_PHASE_TWO_INPUT: &str = "codex.memory.phase2.input";
|
||||
pub(crate) const MEMORY_PHASE_TWO_TOKEN_USAGE: &str = "codex.memory.phase2.token_usage";
|
||||
812
akode-rs/memories/write/src/phase1.rs
Normal file
812
akode-rs/memories/write/src/phase1.rs
Normal file
@@ -0,0 +1,812 @@
|
||||
use crate::build_stage_one_input_message;
|
||||
use crate::metrics::MEMORY_PHASE_ONE_E2E_MS;
|
||||
use crate::metrics::MEMORY_PHASE_ONE_JOBS;
|
||||
use crate::metrics::MEMORY_PHASE_ONE_OUTPUT;
|
||||
use crate::metrics::MEMORY_PHASE_ONE_TOKEN_USAGE;
|
||||
use crate::phase1_output::StageOneOutput;
|
||||
use crate::phase1_output::output_schema;
|
||||
use crate::rollout_input::sanitize_response_item_for_memories;
|
||||
use crate::runtime::MemoryStartupContext;
|
||||
use crate::runtime::StageOneRequestContext;
|
||||
use akode_config::types::MemoriesConfig;
|
||||
use akode_core::Prompt;
|
||||
use akode_core::config::Config;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_protocol::error::CodexErr;
|
||||
use akode_protocol::models::BaseInstructions;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_rollout::INTERACTIVE_SESSION_SOURCES;
|
||||
use akode_rollout::RolloutItem;
|
||||
use akode_secrets::redact_secrets;
|
||||
use futures::StreamExt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
struct JobResult {
|
||||
outcome: JobOutcome,
|
||||
token_usage: Option<TokenUsage>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum JobOutcome {
|
||||
SucceededWithOutput,
|
||||
SucceededNoOutput,
|
||||
Failed,
|
||||
}
|
||||
|
||||
struct Stats {
|
||||
claimed: usize,
|
||||
succeeded_with_output: usize,
|
||||
succeeded_no_output: usize,
|
||||
failed: usize,
|
||||
total_token_usage: Option<TokenUsage>,
|
||||
}
|
||||
|
||||
/// Runs memory phase 1 in strict step order:
|
||||
/// 1) claim eligible rollout jobs
|
||||
/// 2) build one stage-1 request context
|
||||
/// 3) run stage-1 extraction jobs in parallel
|
||||
/// 4) emit metrics and logs
|
||||
pub async fn run(context: Arc<MemoryStartupContext>, config: Arc<Config>) {
|
||||
let stage_one_context = build_request_context(context.as_ref(), config.as_ref()).await;
|
||||
let _phase_one_e2e_timer = stage_one_context.start_timer(MEMORY_PHASE_ONE_E2E_MS);
|
||||
|
||||
// 1. Claim startup job.
|
||||
let Some(claimed_candidates) = claim_startup_jobs(context.as_ref(), &config.memories).await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if claimed_candidates.is_empty() {
|
||||
stage_one_context.counter(
|
||||
MEMORY_PHASE_ONE_JOBS,
|
||||
/*inc*/ 1,
|
||||
&[("status", "skipped_no_candidates")],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Run the parallel sampling.
|
||||
let outcomes = run_jobs(
|
||||
context,
|
||||
config,
|
||||
claimed_candidates,
|
||||
stage_one_context.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// 4. Metrics and logs.
|
||||
let counts = aggregate_stats(outcomes);
|
||||
emit_metrics(&stage_one_context, &counts);
|
||||
info!(
|
||||
"memory stage-1 extraction complete: {} job(s) claimed, {} succeeded ({} with output, {} no output), {} failed",
|
||||
counts.claimed,
|
||||
counts.succeeded_with_output + counts.succeeded_no_output,
|
||||
counts.succeeded_with_output,
|
||||
counts.succeeded_no_output,
|
||||
counts.failed
|
||||
);
|
||||
}
|
||||
|
||||
/// Prune old un-used "dead" raw memories.
|
||||
pub async fn prune(context: &MemoryStartupContext, config: &Config) {
|
||||
if let Some(db) = context.memory_store().await {
|
||||
let max_unused_days = config.memories.max_unused_days;
|
||||
match db
|
||||
.prune_stage1_outputs_for_retention(max_unused_days, crate::stage_one::PRUNE_BATCH_SIZE)
|
||||
.await
|
||||
{
|
||||
Ok(pruned) => {
|
||||
if pruned > 0 {
|
||||
info!(
|
||||
"memory startup pruned {pruned} stale stage-1 output row(s) older than {max_unused_days} days"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"memories db prune_stage1_outputs_for_retention failed during memories startup: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn claim_startup_jobs(
|
||||
context: &MemoryStartupContext,
|
||||
memories_config: &MemoriesConfig,
|
||||
) -> Option<Vec<akode_state::Stage1JobClaim>> {
|
||||
let Some(state_db) = context.memory_store().await else {
|
||||
// This should not happen.
|
||||
warn!("state db unavailable while claiming phase-1 startup jobs; skipping");
|
||||
return None;
|
||||
};
|
||||
|
||||
let allowed_sources = INTERACTIVE_SESSION_SOURCES
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
match state_db
|
||||
.claim_stage1_jobs_for_startup(
|
||||
context.thread_id(),
|
||||
akode_state::Stage1StartupClaimParams {
|
||||
scan_limit: crate::stage_one::THREAD_SCAN_LIMIT,
|
||||
max_claimed: memories_config.max_rollouts_per_startup,
|
||||
max_age_days: memories_config.max_rollout_age_days,
|
||||
min_rollout_idle_hours: memories_config.min_rollout_idle_hours,
|
||||
allowed_sources: allowed_sources.as_slice(),
|
||||
lease_seconds: crate::stage_one::JOB_LEASE_SECONDS,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(claims) => Some(claims),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"memories db claim_stage1_jobs_for_startup failed during memories startup: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_request_context(
|
||||
context: &MemoryStartupContext,
|
||||
config: &Config,
|
||||
) -> StageOneRequestContext {
|
||||
let model_name = match config.memories.extract_model.clone() {
|
||||
Some(model) => model,
|
||||
None => {
|
||||
let preferred = context.provider().memory_extraction_preferred_model();
|
||||
context.auxiliary_model(config, preferred).await
|
||||
}
|
||||
};
|
||||
context
|
||||
.stage_one_request_context(config, &model_name, crate::stage_one::REASONING_EFFORT)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_jobs(
|
||||
context: Arc<MemoryStartupContext>,
|
||||
config: Arc<Config>,
|
||||
claimed_candidates: Vec<akode_state::Stage1JobClaim>,
|
||||
stage_one_context: StageOneRequestContext,
|
||||
) -> Vec<JobResult> {
|
||||
futures::stream::iter(claimed_candidates)
|
||||
.map(|claim| {
|
||||
let context = Arc::clone(&context);
|
||||
let config = Arc::clone(&config);
|
||||
let stage_one_context = stage_one_context.clone();
|
||||
async move {
|
||||
job::run(context.as_ref(), config.as_ref(), claim, &stage_one_context).await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(crate::stage_one::CONCURRENCY_LIMIT)
|
||||
.collect::<Vec<_>>()
|
||||
.await
|
||||
}
|
||||
|
||||
mod job {
|
||||
use super::*;
|
||||
|
||||
pub(crate) async fn run(
|
||||
context: &MemoryStartupContext,
|
||||
config: &Config,
|
||||
claim: akode_state::Stage1JobClaim,
|
||||
stage_one_context: &StageOneRequestContext,
|
||||
) -> JobResult {
|
||||
let claimed_thread = claim.thread;
|
||||
let (stage_one_output, token_usage) = match sample(
|
||||
context,
|
||||
config,
|
||||
&claimed_thread.rollout_path,
|
||||
&claimed_thread.cwd,
|
||||
claimed_thread.git_branch.as_deref(),
|
||||
stage_one_context,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(reason) => {
|
||||
result::failed(
|
||||
context,
|
||||
claimed_thread.id,
|
||||
&claim.ownership_token,
|
||||
&reason.to_string(),
|
||||
)
|
||||
.await;
|
||||
return JobResult {
|
||||
outcome: JobOutcome::Failed,
|
||||
token_usage: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
if stage_one_output
|
||||
.raw_memory
|
||||
.as_ref()
|
||||
.is_some_and(String::is_empty)
|
||||
|| stage_one_output.rollout_summary.is_empty()
|
||||
{
|
||||
return JobResult {
|
||||
outcome: result::no_output(context, claimed_thread.id, &claim.ownership_token)
|
||||
.await,
|
||||
token_usage,
|
||||
};
|
||||
}
|
||||
|
||||
JobResult {
|
||||
outcome: result::success(
|
||||
context,
|
||||
claimed_thread.id,
|
||||
&claim.ownership_token,
|
||||
claimed_thread.updated_at.timestamp(),
|
||||
stage_one_output.raw_memory.as_deref().unwrap_or_default(),
|
||||
&stage_one_output.rollout_summary,
|
||||
stage_one_output.rollout_slug.as_deref(),
|
||||
)
|
||||
.await,
|
||||
token_usage,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the rollout and perform the actual sampling.
|
||||
async fn sample(
|
||||
context: &MemoryStartupContext,
|
||||
config: &Config,
|
||||
rollout_path: &Path,
|
||||
rollout_cwd: &Path,
|
||||
rollout_git_branch: Option<&str>,
|
||||
stage_one_context: &StageOneRequestContext,
|
||||
) -> anyhow::Result<(StageOneOutput, Option<TokenUsage>)> {
|
||||
let rollout_items = crate::rollout_input::read_recent_rollout_items(rollout_path).await?;
|
||||
let rollout_contents = match config.memories.version {
|
||||
MemoryVersion::V1 => serialize_filtered_rollout_response_items(&rollout_items)?,
|
||||
MemoryVersion::V2 => crate::rollout_input::serialize_tiered_input(
|
||||
&rollout_items,
|
||||
crate::prompts::rollout_token_limit(&stage_one_context.model_info),
|
||||
)?,
|
||||
};
|
||||
|
||||
let input_text = match config.memories.version {
|
||||
MemoryVersion::V1 => build_stage_one_input_message(
|
||||
&stage_one_context.model_info,
|
||||
rollout_path,
|
||||
rollout_cwd,
|
||||
&rollout_contents,
|
||||
)?,
|
||||
MemoryVersion::V2 => crate::prompts::build_stage_one_input_v2(
|
||||
rollout_path,
|
||||
rollout_cwd,
|
||||
rollout_git_branch,
|
||||
&rollout_contents,
|
||||
)?,
|
||||
};
|
||||
|
||||
let mut prompt = Prompt::default();
|
||||
prompt.input = match config.memories.version {
|
||||
MemoryVersion::V1 => vec![ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: Some(context.item_id_generator()("msg")),
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText { text: input_text }],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
MemoryVersion::V2 => crate::rollout_input::extraction_messages(&input_text),
|
||||
};
|
||||
prompt.base_instructions = BaseInstructions {
|
||||
text: match config.memories.version {
|
||||
MemoryVersion::V1 => crate::stage_one::PROMPT,
|
||||
MemoryVersion::V2 => include_str!("../templates/memories/stage_one_system_v2.md"),
|
||||
}
|
||||
.to_string(),
|
||||
provenance: None,
|
||||
};
|
||||
prompt.output_schema = Some(output_schema(config.memories.version));
|
||||
prompt.output_schema_strict = true;
|
||||
|
||||
let (result, token_usage) = context
|
||||
.stream_stage_one_prompt(config, &prompt, stage_one_context)
|
||||
.await?;
|
||||
|
||||
let output = StageOneOutput::parse(&result, config.memories.version)?;
|
||||
|
||||
Ok((output, token_usage))
|
||||
}
|
||||
|
||||
mod result {
|
||||
use super::*;
|
||||
|
||||
pub(crate) async fn failed(
|
||||
context: &MemoryStartupContext,
|
||||
thread_id: akode_protocol::ThreadId,
|
||||
ownership_token: &str,
|
||||
reason: &str,
|
||||
) {
|
||||
tracing::warn!("Phase 1 job failed for thread {thread_id}: {reason}");
|
||||
if let Some(state_db) = context.memory_store().await {
|
||||
let _ = state_db
|
||||
.mark_stage1_job_failed(
|
||||
thread_id,
|
||||
ownership_token,
|
||||
reason,
|
||||
crate::stage_one::JOB_RETRY_DELAY_SECONDS,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn no_output(
|
||||
context: &MemoryStartupContext,
|
||||
thread_id: akode_protocol::ThreadId,
|
||||
ownership_token: &str,
|
||||
) -> JobOutcome {
|
||||
let Some(state_db) = context.memory_store().await else {
|
||||
return JobOutcome::Failed;
|
||||
};
|
||||
|
||||
if state_db
|
||||
.mark_stage1_job_succeeded_no_output(thread_id, ownership_token)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
JobOutcome::SucceededNoOutput
|
||||
} else {
|
||||
JobOutcome::Failed
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn success(
|
||||
context: &MemoryStartupContext,
|
||||
thread_id: akode_protocol::ThreadId,
|
||||
ownership_token: &str,
|
||||
source_updated_at: i64,
|
||||
raw_memory: &str,
|
||||
rollout_summary: &str,
|
||||
rollout_slug: Option<&str>,
|
||||
) -> JobOutcome {
|
||||
let Some(state_db) = context.memory_store().await else {
|
||||
return JobOutcome::Failed;
|
||||
};
|
||||
|
||||
if state_db
|
||||
.mark_stage1_job_succeeded(
|
||||
thread_id,
|
||||
ownership_token,
|
||||
source_updated_at,
|
||||
raw_memory,
|
||||
rollout_summary,
|
||||
rollout_slug,
|
||||
)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
JobOutcome::SucceededWithOutput
|
||||
} else {
|
||||
JobOutcome::Failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes filtered stage-1 memory items for prompt inclusion.
|
||||
pub(super) fn serialize_filtered_rollout_response_items(
|
||||
items: &[RolloutItem],
|
||||
) -> akode_protocol::error::Result<String> {
|
||||
let filtered = items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
RolloutItem::ResponseItem(item) => sanitize_response_item_for_memories(&item.item),
|
||||
RolloutItem::InterAgentCommunication(communication) => {
|
||||
Some(communication.to_model_input_item())
|
||||
}
|
||||
RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::Compacted(_)
|
||||
| RolloutItem::TurnContext(_)
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::WorldState(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::EventMsg(_) => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let serialized = serde_json::to_string(&filtered).map_err(|err| {
|
||||
CodexErr::InvalidRequest(format!("failed to serialize rollout memory: {err}"))
|
||||
})?;
|
||||
Ok(redact_secrets(serialized))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::Value;
|
||||
|
||||
#[test]
|
||||
fn output_schema_requires_rollout_slug_and_keeps_it_nullable() {
|
||||
let schema = output_schema(MemoryVersion::V1);
|
||||
let properties = schema
|
||||
.get("properties")
|
||||
.and_then(Value::as_object)
|
||||
.expect("properties object");
|
||||
let required = schema
|
||||
.get("required")
|
||||
.and_then(Value::as_array)
|
||||
.expect("required array");
|
||||
|
||||
let mut required_keys = required
|
||||
.iter()
|
||||
.map(|key| key.as_str().expect("required key string"))
|
||||
.collect::<Vec<_>>();
|
||||
required_keys.sort_unstable();
|
||||
|
||||
assert!(
|
||||
properties.contains_key("rollout_slug"),
|
||||
"schema should declare rollout_slug"
|
||||
);
|
||||
|
||||
let rollout_slug_type = properties
|
||||
.get("rollout_slug")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|entry| entry.get("type"))
|
||||
.and_then(Value::as_array)
|
||||
.expect("rollout_slug type array");
|
||||
let mut rollout_slug_types = rollout_slug_type
|
||||
.iter()
|
||||
.map(|entry| entry.as_str().expect("type entry string"))
|
||||
.collect::<Vec<_>>();
|
||||
rollout_slug_types.sort_unstable();
|
||||
|
||||
assert_eq!(
|
||||
required_keys,
|
||||
vec!["raw_memory", "rollout_slug", "rollout_summary"]
|
||||
);
|
||||
assert_eq!(rollout_slug_types, vec!["null", "string"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn aggregate_stats(outcomes: Vec<JobResult>) -> Stats {
|
||||
let claimed = outcomes.len();
|
||||
let mut succeeded_with_output = 0;
|
||||
let mut succeeded_no_output = 0;
|
||||
let mut failed = 0;
|
||||
let mut total_token_usage = TokenUsage::default();
|
||||
let mut has_token_usage = false;
|
||||
|
||||
for outcome in outcomes {
|
||||
match outcome.outcome {
|
||||
JobOutcome::SucceededWithOutput => succeeded_with_output += 1,
|
||||
JobOutcome::SucceededNoOutput => succeeded_no_output += 1,
|
||||
JobOutcome::Failed => failed += 1,
|
||||
}
|
||||
|
||||
if let Some(token_usage) = outcome.token_usage {
|
||||
total_token_usage.add_assign(&token_usage);
|
||||
has_token_usage = true;
|
||||
}
|
||||
}
|
||||
|
||||
Stats {
|
||||
claimed,
|
||||
succeeded_with_output,
|
||||
succeeded_no_output,
|
||||
failed,
|
||||
total_token_usage: has_token_usage.then_some(total_token_usage),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_metrics(context: &StageOneRequestContext, counts: &Stats) {
|
||||
if counts.claimed > 0 {
|
||||
context.counter(
|
||||
MEMORY_PHASE_ONE_JOBS,
|
||||
counts.claimed as i64,
|
||||
&[("status", "claimed")],
|
||||
);
|
||||
}
|
||||
if counts.succeeded_with_output > 0 {
|
||||
context.counter(
|
||||
MEMORY_PHASE_ONE_JOBS,
|
||||
counts.succeeded_with_output as i64,
|
||||
&[("status", "succeeded")],
|
||||
);
|
||||
context.counter(
|
||||
MEMORY_PHASE_ONE_OUTPUT,
|
||||
counts.succeeded_with_output as i64,
|
||||
&[],
|
||||
);
|
||||
}
|
||||
if counts.succeeded_no_output > 0 {
|
||||
context.counter(
|
||||
MEMORY_PHASE_ONE_JOBS,
|
||||
counts.succeeded_no_output as i64,
|
||||
&[("status", "succeeded_no_output")],
|
||||
);
|
||||
}
|
||||
if counts.failed > 0 {
|
||||
context.counter(
|
||||
MEMORY_PHASE_ONE_JOBS,
|
||||
counts.failed as i64,
|
||||
&[("status", "failed")],
|
||||
);
|
||||
}
|
||||
if let Some(token_usage) = counts.total_token_usage.as_ref() {
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.total_tokens.max(0),
|
||||
&[("token_type", "total")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.input_tokens.max(0),
|
||||
&[("token_type", "input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.cached_input(),
|
||||
&[("token_type", "cached_input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.cache_write_input_tokens.max(0),
|
||||
&[("token_type", "cache_write_input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.output_tokens.max(0),
|
||||
&[("token_type", "output")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_ONE_TOKEN_USAGE,
|
||||
token_usage.reasoning_output_tokens.max(0),
|
||||
&[("token_type", "reasoning_output")],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_protocol::AgentPath;
|
||||
use akode_protocol::protocol::InterAgentCommunication;
|
||||
use akode_protocol::security_risk::SecurityRiskScore;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn serializes_memory_rollout_with_agents_removed_but_environment_kept() {
|
||||
let mixed_contextual_message = ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputText {
|
||||
text:
|
||||
"# AGENTS.md instructions for /tmp\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>"
|
||||
.to_string(),
|
||||
},
|
||||
ContentItem::InputText {
|
||||
text: "# AGENTS.md instructions\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>"
|
||||
.to_string(),
|
||||
},
|
||||
ContentItem::InputText {
|
||||
text: "<environment_context>\n<cwd>/tmp</cwd>\n</environment_context>"
|
||||
.to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
};
|
||||
let skill_message = ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text:
|
||||
"<skill>\n<name>demo</name>\n<path>skills/demo/SKILL.md</path>\nbody\n</skill>"
|
||||
.to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
};
|
||||
let subagent_message = ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "<subagent_notification>{\"agent_id\":\"a\",\"status\":\"completed\"}</subagent_notification>"
|
||||
.to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
};
|
||||
|
||||
let serialized = job::serialize_filtered_rollout_response_items(&[
|
||||
RolloutItem::ResponseItem(mixed_contextual_message.into()),
|
||||
RolloutItem::ResponseItem(skill_message.into()),
|
||||
RolloutItem::SecurityRiskScore(SecurityRiskScore {
|
||||
scores: BTreeMap::from([("action_risk".to_string(), 0.92)]),
|
||||
call_id: None,
|
||||
action: None,
|
||||
sampled_at: None,
|
||||
}),
|
||||
RolloutItem::ResponseItem(subagent_message.clone().into()),
|
||||
])
|
||||
.expect("serialize");
|
||||
let parsed: Vec<ResponseItem> = serde_json::from_str(&serialized).expect("parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
vec![
|
||||
ResponseItem::Message {
|
||||
encrypted_content: None,
|
||||
status: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "<environment_context>\n<cwd>/tmp</cwd>\n</environment_context>"
|
||||
.to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
subagent_message,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_memory_rollout_redacts_secrets_before_prompt_upload() {
|
||||
let serialized =
|
||||
job::serialize_filtered_rollout_response_items(&[RolloutItem::ResponseItem(
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("call_123".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: akode_protocol::models::FunctionCallOutputPayload {
|
||||
body: akode_protocol::models::FunctionCallOutputBody::Text(
|
||||
r#"{"token":"sk-abcdefghijklmnopqrstuvwxyz123456"}"#.to_string(),
|
||||
),
|
||||
success: Some(true),
|
||||
},
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
.into(),
|
||||
)])
|
||||
.expect("serialize");
|
||||
|
||||
assert!(!serialized.contains("sk-abcdefghijklmnopqrstuvwxyz123456"));
|
||||
assert!(serialized.contains("[REDACTED_SECRET]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_inter_agent_communications_for_memory() {
|
||||
let plaintext = InterAgentCommunication::new(
|
||||
AgentPath::root().join("worker").expect("worker path"),
|
||||
AgentPath::root(),
|
||||
Vec::new(),
|
||||
"child done".to_string(),
|
||||
/*trigger_turn*/ false,
|
||||
);
|
||||
let encrypted = InterAgentCommunication::new_encrypted(
|
||||
AgentPath::root(),
|
||||
AgentPath::root().join("worker").expect("worker path"),
|
||||
Vec::new(),
|
||||
"encrypted payload".to_string(),
|
||||
/*trigger_turn*/ true,
|
||||
);
|
||||
let expected = vec![
|
||||
plaintext.to_model_input_item(),
|
||||
encrypted.to_model_input_item(),
|
||||
];
|
||||
|
||||
let serialized = job::serialize_filtered_rollout_response_items(&[
|
||||
RolloutItem::InterAgentCommunication(plaintext),
|
||||
RolloutItem::InterAgentCommunication(encrypted),
|
||||
])
|
||||
.expect("serialize");
|
||||
let parsed: Vec<ResponseItem> = serde_json::from_str(&serialized).expect("parse");
|
||||
|
||||
assert_eq!(parsed, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_agent_message_response_items_for_memory() {
|
||||
let communication = InterAgentCommunication::new(
|
||||
AgentPath::root(),
|
||||
AgentPath::root().join("worker").expect("agent path"),
|
||||
Vec::new(),
|
||||
"delegated task".to_string(),
|
||||
/*trigger_turn*/ true,
|
||||
);
|
||||
let response_item = communication.to_model_input_item();
|
||||
|
||||
let serialized = job::serialize_filtered_rollout_response_items(&[
|
||||
RolloutItem::InterAgentCommunicationMetadata { trigger_turn: true },
|
||||
RolloutItem::ResponseItem(response_item.clone().into()),
|
||||
])
|
||||
.expect("serialize");
|
||||
let parsed: Vec<ResponseItem> = serde_json::from_str(&serialized).expect("parse");
|
||||
|
||||
assert_eq!(parsed, vec![response_item]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_outcomes_sums_token_usage_across_all_jobs() {
|
||||
let counts = aggregate_stats(vec![
|
||||
JobResult {
|
||||
outcome: JobOutcome::SucceededWithOutput,
|
||||
token_usage: Some(TokenUsage {
|
||||
input_tokens: 10,
|
||||
cached_input_tokens: 2,
|
||||
cache_write_input_tokens: 0,
|
||||
output_tokens: 3,
|
||||
reasoning_output_tokens: 1,
|
||||
total_tokens: 13,
|
||||
codex_rollout_budget_units: None,
|
||||
}),
|
||||
},
|
||||
JobResult {
|
||||
outcome: JobOutcome::SucceededNoOutput,
|
||||
token_usage: Some(TokenUsage {
|
||||
input_tokens: 7,
|
||||
cached_input_tokens: 1,
|
||||
cache_write_input_tokens: 0,
|
||||
output_tokens: 2,
|
||||
reasoning_output_tokens: 0,
|
||||
total_tokens: 9,
|
||||
codex_rollout_budget_units: None,
|
||||
}),
|
||||
},
|
||||
JobResult {
|
||||
outcome: JobOutcome::Failed,
|
||||
token_usage: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(counts.claimed, 3);
|
||||
assert_eq!(counts.succeeded_with_output, 1);
|
||||
assert_eq!(counts.succeeded_no_output, 1);
|
||||
assert_eq!(counts.failed, 1);
|
||||
assert_eq!(
|
||||
counts.total_token_usage,
|
||||
Some(TokenUsage {
|
||||
input_tokens: 17,
|
||||
cached_input_tokens: 3,
|
||||
cache_write_input_tokens: 0,
|
||||
output_tokens: 5,
|
||||
reasoning_output_tokens: 1,
|
||||
total_tokens: 22,
|
||||
codex_rollout_budget_units: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_outcomes_keeps_usage_empty_when_no_job_reports_it() {
|
||||
let counts = aggregate_stats(vec![
|
||||
JobResult {
|
||||
outcome: JobOutcome::SucceededWithOutput,
|
||||
token_usage: None,
|
||||
},
|
||||
JobResult {
|
||||
outcome: JobOutcome::Failed,
|
||||
token_usage: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(counts.claimed, 2);
|
||||
assert_eq!(counts.total_token_usage, None);
|
||||
}
|
||||
}
|
||||
83
akode-rs/memories/write/src/phase1_output.rs
Normal file
83
akode-rs/memories/write/src/phase1_output.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! Version-specific extraction contracts; v2 never decodes raw memory.
|
||||
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_secrets::redact_secrets;
|
||||
use akode_utils_output_truncation::TruncationPolicy;
|
||||
use akode_utils_output_truncation::truncate_text;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
pub(crate) struct StageOneOutput {
|
||||
pub(crate) raw_memory: Option<String>,
|
||||
pub(crate) rollout_summary: String,
|
||||
pub(crate) rollout_slug: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct LegacyOutput {
|
||||
raw_memory: String,
|
||||
rollout_summary: String,
|
||||
#[serde(default)]
|
||||
rollout_slug: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SummaryOutput {
|
||||
rollout_summary: String,
|
||||
rollout_slug: String,
|
||||
}
|
||||
|
||||
impl StageOneOutput {
|
||||
pub(crate) fn parse(source: &str, version: MemoryVersion) -> serde_json::Result<Self> {
|
||||
let (raw_memory, rollout_summary, rollout_slug) = match version {
|
||||
MemoryVersion::V1 => {
|
||||
let output: LegacyOutput = serde_json::from_str(source)?;
|
||||
(
|
||||
Some(output.raw_memory),
|
||||
output.rollout_summary,
|
||||
output.rollout_slug,
|
||||
)
|
||||
}
|
||||
MemoryVersion::V2 => {
|
||||
let output: SummaryOutput = serde_json::from_str(source)?;
|
||||
(None, output.rollout_summary, Some(output.rollout_slug))
|
||||
}
|
||||
};
|
||||
let mut rollout_summary = redact_secrets(rollout_summary);
|
||||
if version == MemoryVersion::V2 {
|
||||
rollout_summary = truncate_text(&rollout_summary, TruncationPolicy::Bytes(9_000));
|
||||
}
|
||||
Ok(Self {
|
||||
raw_memory: raw_memory.map(redact_secrets),
|
||||
rollout_summary,
|
||||
rollout_slug: rollout_slug.map(redact_secrets),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn output_schema(version: MemoryVersion) -> Value {
|
||||
match version {
|
||||
MemoryVersion::V1 => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rollout_summary": { "type": "string" },
|
||||
"rollout_slug": { "type": ["string", "null"] },
|
||||
"raw_memory": { "type": "string" }
|
||||
},
|
||||
"required": ["rollout_summary", "rollout_slug", "raw_memory"],
|
||||
"additionalProperties": false
|
||||
}),
|
||||
MemoryVersion::V2 => json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rollout_summary": { "type": "string" },
|
||||
"rollout_slug": { "type": "string" }
|
||||
},
|
||||
"required": ["rollout_summary", "rollout_slug"],
|
||||
"additionalProperties": false
|
||||
}),
|
||||
}
|
||||
}
|
||||
640
akode-rs/memories/write/src/phase2.rs
Normal file
640
akode-rs/memories/write/src/phase2.rs
Normal file
@@ -0,0 +1,640 @@
|
||||
use crate::MemoryWorkspaceLock;
|
||||
use crate::metrics::MEMORY_PHASE_TWO_E2E_MS;
|
||||
use crate::metrics::MEMORY_PHASE_TWO_INPUT;
|
||||
use crate::metrics::MEMORY_PHASE_TWO_JOBS;
|
||||
use crate::metrics::MEMORY_PHASE_TWO_TOKEN_USAGE;
|
||||
use crate::prompts::build_consolidation_prompt_for_version;
|
||||
use crate::prune_old_extension_resources;
|
||||
use crate::rebuild_raw_memories_file_from_memories;
|
||||
use crate::runtime::MemoryStartupContext;
|
||||
use crate::runtime::SpawnedConsolidationAgent;
|
||||
use crate::sync_rollout_summaries_from_memories;
|
||||
use crate::workspace::memory_workspace_diff;
|
||||
use crate::workspace::prepare_memory_workspace;
|
||||
use crate::workspace::remove_memory_symlinks;
|
||||
use crate::workspace::reset_memory_workspace_baseline;
|
||||
use crate::workspace::validate_consolidation_artifacts_for_version;
|
||||
use crate::workspace::write_workspace_diff;
|
||||
use akode_config::Constrained;
|
||||
use akode_core::config::Config;
|
||||
use akode_features::Feature;
|
||||
use akode_model_provider::ModelProvider;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use akode_protocol::protocol::AgentStatus;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
use akode_state::MemoryStore;
|
||||
use akode_state::Stage1Output;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Claim {
|
||||
token: String,
|
||||
watermark: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Counters {
|
||||
input: i64,
|
||||
}
|
||||
|
||||
/// Runs memory phase 2 (aka consolidation) in strict order. The method represents the linear
|
||||
/// flow of the consolidation phase.
|
||||
pub async fn run(
|
||||
context: Arc<MemoryStartupContext>,
|
||||
config: Arc<Config>,
|
||||
parent_permission_profile: PermissionProfile,
|
||||
) {
|
||||
let phase_two_e2e_timer = context.start_timer(MEMORY_PHASE_TWO_E2E_MS);
|
||||
|
||||
let Some(db) = context.memory_store().await else {
|
||||
// This should not happen.
|
||||
return;
|
||||
};
|
||||
let root = config
|
||||
.codex_home
|
||||
.join(config.memories.version.directory_name());
|
||||
let max_raw_memories = config.memories.max_raw_memories_for_consolidation;
|
||||
let max_unused_days = config.memories.max_unused_days;
|
||||
|
||||
let workspace_lock = match MemoryWorkspaceLock::try_acquire(&root) {
|
||||
Ok(lock) => Arc::new(lock),
|
||||
Err(err) => {
|
||||
let status = if err.kind() == std::io::ErrorKind::WouldBlock {
|
||||
"skipped_workspace_busy"
|
||||
} else {
|
||||
tracing::error!("failed locking memory workspace: {err}");
|
||||
"failed_workspace_lock"
|
||||
};
|
||||
context.counter(MEMORY_PHASE_TWO_JOBS, /*inc*/ 1, &[("status", status)]);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Claim the global Phase 2 lock before touching the memory workspace.
|
||||
let claim = match job::claim(context.as_ref(), &db).await {
|
||||
Ok(claim) => claim,
|
||||
Err(e) => {
|
||||
context.counter(MEMORY_PHASE_TWO_JOBS, /*inc*/ 1, &[("status", e)]);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Ensure the memories root has a git baseline repository.
|
||||
if let Err(err) = prepare_memory_workspace(&root).await {
|
||||
tracing::error!("failed preparing memory workspace: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_prepare_workspace").await;
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Build the locked-down config used by the consolidation agent.
|
||||
let Some(mut agent_config) = agent::get_config(
|
||||
config.as_ref(),
|
||||
parent_permission_profile,
|
||||
context.provider(),
|
||||
) else {
|
||||
// If we can't get the config, we can't consolidate.
|
||||
tracing::error!("failed to get agent config");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_sandbox_policy").await;
|
||||
return;
|
||||
};
|
||||
if config.memories.consolidation_model.is_none() {
|
||||
let preferred = context.provider().memory_consolidation_preferred_model();
|
||||
agent_config.model = Some(context.auxiliary_model(config.as_ref(), preferred).await);
|
||||
}
|
||||
|
||||
// 4. Load current DB-backed Phase 2 inputs.
|
||||
let raw_memories = match db
|
||||
.get_phase2_input_selection(max_raw_memories, max_unused_days)
|
||||
.await
|
||||
{
|
||||
Ok(raw_memories) => raw_memories,
|
||||
Err(err) => {
|
||||
tracing::error!("failed to list stage1 outputs from global: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_load_stage1_outputs").await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let raw_memory_count = raw_memories.len();
|
||||
let new_watermark = get_watermark(claim.watermark, &raw_memories);
|
||||
|
||||
// 5. Sync the current inputs into the memory workspace.
|
||||
if let Err(err) = sync_phase2_workspace_inputs(&root, &raw_memories, &config).await {
|
||||
tracing::error!("failed syncing phase2 workspace inputs: {err}");
|
||||
job::failed(
|
||||
context.as_ref(),
|
||||
&db,
|
||||
&claim,
|
||||
"failed_sync_workspace_inputs",
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
// 6. Use git to decide whether the synced workspace actually changed.
|
||||
let workspace_diff = match memory_workspace_diff(&root).await {
|
||||
Ok(diff) => diff,
|
||||
Err(err) => {
|
||||
tracing::error!("failed checking memory workspace changes: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_workspace_status").await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !workspace_diff.has_changes()
|
||||
&& validate_consolidation_artifacts_for_version(&root, config.memories.version)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
tracing::error!("Phase 2 no changes");
|
||||
// We check only after sync of the file system.
|
||||
if job::succeed(
|
||||
context.as_ref(),
|
||||
&db,
|
||||
&claim,
|
||||
new_watermark,
|
||||
&raw_memories,
|
||||
"succeeded_no_workspace_changes",
|
||||
)
|
||||
.await
|
||||
{
|
||||
drop(phase_two_e2e_timer);
|
||||
context.record_storage_size(&root).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 7. Persist the diff for the consolidation agent to inspect.
|
||||
if let Err(err) = write_workspace_diff(&root, &workspace_diff).await {
|
||||
tracing::error!("failed writing memory workspace diff file: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_workspace_diff_file").await;
|
||||
return;
|
||||
}
|
||||
|
||||
// 8. Spawn the consolidation agent.
|
||||
let prompt = agent::get_prompt(&root, config.memories.version);
|
||||
let agent = match context
|
||||
.spawn_consolidation_agent(agent_config, prompt, Arc::clone(&workspace_lock))
|
||||
.await
|
||||
{
|
||||
Ok(agent) => agent,
|
||||
Err(err) => {
|
||||
tracing::error!("failed to spawn global memory consolidation agent: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_spawn_agent").await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 9. Hand off completion handling, heartbeats, and baseline reset.
|
||||
agent::handle(
|
||||
Arc::clone(&context),
|
||||
claim,
|
||||
new_watermark,
|
||||
raw_memories.clone(),
|
||||
root,
|
||||
config.memories.version,
|
||||
agent,
|
||||
workspace_lock,
|
||||
phase_two_e2e_timer,
|
||||
);
|
||||
|
||||
// 10. Emit dispatch metrics.
|
||||
let counters = Counters {
|
||||
input: raw_memory_count as i64,
|
||||
};
|
||||
emit_metrics(context.as_ref(), counters);
|
||||
}
|
||||
|
||||
async fn sync_phase2_workspace_inputs(
|
||||
root: &Path,
|
||||
raw_memories: &[Stage1Output],
|
||||
config: &Config,
|
||||
) -> std::io::Result<()> {
|
||||
let raw_memory_count = raw_memories.len();
|
||||
sync_rollout_summaries_from_memories(root, raw_memories, raw_memory_count).await?;
|
||||
match config.memories.version {
|
||||
MemoryVersion::V1 => {
|
||||
rebuild_raw_memories_file_from_memories(root, raw_memories, raw_memory_count).await?
|
||||
}
|
||||
MemoryVersion::V2 => {}
|
||||
}
|
||||
prune_old_extension_resources(root).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod job {
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn claim(
|
||||
context: &MemoryStartupContext,
|
||||
db: &MemoryStore,
|
||||
) -> Result<Claim, &'static str> {
|
||||
let claim = db
|
||||
.try_claim_global_phase2_job(context.thread_id(), crate::stage_two::JOB_LEASE_SECONDS)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("failed to claim job: {e}");
|
||||
"failed_claim"
|
||||
})?;
|
||||
let (token, watermark) = match claim {
|
||||
akode_state::Phase2JobClaimOutcome::Claimed {
|
||||
ownership_token,
|
||||
input_watermark,
|
||||
} => {
|
||||
context.counter(
|
||||
MEMORY_PHASE_TWO_JOBS,
|
||||
/*inc*/ 1,
|
||||
&[("status", "claimed")],
|
||||
);
|
||||
(ownership_token, input_watermark)
|
||||
}
|
||||
akode_state::Phase2JobClaimOutcome::SkippedRetryUnavailable => {
|
||||
return Err("skipped_retry_unavailable");
|
||||
}
|
||||
akode_state::Phase2JobClaimOutcome::SkippedCooldown => {
|
||||
return Err("skipped_cooldown");
|
||||
}
|
||||
akode_state::Phase2JobClaimOutcome::SkippedRunning => return Err("skipped_running"),
|
||||
};
|
||||
|
||||
Ok(Claim { token, watermark })
|
||||
}
|
||||
|
||||
pub(super) async fn failed(
|
||||
context: &MemoryStartupContext,
|
||||
db: &MemoryStore,
|
||||
claim: &Claim,
|
||||
reason: &'static str,
|
||||
) {
|
||||
context.counter(MEMORY_PHASE_TWO_JOBS, /*inc*/ 1, &[("status", reason)]);
|
||||
if matches!(
|
||||
db.mark_global_phase2_job_failed(
|
||||
&claim.token,
|
||||
reason,
|
||||
crate::stage_two::JOB_RETRY_DELAY_SECONDS,
|
||||
)
|
||||
.await,
|
||||
Ok(false)
|
||||
) {
|
||||
let _ = db
|
||||
.mark_global_phase2_job_failed_if_unowned(
|
||||
&claim.token,
|
||||
reason,
|
||||
crate::stage_two::JOB_RETRY_DELAY_SECONDS,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn succeed(
|
||||
context: &MemoryStartupContext,
|
||||
db: &MemoryStore,
|
||||
claim: &Claim,
|
||||
completion_watermark: i64,
|
||||
selected_outputs: &[akode_state::Stage1Output],
|
||||
reason: &'static str,
|
||||
) -> bool {
|
||||
context.counter(MEMORY_PHASE_TWO_JOBS, /*inc*/ 1, &[("status", reason)]);
|
||||
db.mark_global_phase2_job_succeeded(&claim.token, completion_watermark, selected_outputs)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
mod agent {
|
||||
use super::*;
|
||||
use tracing::warn;
|
||||
|
||||
pub(super) fn get_config(
|
||||
config: &Config,
|
||||
parent_permission_profile: PermissionProfile,
|
||||
provider: &dyn ModelProvider,
|
||||
) -> Option<Config> {
|
||||
let root = config
|
||||
.codex_home
|
||||
.join(config.memories.version.directory_name());
|
||||
let mut agent_config = config.clone();
|
||||
|
||||
agent_config.cwd = root.clone();
|
||||
// Consolidation threads must never feed back into phase-1 memory generation.
|
||||
agent_config.ephemeral = true;
|
||||
agent_config.memories.generate_memories = false;
|
||||
agent_config.memories.use_memories = false;
|
||||
// Background memory work must not send user-facing completion notifications.
|
||||
agent_config.notify = None;
|
||||
agent_config.include_apps_instructions = false;
|
||||
agent_config.mcp_servers = Constrained::allow_only(HashMap::new());
|
||||
// Approval policy
|
||||
agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
||||
// Consolidation runs as an internal worker and must not recursively delegate.
|
||||
let _ = agent_config.features.disable(Feature::Collab);
|
||||
let _ = agent_config.features.disable(Feature::MemoryTool);
|
||||
let _ = agent_config.features.disable(Feature::Apps);
|
||||
let _ = agent_config.features.disable(Feature::Plugins);
|
||||
let _ = agent_config
|
||||
.features
|
||||
.disable(Feature::SkillMcpDependencyInstall);
|
||||
|
||||
// Preserve the parent's explicit choice to skip Codex-managed sandboxing.
|
||||
let permission_profile = match parent_permission_profile {
|
||||
PermissionProfile::Managed { .. } => {
|
||||
// The consolidation agent only needs local memory-root write access and no network.
|
||||
let permission_profile = PermissionProfile::workspace_write_with(
|
||||
std::slice::from_ref(&root),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
agent_config.workspace_roots = vec![root];
|
||||
agent_config.workspace_roots_explicit = true;
|
||||
agent_config
|
||||
.permissions
|
||||
.set_workspace_roots(agent_config.workspace_roots.clone());
|
||||
permission_profile
|
||||
}
|
||||
permission_profile => permission_profile,
|
||||
};
|
||||
agent_config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile)
|
||||
.ok()?;
|
||||
|
||||
agent_config.model = Some(
|
||||
config
|
||||
.memories
|
||||
.consolidation_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| provider.memory_consolidation_preferred_model().to_string()),
|
||||
);
|
||||
agent_config.model_reasoning_effort = Some(crate::stage_two::REASONING_EFFORT);
|
||||
agent_config.service_tier = Some(config.memories.consolidation_service_tier.clone());
|
||||
|
||||
Some(agent_config)
|
||||
}
|
||||
|
||||
pub(super) fn get_prompt(root: &Path, version: MemoryVersion) -> Vec<UserInput> {
|
||||
let prompt = build_consolidation_prompt_for_version(root, version);
|
||||
vec![UserInput::Text {
|
||||
text: prompt,
|
||||
text_elements: vec![],
|
||||
}]
|
||||
}
|
||||
|
||||
/// Handle the agent while it is running.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn handle(
|
||||
context: Arc<MemoryStartupContext>,
|
||||
claim: Claim,
|
||||
new_watermark: i64,
|
||||
selected_outputs: Vec<akode_state::Stage1Output>,
|
||||
memory_root: akode_utils_absolute_path::AbsolutePathBuf,
|
||||
version: MemoryVersion,
|
||||
agent: SpawnedConsolidationAgent,
|
||||
workspace_lock: Arc<MemoryWorkspaceLock>,
|
||||
phase_two_e2e_timer: Option<akode_otel::Timer>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let _workspace_lock = workspace_lock;
|
||||
let Some(db) = context.memory_store().await else {
|
||||
return;
|
||||
};
|
||||
let SpawnedConsolidationAgent { thread_id, thread } = agent;
|
||||
|
||||
// Loop the agent until we have the final status.
|
||||
let final_status =
|
||||
loop_agent(db.clone(), claim.token.clone(), thread_id, &thread).await;
|
||||
|
||||
let agent_completed = matches!(final_status, AgentStatus::Completed(_));
|
||||
if agent_completed
|
||||
&& let Some(token_usage) = thread
|
||||
.token_usage_info()
|
||||
.await
|
||||
.map(|info| info.total_token_usage)
|
||||
{
|
||||
emit_token_usage_metrics(context.as_ref(), &token_usage);
|
||||
}
|
||||
|
||||
if let Err(err) = context
|
||||
.shutdown_consolidation_agent(SpawnedConsolidationAgent { thread_id, thread })
|
||||
.await
|
||||
{
|
||||
warn!("failed to auto-close global memory consolidation agent {thread_id}: {err}");
|
||||
// Keep the existing lease until it expires so another worker cannot race a
|
||||
// consolidation agent whose shutdown has not completed.
|
||||
return;
|
||||
}
|
||||
|
||||
let artifacts_valid = if agent_completed {
|
||||
match validate_consolidation_artifacts_for_version(&memory_root, version).await {
|
||||
Ok(()) => true,
|
||||
Err(err) => {
|
||||
tracing::error!("memory consolidation artifacts are invalid: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_invalid_artifacts")
|
||||
.await;
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if agent_completed && artifacts_valid {
|
||||
// Do not reset the workspace baseline if we lost the lock.
|
||||
let still_owns_lock = match db
|
||||
.heartbeat_global_phase2_job(
|
||||
&claim.token,
|
||||
crate::stage_two::JOB_LEASE_SECONDS,
|
||||
)
|
||||
.await
|
||||
.inspect_err(|err| {
|
||||
tracing::error!(
|
||||
"failed confirming global memory consolidation ownership before resetting workspace baseline: {err}"
|
||||
);
|
||||
}) {
|
||||
Ok(true) => true,
|
||||
Ok(false) => {
|
||||
tracing::error!(
|
||||
"lost global memory consolidation ownership before resetting workspace baseline"
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(_) => {
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_confirm_ownership")
|
||||
.await;
|
||||
false
|
||||
}
|
||||
};
|
||||
if still_owns_lock {
|
||||
if let Err(err) = reset_memory_workspace_baseline(&memory_root).await {
|
||||
tracing::error!("failed resetting memory workspace baseline: {err}");
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_workspace_commit").await;
|
||||
} else if !job::succeed(
|
||||
context.as_ref(),
|
||||
&db,
|
||||
&claim,
|
||||
new_watermark,
|
||||
&selected_outputs,
|
||||
"succeeded",
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"failed marking global memory consolidation job succeeded after resetting workspace baseline"
|
||||
);
|
||||
} else {
|
||||
drop(phase_two_e2e_timer);
|
||||
context.record_storage_size(&memory_root).await;
|
||||
}
|
||||
}
|
||||
} else if !agent_completed {
|
||||
if let Err(err) = remove_memory_symlinks(&memory_root).await {
|
||||
tracing::error!("failed removing memory workspace symbolic links: {err}");
|
||||
}
|
||||
job::failed(context.as_ref(), &db, &claim, "failed_agent").await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn loop_agent(
|
||||
db: MemoryStore,
|
||||
token: String,
|
||||
thread_id: ThreadId,
|
||||
thread: &akode_core::CodexThread,
|
||||
) -> AgentStatus {
|
||||
let mut heartbeat_interval =
|
||||
tokio::time::interval(Duration::from_secs(crate::stage_two::JOB_HEARTBEAT_SECONDS));
|
||||
heartbeat_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut status_poll_interval = tokio::time::interval(Duration::from_secs(1));
|
||||
status_poll_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let session_termination = thread.wait_until_terminated();
|
||||
tokio::pin!(session_termination);
|
||||
|
||||
loop {
|
||||
let status = thread.agent_status().await;
|
||||
if is_final_agent_status(&status) {
|
||||
break status;
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = &mut session_termination => {
|
||||
let status = thread.agent_status().await;
|
||||
if is_final_agent_status(&status) {
|
||||
break status;
|
||||
}
|
||||
tracing::warn!(
|
||||
"memory consolidation agent {thread_id} exited before final status; last status was {status:?}"
|
||||
);
|
||||
break AgentStatus::Errored(format!(
|
||||
"memory consolidation agent exited before final status: {status:?}"
|
||||
));
|
||||
}
|
||||
_ = status_poll_interval.tick() => {
|
||||
}
|
||||
_ = heartbeat_interval.tick() => {
|
||||
match db
|
||||
.heartbeat_global_phase2_job(
|
||||
&token,
|
||||
crate::stage_two::JOB_LEASE_SECONDS,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
tracing::warn!(
|
||||
"lost global phase-2 ownership during heartbeat for memory consolidation agent {thread_id}"
|
||||
);
|
||||
break AgentStatus::Errored(
|
||||
"lost global phase-2 ownership during heartbeat".to_string(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"phase-2 heartbeat update failed for memory consolidation agent {thread_id}: {err}"
|
||||
);
|
||||
break AgentStatus::Errored(format!(
|
||||
"phase-2 heartbeat update failed: {err}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "phase2_sandbox_tests.rs"]
|
||||
mod sandbox_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "phase2_workspace_roots_tests.rs"]
|
||||
mod workspace_roots_tests;
|
||||
|
||||
pub(super) fn get_watermark(
|
||||
claimed_watermark: i64,
|
||||
latest_memories: &[akode_state::Stage1Output],
|
||||
) -> i64 {
|
||||
latest_memories
|
||||
.iter()
|
||||
.map(|memory| memory.source_updated_at.timestamp())
|
||||
.max()
|
||||
.unwrap_or(claimed_watermark)
|
||||
.max(claimed_watermark)
|
||||
}
|
||||
|
||||
fn is_final_agent_status(status: &AgentStatus) -> bool {
|
||||
!matches!(
|
||||
status,
|
||||
AgentStatus::PendingInit | AgentStatus::Running | AgentStatus::Interrupted
|
||||
)
|
||||
}
|
||||
|
||||
fn emit_metrics(context: &MemoryStartupContext, counters: Counters) {
|
||||
if counters.input > 0 {
|
||||
context.counter(MEMORY_PHASE_TWO_INPUT, counters.input, &[]);
|
||||
}
|
||||
|
||||
context.counter(
|
||||
MEMORY_PHASE_TWO_JOBS,
|
||||
/*inc*/ 1,
|
||||
&[("status", "agent_spawned")],
|
||||
);
|
||||
}
|
||||
|
||||
fn emit_token_usage_metrics(context: &MemoryStartupContext, token_usage: &TokenUsage) {
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.total_tokens.max(0),
|
||||
&[("token_type", "total")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.input_tokens.max(0),
|
||||
&[("token_type", "input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.cached_input(),
|
||||
&[("token_type", "cached_input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.cache_write_input_tokens.max(0),
|
||||
&[("token_type", "cache_write_input")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.output_tokens.max(0),
|
||||
&[("token_type", "output")],
|
||||
);
|
||||
context.histogram(
|
||||
MEMORY_PHASE_TWO_TOKEN_USAGE,
|
||||
token_usage.reasoning_output_tokens.max(0),
|
||||
&[("token_type", "reasoning_output")],
|
||||
);
|
||||
}
|
||||
111
akode-rs/memories/write/src/phase2_sandbox_tests.rs
Normal file
111
akode-rs/memories/write/src/phase2_sandbox_tests.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use super::agent;
|
||||
use akode_config::Constrained;
|
||||
use akode_core::config::Permissions;
|
||||
use akode_model_provider::create_model_provider;
|
||||
use akode_protocol::models::ManagedFileSystemPermissions;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::FileSystemPolicyProjection;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::SandboxPolicy;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn consolidation_uses_canonical_parent_enforcement() -> anyhow::Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let test = test_codex()
|
||||
.with_home(home)
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let provider = create_model_provider(
|
||||
test.config.model_provider.clone(),
|
||||
Some(test.thread_manager.auth_manager()),
|
||||
);
|
||||
|
||||
let root = crate::memory_root(&test.config.codex_home);
|
||||
let managed_worker_policy = SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: vec![root.clone()],
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: true,
|
||||
exclude_slash_tmp: true,
|
||||
};
|
||||
|
||||
for (parent_permission_profile, expected_permission_profile) in [
|
||||
(PermissionProfile::Disabled, PermissionProfile::Disabled),
|
||||
(
|
||||
PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
},
|
||||
PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
},
|
||||
),
|
||||
(
|
||||
PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
),
|
||||
(
|
||||
PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
PermissionProfile::from_legacy_sandbox_policy_for_cwd(
|
||||
&managed_worker_policy,
|
||||
root.as_path(),
|
||||
),
|
||||
),
|
||||
] {
|
||||
let agent_config =
|
||||
agent::get_config(&test.config, parent_permission_profile, provider.as_ref())
|
||||
.expect("agent config should be created");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
agent_config.permissions.permission_profile().enforcement(),
|
||||
agent_config.permissions.network_sandbox_policy(),
|
||||
agent_config.permissions.approval_policy.value(),
|
||||
),
|
||||
(
|
||||
expected_permission_profile.enforcement(),
|
||||
expected_permission_profile.network_sandbox_policy(),
|
||||
AskForApproval::Never,
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
agent_config
|
||||
.permissions
|
||||
.effective_permission_profile()
|
||||
.file_system_sandbox_policy()
|
||||
.resolve_for_enforcement(root.as_path(), FileSystemPolicyProjection::Native)?,
|
||||
expected_permission_profile
|
||||
.file_system_sandbox_policy()
|
||||
.resolve_for_enforcement(root.as_path(), FileSystemPolicyProjection::Native)?,
|
||||
);
|
||||
}
|
||||
|
||||
let mut constrained_config = test.config.clone();
|
||||
constrained_config.permissions = Permissions::from_approval_and_profile(
|
||||
Constrained::allow_only(AskForApproval::Never),
|
||||
Constrained::allow_only(PermissionProfile::read_only()),
|
||||
)?;
|
||||
assert!(
|
||||
agent::get_config(
|
||||
&constrained_config,
|
||||
PermissionProfile::workspace_write(),
|
||||
provider.as_ref(),
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
}
|
||||
84
akode-rs/memories/write/src/phase2_workspace_roots_tests.rs
Normal file
84
akode-rs/memories/write/src/phase2_workspace_roots_tests.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use super::agent;
|
||||
use crate::memory_root;
|
||||
use akode_model_provider::create_model_provider;
|
||||
use akode_protocol::permissions::PROTECTED_METADATA_PATH_NAMES;
|
||||
use akode_protocol::protocol::SandboxPolicy;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn consolidation_rebinds_workspace_roots_to_memory_root() -> anyhow::Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let extra_root = TempDir::new()?;
|
||||
let parent_extra_root = extra_root.path().to_path_buf();
|
||||
let test = test_codex()
|
||||
.with_home(home)
|
||||
.with_config(move |config| {
|
||||
config.workspace_roots.push(
|
||||
akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(parent_extra_root)
|
||||
.expect("temporary directory is absolute"),
|
||||
);
|
||||
config.workspace_roots_explicit = false;
|
||||
config
|
||||
.permissions
|
||||
.set_workspace_roots(config.workspace_roots.clone());
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let provider = create_model_provider(
|
||||
test.config.model_provider.clone(),
|
||||
Some(test.thread_manager.auth_manager()),
|
||||
);
|
||||
|
||||
let parent_permission_profile = test.config.permissions.effective_permission_profile();
|
||||
let root = memory_root(&test.config.codex_home);
|
||||
|
||||
for metadata_exists in [false, true] {
|
||||
if metadata_exists {
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
std::fs::create_dir_all(root.join(name))?;
|
||||
}
|
||||
}
|
||||
let agent_config = agent::get_config(
|
||||
&test.config,
|
||||
parent_permission_profile.clone(),
|
||||
provider.as_ref(),
|
||||
)
|
||||
.expect("agent config should be created");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
&agent_config.cwd,
|
||||
&agent_config.workspace_roots,
|
||||
agent_config.permissions.workspace_roots(),
|
||||
agent_config.workspace_roots_explicit,
|
||||
),
|
||||
(&root, &vec![root.clone()], [root.clone()].as_slice(), true),
|
||||
);
|
||||
assert_eq!(
|
||||
agent_config.legacy_sandbox_policy(),
|
||||
SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: Vec::new(),
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: true,
|
||||
exclude_slash_tmp: true,
|
||||
}
|
||||
);
|
||||
let filesystem = agent_config.permissions.file_system_sandbox_policy();
|
||||
assert!(filesystem.can_write_local_path_with_cwd(root.join("memory.md").as_path(), &root));
|
||||
for path in [test.config.cwd.as_path(), extra_root.path()] {
|
||||
assert!(!filesystem.can_write_local_path_with_cwd(path, &root));
|
||||
assert!(filesystem.can_read_local_path_with_cwd(path, &root));
|
||||
}
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
assert!(!filesystem.can_write_local_path_with_cwd(root.join(name).as_path(), &root));
|
||||
}
|
||||
}
|
||||
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
}
|
||||
175
akode-rs/memories/write/src/prompts.rs
Normal file
175
akode-rs/memories/write/src/prompts.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use crate::memory_extensions_root;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_utils_output_truncation::TruncationPolicy;
|
||||
use akode_utils_output_truncation::truncate_text;
|
||||
use akode_utils_template::Template;
|
||||
use std::path::Path;
|
||||
use std::sync::LazyLock;
|
||||
use tracing::warn;
|
||||
|
||||
static CONSOLIDATION_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/memories/consolidation.md"),
|
||||
"memories/consolidation.md",
|
||||
)
|
||||
});
|
||||
static CONSOLIDATION_V2_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/memories/consolidation_v2.md"),
|
||||
"memories/consolidation_v2.md",
|
||||
)
|
||||
});
|
||||
static STAGE_ONE_INPUT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/memories/stage_one_input.md"),
|
||||
"memories/stage_one_input.md",
|
||||
)
|
||||
});
|
||||
static STAGE_ONE_INPUT_V2_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/memories/stage_one_input_v2.md"),
|
||||
"memories/stage_one_input_v2.md",
|
||||
)
|
||||
});
|
||||
static MEMORY_EXTENSIONS_FOLDER_STRUCTURE_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
crate::prompt_blocks::EXTENSIONS_FOLDER_STRUCTURE,
|
||||
"memories/extensions_folder_structure.md",
|
||||
)
|
||||
});
|
||||
static MEMORY_EXTENSIONS_PRIMARY_INPUTS_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
crate::prompt_blocks::EXTENSIONS_PRIMARY_INPUTS,
|
||||
"memories/extensions_primary_inputs.md",
|
||||
)
|
||||
});
|
||||
|
||||
fn parse_embedded_template(source: &'static str, template_name: &str) -> Template {
|
||||
match Template::parse(source) {
|
||||
Ok(template) => template,
|
||||
Err(err) => panic!("embedded template {template_name} is invalid: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the consolidation subagent prompt for a specific memory root.
|
||||
pub fn build_consolidation_prompt(memory_root: &Path) -> String {
|
||||
build_consolidation_prompt_for_version(memory_root, MemoryVersion::V1)
|
||||
}
|
||||
|
||||
pub(crate) fn build_consolidation_prompt_for_version(
|
||||
memory_root: &Path,
|
||||
version: MemoryVersion,
|
||||
) -> String {
|
||||
let memory_extensions_root = memory_extensions_root(memory_root);
|
||||
let memory_extensions_exist = memory_extensions_root.is_dir();
|
||||
let memory_root = memory_root.display().to_string();
|
||||
let memory_extensions_root = memory_extensions_root.display().to_string();
|
||||
let phase2_workspace_diff_file = crate::workspace_diff::FILENAME.to_string();
|
||||
let memory_extensions_folder_structure = if memory_extensions_exist {
|
||||
render_memory_extensions_block(
|
||||
&MEMORY_EXTENSIONS_FOLDER_STRUCTURE_TEMPLATE,
|
||||
&memory_extensions_root,
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let memory_extensions_primary_inputs = if memory_extensions_exist {
|
||||
render_memory_extensions_block(
|
||||
&MEMORY_EXTENSIONS_PRIMARY_INPUTS_TEMPLATE,
|
||||
&memory_extensions_root,
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let template = match version {
|
||||
MemoryVersion::V1 => &CONSOLIDATION_PROMPT_TEMPLATE,
|
||||
MemoryVersion::V2 => &CONSOLIDATION_V2_TEMPLATE,
|
||||
};
|
||||
template.render([
|
||||
("memory_root", memory_root.as_str()),
|
||||
(
|
||||
"memory_extensions_folder_structure",
|
||||
memory_extensions_folder_structure.as_str(),
|
||||
),
|
||||
(
|
||||
"memory_extensions_primary_inputs",
|
||||
memory_extensions_primary_inputs.as_str(),
|
||||
),
|
||||
(
|
||||
"phase2_workspace_diff_file",
|
||||
phase2_workspace_diff_file.as_str(),
|
||||
),
|
||||
])
|
||||
.unwrap_or_else(|err| {
|
||||
warn!("failed to render memories consolidation prompt template: {err}");
|
||||
format!(
|
||||
"## Memory Phase 2 (Consolidation)\nConsolidate Codex memories in: {memory_root}\n\nRead {phase2_workspace_diff_file} first."
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn render_memory_extensions_block(template: &Template, memory_extensions_root: &str) -> String {
|
||||
template
|
||||
.render([("memory_extensions_root", memory_extensions_root)])
|
||||
.unwrap_or_else(|err| {
|
||||
warn!("failed to render memories extension prompt block: {err}");
|
||||
String::new()
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn rollout_token_limit(model_info: &ModelInfo) -> usize {
|
||||
model_info
|
||||
.resolved_context_window()
|
||||
.and_then(|limit| (limit > 0).then_some(limit))
|
||||
.map(|limit| limit.saturating_mul(model_info.effective_context_window_percent) / 100)
|
||||
.map(|limit| (limit.saturating_mul(crate::stage_one::CONTEXT_WINDOW_PERCENT) / 100).max(1))
|
||||
.and_then(|limit| usize::try_from(limit).ok())
|
||||
.unwrap_or(crate::stage_one::DEFAULT_ROLLOUT_TOKEN_LIMIT)
|
||||
}
|
||||
|
||||
/// Builds the stage-1 user message containing rollout metadata and content.
|
||||
///
|
||||
/// Large rollout payloads are truncated to 70% of the active model's effective
|
||||
/// input window token budget while keeping both head and tail context.
|
||||
pub fn build_stage_one_input_message(
|
||||
model_info: &ModelInfo,
|
||||
rollout_path: &Path,
|
||||
rollout_cwd: &Path,
|
||||
rollout_contents: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
let rollout_token_limit = rollout_token_limit(model_info);
|
||||
let truncated_rollout_contents = truncate_text(
|
||||
rollout_contents,
|
||||
TruncationPolicy::Tokens(rollout_token_limit),
|
||||
);
|
||||
|
||||
let rollout_path = rollout_path.display().to_string();
|
||||
let rollout_cwd = rollout_cwd.display().to_string();
|
||||
Ok(STAGE_ONE_INPUT_TEMPLATE.render([
|
||||
("rollout_path", rollout_path.as_str()),
|
||||
("rollout_cwd", rollout_cwd.as_str()),
|
||||
("rollout_contents", truncated_rollout_contents.as_str()),
|
||||
])?)
|
||||
}
|
||||
|
||||
pub(crate) fn build_stage_one_input_v2(
|
||||
rollout_path: &Path,
|
||||
rollout_cwd: &Path,
|
||||
rollout_git_branch: Option<&str>,
|
||||
rollout_contents: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
Ok(STAGE_ONE_INPUT_V2_TEMPLATE.render([
|
||||
("rollout_path", rollout_path.display().to_string().as_str()),
|
||||
("rollout_cwd", rollout_cwd.display().to_string().as_str()),
|
||||
(
|
||||
"rollout_git_branch",
|
||||
rollout_git_branch.unwrap_or("unknown"),
|
||||
),
|
||||
("rollout_contents", rollout_contents),
|
||||
])?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "prompts_tests.rs"]
|
||||
mod tests;
|
||||
71
akode-rs/memories/write/src/prompts_tests.rs
Normal file
71
akode-rs/memories/write/src/prompts_tests.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use super::*;
|
||||
use akode_models_manager::model_info::model_info_from_slug;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn build_stage_one_input_message_truncates_rollout_using_model_context_window() {
|
||||
let input = format!("{}{}{}", "a".repeat(700_000), "middle", "z".repeat(700_000));
|
||||
let mut model_info = model_info_from_slug("gpt-5.3-codex");
|
||||
model_info.context_window = Some(123_000);
|
||||
let expected_rollout_token_limit = usize::try_from(
|
||||
((123_000_i64 * model_info.effective_context_window_percent) / 100)
|
||||
* crate::stage_one::CONTEXT_WINDOW_PERCENT
|
||||
/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let expected_truncated = truncate_text(
|
||||
&input,
|
||||
TruncationPolicy::Tokens(expected_rollout_token_limit),
|
||||
);
|
||||
let message = build_stage_one_input_message(
|
||||
&model_info,
|
||||
Path::new("/tmp/rollout.jsonl"),
|
||||
Path::new("/tmp"),
|
||||
&input,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(expected_truncated.contains("tokens truncated"));
|
||||
assert!(expected_truncated.starts_with('a'));
|
||||
assert!(expected_truncated.ends_with('z'));
|
||||
assert!(message.contains(&expected_truncated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_stage_one_input_message_uses_default_limit_when_model_context_window_missing() {
|
||||
let input = format!("{}{}{}", "a".repeat(700_000), "middle", "z".repeat(700_000));
|
||||
let mut model_info = model_info_from_slug("gpt-5.3-codex");
|
||||
model_info.context_window = None;
|
||||
model_info.max_context_window = None;
|
||||
let expected_truncated = truncate_text(
|
||||
&input,
|
||||
TruncationPolicy::Tokens(crate::stage_one::DEFAULT_ROLLOUT_TOKEN_LIMIT),
|
||||
);
|
||||
let message = build_stage_one_input_message(
|
||||
&model_info,
|
||||
Path::new("/tmp/rollout.jsonl"),
|
||||
Path::new("/tmp"),
|
||||
&input,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(message.contains(&expected_truncated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_consolidation_prompt_points_to_workspace_diff_and_extension_tree() {
|
||||
let temp = tempdir().unwrap();
|
||||
let memory_root = temp.path().join("memories");
|
||||
let memory_extensions_root = memory_root.join("extensions");
|
||||
std::fs::create_dir_all(&memory_extensions_root).unwrap();
|
||||
|
||||
let prompt = build_consolidation_prompt(&memory_root);
|
||||
|
||||
assert!(prompt.contains("Memory workspace diff:"));
|
||||
assert!(prompt.contains("phase2_workspace_diff.md"));
|
||||
assert!(prompt.contains(&format!(
|
||||
"Memory extensions (under {}/):",
|
||||
memory_extensions_root.display()
|
||||
)));
|
||||
assert!(prompt.contains("workspace diff shows deleted extension resource files"));
|
||||
}
|
||||
376
akode-rs/memories/write/src/rollout_input.rs
Normal file
376
akode-rs/memories/write/src/rollout_input.rs
Normal file
@@ -0,0 +1,376 @@
|
||||
//! Reads recent rollout evidence and selects v2 input by provenance in chronological order.
|
||||
//! Human replies retain their questions; message media is replaced with placeholders.
|
||||
//! Budgets use the same token estimate as the rest of the memory pipeline.
|
||||
//! Extraction chunks preserve selected evidence in order within bounded messages.
|
||||
|
||||
use akode_core::context::ContextualUserFragment;
|
||||
use akode_core::context::MemoryContextFragment;
|
||||
use akode_protocol::ToolName;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::MessagePhase;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::InterAgentCommunication;
|
||||
use akode_protocol::request_user_input::RequestUserInputResponse;
|
||||
use akode_rollout::ReverseJsonlScanner;
|
||||
use akode_rollout::RolloutItem;
|
||||
use akode_rollout::ScanOutcome;
|
||||
use akode_rollout::open_rollout_seekable_reader;
|
||||
use akode_rollout::should_persist_response_item_for_memories;
|
||||
use akode_secrets::redact_secrets;
|
||||
use akode_utils_output_truncation::TruncationPolicy;
|
||||
use akode_utils_output_truncation::approx_bytes_for_tokens;
|
||||
use akode_utils_output_truncation::truncate_text;
|
||||
use std::collections::HashMap;
|
||||
use std::io::BufRead;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_ROLLOUT_BYTES: usize = 8 * 1024 * 1024;
|
||||
const MAX_RECORD_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// Keeps the newest sanitized evidence that fits the byte budget, then restores source order.
|
||||
/// Compressed rollouts use the existing temporary-file reader. Older evidence and records over
|
||||
/// the per-record limit are intentionally omitted; this is not a complete history for resume.
|
||||
/// The first line must contain valid session metadata within the same record limit.
|
||||
pub(crate) async fn read_recent_rollout_items(path: &Path) -> anyhow::Result<Vec<RolloutItem>> {
|
||||
let path = path.to_owned();
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
let task = tokio::task::spawn_blocking(move || -> anyhow::Result<Vec<RolloutItem>> {
|
||||
let mut reader = open_rollout_seekable_reader(&path, || stop.is_closed())?;
|
||||
// Validate this session's format from its header, not metadata copied into fork history.
|
||||
// Bound the header read too: session metadata may contain large instructions or schemas.
|
||||
let mut header = String::new();
|
||||
std::io::BufReader::new((&mut reader).take(MAX_RECORD_BYTES as u64))
|
||||
.read_line(&mut header)?;
|
||||
anyhow::ensure!(
|
||||
matches!(
|
||||
akode_rollout::parse_rollout_line(&header)?.item,
|
||||
RolloutItem::SessionMeta(_)
|
||||
),
|
||||
"memory extraction requires valid session metadata within the record limit"
|
||||
);
|
||||
let mut scanner = ReverseJsonlScanner::new(reader)?.with_max_record_bytes(MAX_RECORD_BYTES);
|
||||
let mut remaining = MAX_ROLLOUT_BYTES;
|
||||
let mut items = Vec::new();
|
||||
while !stop.is_closed() {
|
||||
let Some(outcome) = scanner.scan_next_rollout_line()? else {
|
||||
break;
|
||||
};
|
||||
let ScanOutcome::Parsed(mut line) = outcome else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(
|
||||
&line.item,
|
||||
RolloutItem::ResponseItem(_) | RolloutItem::InterAgentCommunication(_)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if let RolloutItem::ResponseItem(item) = &mut line.item {
|
||||
let Some(sanitized) = sanitize_response_item_for_memories(&item.item) else {
|
||||
continue;
|
||||
};
|
||||
item.item = sanitized;
|
||||
}
|
||||
let Some(next_remaining) = remaining.checked_sub(serde_json::to_vec(&line.item)?.len())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
remaining = next_remaining;
|
||||
items.push(line.item);
|
||||
}
|
||||
items.reverse();
|
||||
Ok(items)
|
||||
});
|
||||
let result = task.await?;
|
||||
drop(keep_running);
|
||||
result
|
||||
}
|
||||
|
||||
const OMITTED: &str = "[... response items omitted ...]\n";
|
||||
const TRUNCATION_RESERVE_BYTES: usize = 96;
|
||||
const TOOL_OUTPUT_TOKENS: usize = 2_000;
|
||||
const MAX_ROW_BYTES: usize = 10_000;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Tier {
|
||||
Human,
|
||||
Final,
|
||||
OtherAgent,
|
||||
Commentary,
|
||||
Context,
|
||||
Tool,
|
||||
}
|
||||
|
||||
/// Select newest evidence first within each tier, but render in source order.
|
||||
pub(crate) fn serialize_tiered_input(
|
||||
items: &[RolloutItem],
|
||||
token_limit: usize,
|
||||
) -> anyhow::Result<String> {
|
||||
let mut rows = Vec::new();
|
||||
let mut user_input_calls = HashMap::new();
|
||||
for item in items {
|
||||
let item = match item {
|
||||
RolloutItem::ResponseItem(item) => sanitize_response_item_for_memories(&item.item),
|
||||
RolloutItem::InterAgentCommunication(message) => Some(message.to_model_input_item()),
|
||||
RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::Compacted(_)
|
||||
| RolloutItem::TurnContext(_)
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::WorldState(_)
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::EventMsg(_) => None,
|
||||
};
|
||||
let Some(mut item) = item else { continue };
|
||||
if let ResponseItem::Message { content, .. } = &mut item {
|
||||
for part in content {
|
||||
match part {
|
||||
ContentItem::InputImage { .. } => {
|
||||
*part = ContentItem::InputText {
|
||||
text: "[image omitted]".into(),
|
||||
};
|
||||
}
|
||||
ContentItem::InputAudio { .. } => {
|
||||
*part = ContentItem::InputText {
|
||||
text: "[audio omitted]".into(),
|
||||
};
|
||||
}
|
||||
ContentItem::InputText { .. } | ContentItem::OutputText { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let question = match &item {
|
||||
ResponseItem::FunctionCall {
|
||||
name,
|
||||
namespace,
|
||||
call_id,
|
||||
arguments,
|
||||
..
|
||||
} if name == "request_user_input"
|
||||
&& ToolName::new(namespace.clone(), name).is_default_namespace() =>
|
||||
{
|
||||
user_input_calls.insert(call_id.clone(), arguments.clone());
|
||||
None
|
||||
}
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
output,
|
||||
..
|
||||
} if user_input_calls.contains_key(call_id)
|
||||
&& output
|
||||
.text_content()
|
||||
.and_then(|text| serde_json::from_str::<RequestUserInputResponse>(text).ok())
|
||||
.is_some_and(|reply| {
|
||||
reply
|
||||
.answers
|
||||
.values()
|
||||
.any(|answer| answer.answers.iter().any(|text| !text.trim().is_empty()))
|
||||
}) =>
|
||||
{
|
||||
user_input_calls.remove(call_id)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let tier = match &item {
|
||||
ResponseItem::FunctionCallOutput { .. } if question.is_some() => Tier::Human,
|
||||
ResponseItem::AgentMessage { .. } => Tier::OtherAgent,
|
||||
ResponseItem::Message {
|
||||
role,
|
||||
content,
|
||||
phase,
|
||||
internal_chat_message_metadata_passthrough,
|
||||
..
|
||||
} => {
|
||||
let agent_content = internal_chat_message_metadata_passthrough
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.content_item_kinds.as_ref())
|
||||
.is_some_and(|kinds| {
|
||||
kinds.iter().any(|kind| kind.0.starts_with("multi_agent."))
|
||||
})
|
||||
|| InterAgentCommunication::is_message_content(content)
|
||||
|| content.iter().any(|part| match part {
|
||||
ContentItem::InputText { text } | ContentItem::OutputText { text, .. } => {
|
||||
let text = text.trim_start();
|
||||
text.starts_with("<subagent_notification>")
|
||||
|| (text.starts_with("Message Type:")
|
||||
&& text
|
||||
.lines()
|
||||
.nth(1)
|
||||
.is_some_and(|line| line.starts_with("Task name:"))
|
||||
&& text
|
||||
.lines()
|
||||
.nth(2)
|
||||
.is_some_and(|line| line.starts_with("Sender:"))
|
||||
&& text.lines().nth(3) == Some("Payload:"))
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if agent_content {
|
||||
Tier::OtherAgent
|
||||
} else if role == "user" {
|
||||
let contextual = internal_chat_message_metadata_passthrough.as_ref()
|
||||
.and_then(|metadata| metadata.content_item_kinds.as_ref())
|
||||
.is_some_and(|kinds| !kinds.is_empty() && kinds.iter().all(|kind| !kind.0.starts_with("user.")))
|
||||
|| content.iter().any(|part| matches!(part, ContentItem::InputText { text }
|
||||
if matches_marked_fragment(text, "<environment_context>", "</environment_context>")));
|
||||
if contextual {
|
||||
Tier::Context
|
||||
} else {
|
||||
Tier::Human
|
||||
}
|
||||
} else if matches!(phase, Some(MessagePhase::Commentary)) {
|
||||
Tier::Commentary
|
||||
} else {
|
||||
Tier::Final
|
||||
}
|
||||
}
|
||||
_ => Tier::Tool,
|
||||
};
|
||||
let label = match tier {
|
||||
Tier::Human => "human user",
|
||||
Tier::Final => "assistant final",
|
||||
Tier::Commentary => "assistant commentary",
|
||||
Tier::OtherAgent => "other agent",
|
||||
Tier::Context => "harness context",
|
||||
Tier::Tool => "tool",
|
||||
};
|
||||
let text = serde_json::to_string(&item)?;
|
||||
let mut text = redact_secrets(match question {
|
||||
Some(question) => format!("Assistant question: {question}\nHuman reply: {text}"),
|
||||
None => text,
|
||||
});
|
||||
if tier == Tier::Tool
|
||||
&& matches!(
|
||||
item,
|
||||
ResponseItem::FunctionCallOutput { .. }
|
||||
| ResponseItem::CustomToolCallOutput { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
)
|
||||
{
|
||||
text = truncate_text(
|
||||
&text,
|
||||
TruncationPolicy::Bytes(
|
||||
approx_bytes_for_tokens(TOOL_OUTPUT_TOKENS)
|
||||
.saturating_sub(TRUNCATION_RESERVE_BYTES),
|
||||
),
|
||||
);
|
||||
}
|
||||
text = truncate_text(
|
||||
&text,
|
||||
TruncationPolicy::Bytes(MAX_ROW_BYTES - TRUNCATION_RESERVE_BYTES),
|
||||
);
|
||||
rows.push((tier, format!("[{label}]\n{text}\n")));
|
||||
}
|
||||
let mut remaining = approx_bytes_for_tokens(token_limit).saturating_sub(OMITTED.len());
|
||||
let mut selected = vec![None; rows.len()];
|
||||
for tier in [
|
||||
Tier::Human,
|
||||
Tier::Final,
|
||||
Tier::OtherAgent,
|
||||
Tier::Commentary,
|
||||
Tier::Context,
|
||||
Tier::Tool,
|
||||
] {
|
||||
for (index, (row_tier, text)) in rows.iter().enumerate().rev() {
|
||||
if *row_tier != tier || remaining <= OMITTED.len() + TRUNCATION_RESERVE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let budget = remaining - OMITTED.len();
|
||||
let text = if text.len() <= budget {
|
||||
text.clone()
|
||||
} else {
|
||||
truncate_text(
|
||||
text,
|
||||
TruncationPolicy::Bytes(budget - TRUNCATION_RESERVE_BYTES),
|
||||
)
|
||||
};
|
||||
remaining = remaining.saturating_sub(text.len() + OMITTED.len());
|
||||
selected[index] = Some(text);
|
||||
}
|
||||
}
|
||||
let mut rendered = String::new();
|
||||
let mut gap = false;
|
||||
for row in selected {
|
||||
match row {
|
||||
Some(text) => {
|
||||
rendered.push_str(&text);
|
||||
gap = false;
|
||||
}
|
||||
None if !gap => {
|
||||
rendered.push_str(OMITTED);
|
||||
gap = true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if rendered.len() > approx_bytes_for_tokens(token_limit) {
|
||||
return Ok(String::new());
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
/// Splits already-budgeted extraction input without dropping evidence.
|
||||
pub(crate) fn extraction_messages(mut text: &str) -> Vec<ResponseItem> {
|
||||
let mut messages = Vec::new();
|
||||
while !text.is_empty() {
|
||||
let end = text.floor_char_boundary(text.len().min(8_900));
|
||||
messages.push(ContextualUserFragment::into(
|
||||
MemoryContextFragment::ExtractionEvidence(text[..end].to_string()),
|
||||
));
|
||||
text = &text[end..];
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_response_item_for_memories(item: &ResponseItem) -> Option<ResponseItem> {
|
||||
if !should_persist_response_item_for_memories(item) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut item = item.clone();
|
||||
item.clear_encrypted_content();
|
||||
if let ResponseItem::Message {
|
||||
role,
|
||||
content,
|
||||
status,
|
||||
..
|
||||
} = &mut item
|
||||
&& role == "user"
|
||||
{
|
||||
*status = None;
|
||||
content.retain(|content_item| !is_memory_excluded_contextual_user_fragment(content_item));
|
||||
if content.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
Some(item)
|
||||
}
|
||||
|
||||
fn is_memory_excluded_contextual_user_fragment(content_item: &ContentItem) -> bool {
|
||||
let ContentItem::InputText { text } = content_item else {
|
||||
return false;
|
||||
};
|
||||
|
||||
matches_marked_fragment(text, "# AGENTS.md instructions", "</INSTRUCTIONS>")
|
||||
|| matches_marked_fragment(text, "<skill>", "</skill>")
|
||||
}
|
||||
|
||||
fn matches_marked_fragment(text: &str, start_marker: &str, end_marker: &str) -> bool {
|
||||
let trimmed = text.trim_start();
|
||||
let starts_with_marker = trimmed
|
||||
.get(..start_marker.len())
|
||||
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(start_marker));
|
||||
let trimmed = trimmed.trim_end();
|
||||
let ends_with_marker = trimmed
|
||||
.get(trimmed.len().saturating_sub(end_marker.len())..)
|
||||
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(end_marker));
|
||||
starts_with_marker && ends_with_marker
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rollout_input_tests.rs"]
|
||||
mod tests;
|
||||
116
akode-rs/memories/write/src/rollout_input_tests.rs
Normal file
116
akode-rs/memories/write/src/rollout_input_tests.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Write;
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_rollout_items_bound_history_and_preserve_newest_records() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let path = home.path().join("rollout.jsonl");
|
||||
let mut file = std::fs::File::create(&path)?;
|
||||
let metadata = serde_json::json!({
|
||||
"timestamp": "2026-10-12T00:00:00Z",
|
||||
"type": "session_meta",
|
||||
"payload": akode_rollout::SessionMeta::default()
|
||||
});
|
||||
writeln!(file, "{metadata}")?;
|
||||
let old = serde_json::json!({
|
||||
"timestamp": "2026-10-12T00:00:00Z",
|
||||
"type": "response_item",
|
||||
"payload": {"type": "message", "role": "user", "content": [
|
||||
{"type": "input_text", "text": "older evidence".repeat(/*n*/ 20_000)}
|
||||
]}
|
||||
});
|
||||
let old = serde_json::to_string(&old)?;
|
||||
for _ in 0..(MAX_ROLLOUT_BYTES / old.len() + 2) {
|
||||
writeln!(file, "{old}")?;
|
||||
}
|
||||
let mut newest = Vec::new();
|
||||
for text in ["recent question", "latest correction 🦀"] {
|
||||
// Neither an oversized nor a malformed record may hide the newest valid evidence.
|
||||
writeln!(file, "{}", "x".repeat(MAX_RECORD_BYTES + 1))?;
|
||||
file.write_all(b"\xff\n")?;
|
||||
let line = serde_json::json!({
|
||||
"timestamp": "2026-10-12T00:00:00Z",
|
||||
"type": "response_item",
|
||||
"payload": {"type": "message", "role": "user", "content": [
|
||||
{"type": "input_text", "text": text}
|
||||
]}
|
||||
});
|
||||
writeln!(file, "{line}")?;
|
||||
newest.push(akode_rollout::decode_rollout_line(line)?.item);
|
||||
}
|
||||
drop(file);
|
||||
|
||||
let items = read_recent_rollout_items(&path).await?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(&items[items.len() - newest.len()..])?,
|
||||
serde_json::to_value(&newest)?
|
||||
);
|
||||
let retained_bytes = items.iter().try_fold(/*init*/ 0, |bytes, item| {
|
||||
serde_json::to_vec(item).map(|json| bytes + json.len())
|
||||
})?;
|
||||
assert!(retained_bytes <= MAX_ROLLOUT_BYTES);
|
||||
let older_item_bytes =
|
||||
serde_json::to_vec(&akode_rollout::parse_rollout_line(&old)?.item)?.len();
|
||||
assert!(retained_bytes + older_item_bytes > MAX_ROLLOUT_BYTES);
|
||||
|
||||
let mut metadata = metadata;
|
||||
metadata["payload"]["history_mode"] = serde_json::json!("future");
|
||||
std::fs::write(&path, format!("{metadata}\n{old}\n"))?;
|
||||
assert!(read_recent_rollout_items(&path).await.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_chunks_preserve_unicode_evidence_with_bounded_messages() {
|
||||
let evidence = "User correction: 🐈\n".repeat(2_000);
|
||||
let mut reconstructed = String::new();
|
||||
for message in extraction_messages(&evidence) {
|
||||
let ResponseItem::Message { role, content, .. } = message else {
|
||||
panic!("message")
|
||||
};
|
||||
assert_eq!(role, "user");
|
||||
let [ContentItem::InputText { text }] = content.as_slice() else {
|
||||
panic!("text")
|
||||
};
|
||||
assert!(text.len() < 9_000);
|
||||
reconstructed.push_str(text);
|
||||
}
|
||||
assert_eq!(reconstructed, evidence);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_memory_excluded_fragments() {
|
||||
let cases = [
|
||||
(
|
||||
"# AGENTS.md instructions for /tmp\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"<skill>\n<name>demo</name>\n<path>skills/demo/SKILL.md</path>\nbody\n</skill>",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"<environment_context>\n<cwd>/tmp</cwd>\n</environment_context>",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"<subagent_notification>{\"agent_id\":\"a\",\"status\":\"completed\"}</subagent_notification>",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
for (text, expected) in cases {
|
||||
assert_eq!(
|
||||
is_memory_excluded_contextual_user_fragment(&ContentItem::InputText {
|
||||
text: text.to_string(),
|
||||
}),
|
||||
expected,
|
||||
"{text}",
|
||||
);
|
||||
}
|
||||
}
|
||||
482
akode-rs/memories/write/src/runtime.rs
Normal file
482
akode-rs/memories/write/src/runtime.rs
Normal file
@@ -0,0 +1,482 @@
|
||||
use crate::metrics::MEMORY_STORAGE_BYTES;
|
||||
use crate::workspace::memory_storage_bytes;
|
||||
use akode_core::CodexThread;
|
||||
use akode_core::ModelClient;
|
||||
use akode_core::NewThread;
|
||||
use akode_core::Prompt;
|
||||
use akode_core::ResponseEvent;
|
||||
use akode_core::StartIfIdleSubmission;
|
||||
use akode_core::StartThreadOptions;
|
||||
use akode_core::ThreadManager;
|
||||
use akode_core::TurnInputRequest;
|
||||
use akode_core::TurnStartOptions;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::content_items_to_text;
|
||||
use akode_core::detached_memory_responses_metadata;
|
||||
use akode_core::resolve_installation_id;
|
||||
use akode_features::Feature;
|
||||
use akode_login::AuthManager;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_login::auth_env_telemetry::collect_auth_env_telemetry;
|
||||
use akode_login::default_client::originator;
|
||||
use akode_model_provider::ModelProvider;
|
||||
use akode_model_provider::ProviderAuthContext;
|
||||
use akode_model_provider::SharedModelProvider;
|
||||
use akode_otel::SessionTelemetry;
|
||||
use akode_otel::TelemetryAuthMode;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_protocol::SessionId;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::config_types::ReasoningSummary;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use akode_protocol::protocol::InternalSessionSource;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::ThreadSource;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
use akode_rollout_trace::InferenceTraceContext;
|
||||
use akode_state::MemoryStore;
|
||||
use akode_terminal_detection::user_agent;
|
||||
use futures::StreamExt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) struct SpawnedConsolidationAgent {
|
||||
pub(crate) thread_id: ThreadId,
|
||||
pub(crate) thread: Arc<CodexThread>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct StageOneRequestContext {
|
||||
version: MemoryVersion,
|
||||
pub(crate) model_info: ModelInfo,
|
||||
pub(crate) session_telemetry: SessionTelemetry,
|
||||
pub(crate) reasoning_effort: Option<ReasoningEffort>,
|
||||
pub(crate) reasoning_summary: ReasoningSummary,
|
||||
pub(crate) service_tier: Option<String>,
|
||||
}
|
||||
|
||||
impl StageOneRequestContext {
|
||||
pub(crate) fn start_timer(&self, name: &str) -> Option<akode_otel::Timer> {
|
||||
self.session_telemetry
|
||||
.start_timer(name, &memory_metric_tags(self.version, &[]))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(crate) fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
|
||||
self.session_telemetry
|
||||
.counter(name, inc, &memory_metric_tags(self.version, tags));
|
||||
}
|
||||
|
||||
pub(crate) fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
|
||||
self.session_telemetry
|
||||
.histogram(name, value, &memory_metric_tags(self.version, tags));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct MemoryStartupContext {
|
||||
version: MemoryVersion,
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
provider: SharedModelProvider,
|
||||
session_telemetry: SessionTelemetry,
|
||||
}
|
||||
|
||||
fn memory_metric_tags<'a>(
|
||||
version: MemoryVersion,
|
||||
tags: &[(&'a str, &'a str)],
|
||||
) -> Vec<(&'a str, &'a str)> {
|
||||
let mut tags = tags.to_vec();
|
||||
tags.push((
|
||||
"memory_version",
|
||||
match version {
|
||||
MemoryVersion::V1 => "v1",
|
||||
MemoryVersion::V2 => "v2",
|
||||
},
|
||||
));
|
||||
tags
|
||||
}
|
||||
|
||||
fn build_session_telemetry(
|
||||
auth_manager: &AuthManager,
|
||||
thread_id: ThreadId,
|
||||
config: &Config,
|
||||
source: SessionSource,
|
||||
model: &str,
|
||||
originator: String,
|
||||
) -> SessionTelemetry {
|
||||
let auth = auth_manager.auth_cached();
|
||||
let auth = auth.as_ref();
|
||||
let auth_mode = auth.map(CodexAuth::auth_mode).map(TelemetryAuthMode::from);
|
||||
let auth_env_telemetry = collect_auth_env_telemetry(
|
||||
&config.model_provider,
|
||||
auth_manager.codex_api_key_env_enabled(),
|
||||
);
|
||||
let mut session_telemetry = SessionTelemetry::new(
|
||||
thread_id,
|
||||
model,
|
||||
model,
|
||||
/*account_id*/ None,
|
||||
/*account_email*/ None,
|
||||
auth_mode,
|
||||
originator,
|
||||
config.otel.log_user_prompt,
|
||||
user_agent(),
|
||||
source,
|
||||
)
|
||||
.with_auth_env(auth_env_telemetry.to_otel_metadata());
|
||||
if !config.otel.log_sse_deltas {
|
||||
session_telemetry = session_telemetry.without_sse_delta_logs();
|
||||
}
|
||||
session_telemetry
|
||||
}
|
||||
|
||||
impl MemoryStartupContext {
|
||||
pub(crate) fn item_id_generator(&self) -> &akode_protocol::ItemIdGenerator {
|
||||
self.thread.item_id_generator()
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
auth: Arc<ProviderAuthContext>,
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
config: &Config,
|
||||
source: SessionSource,
|
||||
) -> Self {
|
||||
let provider = auth.model_provider(config.model_provider.clone());
|
||||
Self::new_with_provider(
|
||||
thread_manager,
|
||||
Arc::clone(&auth.credentials),
|
||||
thread_id,
|
||||
thread,
|
||||
config,
|
||||
source,
|
||||
provider,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_for_testing(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
config: &Config,
|
||||
source: SessionSource,
|
||||
provider: SharedModelProvider,
|
||||
) -> Self {
|
||||
Self::new_with_provider(
|
||||
thread_manager,
|
||||
auth_manager,
|
||||
thread_id,
|
||||
thread,
|
||||
config,
|
||||
source,
|
||||
provider,
|
||||
)
|
||||
}
|
||||
|
||||
fn new_with_provider(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
config: &Config,
|
||||
source: SessionSource,
|
||||
provider: SharedModelProvider,
|
||||
) -> Self {
|
||||
let model = config.model.as_deref().unwrap_or("unknown");
|
||||
let session_telemetry = build_session_telemetry(
|
||||
&auth_manager,
|
||||
thread_id,
|
||||
config,
|
||||
source,
|
||||
model,
|
||||
originator().value,
|
||||
);
|
||||
|
||||
Self {
|
||||
version: config.memories.version,
|
||||
thread_id,
|
||||
thread,
|
||||
thread_manager,
|
||||
auth_manager,
|
||||
provider,
|
||||
session_telemetry,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn thread_id(&self) -> ThreadId {
|
||||
self.thread_id
|
||||
}
|
||||
|
||||
pub(crate) async fn record_storage_size(&self, root: &Path) {
|
||||
let bytes = match memory_storage_bytes(root).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(err) => {
|
||||
tracing::warn!("failed measuring memory storage size: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.session_telemetry.histogram_with_boundaries(
|
||||
MEMORY_STORAGE_BYTES,
|
||||
i64::try_from(bytes).unwrap_or(i64::MAX),
|
||||
// Log-spaced byte buckets cover small summaries through large memory collections.
|
||||
&[
|
||||
0.0,
|
||||
1_024.0,
|
||||
4_096.0,
|
||||
16_384.0,
|
||||
65_536.0,
|
||||
262_144.0,
|
||||
1_048_576.0,
|
||||
4_194_304.0,
|
||||
16_777_216.0,
|
||||
67_108_864.0,
|
||||
268_435_456.0,
|
||||
1_073_741_824.0,
|
||||
],
|
||||
&memory_metric_tags(self.version, &[]),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) async fn memory_store(&self) -> Option<MemoryStore> {
|
||||
match self
|
||||
.thread
|
||||
.state_db()?
|
||||
.memories_for_version(self.version)
|
||||
.await
|
||||
{
|
||||
Ok(store) => Some(store),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed opening memory store: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provider(&self) -> &dyn ModelProvider {
|
||||
self.provider.as_ref()
|
||||
}
|
||||
|
||||
/// Model for a memory job: the provider-preferred model when the provider advertises
|
||||
/// it, otherwise the session's current model.
|
||||
pub(crate) async fn auxiliary_model(&self, config: &Config, preferred: &str) -> String {
|
||||
let session_model = self.thread.config_snapshot().await.model;
|
||||
akode_models_manager::manager::auxiliary_model(
|
||||
self.thread_manager.get_models_manager().as_ref(),
|
||||
preferred,
|
||||
&session_model,
|
||||
config.http_client_factory(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
|
||||
self.session_telemetry
|
||||
.counter(name, inc, &memory_metric_tags(self.version, tags));
|
||||
}
|
||||
|
||||
pub(crate) fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
|
||||
self.session_telemetry
|
||||
.histogram(name, value, &memory_metric_tags(self.version, tags));
|
||||
}
|
||||
|
||||
pub(crate) fn start_timer(&self, name: &str) -> Option<akode_otel::Timer> {
|
||||
self.session_telemetry
|
||||
.start_timer(name, &memory_metric_tags(self.version, &[]))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(crate) async fn stage_one_request_context(
|
||||
&self,
|
||||
config: &Config,
|
||||
model_name: &str,
|
||||
reasoning_effort: ReasoningEffort,
|
||||
) -> StageOneRequestContext {
|
||||
let config_snapshot = self.thread.config_snapshot().await;
|
||||
let model_info = self
|
||||
.thread_manager
|
||||
.get_models_manager()
|
||||
.get_model_info(model_name, &config.to_models_manager_config())
|
||||
.await;
|
||||
let reasoning_summary = config
|
||||
.model_reasoning_summary
|
||||
.unwrap_or(model_info.default_reasoning_summary);
|
||||
|
||||
StageOneRequestContext {
|
||||
version: self.version,
|
||||
model_info: Arc::unwrap_or_clone(model_info.model),
|
||||
session_telemetry: build_session_telemetry(
|
||||
&self.auth_manager,
|
||||
self.thread_id,
|
||||
config,
|
||||
config_snapshot.session_source,
|
||||
model_name,
|
||||
config_snapshot.originator,
|
||||
),
|
||||
reasoning_effort: Some(reasoning_effort),
|
||||
reasoning_summary,
|
||||
service_tier: config_snapshot.service_tier,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn stream_stage_one_prompt(
|
||||
&self,
|
||||
config: &Config,
|
||||
prompt: &Prompt,
|
||||
context: &StageOneRequestContext,
|
||||
) -> anyhow::Result<(String, Option<TokenUsage>)> {
|
||||
let installation_id = resolve_installation_id(&config.codex_home).await?;
|
||||
let config_snapshot = self.thread.config_snapshot().await;
|
||||
let session_source = config_snapshot.session_source;
|
||||
let session_id = SessionId::from(self.thread_id);
|
||||
let session_id_string = session_id.to_string();
|
||||
let model_client = ModelClient::new(
|
||||
Arc::clone(&self.provider),
|
||||
self.thread_id,
|
||||
Arc::clone(self.item_id_generator()),
|
||||
session_source.clone(),
|
||||
config_snapshot.originator,
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::ContentItemKinds),
|
||||
config.features.enabled(Feature::ReasoningEffortOverride),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
/*beta_features_header*/ None,
|
||||
/*concurrent_reasoning_summaries_enabled*/ false,
|
||||
/*output_token_replay_enabled*/ false,
|
||||
config.http_client_factory(),
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
let mut client_session = model_client.new_session();
|
||||
let window_id = format!("{}:0", self.thread_id);
|
||||
let responses_metadata = detached_memory_responses_metadata(
|
||||
&self.thread_manager,
|
||||
installation_id,
|
||||
session_id_string,
|
||||
self.thread_id.to_string(),
|
||||
window_id,
|
||||
&session_source,
|
||||
&config.cwd,
|
||||
&config_snapshot.permission_profile,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await;
|
||||
let mut stream = client_session
|
||||
.stream(
|
||||
prompt,
|
||||
&context.model_info,
|
||||
&context.session_telemetry,
|
||||
context.reasoning_effort.clone(),
|
||||
context.reasoning_summary,
|
||||
context.service_tier.clone(),
|
||||
&responses_metadata,
|
||||
&InferenceTraceContext::disabled(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut result = String::new();
|
||||
let mut token_usage = None;
|
||||
while let Some(message) = stream.next().await.transpose()? {
|
||||
match message {
|
||||
ResponseEvent::OutputTextDelta(delta) => result.push_str(&delta),
|
||||
ResponseEvent::OutputItemDone(item) => {
|
||||
if result.is_empty()
|
||||
&& let akode_protocol::models::ResponseItem::Message { content, .. } = item
|
||||
&& let Some(text) = content_items_to_text(&content)
|
||||
{
|
||||
result.push_str(&text);
|
||||
}
|
||||
}
|
||||
ResponseEvent::Completed {
|
||||
token_usage: usage, ..
|
||||
} => {
|
||||
token_usage = usage;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((result, token_usage))
|
||||
}
|
||||
|
||||
pub(crate) async fn spawn_consolidation_agent(
|
||||
&self,
|
||||
config: Config,
|
||||
prompt: Vec<UserInput>,
|
||||
workspace_lock: Arc<crate::MemoryWorkspaceLock>,
|
||||
) -> anyhow::Result<SpawnedConsolidationAgent> {
|
||||
let NewThread {
|
||||
thread_id, thread, ..
|
||||
} = self
|
||||
.thread_manager
|
||||
.start_thread(StartThreadOptions {
|
||||
session_source: Some(SessionSource::Internal(
|
||||
InternalSessionSource::MemoryConsolidation,
|
||||
)),
|
||||
thread_source: Some(ThreadSource::MemoryConsolidation),
|
||||
..StartThreadOptions::new(config)
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Cancellation or a shutdown timeout must not release workspace ownership
|
||||
// while the agent can still write. The phase-2 handler keeps another owner
|
||||
// through the final baseline reset after this thread has terminated.
|
||||
let running_thread = Arc::clone(&thread);
|
||||
tokio::spawn(async move {
|
||||
running_thread.wait_until_terminated().await;
|
||||
drop(workspace_lock);
|
||||
});
|
||||
|
||||
let agent = SpawnedConsolidationAgent { thread_id, thread };
|
||||
let submit_result = match agent
|
||||
.thread
|
||||
.start_turn_if_idle(
|
||||
TurnInputRequest::user_input(prompt).on_start(TurnStartOptions {
|
||||
turn_trigger: Some("memory_consolidation".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(StartIfIdleSubmission::Started { .. }) => Ok(()),
|
||||
Ok(submission) => Err(anyhow::anyhow!(
|
||||
"memory consolidation input was not started: {submission:?}"
|
||||
)),
|
||||
Err(err) => Err(err.into()),
|
||||
};
|
||||
if let Err(err) = submit_result {
|
||||
if let Err(shutdown_err) = self.shutdown_consolidation_agent(agent).await {
|
||||
tracing::warn!(
|
||||
"failed to shut down consolidation agent after submit error: {shutdown_err}"
|
||||
);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown_consolidation_agent(
|
||||
&self,
|
||||
agent: SpawnedConsolidationAgent,
|
||||
) -> anyhow::Result<()> {
|
||||
let SpawnedConsolidationAgent { thread_id, thread } = agent;
|
||||
tokio::time::timeout(Duration::from_secs(10), thread.shutdown_and_wait())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!("memory consolidation agent {thread_id} shutdown timed out")
|
||||
})??;
|
||||
|
||||
self.thread_manager.remove_thread(&thread_id).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
91
akode-rs/memories/write/src/start.rs
Normal file
91
akode-rs/memories/write/src/start.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
use crate::ensure_layout;
|
||||
use crate::extensions::seed_extension_instructions;
|
||||
use crate::phase1;
|
||||
use crate::phase2;
|
||||
use crate::runtime::MemoryStartupContext;
|
||||
use akode_core::CodexThread;
|
||||
use akode_core::ThreadManager;
|
||||
use akode_core::config::Config;
|
||||
use akode_features::Feature;
|
||||
use akode_model_provider::ProviderAuthContext;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use std::sync::Arc;
|
||||
use tracing::warn;
|
||||
|
||||
/// Starts the asynchronous startup memory pipeline for an eligible root session.
|
||||
///
|
||||
/// The pipeline is skipped for ephemeral sessions, disabled feature flags, and
|
||||
/// subagent sessions.
|
||||
pub fn start_memories_startup_task(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
config: Arc<Config>,
|
||||
parent_permission_profile: PermissionProfile,
|
||||
source: &SessionSource,
|
||||
) {
|
||||
if config.ephemeral
|
||||
|| !config.features.enabled(Feature::MemoryTool)
|
||||
|| source.is_non_root_agent()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::expect_used,
|
||||
reason = "Core installs provider auth before starting memories"
|
||||
)]
|
||||
let auth = thread
|
||||
.thread_extension_data()
|
||||
.get::<ProviderAuthContext>()
|
||||
.expect("session startup installs the provider auth context");
|
||||
// Dual-write warms v2 while v1 is selected; it is no longer needed after cutover.
|
||||
let versions = if config.memories.dual_write && config.memories.version == MemoryVersion::V1 {
|
||||
vec![MemoryVersion::V1, MemoryVersion::V2]
|
||||
} else {
|
||||
vec![config.memories.version]
|
||||
};
|
||||
for version in versions {
|
||||
let mut pipeline_config = config.as_ref().clone();
|
||||
pipeline_config.memories.version = version;
|
||||
let config = Arc::new(pipeline_config);
|
||||
let auth = Arc::clone(&auth);
|
||||
let parent_permission_profile = parent_permission_profile.clone();
|
||||
let context = Arc::new(MemoryStartupContext::new(
|
||||
Arc::clone(&thread_manager),
|
||||
Arc::clone(&auth),
|
||||
thread_id,
|
||||
Arc::clone(&thread),
|
||||
config.as_ref(),
|
||||
source.clone(),
|
||||
));
|
||||
tokio::spawn(async move {
|
||||
if context.memory_store().await.is_none() {
|
||||
warn!("state db unavailable for memories startup pipeline; skipping");
|
||||
return;
|
||||
}
|
||||
let root = config
|
||||
.codex_home
|
||||
.join(config.memories.version.directory_name());
|
||||
if let Err(err) = ensure_layout(&root).await {
|
||||
warn!("failed preparing memories root: {err}");
|
||||
return;
|
||||
}
|
||||
if let Err(err) = seed_extension_instructions(&root).await {
|
||||
warn!("failed seeding memory extension instructions: {err}");
|
||||
}
|
||||
|
||||
// Clean memories to make preserve DB size. This does not consume tokens so can be
|
||||
// done before the quota check.
|
||||
phase1::prune(context.as_ref(), &config).await;
|
||||
|
||||
// Run phase 1.
|
||||
phase1::run(Arc::clone(&context), Arc::clone(&config)).await;
|
||||
// Run phase 2.
|
||||
phase2::run(context, config, parent_permission_profile).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
150
akode-rs/memories/write/src/startup_dual_write_tests.rs
Normal file
150
akode-rs/memories/write/src/startup_dual_write_tests.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
//! Exercises dual-write and v2 cutover through model requests and committed versioned state.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::MemoryVersion;
|
||||
use core_test_support::responses::sse_response;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path_regex;
|
||||
|
||||
#[tokio::test]
|
||||
async fn dual_write_runs_both_versions_until_v2_is_selected() -> anyhow::Result<()> {
|
||||
for (version, expected_pipelines) in [(Some("v1"), 2), (Some("v2"), 1), (None, 1)] {
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let version_config = version
|
||||
.map(|version| format!("version = {version:?}"))
|
||||
.unwrap_or_default();
|
||||
tokio::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"[features]\nmemories = true\n\
|
||||
[memories]\ndual_write = true\nmax_raw_memories_for_consolidation = 1\n\
|
||||
min_rollout_idle_hours = 0\n{version_config}\n"
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let test = test_codex()
|
||||
.with_home(Arc::clone(&home))
|
||||
.build(&server)
|
||||
.await?;
|
||||
let selected_version = test.config.memories.version;
|
||||
assert_eq!(
|
||||
selected_version,
|
||||
if version == Some("v1") {
|
||||
MemoryVersion::V1
|
||||
} else {
|
||||
MemoryVersion::V2
|
||||
}
|
||||
);
|
||||
let db = test.codex.state_db().expect("memory state");
|
||||
let source = seed_stage1_candidate(
|
||||
&db,
|
||||
home.path(),
|
||||
chrono::Utc::now() - chrono::Duration::hours(2),
|
||||
"dual-write",
|
||||
)
|
||||
.await?;
|
||||
let v1_root = home.path().join("memories");
|
||||
let v2_root = home.path().join("memories_v2");
|
||||
if version.is_some() {
|
||||
seed_required_memory_artifacts(&v1_root).await?;
|
||||
}
|
||||
tokio::fs::create_dir_all(&v2_root).await?;
|
||||
tokio::fs::write(
|
||||
v2_root.join("memory_summary.md"),
|
||||
"v1\n\n## User Profile\nV2 user\n\n## User preferences\nV2 preference\n\n## General Tips\nV2 tip\n\n## What's in Memory\nV2 source\n",
|
||||
)
|
||||
.await?;
|
||||
// Dispatch by the output contract rather than request order: both pipelines
|
||||
// run concurrently, and each phase two can start before the other phase one.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(".*/responses$"))
|
||||
.respond_with(|request: &wiremock::Request| {
|
||||
let body: serde_json::Value = request.body_json().expect("response request");
|
||||
let properties = &body["text"]["format"]["schema"]["properties"];
|
||||
let output = if properties.get("raw_memory").is_some() {
|
||||
r#"{"raw_memory":"legacy fact","rollout_summary":"legacy rollout","rollout_slug":"legacy"}"#
|
||||
} else if properties.get("rollout_summary").is_some() {
|
||||
r#"{"rollout_summary":"v2 rollout","rollout_slug":"v2"}"#
|
||||
} else {
|
||||
"consolidation complete"
|
||||
};
|
||||
sse_response(sse(vec![
|
||||
ev_response_created("response"),
|
||||
ev_assistant_message("message", output),
|
||||
ev_completed("response"),
|
||||
]))
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
trigger_memories_startup(&test).await;
|
||||
for (version, root, expected_raw, expected_summary) in [
|
||||
(MemoryVersion::V2, &v2_root, "", "v2 rollout"),
|
||||
(MemoryVersion::V1, &v1_root, "legacy fact", "legacy rollout"),
|
||||
] {
|
||||
let store = db.memories_for_version(version).await?;
|
||||
if selected_version == MemoryVersion::V2 && version == MemoryVersion::V1 {
|
||||
assert_eq!(
|
||||
store.list_stage1_outputs_for_global(/*n*/ 10).await?,
|
||||
vec![]
|
||||
);
|
||||
assert_eq!(store.max_consolidated_thread_count().await?, 0);
|
||||
assert!(!root.join("rollout_summaries").exists());
|
||||
continue;
|
||||
}
|
||||
// Both pipelines initialize Git workspaces and run consolidation agents.
|
||||
// Allow for process startup under contention on Windows CI runners.
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while store.max_consolidated_thread_count().await? == 0 {
|
||||
anyhow::ensure!(
|
||||
Instant::now() < deadline,
|
||||
"pipeline {version:?} did not consolidate"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
let outputs = store.list_stage1_outputs_for_global(/*n*/ 10).await?;
|
||||
assert_eq!(
|
||||
outputs
|
||||
.iter()
|
||||
.map(|output| (
|
||||
output.thread_id,
|
||||
output.raw_memory.as_str(),
|
||||
output.rollout_summary.as_str()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(source, expected_raw, expected_summary)]
|
||||
);
|
||||
let summaries = read_rollout_summary_bodies(root).await?;
|
||||
assert_eq!(summaries.len(), 1);
|
||||
assert!(summaries[0].contains(expected_summary));
|
||||
}
|
||||
let requests = server.received_requests().await.expect("recorded requests");
|
||||
let bodies = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path().ends_with("/responses"))
|
||||
.map(|request| {
|
||||
request
|
||||
.body_json::<serde_json::Value>()
|
||||
.expect("request JSON")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(bodies.len(), expected_pipelines * 2);
|
||||
assert_eq!(
|
||||
bodies
|
||||
.iter()
|
||||
.filter(|body| body["text"]["format"]["schema"].is_null())
|
||||
.count(),
|
||||
expected_pipelines
|
||||
);
|
||||
assert!(!v2_root.join("MEMORY.md").exists());
|
||||
assert!(!v2_root.join("raw_memories.md").exists());
|
||||
if version.is_none() {
|
||||
assert!(!v1_root.exists());
|
||||
}
|
||||
shutdown_test_codex(&test).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
1683
akode-rs/memories/write/src/startup_tests.rs
Normal file
1683
akode-rs/memories/write/src/startup_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
242
akode-rs/memories/write/src/storage.rs
Normal file
242
akode-rs/memories/write/src/storage.rs
Normal file
@@ -0,0 +1,242 @@
|
||||
use akode_state::Stage1Output;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write as _;
|
||||
use std::path::Path;
|
||||
use tracing::warn;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::ensure_layout;
|
||||
use crate::raw_memories_file;
|
||||
use crate::rollout_summaries_dir;
|
||||
|
||||
/// Rebuild `raw_memories.md` from DB-backed stage-1 outputs.
|
||||
pub async fn rebuild_raw_memories_file_from_memories(
|
||||
root: &Path,
|
||||
memories: &[Stage1Output],
|
||||
max_raw_memories_for_consolidation: usize,
|
||||
) -> std::io::Result<()> {
|
||||
ensure_layout(root).await?;
|
||||
rebuild_raw_memories_file(root, memories, max_raw_memories_for_consolidation).await
|
||||
}
|
||||
|
||||
/// Syncs canonical rollout summary files from DB-backed stage-1 output rows.
|
||||
pub async fn sync_rollout_summaries_from_memories(
|
||||
root: &Path,
|
||||
memories: &[Stage1Output],
|
||||
max_raw_memories_for_consolidation: usize,
|
||||
) -> std::io::Result<()> {
|
||||
ensure_layout(root).await?;
|
||||
|
||||
let retained = retained_memories(memories, max_raw_memories_for_consolidation);
|
||||
let keep = retained
|
||||
.iter()
|
||||
.map(rollout_summary_file_stem)
|
||||
.collect::<HashSet<_>>();
|
||||
prune_rollout_summaries(root, &keep).await?;
|
||||
|
||||
for memory in retained {
|
||||
write_rollout_summary_for_thread(root, memory).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn rebuild_raw_memories_file(
|
||||
root: &Path,
|
||||
memories: &[Stage1Output],
|
||||
max_raw_memories_for_consolidation: usize,
|
||||
) -> std::io::Result<()> {
|
||||
let retained = retained_memories(memories, max_raw_memories_for_consolidation);
|
||||
let mut body = String::from("# Raw Memories\n\n");
|
||||
|
||||
if retained.is_empty() {
|
||||
body.push_str("No raw memories yet.\n");
|
||||
return tokio::fs::write(raw_memories_file(root), body).await;
|
||||
}
|
||||
|
||||
body.push_str("Merged stage-1 raw memories (stable ascending thread-id order):\n\n");
|
||||
for memory in retained {
|
||||
writeln!(body, "## Thread `{}`", memory.thread_id).map_err(raw_memories_format_error)?;
|
||||
writeln!(
|
||||
body,
|
||||
"updated_at: {}",
|
||||
memory.source_updated_at.to_rfc3339()
|
||||
)
|
||||
.map_err(raw_memories_format_error)?;
|
||||
writeln!(body, "cwd: {}", memory.cwd.display()).map_err(raw_memories_format_error)?;
|
||||
writeln!(body, "rollout_path: {}", memory.rollout_path.display())
|
||||
.map_err(raw_memories_format_error)?;
|
||||
let rollout_summary_file = format!("{}.md", rollout_summary_file_stem(memory));
|
||||
writeln!(body, "rollout_summary_file: {rollout_summary_file}")
|
||||
.map_err(raw_memories_format_error)?;
|
||||
writeln!(body).map_err(raw_memories_format_error)?;
|
||||
body.push_str(memory.raw_memory.trim());
|
||||
body.push_str("\n\n");
|
||||
}
|
||||
|
||||
tokio::fs::write(raw_memories_file(root), body).await
|
||||
}
|
||||
|
||||
async fn prune_rollout_summaries(root: &Path, keep: &HashSet<String>) -> std::io::Result<()> {
|
||||
let dir_path = rollout_summaries_dir(root);
|
||||
let mut dir = match tokio::fs::read_dir(&dir_path).await {
|
||||
Ok(dir) => dir,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
while let Some(entry) = dir.next_entry().await? {
|
||||
let path = entry.path();
|
||||
let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(stem) = file_name.strip_suffix(".md") else {
|
||||
continue;
|
||||
};
|
||||
if !keep.contains(stem)
|
||||
&& let Err(err) = tokio::fs::remove_file(&path).await
|
||||
&& err.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(
|
||||
"failed pruning outdated rollout summary {}: {err}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_rollout_summary_for_thread(
|
||||
root: &Path,
|
||||
memory: &Stage1Output,
|
||||
) -> std::io::Result<()> {
|
||||
let file_stem = rollout_summary_file_stem(memory);
|
||||
let path = rollout_summaries_dir(root).join(format!("{file_stem}.md"));
|
||||
|
||||
let mut body = String::new();
|
||||
writeln!(body, "thread_id: {}", memory.thread_id).map_err(rollout_summary_format_error)?;
|
||||
writeln!(
|
||||
body,
|
||||
"updated_at: {}",
|
||||
memory.source_updated_at.to_rfc3339()
|
||||
)
|
||||
.map_err(rollout_summary_format_error)?;
|
||||
writeln!(body, "rollout_path: {}", memory.rollout_path.display())
|
||||
.map_err(rollout_summary_format_error)?;
|
||||
writeln!(body, "cwd: {}", memory.cwd.display()).map_err(rollout_summary_format_error)?;
|
||||
if let Some(git_branch) = memory.git_branch.as_deref() {
|
||||
writeln!(body, "git_branch: {git_branch}").map_err(rollout_summary_format_error)?;
|
||||
}
|
||||
writeln!(body).map_err(rollout_summary_format_error)?;
|
||||
body.push_str(&memory.rollout_summary);
|
||||
body.push('\n');
|
||||
|
||||
tokio::fs::write(path, body).await
|
||||
}
|
||||
|
||||
fn retained_memories(
|
||||
memories: &[Stage1Output],
|
||||
max_raw_memories_for_consolidation: usize,
|
||||
) -> &[Stage1Output] {
|
||||
&memories[..memories.len().min(max_raw_memories_for_consolidation)]
|
||||
}
|
||||
|
||||
fn raw_memories_format_error(err: std::fmt::Error) -> std::io::Error {
|
||||
std::io::Error::other(format!("format raw memories: {err}"))
|
||||
}
|
||||
|
||||
fn rollout_summary_format_error(err: std::fmt::Error) -> std::io::Error {
|
||||
std::io::Error::other(format!("format rollout summary: {err}"))
|
||||
}
|
||||
|
||||
pub fn rollout_summary_file_stem(memory: &Stage1Output) -> String {
|
||||
rollout_summary_file_stem_from_parts(
|
||||
memory.thread_id,
|
||||
memory.source_updated_at,
|
||||
memory.rollout_slug.as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
fn rollout_summary_file_stem_from_parts(
|
||||
thread_id: akode_protocol::ThreadId,
|
||||
source_updated_at: chrono::DateTime<chrono::Utc>,
|
||||
rollout_slug: Option<&str>,
|
||||
) -> String {
|
||||
const ROLLOUT_SLUG_MAX_LEN: usize = 60;
|
||||
const SHORT_HASH_ALPHABET: &[u8; 62] =
|
||||
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
const SHORT_HASH_SPACE: u32 = 14_776_336;
|
||||
|
||||
let thread_id = thread_id.to_string();
|
||||
let (timestamp_fragment, short_hash_seed) = match Uuid::parse_str(&thread_id) {
|
||||
Ok(thread_uuid) => {
|
||||
let timestamp = thread_uuid
|
||||
.get_timestamp()
|
||||
.and_then(|uuid_timestamp| {
|
||||
let (seconds, nanos) = uuid_timestamp.to_unix();
|
||||
i64::try_from(seconds).ok().and_then(|secs| {
|
||||
chrono::DateTime::<chrono::Utc>::from_timestamp(secs, nanos)
|
||||
})
|
||||
})
|
||||
.unwrap_or(source_updated_at);
|
||||
let short_hash_seed = (thread_uuid.as_u128() & 0xFFFF_FFFF) as u32;
|
||||
(
|
||||
timestamp.format("%Y-%m-%dT%H-%M-%S").to_string(),
|
||||
short_hash_seed,
|
||||
)
|
||||
}
|
||||
Err(_) => {
|
||||
let mut short_hash_seed = 0u32;
|
||||
for byte in thread_id.bytes() {
|
||||
short_hash_seed = short_hash_seed
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(u32::from(byte));
|
||||
}
|
||||
(
|
||||
source_updated_at.format("%Y-%m-%dT%H-%M-%S").to_string(),
|
||||
short_hash_seed,
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut short_hash_value = short_hash_seed % SHORT_HASH_SPACE;
|
||||
let mut short_hash_chars = ['0'; 4];
|
||||
for idx in (0..short_hash_chars.len()).rev() {
|
||||
let alphabet_idx = (short_hash_value % SHORT_HASH_ALPHABET.len() as u32) as usize;
|
||||
short_hash_chars[idx] = SHORT_HASH_ALPHABET[alphabet_idx] as char;
|
||||
short_hash_value /= SHORT_HASH_ALPHABET.len() as u32;
|
||||
}
|
||||
let short_hash: String = short_hash_chars.iter().collect();
|
||||
let file_prefix = format!("{timestamp_fragment}-{short_hash}");
|
||||
|
||||
let Some(raw_slug) = rollout_slug else {
|
||||
return file_prefix;
|
||||
};
|
||||
|
||||
let mut slug = String::with_capacity(ROLLOUT_SLUG_MAX_LEN);
|
||||
for ch in raw_slug.chars() {
|
||||
if slug.len() >= ROLLOUT_SLUG_MAX_LEN {
|
||||
break;
|
||||
}
|
||||
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch.to_ascii_lowercase());
|
||||
} else {
|
||||
slug.push('_');
|
||||
}
|
||||
}
|
||||
|
||||
while slug.ends_with('_') {
|
||||
slug.pop();
|
||||
}
|
||||
|
||||
if slug.is_empty() {
|
||||
file_prefix
|
||||
} else {
|
||||
format!("{file_prefix}-{slug}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "storage_tests.rs"]
|
||||
mod tests;
|
||||
149
akode-rs/memories/write/src/storage_tests.rs
Normal file
149
akode-rs/memories/write/src/storage_tests.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use super::rollout_summary_file_stem;
|
||||
use crate::ensure_layout;
|
||||
use crate::raw_memories_file;
|
||||
use crate::rebuild_raw_memories_file_from_memories;
|
||||
use crate::rollout_summaries_dir;
|
||||
use crate::sync_rollout_summaries_from_memories;
|
||||
use chrono::TimeZone;
|
||||
use chrono::Utc;
|
||||
use akode_config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_state::Stage1Output;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::tempdir;
|
||||
|
||||
const FIXED_PREFIX: &str = "2025-02-11T15-35-19-jqmb";
|
||||
|
||||
fn stage1_output_with_slug(thread_id: ThreadId, rollout_slug: Option<&str>) -> Stage1Output {
|
||||
Stage1Output {
|
||||
thread_id,
|
||||
source_updated_at: Utc.timestamp_opt(123, 0).single().expect("timestamp"),
|
||||
raw_memory: "raw memory".to_string(),
|
||||
rollout_summary: "summary".to_string(),
|
||||
rollout_slug: rollout_slug.map(ToString::to_string),
|
||||
rollout_path: PathBuf::from("/tmp/rollout.jsonl"),
|
||||
cwd: PathBuf::from("/tmp/workspace"),
|
||||
git_branch: None,
|
||||
generated_at: Utc.timestamp_opt(124, 0).single().expect("timestamp"),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_thread_id() -> ThreadId {
|
||||
ThreadId::try_from("0194f5a6-89ab-7cde-8123-456789abcdef").expect("valid thread id")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_summary_file_stem_uses_uuid_timestamp_and_hash_when_slug_missing() {
|
||||
let thread_id = fixed_thread_id();
|
||||
let memory = stage1_output_with_slug(thread_id, /*rollout_slug*/ None);
|
||||
|
||||
assert_eq!(rollout_summary_file_stem(&memory), FIXED_PREFIX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_summary_file_stem_sanitizes_and_truncates_slug() {
|
||||
let thread_id = fixed_thread_id();
|
||||
let memory = stage1_output_with_slug(
|
||||
thread_id,
|
||||
Some("Unsafe Slug/With Spaces & Symbols + EXTRA_LONG_12345_67890_ABCDE_fghij_klmno"),
|
||||
);
|
||||
|
||||
let stem = rollout_summary_file_stem(&memory);
|
||||
let slug = stem
|
||||
.strip_prefix(&format!("{FIXED_PREFIX}-"))
|
||||
.expect("slug suffix should be present");
|
||||
assert_eq!(slug.len(), 60);
|
||||
assert_eq!(
|
||||
slug,
|
||||
"unsafe_slug_with_spaces___symbols___extra_long_12345_67890_a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_summary_file_stem_uses_uuid_timestamp_and_hash_when_slug_is_empty() {
|
||||
let thread_id = fixed_thread_id();
|
||||
let memory = stage1_output_with_slug(thread_id, Some(""));
|
||||
|
||||
assert_eq!(rollout_summary_file_stem(&memory), FIXED_PREFIX);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let root = dir.path().join("memory");
|
||||
ensure_layout(&root).await.expect("ensure layout");
|
||||
|
||||
let keep_id = ThreadId::default().to_string();
|
||||
let drop_id = ThreadId::default().to_string();
|
||||
let keep_path = rollout_summaries_dir(&root).join(format!("{keep_id}.md"));
|
||||
let drop_path = rollout_summaries_dir(&root).join(format!("{drop_id}.md"));
|
||||
tokio::fs::write(&keep_path, "keep")
|
||||
.await
|
||||
.expect("write keep");
|
||||
tokio::fs::write(&drop_path, "drop")
|
||||
.await
|
||||
.expect("write drop");
|
||||
|
||||
let memories = vec![Stage1Output {
|
||||
thread_id: ThreadId::try_from(keep_id.clone()).expect("thread id"),
|
||||
source_updated_at: Utc.timestamp_opt(100, 0).single().expect("timestamp"),
|
||||
raw_memory: "raw memory".to_string(),
|
||||
rollout_summary: "short summary".to_string(),
|
||||
rollout_slug: None,
|
||||
rollout_path: PathBuf::from("/tmp/rollout-100.jsonl"),
|
||||
cwd: PathBuf::from("/tmp/workspace"),
|
||||
git_branch: None,
|
||||
generated_at: Utc.timestamp_opt(101, 0).single().expect("timestamp"),
|
||||
}];
|
||||
|
||||
sync_rollout_summaries_from_memories(
|
||||
&root,
|
||||
&memories,
|
||||
DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION,
|
||||
)
|
||||
.await
|
||||
.expect("sync rollout summaries");
|
||||
rebuild_raw_memories_file_from_memories(
|
||||
&root,
|
||||
&memories,
|
||||
DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION,
|
||||
)
|
||||
.await
|
||||
.expect("rebuild raw memories");
|
||||
|
||||
assert!(
|
||||
!tokio::fs::try_exists(&keep_path)
|
||||
.await
|
||||
.expect("check stale keep path"),
|
||||
"sync should prune stale filename that used thread id only"
|
||||
);
|
||||
assert!(
|
||||
!tokio::fs::try_exists(&drop_path)
|
||||
.await
|
||||
.expect("check stale drop path"),
|
||||
"sync should prune stale filename for dropped thread"
|
||||
);
|
||||
|
||||
let mut dir = tokio::fs::read_dir(rollout_summaries_dir(&root))
|
||||
.await
|
||||
.expect("open rollout summaries dir");
|
||||
let mut files = Vec::new();
|
||||
while let Some(entry) = dir.next_entry().await.expect("read dir entry") {
|
||||
files.push(entry.file_name().to_string_lossy().to_string());
|
||||
}
|
||||
files.sort_unstable();
|
||||
assert_eq!(files.len(), 1);
|
||||
let canonical_rollout_summary_file = &files[0];
|
||||
|
||||
let raw_memories = tokio::fs::read_to_string(raw_memories_file(&root))
|
||||
.await
|
||||
.expect("read raw memories");
|
||||
assert!(raw_memories.contains("raw memory"));
|
||||
assert!(raw_memories.contains(&keep_id));
|
||||
assert!(raw_memories.contains("cwd: /tmp/workspace"));
|
||||
assert!(raw_memories.contains("rollout_path: /tmp/rollout-100.jsonl"));
|
||||
assert!(raw_memories.contains(&format!(
|
||||
"rollout_summary_file: {canonical_rollout_summary_file}"
|
||||
)));
|
||||
}
|
||||
233
akode-rs/memories/write/src/workspace.rs
Normal file
233
akode-rs/memories/write/src/workspace.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
use anyhow::Context;
|
||||
use akode_git_utils::GitBaselineDiff;
|
||||
use akode_git_utils::diff_since_latest_init;
|
||||
use akode_git_utils::ensure_git_baseline_repository;
|
||||
use akode_git_utils::reset_git_repository;
|
||||
use akode_protocol::MemoryVersion;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
use std::path::Path;
|
||||
|
||||
/// Prepares the memory directory for git-baseline diffing.
|
||||
///
|
||||
/// This keeps an existing current-version `.git/` baseline intact. Missing, outdated or unusable
|
||||
/// metadata is replaced with an empty baseline so existing memory files are reconsidered. Any stale
|
||||
/// generated `phase2_workspace_diff.md` is removed so it does not enter the next diff.
|
||||
pub async fn prepare_memory_workspace(root: &Path) -> anyhow::Result<()> {
|
||||
crate::ensure_layout(root)
|
||||
.await
|
||||
.with_context(|| format!("prepare memory workspace {}", root.display()))?;
|
||||
remove_workspace_diff(root).await?;
|
||||
ensure_git_baseline_repository(root).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the current workspace diff after removing any stale generated diff artifact.
|
||||
///
|
||||
/// Memory artifacts are left intact. The baseline is invalidated if a tracked file has grown
|
||||
/// beyond the snapshot size limit since preparation.
|
||||
pub async fn memory_workspace_diff(root: &Path) -> anyhow::Result<GitBaselineDiff> {
|
||||
remove_workspace_diff(root).await?;
|
||||
diff_since_latest_init(root).await
|
||||
}
|
||||
|
||||
/// Writes `phase2_workspace_diff.md` with a bounded git-style diff from the current baseline.
|
||||
pub async fn write_workspace_diff(root: &Path, diff: &GitBaselineDiff) -> anyhow::Result<()> {
|
||||
let path = root.join(crate::workspace_diff::FILENAME);
|
||||
tokio::fs::write(&path, render_workspace_diff_file(diff))
|
||||
.await
|
||||
.with_context(|| format!("write memory workspace diff file {}", path.display()))
|
||||
}
|
||||
|
||||
/// Marks the current memory root as the new baseline.
|
||||
///
|
||||
/// The generated diff file is removed before resetting the baseline so deleted memory content is
|
||||
/// not retained in the prompt artifact or in unreachable git objects.
|
||||
pub async fn reset_memory_workspace_baseline(root: &Path) -> anyhow::Result<()> {
|
||||
remove_workspace_diff(root).await?;
|
||||
reset_git_repository(root).await
|
||||
}
|
||||
|
||||
/// Sums regular-file contents without reading them, excluding git metadata and symbolic links.
|
||||
pub(crate) async fn memory_storage_bytes(root: &Path) -> std::io::Result<u64> {
|
||||
let mut paths = vec![root.to_path_buf()];
|
||||
let mut bytes = 0_u64;
|
||||
while let Some(path) = paths.pop() {
|
||||
let metadata = tokio::fs::symlink_metadata(&path).await?;
|
||||
if metadata.is_file() {
|
||||
bytes = bytes.saturating_add(metadata.len());
|
||||
} else if metadata.is_dir() {
|
||||
let mut entries = tokio::fs::read_dir(&path).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
if entry.file_name() != ".git" {
|
||||
paths.push(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Verifies that a completed consolidation run left the required memory artifacts in place.
|
||||
pub async fn validate_consolidation_artifacts(root: &Path) -> anyhow::Result<()> {
|
||||
validate_consolidation_artifacts_for_version(root, MemoryVersion::V1).await
|
||||
}
|
||||
|
||||
pub(crate) async fn validate_consolidation_artifacts_for_version(
|
||||
root: &Path,
|
||||
version: MemoryVersion,
|
||||
) -> anyhow::Result<()> {
|
||||
let removed_symlinks = remove_memory_symlinks(root).await?;
|
||||
anyhow::ensure!(
|
||||
removed_symlinks == 0,
|
||||
"removed {removed_symlinks} symbolic links from consolidated memory workspace"
|
||||
);
|
||||
|
||||
if version == MemoryVersion::V1 {
|
||||
let memory_path = root.join("MEMORY.md");
|
||||
let memory_metadata = tokio::fs::metadata(&memory_path).await.with_context(|| {
|
||||
format!(
|
||||
"read consolidated memory artifact {}",
|
||||
memory_path.display()
|
||||
)
|
||||
})?;
|
||||
anyhow::ensure!(
|
||||
memory_metadata.is_file(),
|
||||
"consolidated memory artifact is not a file: {}",
|
||||
memory_path.display()
|
||||
);
|
||||
}
|
||||
|
||||
let summary_path = root.join("memory_summary.md");
|
||||
let summary = tokio::fs::read_to_string(&summary_path)
|
||||
.await
|
||||
.with_context(|| format!("read memory summary artifact {}", summary_path.display()))?;
|
||||
anyhow::ensure!(
|
||||
summary.lines().next() == Some("v1"),
|
||||
"memory summary artifact does not start with v1: {}",
|
||||
summary_path.display()
|
||||
);
|
||||
|
||||
if version == MemoryVersion::V2 {
|
||||
anyhow::ensure!(is_valid_v2_summary(&summary), "invalid v2 memory summary");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks the artifact shared by the writer and the read-only readiness endpoint.
|
||||
pub fn is_valid_v2_summary(summary: &str) -> bool {
|
||||
summary.lines().next() == Some("v1")
|
||||
&& summary.len() < 10_000
|
||||
&& [
|
||||
"## User Profile",
|
||||
"## User preferences",
|
||||
"## General Tips",
|
||||
"## What's in Memory",
|
||||
]
|
||||
.iter()
|
||||
.all(|heading| summary.lines().any(|line| line.trim() == *heading))
|
||||
}
|
||||
|
||||
pub(crate) async fn remove_memory_symlinks(root: &Path) -> std::io::Result<usize> {
|
||||
let mut directories = vec![root.to_path_buf()];
|
||||
let mut removed = 0;
|
||||
|
||||
while let Some(directory) = directories.pop() {
|
||||
let mut entries = tokio::fs::read_dir(directory).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
let file_type = entry.file_type().await?;
|
||||
if file_type.is_symlink() {
|
||||
#[cfg(windows)]
|
||||
if file_type.is_symlink_dir() {
|
||||
tokio::fs::remove_dir(&path).await?;
|
||||
} else {
|
||||
tokio::fs::remove_file(&path).await?;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
tokio::fs::remove_file(&path).await?;
|
||||
|
||||
tracing::warn!(
|
||||
"removed symbolic link from memory workspace: {}",
|
||||
path.display()
|
||||
);
|
||||
removed += 1;
|
||||
} else if file_type.is_dir() {
|
||||
directories.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Removes the generated `phase2_workspace_diff.md` prompt artifact.
|
||||
///
|
||||
/// This does not remove `.git/`, reset the baseline, or delete memory content. It is used before
|
||||
/// diffing and before baseline reset so the generated diff file itself is not treated as memory
|
||||
/// workspace input.
|
||||
pub(super) async fn remove_workspace_diff(root: &Path) -> anyhow::Result<()> {
|
||||
let path = root.join(crate::workspace_diff::FILENAME);
|
||||
match tokio::fs::remove_file(&path).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err)
|
||||
.with_context(|| format!("remove memory workspace diff file {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_workspace_diff_file(diff: &GitBaselineDiff) -> String {
|
||||
let mut rendered = String::from(
|
||||
"# Memory Workspace Diff\n\n\
|
||||
Generated by Codex before Phase 2 memory consolidation. Read this file first and do not edit it.\n\n\
|
||||
## Status\n",
|
||||
);
|
||||
|
||||
if !diff.has_changes() {
|
||||
rendered.push_str("- none\n");
|
||||
return rendered;
|
||||
}
|
||||
|
||||
for change in &diff.changes {
|
||||
rendered.push_str(&format!("- {} {}\n", change.status.label(), change.path));
|
||||
}
|
||||
rendered.push_str("\n## Diff\n\n```diff\n");
|
||||
append_bounded_diff(&mut rendered, &diff.unified_diff);
|
||||
rendered.push_str("```\n");
|
||||
rendered
|
||||
}
|
||||
|
||||
fn append_bounded_diff(rendered: &mut String, diff: &str) {
|
||||
if diff.len() <= crate::workspace_diff::MAX_BYTES {
|
||||
rendered.push_str(diff);
|
||||
if !diff.ends_with('\n') {
|
||||
rendered.push('\n');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let boundary = previous_char_boundary(diff, crate::workspace_diff::MAX_BYTES);
|
||||
rendered.push_str(&diff[..boundary]);
|
||||
if !rendered.ends_with('\n') {
|
||||
rendered.push('\n');
|
||||
}
|
||||
rendered.push_str(&format!(
|
||||
"\n[workspace diff truncated at {} bytes]\n",
|
||||
crate::workspace_diff::MAX_BYTES
|
||||
));
|
||||
}
|
||||
|
||||
fn previous_char_boundary(value: &str, max_bytes: usize) -> usize {
|
||||
if max_bytes >= value.len() {
|
||||
return value.len();
|
||||
}
|
||||
let mut index = max_bytes;
|
||||
while !value.is_char_boundary(index) {
|
||||
index -= 1;
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "workspace_tests.rs"]
|
||||
mod tests;
|
||||
35
akode-rs/memories/write/src/workspace_lock.rs
Normal file
35
akode-rs/memories/write/src/workspace_lock.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Cross-process exclusion between memory imports and consolidation.
|
||||
//! Lock files live beside memory roots and must not be removed or replaced.
|
||||
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
use std::fs::TryLockError;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// Keeps a memory workspace exclusively owned until all writers have stopped.
|
||||
pub struct MemoryWorkspaceLock {
|
||||
_file: File,
|
||||
}
|
||||
|
||||
impl MemoryWorkspaceLock {
|
||||
/// Returns `WouldBlock` when another import or consolidation owns this root.
|
||||
pub fn try_acquire(memory_root: &Path) -> io::Result<Self> {
|
||||
// Keep this outside the workspace: baseline resets and memory resets must
|
||||
// not replace the inode while another process still owns its lock.
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(memory_root.with_extension("lock"))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Self { _file: file }),
|
||||
Err(TryLockError::WouldBlock) => Err(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
"memory workspace is busy; retry after consolidation or another import finishes",
|
||||
)),
|
||||
Err(TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
166
akode-rs/memories/write/src/workspace_tests.rs
Normal file
166
akode-rs/memories/write/src/workspace_tests.rs
Normal file
@@ -0,0 +1,166 @@
|
||||
use super::*;
|
||||
use akode_git_utils::GitBaselineChange;
|
||||
use akode_git_utils::GitBaselineChangeStatus;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn render_workspace_diff_file_bounds_large_diff() {
|
||||
let diff = GitBaselineDiff {
|
||||
changes: vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Modified,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}],
|
||||
unified_diff: "a".repeat(crate::workspace_diff::MAX_BYTES + 128),
|
||||
};
|
||||
|
||||
let rendered = render_workspace_diff_file(&diff);
|
||||
|
||||
assert!(rendered.contains("- M MEMORY.md"));
|
||||
assert!(rendered.contains("[workspace diff truncated at 4194304 bytes]"));
|
||||
assert!(rendered.ends_with("```\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_memory_workspace_baseline_removes_generated_diff() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("memories");
|
||||
prepare_memory_workspace(&root)
|
||||
.await
|
||||
.expect("prepare memory workspace");
|
||||
fs::write(root.join("MEMORY.md"), "memory").expect("write memory");
|
||||
write_workspace_diff(
|
||||
&root,
|
||||
&GitBaselineDiff {
|
||||
changes: vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}],
|
||||
unified_diff: "+memory\n".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write workspace diff");
|
||||
|
||||
reset_memory_workspace_baseline(&root)
|
||||
.await
|
||||
.expect("reset baseline");
|
||||
|
||||
assert!(!root.join(crate::workspace_diff::FILENAME).exists());
|
||||
assert_eq!(memory_storage_bytes(&root).await.expect("storage size"), 6);
|
||||
let diff = memory_workspace_diff(&root)
|
||||
.await
|
||||
.expect("load workspace diff");
|
||||
assert_eq!(diff.changes, Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_storage_size_counts_nested_files_but_not_git_or_symlinks() -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
for version in [MemoryVersion::V1, MemoryVersion::V2] {
|
||||
let root = home.path().join(version.directory_name());
|
||||
fs::create_dir_all(root.join("rollout_summaries"))?;
|
||||
fs::create_dir_all(root.join("extensions/notes"))?;
|
||||
fs::create_dir_all(root.join(".git/objects"))?;
|
||||
fs::write(
|
||||
root.join(".git/objects/baseline"),
|
||||
"git metadata is not memory",
|
||||
)?;
|
||||
let files = [
|
||||
("memory_summary.md", "summary"),
|
||||
("rollout_summaries/thread.md", "rollout"),
|
||||
("extensions/notes/note.md", "café"),
|
||||
];
|
||||
for (path, content) in files {
|
||||
fs::write(root.join(path), content)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::symlink;
|
||||
symlink(root.join("memory_summary.md"), root.join("file-link"))?;
|
||||
symlink(&root, root.join("directory-loop"))?;
|
||||
symlink(root.join("missing"), root.join("broken-link"))?;
|
||||
}
|
||||
assert_eq!(
|
||||
memory_storage_bytes(&root).await?,
|
||||
files
|
||||
.iter()
|
||||
.map(|(_, content)| content.len() as u64)
|
||||
.sum::<u64>(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prepare_memory_workspace_recovers_unusable_git_dir() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("memories");
|
||||
fs::create_dir_all(root.join(".git")).expect("create unusable git dir");
|
||||
fs::write(root.join("MEMORY.md"), "memory").expect("write memory");
|
||||
|
||||
prepare_memory_workspace(&root)
|
||||
.await
|
||||
.expect("prepare memory workspace");
|
||||
|
||||
let diff = memory_workspace_diff(&root)
|
||||
.await
|
||||
.expect("load workspace diff");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previous_char_boundary_handles_multibyte_text() {
|
||||
let text = "aé";
|
||||
assert_eq!(previous_char_boundary(text, /*max_bytes*/ 2), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_consolidation_artifacts_rejects_invalid_summary() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("memories");
|
||||
fs::create_dir_all(&root).expect("create memory root");
|
||||
fs::write(root.join("MEMORY.md"), "memory").expect("write memory");
|
||||
fs::write(root.join("memory_summary.md"), "outdated\n").expect("write summary");
|
||||
|
||||
let err = validate_consolidation_artifacts(&root)
|
||||
.await
|
||||
.expect_err("invalid summary should fail validation");
|
||||
|
||||
assert!(err.to_string().contains("does not start with v1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_accepts_summary_only_and_checks_its_format_and_size() -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let root = home.path();
|
||||
fs::write(
|
||||
root.join("memory_summary.md"),
|
||||
"v1\n\n## User Profile\nProfile\n## User preferences\nPreferences\n## General Tips\nTips\n## What's in Memory\nIndex\n",
|
||||
)?;
|
||||
validate_consolidation_artifacts_for_version(root, MemoryVersion::V2).await?;
|
||||
assert!(validate_consolidation_artifacts(root).await.is_err());
|
||||
fs::write(root.join("memory_summary.md"), "v2\nsummary")?;
|
||||
assert!(
|
||||
validate_consolidation_artifacts_for_version(root, MemoryVersion::V2)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
fs::write(
|
||||
root.join("memory_summary.md"),
|
||||
format!("v1\n{}", "x".repeat(10_000)),
|
||||
)?;
|
||||
assert!(
|
||||
validate_consolidation_artifacts_for_version(root, MemoryVersion::V2)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user