Skip to main content

agentmux_srv/server/
native_memory_diff.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The line diff Memory's history views show, for Personal and Global
5//! Memory alike (`native_memory_handlers`, `app_api::global_memory`).
6
7/// Cap on the LCS table's cell COUNT (from_lines.len() * to_lines.len()),
8/// not on either side's line count independently — reagent P1: the
9/// original per-side-only cap (20,000 lines each) bounded neither
10/// dimension against the other, so two files each under that cap could
11/// still produce a ~3.2GB `usize` table (20_000 * 20_000 * 8 bytes) in the
12/// shared agentmux-srv process. 4,000,000 cells keeps the table under
13/// ~32MB (`* size_of::<usize>()`) regardless of how the two side lengths
14/// are distributed — generous for memory files (markdown notes, not logs)
15/// while still bounded for any combination of sizes.
16const MAX_DIFF_CELLS: usize = 4_000_000;
17
18/// A minimal unified-diff-style line comparison: longest-common-subsequence
19/// based, output lines prefixed `"  "` (context), `"- "` (removed, `from`
20/// only), or `"+ "` (added, `to` only). No `@@` hunk headers or context
21/// trimming in v1 — every line is included, which is fine for memory files.
22pub(crate) fn line_diff(from: &str, to: &str) -> String {
23    let from_lines: Vec<&str> = from.lines().collect();
24    let to_lines: Vec<&str> = to.lines().collect();
25
26    if from_lines.len().saturating_mul(to_lines.len()) > MAX_DIFF_CELLS {
27        return format!(
28            "(diff omitted: {} x {} lines exceeds the {MAX_DIFF_CELLS}-cell comparison cap)",
29            from_lines.len(),
30            to_lines.len(),
31        );
32    }
33
34    let n = from_lines.len();
35    let m = to_lines.len();
36    let cols = m + 1;
37    // A single flat allocation, not `n + 1` separate `Vec<usize>` rows —
38    // reagent P2: MAX_DIFF_CELLS bounds the cell COUNT (n * m), but a
39    // maximally lopsided diff (e.g. ~4,000,000 short lines vs. 1 line)
40    // stays under that cap while `vec![vec![...]; n + 1]` would still
41    // perform ~4,000,001 individual heap allocations — one per row — whose
42    // allocator overhead and allocation-count latency dwarf the actual
43    // cell-data cost the cap was meant to bound. lcs[i][j] (length of the
44    // longest common subsequence of from_lines[i..] and to_lines[j..])
45    // lives at flat index i * cols + j.
46    let mut lcs = vec![0usize; (n + 1) * cols];
47    let idx = |i: usize, j: usize| i * cols + j;
48    for i in (0..n).rev() {
49        for j in (0..m).rev() {
50            lcs[idx(i, j)] = if from_lines[i] == to_lines[j] {
51                lcs[idx(i + 1, j + 1)] + 1
52            } else {
53                lcs[idx(i + 1, j)].max(lcs[idx(i, j + 1)])
54            };
55        }
56    }
57
58    let mut out = String::new();
59    let (mut i, mut j) = (0, 0);
60    while i < n && j < m {
61        if from_lines[i] == to_lines[j] {
62            out.push_str("  ");
63            out.push_str(from_lines[i]);
64            out.push('\n');
65            i += 1;
66            j += 1;
67        } else if lcs[idx(i + 1, j)] >= lcs[idx(i, j + 1)] {
68            out.push_str("- ");
69            out.push_str(from_lines[i]);
70            out.push('\n');
71            i += 1;
72        } else {
73            out.push_str("+ ");
74            out.push_str(to_lines[j]);
75            out.push('\n');
76            j += 1;
77        }
78    }
79    while i < n {
80        out.push_str("- ");
81        out.push_str(from_lines[i]);
82        out.push('\n');
83        i += 1;
84    }
85    while j < m {
86        out.push_str("+ ");
87        out.push_str(to_lines[j]);
88        out.push('\n');
89        j += 1;
90    }
91    out
92}