Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { existsSync, readFileSync, mkdirSync } from 'fs';
import { dirname, resolve } from 'path';
import { replaceTaggedContent } from './claude-md-utils.js';
import { toBmpSafe } from './bmp-safe.js';
import { writeTextFileAtomic } from '../shared/atomic-json.js';
import { logger } from './logger.js';
export function writeAgentsMd(agentsPath: string, context: string): void {
if (!agentsPath) return;
const resolvedPath = resolve(agentsPath);
if (resolvedPath.includes('/.git/') || resolvedPath.includes('\\.git\\') || resolvedPath.endsWith('/.git') || resolvedPath.endsWith('\\.git')) return;
const dir = dirname(agentsPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
let existingContent = '';
if (existsSync(agentsPath)) {
existingContent = readFileSync(agentsPath, 'utf-8');
}
const contentBlock = `# Memory Context\n\n${context}`;
// #2787: never write astral (surrogate-pair) code points into auto-loaded
// context — a host truncation can split a pair and brick the session. The
// context comes from /api/context/inject, whose observation type markers are
// emoji (modes/*.json), so this is the same input claude-md-utils sanitizes
// for CLAUDE.md and every other writer here already does.
const finalContent = replaceTaggedContent(existingContent, toBmpSafe(contentBlock));
try {
// writeTextFileAtomic resolves a symlinked AGENTS.md to its real target,
// writes via a random exclusive-create temp file, fsyncs, and preserves
// the file's mode. The random name matters: a predictable `${target}.tmp`
// sibling can be planted inside a checkout as a symlink, and a following
// write would then clobber whatever it points at. Failures are logged
// rather than thrown, matching this writer's contract that an unwritable
// target (e.g. a symlink loop) never breaks the caller's session.
writeTextFileAtomic(agentsPath, finalContent);
} catch (error: unknown) {
logger.error('AGENTS_MD', 'Failed to write AGENTS.md', { agentsPath }, error instanceof Error ? error : new Error(String(error)));
}
}