Skip to content

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

18.2 KB
Raw Blame

import { existsSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'fs';
import { randomUUID } from 'crypto';
import path from 'path';
import { logger } from './logger.js';
import { ensureDirectoryExists, resolveSymlinkWriteTarget } from '../shared/atomic-json.js';
import { formatDate, groupByDate } from '../shared/timeline-formatting.js';
import { SettingsDefaultsManager } from '../shared/SettingsDefaultsManager.js';
import { workerHttpRequest } from '../shared/worker-utils.js';
import { paths } from '../shared/paths.js';
import { matchesAnyGlob } from './project-filter.js';
import { toBmpSafe } from './bmp-safe.js';
import { parseContextCountValue } from '../shared/context-count.js';
import { CONTEXT_TAG_CLOSE, CONTEXT_TAG_OPEN, findContextBlockRange } from './context-injection.js';

const SETTINGS_PATH = paths.settings();

const CLAUDE_MD_FILENAME = 'CLAUDE.md';

const CLAUDE_LOCAL_MD_FILENAME = 'CLAUDE.local.md';

export function getTargetFilename(settings?: ReturnType<typeof SettingsDefaultsManager.loadFromFile>): string {
  const s = settings ?? SettingsDefaultsManager.loadFromFile(SETTINGS_PATH);
  return s.CLAUDE_MEM_FOLDER_USE_LOCAL_MD === 'true' ? CLAUDE_LOCAL_MD_FILENAME : CLAUDE_MD_FILENAME;
}

function hasConsecutiveDuplicateSegments(resolvedPath: string): boolean {
  const segments = resolvedPath.split(path.sep).filter(s => s && s !== '.' && s !== '..');
  for (let i = 1; i < segments.length; i++) {
    if (segments[i] === segments[i - 1]) return true;
  }
  return false;
}

function isValidPathForClaudeMd(filePath: string, projectRoot?: string): boolean {
  if (!filePath || !filePath.trim()) return false;

  if (filePath.startsWith('~')) return false;

  if (filePath.startsWith('http://') || filePath.startsWith('https://')) return false;

  if (filePath.includes(' ')) return false;

  if (filePath.includes('#')) return false;

  if (projectRoot) {
    // Resolve an absolute path too: on Windows `/repo/src/x.ts` or `C:/repo/src/x.ts`
    // must be compared in the same normalized form as the root, `C:\repo`.
    const resolved = path.resolve(projectRoot, filePath);
    const normalizedRoot = path.resolve(projectRoot);
    if (!resolved.startsWith(normalizedRoot + path.sep) && resolved !== normalizedRoot) {
      return false;
    }

    // Start at the project folder's own name, so a doubled prefix like
    // frontend/frontend still matches (#814) but a project checked out at
    // ~/code/app/app does not reject every path.
    if (hasConsecutiveDuplicateSegments(path.relative(path.dirname(normalizedRoot), resolved))) {
      return false;
    }
  }

  return true;
}

export function replaceTaggedContent(existingContent: string, newContent: string): string {
  const wrappedContent = `${CONTEXT_TAG_OPEN}\n${newContent}\n${CONTEXT_TAG_CLOSE}`;

  if (!existingContent) {
    return wrappedContent;
  }

  const block = findContextBlockRange(existingContent);

  if (block) {
    return existingContent.substring(0, block.start) +
      wrappedContent +
      existingContent.substring(block.end);
  }

  return existingContent + `\n\n${wrappedContent}`;
}

export function writeClaudeMdToFolder(folderPath: string, newContent: string, targetFilename?: string): void {
  const resolvedPath = path.resolve(folderPath);

  if (resolvedPath.includes('/.git/') || resolvedPath.includes('\\.git\\') || resolvedPath.endsWith('/.git') || resolvedPath.endsWith('\\.git')) return;

  const filename = targetFilename ?? getTargetFilename();
  const claudeMdPath = path.join(folderPath, filename);

  if (!existsSync(folderPath)) {
    logger.debug('FOLDER_INDEX', 'Skipping non-existent folder', { folderPath });
    return;
  }

  let existingContent = '';
  if (existsSync(claudeMdPath)) {
    existingContent = readFileSync(claudeMdPath, 'utf-8');
  }

  // #2787: never write astral (surrogate-pair) code points into auto-loaded
  // context — a Claude Code truncation can split a pair and brick the session.
  const finalContent = replaceTaggedContent(existingContent, toBmpSafe(newContent));

  // A symlinked CLAUDE.md stays a symlink: write onto its final target. A
  // symlink loop or an unwritable target throws, as any write failure does.
  const writeTarget = resolveSymlinkWriteTarget(claudeMdPath);
  ensureDirectoryExists(path.dirname(writeTarget));
  // Random name + exclusive create: a predictable `.tmp` sibling can be
  // shipped inside a checkout as a symlink, and a following write would then
  // clobber whatever it points at (the rename only replaces the link itself).
  const tempFile = `${writeTarget}.${randomUUID()}.tmp`;
  writeFileSync(tempFile, finalContent, { flag: 'wx' });
  try {
    renameSync(tempFile, writeTarget);
  } catch (error) {
    try { unlinkSync(tempFile); } catch { /* best effort */ }
    throw error;
  }
}

interface ParsedObservation {
  id: string;
  time: string;
  typeEmoji: string;
  title: string;
  tokens: string;
  epoch: number; 
}

export function formatTimelineForClaudeMd(timelineText: string): string {
  const lines: string[] = [];
  lines.push('# Recent Activity');
  lines.push('');

  const apiLines = timelineText.split('\n');

  const observations: ParsedObservation[] = [];
  let lastTimeStr = '';
  let currentDate: Date | null = null;

  for (const line of apiLines) {
    const dateMatch = line.match(/^###\s+(.+)$/);
    if (dateMatch) {
      const dateStr = dateMatch[1].trim();
      const parsedDate = new Date(dateStr);
      if (!isNaN(parsedDate.getTime())) {
        currentDate = parsedDate;
      }
      continue;
    }

    // The title cell is written verbatim and may itself contain `|`, so it runs
    // up to the Read cell (`~N`, or `-` for sessions) instead of the next pipe.
    const match = line.match(/^\|\s*(#[S]?\d+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*(.+?)\s*\|\s*(~\d+|-)\s*\|/);
    if (match) {
      const [, id, timeStr, typeEmoji, title, tokens] = match;

      let time: string;
      if (timeStr.trim() === '″' || timeStr.trim() === '"') {
        time = lastTimeStr;
      } else {
        time = timeStr.trim();
        lastTimeStr = time;
      }

      const baseDate = currentDate ? new Date(currentDate) : new Date();
      const timeParts = time.match(/(\d+):(\d+)\s*(AM|PM)/i);
      let epoch = baseDate.getTime();
      if (timeParts) {
        let hours = parseInt(timeParts[1], 10);
        const minutes = parseInt(timeParts[2], 10);
        const isPM = timeParts[3].toUpperCase() === 'PM';
        if (isPM && hours !== 12) hours += 12;
        if (!isPM && hours === 12) hours = 0;
        baseDate.setHours(hours, minutes, 0, 0);
        epoch = baseDate.getTime();
      }

      observations.push({
        id: id.trim(),
        time,
        typeEmoji: typeEmoji.trim(),
        title: title.trim(),
        tokens: tokens.trim(),
        epoch
      });
    }
  }

  if (observations.length === 0) {
    return '';
  }

  // Same newest-first day order the by-file route renders; rows inside a day keep the route's order.
  const byDate = groupByDate(observations, obs => new Date(obs.epoch).toISOString(), { order: 'desc' });

  for (const [day, dayObs] of byDate) {
    lines.push(`### ${day}`);
    lines.push('');
    lines.push('| ID | Time | T | Title | Read |');
    lines.push('|----|------|---|-------|------|');

    let lastTime = '';
    for (const obs of dayObs) {
      const timeDisplay = obs.time === lastTime ? '"' : obs.time;
      lastTime = obs.time;
      lines.push(`| ${obs.id} | ${timeDisplay} | ${obs.typeEmoji} | ${obs.title} | ${obs.tokens} |`);
    }

    lines.push('');
  }

  return lines.join('\n').trim();
}

const EXCLUDED_UNSAFE_DIRECTORIES = new Set([
  'res',
  '.git',
  'build',
  'node_modules',
  '__pycache__'
]);

function isExcludedUnsafeDirectory(folderPath: string, projectRoot?: string): boolean {
  // Only directories inside the project count: a project checked out under
  // ~/build or ~/res is not itself an unsafe directory.
  const normalized = path.normalize(projectRoot ? path.relative(projectRoot, folderPath) : folderPath);
  const segments = normalized.split(path.sep);
  return segments.some(segment => EXCLUDED_UNSAFE_DIRECTORIES.has(segment));
}

function isProjectRoot(folderPath: string): boolean {
  const gitPath = path.join(folderPath, '.git');
  return existsSync(gitPath);
}

/**
 * A folder list setting. settings.json is hand-edited JSON, so the list may be
 * saved as a JSON list (`["/path"]`) as well as the JSON text of one (an env
 * override is always text). Anything else counts as an empty list.
 */
function parseFolderListSetting(
  settings: ReturnType<typeof SettingsDefaultsManager.loadFromFile>,
  key: 'CLAUDE_MEM_FOLDER_MD_EXCLUDE' | 'CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST',
): string[] {
  const raw: unknown = settings[key];
  try {
    const parsed: unknown = Array.isArray(raw) ? raw : JSON.parse(typeof raw === 'string' && raw ? raw : '[]');
    if (Array.isArray(parsed)) {
      return parsed.filter((p): p is string => typeof p === 'string');
    }
  } catch {
    logger.warn('FOLDER_INDEX', `Failed to parse ${key} setting`);
  }
  return [];
}

function isExcludedFolder(folderPath: string, excludePaths: string[]): boolean {
  const normalizedFolder = path.resolve(folderPath);
  for (const excludePath of excludePaths) {
    const normalizedExclude = path.resolve(excludePath);
    if (normalizedFolder === normalizedExclude ||
        normalizedFolder.startsWith(normalizedExclude + path.sep)) {
      return true;
    }
  }
  return false;
}

// Folders whose CLAUDE.md mirror update failed and has not succeeded since,
// keyed by project. In-memory only — nothing is persisted or replayed: the
// next observation that touches the folder runs the update again through the
// normal path, and a successful write removes the entry. The set exists so a
// failure is visible state, not only a log line, and so the retry is logged
// as a retry. The set is capped per project: a folder that is never touched
// again would otherwise stay marked for the worker's lifetime. Dropping the
// oldest mark loses only its retry log line — a later observation for that
// folder still runs the update through the normal path.
const MAX_FAILED_FOLDER_CLAUDE_MD_UPDATES_PER_PROJECT = 100;
const failedFolderClaudeMdUpdates = new Map<string, Set<string>>();

function markFolderClaudeMdUpdateFailed(project: string, folderPath: string): void {
  let folders = failedFolderClaudeMdUpdates.get(project);
  if (!folders) {
    folders = new Set<string>();
    failedFolderClaudeMdUpdates.set(project, folders);
  }
  folders.add(folderPath);
  while (folders.size > MAX_FAILED_FOLDER_CLAUDE_MD_UPDATES_PER_PROJECT) {
    const oldest = folders.values().next().value;
    if (oldest === undefined) break;
    folders.delete(oldest);
  }
}

function clearFolderClaudeMdUpdateFailure(project: string, folderPath: string): void {
  const folders = failedFolderClaudeMdUpdates.get(project);
  if (!folders) return;
  folders.delete(folderPath);
  if (folders.size === 0) failedFolderClaudeMdUpdates.delete(project);
}

// Folder updates are independent, so a few run at once. The bound keeps a
// large batch from flooding the worker that also serves live requests.
const FOLDER_UPDATE_CONCURRENCY = 8;

async function runWithConcurrency<T>(
  items: T[],
  limit: number,
  task: (item: T) => Promise<void>
): Promise<void> {
  let next = 0;
  const runNext = async (): Promise<void> => {
    while (next < items.length) {
      await task(items[next++]);
    }
  };
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runNext));
}

export async function updateFolderClaudeMdFiles(
  filePaths: string[],
  project: string,
  projectRoot?: string
): Promise<void> {
  const settings = SettingsDefaultsManager.loadFromFile(SETTINGS_PATH);
  const limit = parseContextCountValue(settings.CLAUDE_MEM_CONTEXT_OBSERVATIONS) ?? 50;
  // A count of 0 means the user wants no observations, so no folder file is fetched or written.
  if (limit === 0) return;
  const targetFilename = getTargetFilename(settings);

  const folderMdExcludePaths = parseFolderListSetting(settings, 'CLAUDE_MEM_FOLDER_MD_EXCLUDE');

  // #2400 — deny-list of glob patterns where an empty/skeleton CLAUDE.md must
  // NOT be injected. Unlike CLAUDE_MEM_FOLDER_MD_EXCLUDE (which excludes the
  // folder entirely), this only suppresses injection when the generated content
  // is empty/skeleton; folders with real activity still get a CLAUDE.md.
  const skeletonDenylistPatterns = parseFolderListSetting(settings, 'CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST');

  const foldersWithActiveClaudeMd = new Set<string>();

  for (const filePath of filePaths) {
    if (!filePath) continue;
    const basename = path.basename(filePath);
    if (basename === CLAUDE_MD_FILENAME || basename === CLAUDE_LOCAL_MD_FILENAME) {
      let absoluteFilePath = filePath;
      if (projectRoot && !path.isAbsolute(filePath)) {
        absoluteFilePath = path.join(projectRoot, filePath);
      }
      const folderPath = path.dirname(absoluteFilePath);
      // Keyed resolved: on Windows one batch can spell the same folder with `\` and `/`.
      foldersWithActiveClaudeMd.add(path.resolve(folderPath));
      logger.debug('FOLDER_INDEX', 'Detected active context file, will skip folder', { folderPath, basename });
    }
  }

  const folderPaths = new Set<string>();
  for (const filePath of filePaths) {
    if (!filePath || filePath === '') continue;
    if (!isValidPathForClaudeMd(filePath, projectRoot)) {
      logger.debug('FOLDER_INDEX', 'Skipping invalid file path', {
        filePath,
        reason: 'Failed path validation'
      });
      continue;
    }
    let absoluteFilePath = filePath;
    if (projectRoot && !path.isAbsolute(filePath)) {
      absoluteFilePath = path.join(projectRoot, filePath);
    }
    const folderPath = path.dirname(absoluteFilePath);
    if (folderPath && folderPath !== '.' && folderPath !== '/') {
      if (isProjectRoot(folderPath)) {
        logger.debug('FOLDER_INDEX', 'Skipping project root CLAUDE.md', { folderPath });
        continue;
      }
      if (isExcludedUnsafeDirectory(folderPath, projectRoot)) {
        logger.debug('FOLDER_INDEX', 'Skipping unsafe directory for CLAUDE.md', { folderPath });
        continue;
      }
      if (foldersWithActiveClaudeMd.has(path.resolve(folderPath))) {
        logger.debug('FOLDER_INDEX', 'Skipping folder with active CLAUDE.md to avoid race condition', { folderPath });
        continue;
      }
      if (folderMdExcludePaths.length > 0 && isExcludedFolder(folderPath, folderMdExcludePaths)) {
        logger.debug('FOLDER_INDEX', 'Skipping excluded folder', { folderPath });
        continue;
      }
      folderPaths.add(folderPath);
    }
  }

  if (folderPaths.size === 0) return;

  const updateFolder = async (folderPath: string): Promise<void> => {
    if (failedFolderClaudeMdUpdates.get(project)?.has(folderPath)) {
      logger.warn('FOLDER_INDEX', 'Retrying CLAUDE.md update for folder whose previous update failed', { folderPath, project });
    }

    let response: Response;
    try {
      // The folder mirror is chronological. An explicit date order keeps the lookup on SQLite.
      response = await workerHttpRequest(
        `/api/search/by-file?filePath=${encodeURIComponent(folderPath)}&limit=${limit}&project=${encodeURIComponent(project)}&isFolder=true&orderBy=date_desc`
      );
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      const stack = error instanceof Error ? error.stack : undefined;
      logger.error('FOLDER_INDEX', `Failed to fetch timeline for ${targetFilename}`, {
        folderPath,
        errorMessage: message,
        errorStack: stack
      });
      markFolderClaudeMdUpdateFailed(project, folderPath);
      return;
    }

    if (!response.ok) {
      logger.error('FOLDER_INDEX', 'Failed to fetch timeline', { folderPath, status: response.status });
      markFolderClaudeMdUpdateFailed(project, folderPath);
      return;
    }

    // Parsing and writing are per-folder steps: a failure here (bad payload,
    // unwritable folder) must not reject the whole update and skip the
    // remaining folders. Log it with the folder, remember the folder, and
    // let the next observation for it retry through the normal path.
    try {
      const result = await response.json() as { content?: Array<{ text?: string }> };
      if (!result.content?.[0]?.text) {
        logger.debug('FOLDER_INDEX', 'No content for folder', { folderPath });
        return;
      }

      const formatted = formatTimelineForClaudeMd(result.content[0].text);

      const claudeMdPath = path.join(folderPath, targetFilename);
      const hasNoActivity = formatted.includes('*No recent activity*');
      const isEmptyOrSkeleton = formatted.trim() === '' || hasNoActivity;
      const fileExists = existsSync(claudeMdPath);

      // #2400 — when the generated content is empty/skeleton AND the folder
      // matches the user's deny-list, never inject (skip even if the file exists,
      // so we don't pollute non-content dirs with empty skeletons).
      if (isEmptyOrSkeleton && matchesAnyGlob(folderPath, skeletonDenylistPatterns)) {
        logger.debug('FOLDER_INDEX', 'Skipping skeleton CLAUDE.md in deny-listed folder', { folderPath, targetFilename });
        return;
      }

      if (isEmptyOrSkeleton && !fileExists) {
        logger.debug('FOLDER_INDEX', 'Skipping empty context file creation', { folderPath, targetFilename });
        return;
      }

      writeClaudeMdToFolder(folderPath, formatted, targetFilename);
      clearFolderClaudeMdUpdateFailure(project, folderPath);

      logger.debug('FOLDER_INDEX', 'Updated context file', { folderPath, targetFilename });
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      const stack = error instanceof Error ? error.stack : undefined;
      logger.error('FOLDER_INDEX', `Failed to update ${targetFilename}; will retry on the next observation for this folder`, {
        folderPath,
        project,
        errorMessage: message,
        errorStack: stack
      });
      markFolderClaudeMdUpdateFailed(project, folderPath);
    }
  };

  const startedAt = Date.now();
  await runWithConcurrency([...folderPaths], FOLDER_UPDATE_CONCURRENCY, updateFolder);
  logger.debug('FOLDER_INDEX', 'Finished CLAUDE.md updates', {
    project,
    folderCount: folderPaths.size,
    durationMs: Date.now() - startedAt
  });
}