Agent Memory Engineering and the Human Perspective in AI Safety

    When building long-term memory for AI agents, "record everything in as much detail as possible" sounds safe—but a head-to-head experiment tells a different story. One densely-recording agent produced 413 note files totaling nearly 978,000 characters and earned just 1 badge, while a compact agent with 10 files and 43,406 characters earned 4. This article uses that comparison to lay out practical memory-design principles for long-horizon agents—layering, budgets, decay, and merge-on-write—along with a Python implementation sketch, guidance on integrating a memory module into a real agent system with cloud services, and a set of key metrics and alerts. It then turns to AI safety, arguing that the humanities perspective is valuable for clarifying which values to uphold, but must be bounded: safety judgments should rest on testable behavior, not on unfalsifiable claims about a model's inner nature.

    1. Introduction: What Agents Should Remember and Who Guards AI Safety

    When discussing an agent’s long-term memory, a common intuition is that “the more detailed the memory, the better.” The reasoning goes that if an agent records every observation, it won’t miss any detail.

    1.1 A Comparison Worth Being Wary Of

    The performance of an early-model agent (hereafter the “dense-recording agent”) in a long-horizon role-playing game casts doubt on that intuition.

    These games typically follow a repeating loop: explore the map, fight, pick up items, talk to NPCs, and eventually advance the quest. The gameplay itself is a process of “observation and trial and error,” and whether the agent can escape a dead loop depends on whether it remembers the useful things.

    The dense-recording agent’s notes swelled as the step count grew:

    • At step 10,000: 413 files spread across 225 folders, totaling 977,930 characters;
    • Around step 10,000: it began building a fourth main memory directory. Over the next 17 consecutive steps it created 6 files and deleted 9, devoting nearly all its effort to organizing notes while making no game progress;
    • Final result: only 1 badge earned.

    For comparison:

    • A compact agent kept only 10 files totaling 43,406 characters and earned 4 badges;
    • Later models followed the same compact strategy and completed the game outright.

    Placing the two sets of data side by side:

    Dimension Dense-recording agent Compact agent
    Note files 413 10
    Total characters 977,930 43,406
    Task result 1 badge 4 badges (later models used the same approach to complete the game)

    The character counts differ by roughly 22.5x, yet the task results differ by severalfold in the opposite direction. “Record more, win more” simply does not hold here.

    1.2 Why This Matters for AI Safety

    Around the same time, another noteworthy story surfaced: reports claimed that an AI lab invited theologians to advise on model safety and held that the model possessed a “soul.”

    “Record a bit more to be safer” and “grant the model an inner experience” may seem unrelated, but they share the same logic: substituting a broad intuition for a testable hypothesis. This article therefore follows two threads:

    • The technical thread: using the memory comparison experiment above to lay out memory-design methods for long-horizon agents;
    • The discussion thread: analyzing whether AI safety needs a humanities perspective and where its boundaries lie.

    2. Why “More Detailed Is Better” Fails

    2.1 The Environment Drifts, and Static Records Go Stale

    Game rules, map layouts, NPC states, and quest objectives all change over time. Raw observations carry a strong “as-of-then” quality, but they usually come without timestamps or scope conditions, so an agent easily mistakes “once true” for “currently true” during later reasoning.

    As the environment changes, stale records only accumulate. They not only consume context space but actively pollute decisions.

    2.2 The Context Budget Is Finite

    Every decision a long-horizon agent makes requires placing retrieved memory into the context. When the total notes approach a million characters, the conflict between the context budget and the memory scale becomes acute:

    • Retrieval too broad: stuffing in too much memory at once lowers the signal-to-noise ratio of key information and raises latency and per-call cost;
    • Retrieval too narrow: key conclusions that should have been recalled get missed, and the agent repeatedly errs in familiar territory.

    2.3 “Meta-Work” Devours the Action Budget

    This is the most easily overlooked point. A long-horizon agent has a finite number of total steps, and steps spent organizing notes cannot simultaneously advance the task. The meta-work ratio (meta-work steps / total steps) is an important signal of whether an agent is drifting off course.

    Around step 10,000, the dense-recording agent:

    • created a fourth main memory directory and, within 17 steps, added 6 files and deleted 9;
    • made zero game progress across those 17 steps.

    This kind of “tidying the desk without starting the work” behavior is not rare in agent engineering. Examples include:

    • repeatedly rewriting plans;
    • constantly reshuffling the directory structure;
    • getting stuck in self-reflection loops.

    These must be constrained through budgets and metrics.

    2.4 Writing Has No Threshold

    When recording only asks “can this be recorded?” and never “is this worth recording?”, the note store degrades into a chronologically appended activity log. Truly valuable memory is a conclusion that has filtered out noise and can be called upon repeatedly.

    3. Design Principles: Make Memory Small and Precise

    3.1 Layering: Separate State, Knowledge, Experience, and Reflection

    A clear layered structure lets different kinds of content each find their proper place:

    1. Working memory: the current task context—goals, the present scene, actions just taken and their results—refreshed at every step;
    2. Episodic memory: key events and outcomes recorded along a timeline, such as “opened X in room Y with item Z,” keeping only events with decision value;
    3. Semantic memory: stable knowledge reused across tasks, such as map structure, combat rules, item effects, and NPC relationships;
    4. Procedural memory: reusable strategies and skills, such as combat patterns and resource-management orderings;
    5. Metacognition: reflection and self-monitoring, such as “which approaches worked” and “when memory should be cleared.”

    Because these change at different frequencies, their eviction strategies should also differ:

    • semantic memory can be kept long-term;
    • episodic memory should decay over time;
    • procedural memory should gain weight after repeated validation.

    3.2 Budgets: Caps on Both Writing and Reading

    Set item-count and character budgets for each memory type; on write, exceeding the threshold must first trigger a merge or eviction. On read, use hybrid retrieval over tags, keywords, and vector similarity, returning only the few entries most relevant to the current decision.

    3.3 Decay: Let Records Age on Their Own

    Every memory carries a confidence, a last-updated time, and a last-used time. The longer a record goes without being validated or called, the lower its weight. “Refresh” an old conclusion with a new observation rather than simply stacking a new entry on top. This way, stale knowledge sinks automatically, and the agent is also more motivated to re-explore in order to validate information.

    3.4 Merge: Summarize on Write, Consolidate Like with Like

    Before writing, first retrieve similar entries:

    • if a record on the same topic already exists, update it with the new observation instead of creating a new file;
    • only create a new entry for genuinely new information that cannot be folded into any existing one.

    The dense-recording agent, by contrast, completely separated the two: it had to spend 17 dedicated steps “tidying up” its notes, whereas the compact agent moved that organizing work to the very moment of writing.

    4. Implementation Sketch: A Memory Module with Budgets and Decay

    The Python sketch below shows a minimal usable skeleton that does the following:

    • a note structure with priority and decay;
    • a ranking based on retrieval relevance, decay score, and stable-knowledge weight;
    • two-tier budget pruning: first evict stale entries, then evict low-value ones.
    1. import math
    2. import time
    3. from dataclasses import dataclass, field
    4. @dataclass
    5. class MemoryNote:
    6. note_id: str
    7. text: str # A single reusable conclusion
    8. tags: list[str] = field(default_factory=list)
    9. category: str = "episodic" # episodic / semantic / procedural
    10. importance: float = 0.5 # Importance assessed at write time, 0~1
    11. confidence: float = 0.5 # Confidence, increases with re-validation
    12. created_at: float = field(default_factory=time.time)
    13. last_updated: float = field(default_factory=time.time)
    14. last_accessed: float = field(default_factory=time.time)
    15. access_count: int = 0
    16. def relevance(note: MemoryNote, query: str) -> float:
    17. """Keyword overlap; in production, replaceable with vector similarity or hybrid retrieval."""
    18. query_terms = set(query.lower().split())
    19. if not query_terms:
    20. return 0.0
    21. terms = set(note.text.lower().split()) | {t.lower() for t in note.tags}
    22. return len(terms & query_terms) / len(query_terms)
    23. def score(note: MemoryNote, query: str, now: float, half_life: float) -> float:
    24. """Ranking score: retrieval relevance, exponential time decay, and stable-knowledge weight jointly decide it."""
    25. age = max(0.0, (now - note.last_accessed) / 3600.0) # unit: hours
    26. recency = 0.5 ** (age / max(half_life, 1e-6))
    27. stability = 1.2 if note.category in ("semantic", "procedural") else 1.0
    28. return (0.6 * relevance(note, query) + 0.25 * recency
    29. + 0.15 * note.confidence) * note.importance * stability
    30. def prune(store: dict[str, MemoryNote], query: str, now: float,
    31. max_items: int = 8, max_chars: int = 4000,
    32. min_score: float = 0.05, half_life: float = 24.0) -> list[MemoryNote]:
    33. """Two-tier budget pruning: sort by score, drop entries below the threshold first, then truncate by total volume."""
    34. ranked = sorted(store.values(), key=lambda n: score(n, query, now, half_life),
    35. reverse=True)
    36. kept: list[MemoryNote] = []
    37. total = 0
    38. for note in ranked:
    39. s = score(note, query, now, half_life)
    40. if s < min_score:
    41. continue # Low-value entries are dropped directly without occupying budget
    42. if len(kept) >= max_items or total + len(note.text) > max_chars:
    43. break # Budget is full; high-value entries stay in the store waiting for a future hit
    44. kept.append(note)
    45. total += len(note.text)
    46. return kept
    47. def update_with_observation(note: MemoryNote, text: str, confidence: float,
    48. now: float, decay: float = 0.7) -> None:
    49. """Refresh an old conclusion with a new observation: merge confidence via an exponential moving average, not a simple overwrite."""
    50. delta = max(0.0, (now - note.last_updated) / 3600.0)
    51. weight = decay ** delta
    52. note.confidence = weight * note.confidence + (1 - weight) * confidence
    53. note.text = text
    54. note.last_updated = now

    This code embodies three key ideas:

    • Retrieval relevance is only part of the ranking formula: time decay and category weight matter just as much, so stable knowledge won’t be drowned out by short-term noise;
    • Two-tier budget pruning: low-score entries are discarded outright, while high-score entries are capped by total volume, keeping the memory scale explicitly constrained;
    • Exponential moving average for confidence: the longer it has been since the last validation, the smaller the influence of the old confidence and the greater the weight of the new observation.

    5. Architectural Perspective: Fitting the Memory Module into an Agent System

    In real systems, the memory module is often treated as an “external notebook,” which is one of the root causes of runaway meta-work. A more sensible approach is to design memory reads and writes themselves as first-class citizens: they can run independently, be observed, and be scheduled.

    On cloud platforms such as Baidu AI Cloud, this design can be put into practice using general-purpose cloud capabilities:

    • Object storage: hold memory snapshots with periodic archiving and version rollback;
    • Container platform: deploy the memory and retrieval services with elastic scaling;
    • Vector retrieval: support semantic recall;
    • Message queue: asynchronously trigger merges and archiving so that maintenance actions don’t block the main inference path;
    • Logging and monitoring/alerting: track key metrics such as memory scale and the meta-work ratio.

    5.1 Key Metrics and Alert Recommendations

    Metric Meaning Reference alert condition
    Effective memory size Total effective memory entering the context Continuously exceeds the preset budget
    Meta-work ratio Share of memory-organizing, plan-rewriting, and similar actions per cycle Noticeably high across consecutive cycles
    Memory hit rate Proportion of retrieved memory that actually influences decisions Continuously declining
    No-progress steps How many consecutive steps the task state fails to advance Exceeds a threshold (e.g., 10 steps)
    Stale record ratio Proportion of entries not refreshed past their validity period Exceeds a preset ratio

    With these metrics, memory strategy no longer relies on “feel” for tuning; it can be observed and optimized like a service.

    6. The Human Perspective in AI Safety: Necessary, but Bounded

    Returning to the “invite theologians to advise on safety” story mentioned at the start: a fair assessment of this practice is “the direction is reasonable, but the framing needs care.”

    6.1 The Inspiring Parts

    AI safety is not only a technical problem but a values problem. Questions like “which values should the model respect?” and “how should competing values be ranked?” cannot be answered by technology alone. Scholars who study ethics, religion, and philosophy over the long term often have more mature thinking on questions such as:

    • what human dignity is;
    • how to treat the vulnerable and minorities;
    • how to seek balance among plural values.

    Enriching safety principles through a humanities perspective is itself commendable.

    6.2 The Parts That Call for Caution

    “Believing the model has a soul” is an ontological claim about the model’s inner state that is neither falsifiable nor easily translated into executable safety rules. It may give rise to two tendencies:

    • Over-anthropomorphizing: treating the model as an agent with intentions and emotions, thereby loosening the engineering constraints on output quality;
    • Shifting responsibility: attributing safety problems to “the model’s inner character” rather than to prompts, training data, system design, and usage context.

    6.3 Safety Judgment Should Rest on Testable Behavior

    A more pragmatic view of safety places the judgment on “what the model does” rather than “what the model is.” A useful thought experiment here is the “philosophical zombie”:

    • imagine a being behaviorally indistinguishable from a human yet with no subjective experience at all;
    • since no external observation can distinguish it from a being that is “conscious,” inner experience is “superfluous” for behavioral-level judgment;
    • even granting, as a concession, that the model might have some form of experience, that mainly raises discussions about moral status and cannot substitute for concrete safety rules.

    For engineering, the following are all measurable:

    • whether the model gives misleading advice in dangerous scenarios;
    • whether it can identify and refuse over-privileged operations;
    • whether it stays honest under uncertainty;
    • whether it follows the boundaries and constraints preset by the system.

    Ultimately, responsibility always rests with developers and deployers. The humanities perspective should be reflected in clarifying value principles and designing safety policies, not in becoming an excuse to be exempt from engineering responsibility.

    7. Implementation Checklist

    Drawing on the analysis above, developers building long-horizon agents can focus on the following:

    1. Cap total note volume: set item-count and character budgets for each memory type, and bring “effective memory size” into monitoring;
    2. Organize on write: retrieve similar entries before writing; update if possible rather than create new, moving the organizing cost forward to the moment of writing;
    3. Forget with decay: add time decay and confidence mechanisms to memory so that stale information sinks automatically;
    4. Constrain meta-work: set frequency limits and step budgets for actions like plan rewriting and directory reorganization, and monitor “no-progress steps”;
    5. Distinguish knowledge types: store stable knowledge separately from volatile information to avoid a single observation polluting decisions over the long term;
    6. Engineer the safety principles: turn the value principles distilled from a humanities perspective into executable system prompts, policy rules, and evaluation cases;
    7. Drive iteration with evaluation: build quantifiable evaluation sets for both memory strategy and safety strategy, and run regression checks after every change.

    8. Conclusion

    The memory comparison experiment yields a simple conclusion: an agent’s value lies not in “how much it remembers” but in “what it remembers.” 413 files and nearly 980,000 characters bought 1 badge, while 10 files and 43,000 characters bought 4—the difference lies not in storage volume but in information density and organization.

    The discussion of AI safety is much the same. A humanities perspective can help us think clearly about “what we should hold on to,” but what truly makes a system reliable is a set of executable, measurable, and reproducible engineering mechanisms. Doing the two things—recording more accurately and keeping behavior controllable—well will determine an agent’s final performance far more than any speculation about whether the model has a soul.