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

7.9 KB
Raw Blame
import type { WorkStateEntry, WorkStateFields } from '../../sqlite/work-state.js';
import { describeDuration } from '../../../shared/observer-health.js';
import { relativeTimePlaceholder } from '../../../shared/context-cache.js';
import { isOwnerGoalsList } from '../../work-view/owner-goals.mjs';
import { isMyRulesList } from '../../work-view/my-rules.mjs';
import { isMyFocusList } from '../../work-view/my-focus.mjs';
import { isSharedWorkList } from '../../work-view/shared-records.mjs';
import { isClosedWorkStateStatus } from '../../work-view/work-state-status.mjs';

/**
 * When "updated N ago" is measured from: an epoch, or 'placeholders' to leave
 * the durations as placeholders that `fillContextPlaceholders` measures at read
 * time (the cached SessionStart block, shared/context-cache.ts).
 */
export type WorkStateClock = number | 'placeholders';

/** Keeps the section small enough to leave most of the 10K hook budget to memory. */
export const WORK_STATE_SECTION_CHARACTER_LIMIT = 3_000;

/** Heads the open lists in the SessionStart context; how to use work state is in the MCP server's instructions. */
export const WORK_STATE_SECTION_HEADING = 'Work state, still open:';

export interface FoldedWorkStateList {
  /** Latest value of every key written without a `task`. */
  state: WorkStateFields;
  stateUpdatedAtEpoch: number | null;
  /** Latest fields of each task, in first-seen order. */
  tasks: Map<string, { fields: WorkStateFields; updatedAtEpoch: number }>;
}

/** Replay one list's entries in order; the latest value of each key wins. */
export function foldWorkStateList(entries: WorkStateEntry[]): FoldedWorkStateList {
  const folded: FoldedWorkStateList = { state: {}, stateUpdatedAtEpoch: null, tasks: new Map() };
  for (const entry of entries) {
    const taskName = entry.fields.task;
    if (taskName === undefined || taskName === null || taskName === '') {
      folded.state = { ...folded.state, ...entry.fields };
      folded.stateUpdatedAtEpoch = entry.created_at_epoch;
      continue;
    }
    const taskKey = String(taskName);
    folded.tasks.set(taskKey, {
      fields: { ...folded.tasks.get(taskKey)?.fields, ...entry.fields },
      updatedAtEpoch: entry.created_at_epoch,
    });
  }
  return folded;
}

/** `key=value` pairs; null values are skipped because null clears a key. */
function formatFields(fields: WorkStateFields, omittedKeys: string[]): string {
  return Object.entries(fields)
    .filter(([key, value]) => !omittedKeys.includes(key) && value !== null)
    .map(([key, value]) => `${key}=${String(value)}`)
    .join(', ');
}

function updatedAgo(epoch: number, nowEpoch: WorkStateClock): string {
  const duration = nowEpoch === 'placeholders' ? relativeTimePlaceholder(epoch) : describeDuration(nowEpoch - epoch);
  return `updated ${duration} ago`;
}

/**
 * Lines for one list. A closed list hides its state line but still shows any
 * task left open in it; `includeClosed` shows everything.
 */
export function renderWorkStateList(
  listName: string,
  folded: FoldedWorkStateList,
  nowEpoch: WorkStateClock,
  includeClosed: boolean = false,
): string[] {
  const taskLines = [...folded.tasks.entries()]
    .filter(([, task]) => includeClosed || !isClosedWorkStateStatus(task.fields.status))
    .map(([taskName, task]) => {
      const status = task.fields.status === undefined || task.fields.status === null ? '' : `[${String(task.fields.status)}] `;
      const details = formatFields(task.fields, ['task', 'status']);
      return `  - ${status}${taskName}${details ? ` (${details})` : ''}, ${updatedAgo(task.updatedAtEpoch, nowEpoch)}`;
    });

  const stateFields = formatFields(folded.state, ['task']);
  const showState = stateFields !== '' && (includeClosed || !isClosedWorkStateStatus(folded.state.status));
  if (!showState && taskLines.length === 0) return [];

  // A shown state line always has a state entry behind it; the fallback only satisfies the type.
  const stateUpdatedAtEpoch = folded.stateUpdatedAtEpoch ?? (nowEpoch === 'placeholders' ? 0 : nowEpoch);
  const header = showState
    ? `- ${listName}: ${stateFields}, ${updatedAgo(stateUpdatedAtEpoch, nowEpoch)}`
    : `- ${listName}`;
  return [header, ...taskLines];
}

/** Lines for every list in `entries`, the most recently written list first. */
export function renderWorkStateLines(entries: WorkStateEntry[], nowEpoch: WorkStateClock, includeClosed: boolean = false): string[] {
  entries = entries.filter(entry => !isSharedWorkList(entry.list_name));
  const entriesByList = new Map<string, WorkStateEntry[]>();
  const listProjectCounts = new Map<string, number>();
  /** Position of each list's latest entry in `entries`, which arrive in write order. */
  const lastPositionByList = new Map<WorkStateEntry[], number>();
  entries.forEach((entry, position) => {
    // Checkout aliases share one list; adopted source projects keep separate lists.
    const projectKey = (entry.scope_project ?? entry.project).replace(/[A-Z]/g, character => character.toLowerCase());
    const key = JSON.stringify([projectKey, entry.list_name]);
    let listEntries = entriesByList.get(key);
    if (!listEntries) {
      listEntries = [];
      entriesByList.set(key, listEntries);
      listProjectCounts.set(entry.list_name, (listProjectCounts.get(entry.list_name) ?? 0) + 1);
    }
    listEntries.push(entry);
    lastPositionByList.set(listEntries, position);
  });
  // Most recently written list first, by write clock rather than rowid: a list
  // pulled from another device sorts by when it was written, not when it landed.
  // A same-millisecond tie goes by write order, not by this device's rowids,
  // so every device lists them alike.
  return [...entriesByList.values()]
    .sort((a, b) => (b[b.length - 1].created_at_epoch - a[a.length - 1].created_at_epoch)
      || (lastPositionByList.get(b)! - lastPositionByList.get(a)!))
    .flatMap(listEntries => {
      const first = listEntries[0];
      const label = (listProjectCounts.get(first.list_name) ?? 0) > 1
        ? `${first.list_name} [${first.scope_project ?? first.project}]`
        : first.list_name;
      return renderWorkStateList(label, foldWorkStateList(listEntries), nowEpoch, includeClosed);
    });
}

/**
 * Whether the SessionStart section shows this list. Goals lists (owner-goals
 * and its past months), My Rules and My Focus show in My Work; their quotes
 * would fill this section. Approved rules reach agents through
 * ~/.claude-mem/MY-RULES.md instead. Shared My Work records never show.
 */
export function isSessionStartWorkStateList(listName: string): boolean {
  return !isOwnerGoalsList(listName) && !isMyRulesList(listName) && !isMyFocusList(listName) && !isSharedWorkList(listName);
}

/**
 * The SessionStart section: what is still open, cut to `characterLimit`, or
 * `''` when nothing is. The rule for using work state is not repeated here: it
 * is in the MCP server's instructions (shared/memory-instructions.ts).
 */
export function buildWorkStateContextSection(
  entries: WorkStateEntry[],
  nowEpoch: WorkStateClock,
  characterLimit: number = WORK_STATE_SECTION_CHARACTER_LIMIT,
): string {
  const openLines = renderWorkStateLines(entries.filter(entry => isSessionStartWorkStateList(entry.list_name)), nowEpoch);
  if (openLines.length === 0) return '';
  return fitWorkStateLines(WORK_STATE_SECTION_HEADING, openLines, characterLimit);
}

/** `heading`, then as many of `lines` as fit in `characterLimit`, then how many were left out. */
export function fitWorkStateLines(heading: string, lines: string[], characterLimit: number): string {
  let text = heading;
  for (let index = 0; index < lines.length; index++) {
    const remaining = lines.length - index;
    const overflowLine = `\n- ...${remaining} more line${remaining === 1 ? '' : 's'}; read them with work_state_read`;
    const candidate = `${text}\n${lines[index]}`;
    const needsOverflowRoom = index < lines.length - 1;
    if (candidate.length + (needsOverflowRoom ? overflowLine.length : 0) > characterLimit) {
      return text + overflowLine;
    }
    text = candidate;
  }
  return text;
}