Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

ci(codeql): route new session-id and username output through log barriers

AkitaOnRails9827c0e3b83c
diff --git a/.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml b/.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml
index 3ad92b18..8d1653d0 100644
--- a/.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml
+++ b/.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml
@@ -4,14 +4,23 @@
# the operator's own terminal, not a credential.
#
# `display_session_id` is the one helper that renders a session id for
-# terminal output; declaring its return value a log barrier clears those
-# alerts while a real secret (an `api_key`, a token) logged anywhere else is
-# still reported. Route any new session-id output through it rather than
-# adding more rows here; the CLI test `codeql_model_targets_exist` fails if a
-# modeled function is renamed or moved.
+# terminal output (the CLI's, and the importer's copy, since the importer is
+# a separate workspace that cannot call the CLI); declaring its return value
+# a log barrier clears those alerts while a real secret (an `api_key`, a
+# token) logged anywhere else is still reported. Route any new session-id
+# output through it rather than adding more rows here.
+#
+# The same heuristic reads `username` as account information. A username is
+# the operator-chosen login name, not a credential, so `ai-memory user`
+# prints it through `display_username`.
+#
+# The CLI test `codeql_model_targets_exist` fails if a modeled function is
+# renamed or moved.
extensions:
- addsTo:
pack: codeql/rust-all
extensible: barrierModel
data:
- ["ai_memory_cli::commands::run::display_session_id", "ReturnValue", "log-injection", "manual"]
+ - ["ai_memory_cli::commands::user::display_username", "ReturnValue", "log-injection", "manual"]
+ - ["ai_memory_importer::agentmemory::display_session_id", "ReturnValue", "log-injection", "manual"]
diff --git a/companions/ai-memory-importer/src/agentmemory/export.rs b/companions/ai-memory-importer/src/agentmemory/export.rs
index 5f87c70c..08b85fe1 100644
--- a/companions/ai-memory-importer/src/agentmemory/export.rs
+++ b/companions/ai-memory-importer/src/agentmemory/export.rs
@@ -32,9 +32,9 @@ use serde_json::{Value, json};
use super::{
DEFAULT_DEST_PREFIX, Destination, HookSessionEntry, MAX_EXPLICIT_TITLE_CHARS, MAX_TITLE_CHARS,
- Manifest, PlannedPage, PlannedVersion, RunStatus, apply_pages, ingest_key, link_target,
- memory_kind_tier, one_line, preflight, print_done, print_plan, provenance_line, tags_from,
- validate_dest_prefix, validate_id, validate_planned_path,
+ Manifest, PlannedPage, PlannedVersion, RunStatus, apply_pages, display_session_id, ingest_key,
+ link_target, memory_kind_tier, one_line, preflight, print_done, print_plan, provenance_line,
+ tags_from, validate_dest_prefix, validate_id, validate_planned_path,
};
use crate::{
DEFAULT_SERVER_URL, ImportClient, MAX_EXTENSION_MESSAGE_BYTES, PlannedHookEvent,
@@ -444,7 +444,7 @@ pub(crate) async fn run(args: ExportArgs) -> Result<()> {
for session in &plan.hook_sessions {
println!(
" replay session {} -> {}/{} ({} hook events)",
- session.source_session_id,
+ display_session_id(&session.source_session_id),
session.destination.workspace,
session.destination.project,
session.events.len()
diff --git a/companions/ai-memory-importer/src/agentmemory/mod.rs b/companions/ai-memory-importer/src/agentmemory/mod.rs
index 54ebe9c6..76cebf8e 100644
--- a/companions/ai-memory-importer/src/agentmemory/mod.rs
+++ b/companions/ai-memory-importer/src/agentmemory/mod.rs
@@ -129,7 +129,7 @@ pub(crate) fn validate_planned_path(path: &str, prefix: &str) -> Result<()> {
}
/// Validate an agentmemory record id before it names a path or a key.
-pub(crate) fn validate_id<'a>(id: &'a str, what: &str) -> Result<&'a str> {
+pub(crate) fn validate_id(id: &str, what: &str) -> Result<()> {
if id.trim().is_empty() || id.len() > MAX_ID_BYTES || id.chars().any(char::is_control) {
bail!(
"{what} id must be non-empty, at most {MAX_ID_BYTES} bytes and free of control characters"
@@ -137,7 +137,22 @@ pub(crate) fn validate_id<'a>(id: &'a str, what: &str) -> Result<&'a str> {
}
ai_memory_client::reject_sensitive(&serde_json::json!(id))
.with_context(|| format!("{what} id looks like a credential; refusing it"))?;
- Ok(id)
+ Ok(())
+}
+
+/// Render an agentmemory session id for terminal output, bounded so a long
+/// id cannot flood the report. CodeQL's sensitive-data heuristic reads any
+/// `session_id` name as account information; this is the one function its
+/// `rust/cleartext-logging` barrier model names
+/// (`.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml`),
+/// so print every session id through it.
+pub(crate) fn display_session_id(value: &str) -> String {
+ const MAX_CHARS: usize = 64;
+ let mut output = value.chars().take(MAX_CHARS).collect::<String>();
+ if value.chars().count() > MAX_CHARS {
+ output.push_str("...");
+ }
+ output
}
/// ai-memory `kind` and `tier` for an agentmemory memory `type`.
@@ -659,6 +674,15 @@ mod tests {
assert!(validate_id("sk-1234567890abcdefghijklmnop", "memory").is_err());
}
+ #[test]
+ fn session_ids_display_whole_up_to_the_bound_and_truncated_past_it() {
+ assert_eq!(display_session_id("ses_1"), "ses_1");
+ let exact = "s".repeat(64);
+ assert_eq!(display_session_id(&exact), exact);
+ let long = format!("{exact}tail");
+ assert_eq!(display_session_id(&long), format!("{exact}..."));
+ }
+
#[test]
fn wikilinks_resolve_or_fall_back_to_plain_text() {
let resolve = |target: &str| {
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 0b918c65..7a9b4293 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -150,7 +150,8 @@ async fn replay_prompts(
}
let Some(home) = super::run::native_home(config) else {
eprintln!(
- "ai-memory: no home directory; session {session_id} is finalized without its prompts"
+ "ai-memory: no home directory; session {} is finalized without its prompts",
+ super::run::display_session_id(session_id)
);
return;
};
@@ -166,7 +167,8 @@ async fn replay_prompts(
.await
{
eprintln!(
- "ai-memory: could not replay the prompts of session {session_id} ({error:#}); finalizing without them"
+ "ai-memory: could not replay the prompts of session {} ({error:#}); finalizing without them",
+ super::run::display_session_id(session_id)
);
}
}
diff --git a/crates/ai-memory-cli/src/commands/recovery.rs b/crates/ai-memory-cli/src/commands/recovery.rs
index 5334bcb5..02d9bbad 100644
--- a/crates/ai-memory-cli/src/commands/recovery.rs
+++ b/crates/ai-memory-cli/src/commands/recovery.rs
@@ -1182,10 +1182,10 @@ fn print_report(report: &RecoverReport) {
);
}
for session in &report.sessions {
- let target = session
- .native_session_id
- .as_deref()
- .unwrap_or("(no session id)");
+ let target = session.native_session_id.as_deref().map_or_else(
+ || "(no session id)".to_owned(),
+ super::run::display_session_id,
+ );
let mut line = format!(
" [{}] {} {} in {}/{} — {}",
session.kind,
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index bd79ec51..e6ccdd33 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -3679,7 +3679,11 @@ fn choose_native_session(
}
}
-fn display_session_id(value: &str) -> String {
+/// Render a native session id for terminal output, bounded so a long id
+/// cannot flood the line. CodeQL's `rust/cleartext-logging` barrier model
+/// (`.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml`)
+/// names this function, so every session id the CLI prints goes through it.
+pub(crate) fn display_session_id(value: &str) -> String {
const MAX_CHARS: usize = 64;
let mut output = value.chars().take(MAX_CHARS).collect::<String>();
if value.chars().count() > MAX_CHARS {
diff --git a/crates/ai-memory-cli/src/commands/user.rs b/crates/ai-memory-cli/src/commands/user.rs
index 872482fc..aa231a53 100644
--- a/crates/ai-memory-cli/src/commands/user.rs
+++ b/crates/ai-memory-cli/src/commands/user.rs
@@ -262,13 +262,23 @@ async fn patch(ep: &ServerEndpoint, args: UserPatchArgs) -> Result<()> {
} else {
println!(
"✓ updated user '{}' ({})",
- resp.user.username,
+ display_username(&resp.user.username),
resp.user.status()
);
}
Ok(())
}
+/// The one place a username reaches terminal output unchanged. CodeQL's
+/// sensitive-data heuristic reads any `username` as account information; a
+/// username is the operator-chosen login name, not a credential, and the
+/// `rust/cleartext-logging` barrier model
+/// (`.github/codeql/extensions/ai-memory-models/models/log-barriers.model.yml`)
+/// names this function so printing one here raises no alert.
+fn display_username(value: &str) -> &str {
+ value
+}
+
fn print_temp_password(resp: &UserWithPassword, json: bool, verb: &str) -> Result<()> {
if json {
println!(
diff --git a/crates/ai-memory-cli/tests/suite/repo_layout.rs b/crates/ai-memory-cli/tests/suite/repo_layout.rs
index 91a06191..3ce56a27 100644
--- a/crates/ai-memory-cli/tests/suite/repo_layout.rs
+++ b/crates/ai-memory-cli/tests/suite/repo_layout.rs
@@ -108,6 +108,14 @@ fn codeql_model_targets_exist() {
.parent()
.expect("crates/ lives in the repository root")
.to_path_buf();
+ // Crate name in a model path -> that crate's source root.
+ let crate_roots = [
+ ("ai_memory_cli", crates_dir().join("ai-memory-cli/src")),
+ (
+ "ai_memory_importer",
+ repo_root.join("companions/ai-memory-importer/src"),
+ ),
+ ];
let models_dir = repo_root.join(".github/codeql/extensions/ai-memory-models/models");
let mut targets = 0;
let mut problems = Vec::new();
@@ -116,26 +124,32 @@ fn codeql_model_targets_exist() {
.flatten()
{
let text = fs::read_to_string(entry.path()).expect("read model file");
- for target in text
- .split('"')
- .filter(|token| token.starts_with("ai_memory_cli::"))
- {
+ for token in text.split('"') {
+ let mut segments: Vec<&str> = token.split("::").collect();
+ let Some((_, src)) = crate_roots
+ .iter()
+ .find(|(name, _)| segments.len() > 1 && segments[0] == *name)
+ else {
+ continue;
+ };
targets += 1;
- let mut segments: Vec<&str> = target.split("::").skip(1).collect();
+ segments.remove(0);
let function = segments.pop().expect("a path names a function");
- let file = crates_dir()
- .join("ai-memory-cli/src")
- .join(format!("{}.rs", segments.join("/")));
- let source = fs::read_to_string(&file).unwrap_or_default();
+ let module = segments.join("/");
+ // A module is either `name.rs` or `name/mod.rs`.
+ let source = [format!("{module}.rs"), format!("{module}/mod.rs")]
+ .iter()
+ .find_map(|file| fs::read_to_string(src.join(file)).ok())
+ .unwrap_or_default();
if !source.contains(&format!("fn {function}(")) {
problems.push(format!(
- "{target}: no `fn {function}(` in {}",
- file.display()
+ "{token}: no `fn {function}(` in {}/{module}{{.rs,/mod.rs}}",
+ src.display()
));
}
}
}
- assert!(targets > 0, "the model dir names no ai_memory_cli function");
+ assert!(targets > 0, "the model dir names no modeled function");
assert!(
problems.is_empty(),
"stale CodeQL model targets:\n{}",