How Persona (L3) Represents Long-Term Cognition in the TencentDB Agent

Persona (L3) represents long-term cognition by persisting distilled operational knowledge in a markdown file (persona.md) that is prepended to every LLM system prompt, creating a stable, human-readable "brain" that survives restarts and evolves incrementally from scene data.

The TencentDB-Agent-Memory repository implements a hierarchical memory architecture where raw conversation atoms (L1) aggregate into contextual scenes (L2), which ultimately distill into the Persona (L3) layer. Understanding how Persona (L3) represents long-term cognition is essential for developers building agents that maintain consistent identity across sessions.

The Architecture of Long-Term Cognition

The Persona layer serves as the cornerstone of the agent's long-term cognition, bridging transient short-term context with persistent operational doctrine.

From Scene Data to Persistent Identity

Unlike ephemeral scene blocks (L2) that capture recent interaction contexts, the Persona layer accumulates high-level knowledge across all historical scenes. According to the TencentDB-Agent-Memory source code, this layer is constructed from accumulated scene data (L2) and distilled into a structured markdown document located at persona.md in the data directory.

The system employs incremental generation: the PersonaGenerator reads the scene index (scene_blocks) and filters for blocks that have changed since the last persona timestamp (last_persona_time). Only these changed scenes are fed to the LLM, making generation efficient and allowing the persona to evolve gradually without re-processing the entire knowledge base.

Dual-Purpose Design

The persona.md file serves two complementary functions that define long-term cognition:

  1. Persistent long-term profile – The file captures the user/team's operating doctrine, preferences, and high-level knowledge that persists across sessions. It is updated only when a generation trigger fires (managed by PersonaTrigger) and is never regenerated on every request, preserving a stable "identity".

  2. System-prompt injection – When processing requests, the MemoryCore pipeline prepends the persona content (minus the scene-navigation footer) to the system prompt via composeMemorySystemPrompt. This supplies the LLM with concise, KV-cache-friendly context so every conversation starts from the same long-term grounding.

The Persona Generation Pipeline

Long-term cognition requires careful orchestration to balance freshness with stability. The generation pipeline evaluates necessity, processes changes incrementally, and maintains checkpoint integrity.

Trigger Evaluation with PersonaTrigger

The PersonaTrigger class in /MemoryCore/src/core/persona/persona-trigger.ts inspects the checkpoint (recall_checkpoint.json) and the presence/health of the persona file to determine if regeneration is required. It evaluates five prioritized conditions:

  • Explicit request
  • Cold-start (no existing persona)
  • Recovery mode
  • First scene block creation
  • Threshold of new memories accumulated
import { PersonaTrigger } from './MemoryCore/src/core/persona/persona-trigger.js';

const trigger = new PersonaTrigger({
  dataDir: '/data/memory',
  interval: 100,               // generate after 100 new memories
  logger: console,
});

const { should, reason } = await trigger.shouldGenerate();
if (should) {
  console.log('Persona needs regeneration:', reason);
}

Only when shouldGenerate returns true does the system proceed to update the long-term cognition layer, preventing unnecessary KV-cache churn.

Incremental Scene Processing

Once triggered, the PersonaGenerator performs scene change detection by comparing current scene blocks against last_persona_time. The buildPersonaPrompt function in /MemoryCore/src/core/prompts/persona-generation.ts constructs a system prompt containing:

  • The existing persona (if any)
  • A summary of changed scenes
  • Meta-parameters such as total processed items and current time

This incremental approach ensures that long-term cognition evolves gradually without the computational overhead of re-summarizing unchanged historical data.

LLM Execution and Checkpoint Updates

The generation process utilizes CleanContextRunner to execute the LLM, which writes the updated persona.md directly using tools. Post-processing strips navigation footers, sanitizes XML tags, and appends fresh scene navigation via generateSceneNavigation before persisting.

After successful write, CheckpointManager.markPersonaGenerated records the new last_persona_at and last_persona_time timestamps in /MemoryCore/src/utils/checkpoint.ts. These checkpoints enable future triggers to perform accurate differential updates.

import { PersonaGenerator } from './MemoryCore/src/core/persona/persona-generator.js';

const generator = new PersonaGenerator({
  dataDir: '/data/memory',
  config: {/* OpenClaw config */},
  logger: console,
  backupCount: 5,
});

const updated = await generator.generateLocalPersona('scene updates detected');
if (updated) {
  console.log('Persona regenerated successfully.');
}

Generation latency and persona length are reported via reportL3LatencyMetrics to monitor the health of long-term cognition.

Runtime Consumption of Long-Term Memory

During inference, the agent must efficiently inject long-term cognition without bloating the context window or polluting the semantic space.

System Prompt Composition

When an agent processes a request, the pipeline loads the persona file via StorageAdapter or local filesystem, then calls stripSceneNavigation to retain only the core persona content. The composeMemorySystemPrompt function merges this cleaned persona with custom memory-prompt configurations:

import { readFile } from 'fs/promises';
import { stripSceneNavigation } from './MemoryCore/src/core/scene/scene-navigation.js';
import { composeMemorySystemPrompt } from './MemoryCore/src/core/memory-prompt/composer.js';

async function getSystemPrompt() {
  const raw = await readFile('/data/memory/persona.md', 'utf-8');
  const persona = stripSceneNavigation(raw).trim();      // keep only core persona
  const basePrompt = `You are an assistant...`;
  return composeMemorySystemPrompt(basePrompt, undefined, persona);
}

This ensures the model sees the same high-level persona before any transient dialogue, effectively treating Persona (L3) as a stable "brain" while mutable scene (L2) and atom (L1) layers capture short-term context.

The stripSceneNavigation utility in /MemoryCore/src/core/scene/scene-navigation.ts removes the scene-navigation footer appended during generation, preventing the LLM from conflating navigation metadata with core identity knowledge. This clean separation ensures that only substantive long-term cognition enters the KV cache.

Why Persona (L3) Defines Long-Term Cognition

The implementation details in TencentDB-Agent-Memory demonstrate five key characteristics that establish Persona (L3) as the definitive long-term cognition layer:

  • Persistence – Stored as a markdown file on disk (persona.md), surviving container restarts and shared across agents in the same team.

  • Stability – Generated only when significant changes happen (trigger logic), avoiding KV-cache churn and preserving the model's long-term "memory" of the user's operational context.

  • Incremental Evolution – The generator receives only changed scene blocks, allowing the persona to evolve gradually without re-processing the entire knowledge base.

  • Metric Tracking – Generation latency and persona length are reported (reportL3LatencyMetrics) to monitor the health of long-term cognition.

  • Human-Readable – The persona is a markdown document that can be reviewed, edited, and version-controlled, giving developers explicit control over the agent's long-term behavior.

Summary

  • Persona (L3) represents long-term cognition as a persistent markdown file (persona.md) that survives restarts and serves as the agent's stable identity.
  • The PersonaTrigger class in /MemoryCore/src/core/persona/persona-trigger.ts evaluates five conditions to determine when regeneration is necessary, balancing freshness with computational efficiency.
  • Incremental generation processes only changed scene blocks since the last checkpoint, enabling efficient evolution of long-term knowledge.
  • At runtime, the MemoryCore pipeline injects the persona into system prompts via composeMemorySystemPrompt, creating consistent context for every interaction.
  • The architecture separates core persona content from transient scene navigation, ensuring KV-cache-friendly operation.

Frequently Asked Questions

How does Persona (L3) differ from Scene (L2) memory?

Scene (L2) memory captures recent, contextual interaction blocks that represent short-term working memory, while Persona (L3) distills accumulated scene data into a stable, long-term profile. The persona persists across sessions and is only updated when trigger conditions are met, whereas scenes update continuously with new interactions.

What triggers a Persona regeneration in TencentDB Agent?

According to /MemoryCore/src/core/persona/persona-trigger.ts, regeneration triggers include explicit user requests, cold-start scenarios (no existing persona), recovery modes, the creation of the first scene block, or accumulating a threshold of new memories (e.g., 100 new items). The shouldGenerate() method evaluates these conditions in priority order.

Is the persona.md file human-editable?

Yes. The persona is stored as a human-readable markdown document that developers can review, edit, and version-control. This design gives teams explicit control over the agent's long-term behavior and operational doctrine, though manual edits should respect the file structure expected by stripSceneNavigation and composeMemorySystemPrompt.

How does the persona maintain low latency during inference?

The persona achieves low latency by being pre-computed and static during inference—unlike real-time retrieval systems, it is read once from disk and prepended to the system prompt. The stripSceneNavigation function ensures only essential content enters the KV cache, and the incremental generation strategy prevents regeneration delays from blocking requests.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →