Skip to content

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

Rust

fix(cli): harden untrusted terminal rendering

AkitaOnRails4e32ec54e52c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38e00892..4d313bc9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,11 +15,9 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
-- The `user grants` and `project grants` tables no longer misalign on a
- workspace, project or user name outside ASCII. Column widths were measured
- in bytes while the formatter pads in characters, so a row such as
- `default/café` was padded one column too far and its `USERNAME` and
- `LEVEL` cells sat right of every other row's.
+- The `user grants` and `project grants` tables now measure terminal display
+ cells, so accented and double-width CJK workspace, project and user names
+ keep the `USERNAME` and `LEVEL` columns aligned.
([#1564](https://github.com/akitaonrails/ai-memory/pull/1564))
- Fixed a 3.2.0 regression that serialized local document embedding and
dropped the vector stream from queries that raced a document embed: the
@@ -520,8 +518,8 @@ version in [`docs/changelog/`](docs/changelog/):
security notice and the body between two literal fence lines, neither
escaped, so a newline in the subject forged lines in the provenance block
and an `---- end of body ----` line in the body closed the fence early. The
- subject now renders on one line and the body's fence markers are
- neutralized; both JSON paths were already structural and are unchanged.
+ subject now renders on one line, body fence markers are neutralized, and
+ terminal control sequences are stripped; both JSON paths remain structural.
([#1563](https://github.com/akitaonrails/ai-memory/pull/1563))
- Memory health no longer counts a link from a superseded or TTL-expired page
version as a reference. A page whose only inbound link was removed by a later
diff --git a/crates/ai-memory-cli/src/commands/grant.rs b/crates/ai-memory-cli/src/commands/grant.rs
index e388952d..5748ff2c 100644
--- a/crates/ai-memory-cli/src/commands/grant.rs
+++ b/crates/ai-memory-cli/src/commands/grant.rs
@@ -54,41 +54,48 @@ fn print_grants(grants: &[GrantRow], json: bool) -> Result<()> {
write_grants(grants, &mut std::io::stdout().lock())
}
-/// Lay out the grants table. Widths are measured in characters because
-/// `{:<width$}` pads in characters: a project or user name outside ASCII has
-/// more bytes than columns, and a byte count would shift the later columns of
-/// that row alone. Workspace and project names come from a checkout's
-/// directory basename or a marker's `project` key, so they are free-form
-/// UTF-8.
+/// Lay out the grants table using terminal display-cell widths. Workspace and
+/// project names come from a checkout's directory basename or a marker's
+/// `project` key, so they are free-form UTF-8.
fn write_grants(grants: &[GrantRow], out: &mut impl std::io::Write) -> Result<()> {
let project_w = grants
.iter()
- .map(|g| g.workspace.chars().count() + 1 + g.project.chars().count())
+ .map(|g| {
+ unicode_width::UnicodeWidthStr::width(format!("{}/{}", g.workspace, g.project).as_str())
+ })
.max()
.unwrap_or(7)
.max(7);
let user_w = grants
.iter()
- .map(|g| g.username.chars().count())
+ .map(|g| unicode_width::UnicodeWidthStr::width(g.username.as_str()))
.max()
.unwrap_or(8)
.max(8);
writeln!(
out,
- "{:<project_w$} {:<user_w$} LEVEL",
- "PROJECT", "USERNAME"
+ "{} {} LEVEL",
+ pad_cell("PROJECT", project_w),
+ pad_cell("USERNAME", user_w)
)?;
for g in grants {
let project = format!("{}/{}", g.workspace, g.project);
writeln!(
out,
- "{project:<project_w$} {:<user_w$} {}",
- g.username, g.level
+ "{} {} {}",
+ pad_cell(&project, project_w),
+ pad_cell(&g.username, user_w),
+ g.level
)?;
}
Ok(())
}
+fn pad_cell(value: &str, width: usize) -> String {
+ let padding = width.saturating_sub(unicode_width::UnicodeWidthStr::width(value));
+ format!("{value}{}", " ".repeat(padding))
+}
+
/// `ai-memory user grants [--user NAME]`.
///
/// # Errors
@@ -215,15 +222,10 @@ mod tests {
}
}
- /// The character offset at which `line` carries `username`, or `None`.
+ /// The display-cell offset at which `line` carries `username`, or `None`.
fn username_column(line: &str, username: &str) -> Option<usize> {
- let chars: Vec<char> = line.chars().collect();
- (0..chars.len()).find(|start| {
- chars[*start..]
- .iter()
- .collect::<String>()
- .starts_with(username)
- })
+ line.find(username)
+ .map(|byte| unicode_width::UnicodeWidthStr::width(&line[..byte]))
}
#[test]
@@ -257,5 +259,18 @@ mod tests {
"ascii rows must line up as well:\n{ascii}"
);
}
+
+ let cjk_rows = [grant("記憶管理", "利用者"), grant("web", "bob")];
+ let mut cjk_buf = Vec::new();
+ write_grants(&cjk_rows, &mut cjk_buf).unwrap();
+ let cjk = String::from_utf8(cjk_buf).unwrap();
+ let cjk_user_col = username_column(cjk.lines().next().unwrap(), "USERNAME").unwrap();
+ for (line, row) in cjk.lines().skip(1).zip(cjk_rows.iter()) {
+ assert_eq!(
+ username_column(line, &row.username),
+ Some(cjk_user_col),
+ "{cjk}"
+ );
+ }
}
}
diff --git a/crates/ai-memory-cli/src/commands/message.rs b/crates/ai-memory-cli/src/commands/message.rs
index 42e37698..e34590ad 100644
--- a/crates/ai-memory-cli/src/commands/message.rs
+++ b/crates/ai-memory-cli/src/commands/message.rs
@@ -252,20 +252,26 @@ fn render_popped(
let _ = writeln!(
out,
"Popped message {} for {workspace}/{project}.",
- message.id
+ super::show::terminal_text(&message.id)
);
let _ = writeln!(
out,
" from: {}/{} (agent: {})",
- message.from_workspace_id, message.from_project_id, message.from_agent
+ super::show::terminal_text(&message.from_workspace_id),
+ super::show::terminal_text(&message.from_project_id),
+ super::show::terminal_text(&message.from_agent)
);
if let Some(owner) = message.from_owner_user.as_deref() {
- let _ = writeln!(out, " sent by: {owner}");
+ let _ = writeln!(out, " sent by: {}", super::show::terminal_text(owner));
}
if let Some(subject) = message.subject.as_deref() {
let _ = writeln!(out, " subject: {}", super::show::terminal_text(subject));
}
- let _ = writeln!(out, " created: {}", message.created_at);
+ let _ = writeln!(
+ out,
+ " created: {}",
+ super::show::terminal_text(&message.created_at)
+ );
let _ = writeln!(out, "\n{security_notice}");
let _ = writeln!(out, "{BODY_FENCE_OPEN}");
let _ = writeln!(out, "{}", escape_body_fence(&message.body));
@@ -277,6 +283,16 @@ fn render_popped(
/// — a reader can see what was written — but no longer starts the line, so it
/// cannot be mistaken for the renderer's own fence.
fn escape_body_fence(body: &str) -> String {
+ let body: String = body
+ .chars()
+ .map(|character| {
+ if character == '\n' || character == '\t' || !character.is_control() {
+ character
+ } else {
+ '?'
+ }
+ })
+ .collect();
body.replace(BODY_FENCE_OPEN, &format!("(escaped) {BODY_FENCE_OPEN}"))
.replace(BODY_FENCE_CLOSE, &format!("(escaped) {BODY_FENCE_CLOSE}"))
}
@@ -368,6 +384,15 @@ mod tests {
1,
"only the renderer's own terminator may be a bare fence line: {rendered}"
);
+
+ let controls = render_popped(
+ &message(None, "before\u{1b}[31mred\r\nafter"),
+ "ws",
+ "recipient",
+ "NOTICE",
+ );
+ assert!(!controls.contains('\u{1b}'), "{controls:?}");
+ assert!(controls.contains("before?[31mred?\nafter"), "{controls:?}");
assert_eq!(
lines.last().copied(),
Some(BODY_FENCE_CLOSE),
diff --git a/crates/ai-memory-cli/src/commands/path_util.rs b/crates/ai-memory-cli/src/commands/path_util.rs
index 647b291b..93a6e73b 100644
--- a/crates/ai-memory-cli/src/commands/path_util.rs
+++ b/crates/ai-memory-cli/src/commands/path_util.rs
@@ -92,7 +92,16 @@ pub(crate) fn claude_config_paths(
/// which the canonical data dir carries on Windows and which `cmd` and most
/// scripts cannot use when the path is copied out of a message.
pub(crate) fn display_path(path: &Path) -> String {
- strip_windows_verbatim_prefix(&path.to_string_lossy()).into_owned()
+ strip_windows_verbatim_prefix(&path.to_string_lossy())
+ .chars()
+ .map(|character| {
+ if character.is_control() {
+ '?'
+ } else {
+ character
+ }
+ })
+ .collect()
}
/// Strip only Windows verbatim path prefixes that are safe to render as plain
@@ -184,6 +193,10 @@ mod tests {
display_path(Path::new("/home/alice/.local/share/ai-memory")),
"/home/alice/.local/share/ai-memory"
);
+ assert_eq!(
+ display_path(Path::new("/tmp/line\nbreak")),
+ "/tmp/line?break"
+ );
}
#[test]