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

8.0 KB
Raw Blame

import os from 'os';
import path from 'path';
import { logger } from '../utils/logger.js';

export function parseJsonArray(json: string | null): string[] {
  if (!json) return [];
  try {
    const parsed = JSON.parse(json);
    return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : [];
  } catch (err: unknown) {
    logger.debug('PARSER', 'Failed to parse JSON array, using empty fallback', {
      preview: json?.substring(0, 50)
    }, err instanceof Error ? err : new Error(String(err)));
    return [];
  }
}

// Some runtimes (Bun/JavaScriptCore on Windows with an unresolvable system time
// zone) throw `failed to initialize DateTimeFormat` from toLocale* calls. These
// helpers run inside the session-start context build, so a throw there loses the
// whole memory injection. Fall back to a fixed date/time instead of failing.
function guardInvalid(date: Date, build: (date: Date) => string): string {
  if (Number.isNaN(date.getTime())) return 'Invalid Date';
  return build(date);
}

// The 12-hour clock the folder-timeline parser (claude-md-utils) reads back: it
// matches only `H:MM AM/PM`, so a 24-hour fallback would drop the row's time and
// leave it at the day header's midnight. Uses UTC because the local zone is the
// thing that failed.
function isoClock(date: Date): string {
  const hours = date.getUTCHours();
  const period = hours < 12 ? 'AM' : 'PM';
  const minutes = date.getUTCMinutes().toString().padStart(2, '0');
  return `${hours % 12 || 12}:${minutes} ${period}`;
}

function isoDay(date: Date): string {
  return date.toISOString().slice(0, 10);
}

function safeFormat(format: () => string, fallback: () => string): string {
  try {
    return format();
  } catch (err: unknown) {
    logger.debug('PARSER', 'Locale date formatter unavailable, using ISO fallback', {},
      err instanceof Error ? err : new Error(String(err)));
    return fallback();
  }
}

const DATE_TIME_OPTIONS: Intl.DateTimeFormatOptions = {
  month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true,
};
const TIME_OPTIONS: Intl.DateTimeFormatOptions = {
  hour: 'numeric', minute: '2-digit', hour12: true,
};
const DATE_OPTIONS: Intl.DateTimeFormatOptions = {
  month: 'short', day: 'numeric', year: 'numeric',
};

/**
 * Reuse ICU formatters within one timeline render. Construct lazily so an
 * empty timeline does no locale work, and never share them across requests:
 * a later render must observe the current system time zone.
 */
export function createTimelineDateFormatters() {
  const cached = (options: Intl.DateTimeFormatOptions, fallback: (date: Date) => string) => {
    let formatter: Intl.DateTimeFormat | undefined;
    return (dateInput: string | number): string => {
      const date = new Date(dateInput);
      return guardInvalid(date, d => safeFormat(
        () => (formatter ??= new Intl.DateTimeFormat('en-US', options)).format(d),
        () => fallback(d),
      ));
    };
  };
  return {
    formatDate: cached(DATE_OPTIONS, isoDay),
    formatTime: cached(TIME_OPTIONS, isoClock),
    formatDateTime: cached(DATE_TIME_OPTIONS, d => `${isoDay(d)} ${isoClock(d)}`),
  };
}

export function formatDateTime(dateInput: string | number): string {
  const date = new Date(dateInput);
  return safeFormat(
    () => date.toLocaleString('en-US', DATE_TIME_OPTIONS),
    () => guardInvalid(date, d => `${isoDay(d)} ${isoClock(d)}`)
  );
}

export function formatTime(dateInput: string | number): string {
  const date = new Date(dateInput);
  return safeFormat(
    () => date.toLocaleString('en-US', TIME_OPTIONS),
    () => guardInvalid(date, isoClock)
  );
}

/**
 * Shorten a formatTime() clock ("3:05 PM" -> "3:05p"). ICU 72+ (Node 20+,
 * recent Bun) puts U+202F NARROW NO-BREAK SPACE before the meridiem, so the
 * separator is matched as any whitespace rather than a literal space.
 */
export function compactTime(time: string): string {
  return time.toLowerCase().replace(/\s+([ap])m\b/g, '$1');
}

export function formatDate(dateInput: string | number): string {
  const date = new Date(dateInput);
  return safeFormat(
    () => date.toLocaleString('en-US', DATE_OPTIONS),
    () => guardInvalid(date, isoDay)
  );
}

/**
 * The system locale's date and time, exactly as a bare toLocaleString() prints
 * it, for records that can be from any year (search results, session context).
 * Guarded like the helpers above: on a host whose formatter cannot initialize,
 * an ISO date and a UTC clock.
 */
export function formatSystemLocaleDateTime(dateInput: string | number): string {
  const date = new Date(dateInput);
  return safeFormat(
    () => date.toLocaleString(),
    () => guardInvalid(date, d => `${isoDay(d)} ${isoClock(d)} UTC`)
  );
}

export function formatHeaderDateTime(now: Date = new Date()): string {
  return safeFormat(
    () => {
      const date = now.toLocaleDateString('en-CA');
      const time = now.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true
      }).toLowerCase().replace(/\s+/g, '');
      const tz = now.toLocaleTimeString('en-US', { timeZoneName: 'short' }).split(' ').pop();
      return `${date} ${time} ${tz}`;
    },
    () => guardInvalid(now, d => `${isoDay(d)} ${isoClock(d)} UTC`)
  );
}

function isInside(relative: string): boolean {
  return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}

/**
 * How a file is labelled in context and search output: relative to the
 * project when it lives inside it, otherwise `~/...` when it lives under the
 * home directory. A file outside the project (`~/.ssh/config`, `~/.gemini/...`)
 * would otherwise render as a long `../../../../../../` climb that depends on
 * how deep the checkout is and does not say where the file is.
 */
export function toRelativePath(filePath: string, cwd: string, homeDir: string = os.homedir()): string {
  if (!path.isAbsolute(filePath)) {
    return filePath;
  }
  const fromCwd = path.relative(cwd, filePath);
  if (isInside(fromCwd)) {
    // Timeline labels are display text, not filesystem paths. Keep them stable
    // across Windows and POSIX, where path.relative uses different separators.
    return fromCwd.split(path.sep).join('/');
  }
  if (homeDir) {
    const fromHome = path.relative(homeDir, filePath);
    if (fromHome && isInside(fromHome)) {
      return `~/${fromHome.split(path.sep).join('/')}`;
    }
  }
  return filePath;
}

export function extractFirstFile(
  filesModified: string | null,
  cwd: string,
  filesRead?: string | null
): string {
  const modified = parseJsonArray(filesModified);
  if (modified.length > 0) {
    return toRelativePath(modified[0], cwd);
  }

  if (filesRead) {
    const read = parseJsonArray(filesRead);
    if (read.length > 0) {
      return toRelativePath(read[0], cwd);
    }
  }

  return 'General';
}

export function estimateTokens(text: string | null): number {
  if (!text) return 0;
  return Math.ceil(text.length / 4);
}

export interface GroupByDateOptions {
  /**
   * Order of the day groups:
   * - 'asc' (default): oldest day first.
   * - 'desc': newest day first, for date_desc results.
   * - 'first-seen': the order in which each day's first item appears in `items`, so a
   *   relevance-ordered input stays relevance-ordered across day headers.
   */
  order?: 'asc' | 'desc' | 'first-seen';
}

export function groupByDate<T>(
  items: T[],
  getDate: (item: T) => string,
  options: GroupByDateOptions = {}
): Map<string, T[]> {
  const { order = 'asc' } = options;
  const { formatDate } = createTimelineDateFormatters();
  const itemsByDay = new Map<string, T[]>();
  for (const item of items) {
    const itemDate = getDate(item);
    const day = formatDate(itemDate);
    if (!itemsByDay.has(day)) {
      itemsByDay.set(day, []);
    }
    itemsByDay.get(day)!.push(item);
  }

  if (order === 'first-seen') {
    return itemsByDay;
  }

  const sortedEntries = Array.from(itemsByDay.entries()).sort((a, b) => {
    const aDate = new Date(a[0]).getTime();
    const bDate = new Date(b[0]).getTime();
    return order === 'desc' ? bDate - aDate : aDate - bDate;
  });

  return new Map(sortedEntries);
}