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

24.8 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0

import { parseAgentXml, type ParsedObservation, type ParsedSummary } from '../../sdk/parser.js';
import { logger } from '../../utils/logger.js';
import {
  PostgresObservationRepository,
  PostgresObservationSourcesRepository,
  buildObservationGenerationKey,
  type PostgresObservation,
} from '../../storage/postgres/observations.js';
import {
  PostgresObservationGenerationJobEventsRepository,
  PostgresObservationGenerationJobRepository,
  type PostgresObservationGenerationJob,
} from '../../storage/postgres/generation-jobs.js';
import { PostgresAuthRepository } from '../../storage/postgres/auth.js';
import { PostgresUsageRepository } from '../../storage/postgres/usage.js';
import {
  withPostgresTransaction,
  type PostgresPool,
  type PostgresPoolClient,
} from '../../storage/postgres/pool.js';
import { stripMemoryTagsFromJsonStrings, stripTags } from '../../utils/tag-stripping.js';
import { PostgresObservationEmbeddingsRepository } from '../../storage/postgres/observation-embeddings.js';
import { embedObservationRows } from '../services/ObservationEmbeddingService.js';

// processGeneratedResponse owns the full "we got XML from a provider →
// persist + link + advance outbox" pipeline. Every side-effect runs inside
// a single Postgres transaction so retries are idempotent:
//
//   - observations.generation_key (UNIQUE per team/project) collapses retry
//     duplicates to a single row.
//   - observation_sources (UNIQUE on observation_id, source_type, source_id)
//     collapses duplicate source links.
//   - observation_generation_jobs.transitionStatus is the lifecycle gate.
//
// The function NEVER touches worker SessionStore tables, NEVER assumes a
// Claude Code transcript shape, and ALWAYS reloads the job before mutating.
// BullMQ payload data is advisory; the outbox row is canonical.

export type ProcessGeneratedResponseOutcome =
  | {
      kind: 'completed';
      jobId: string;
      observations: PostgresObservation[];
      privateContentDetected: boolean;
    }
  | { kind: 'parse_error'; jobId: string; reason: string }
  | { kind: 'superseded'; jobId: string }
  // Distinct from parse_error: the provider returned no content at all
  // (safety block, MAX_TOKENS truncation, gateway hiccup). Detected before
  // parsing so the failure is attributed to the provider, not the parser,
  // and the caller can fail fast instead of burning queue retries.
  | { kind: 'empty_response'; jobId: string; reason: string };

export interface ProcessGeneratedResponseInput {
  pool: PostgresPool;
  /**
   * How many events the provider was actually handed. Recorded on the
   * completion so an `observationCount: 0` always says WHY: nothing was
   * loaded, or plenty was loaded and the model still declined.
   */
  inputEventCount?: number;
  job: PostgresObservationGenerationJob;
  rawText: string;
  modelId?: string;
  providerLabel: string;
  workerId?: string;
  // Phase 11 — identity context propagated from the BullMQ payload (and
  // ultimately the API-key that ingested the source row). Persisted on
  // observation_sources.metadata for traceability and re-emitted in the
  // observation.created audit row.
  apiKeyId?: string | null;
  actorId?: string | null;
  sourceAdapter?: string | null;
  // Provider tokens this job spent (from the generate() result), for cost metering.
  tokensUsed?: number;
}

export async function processGeneratedResponse(
  input: ProcessGeneratedResponseInput,
): Promise<ProcessGeneratedResponseOutcome> {
  const { job, rawText } = input;

  if (!rawText.trim()) {
    return { kind: 'empty_response', jobId: job.id, reason: 'provider returned empty content' };
  }

  const parsed = parseAgentXml(rawText, job.id);
  if (!parsed.valid) {
    return { kind: 'parse_error', jobId: job.id, reason: 'parser rejected response' };
  }

  // Skip-summary or zero-observation responses are still a success — the
  // provider explicitly decided there's nothing worth recording (e.g.
  // privacy-stripped batch). Mark the job completed with no observations.
  const observationsToWrite = parsed.observations ?? [];
  const skipped = parsed.summary?.skipped === true;
  const privateContentDetected = skipped || observationsToWrite.length === 0;

  return persistGeneratedObservations(
    input,
    observationsToWrite.map(observation => ({
      kind: observation.type ?? 'observation',
      content: renderObservationContent(observation),
      metadata: {
        title: observation.title,
        subtitle: observation.subtitle,
        facts: observation.facts,
        narrative: observation.narrative,
        concepts: observation.concepts,
        files_read: observation.files_read,
        files_modified: observation.files_modified,
      },
    })),
    privateContentDetected,
  );
}

export interface MarkGenerationFailedInput {
  pool: PostgresPool;
  job: PostgresObservationGenerationJob;
  reason: string;
  classification?: string;
  retryable: boolean;
  workerId?: string;
  /** Required for worker failures after claiming; absent for pre-claim guards. */
  expectedAttempt?: PostgresObservationGenerationJob;
}

/**
 * Move a generation job to a non-success terminal state. Used when the
 * provider returned an error or invalid XML. Retryable failures move the
 * job back to `queued` so reconciliation can re-enqueue; non-retryable
 * failures move to `failed`.
 *
 * Resolves to the status the job was moved to, or null when the row was left
 * alone (already completed or cancelled, or the attempt no longer owns it).
 */
export async function markGenerationFailed(input: MarkGenerationFailedInput): Promise<'queued' | 'failed' | null> {
  return await withPostgresTransaction(input.pool, async (client) => {
    const jobsRepo = new PostgresObservationGenerationJobRepository(client);
    const eventsLogRepo = new PostgresObservationGenerationJobEventsRepository(client);

    const fresh = await jobsRepo.getByIdForScope({
      id: input.job.id,
      projectId: input.job.projectId,
      teamId: input.job.teamId,
      forUpdate: true,
    });
    if (!fresh || fresh.status === 'completed' || fresh.status === 'cancelled') {
      return null;
    }
    if (input.expectedAttempt && !ownsProcessingAttempt(fresh, input.expectedAttempt)) {
      return null;
    }

    const canRetry = input.retryable && fresh.attempts < fresh.maxAttempts;
    const target = canRetry ? 'queued' : 'failed';

    await jobsRepo.transitionStatus({
      id: fresh.id,
      projectId: fresh.projectId,
      teamId: fresh.teamId,
      status: target,
      lastError: { reason: input.reason, classification: input.classification ?? null },
      ...(canRetry ? { nextAttemptAt: new Date(Date.now() + retryDelayMs(fresh.attempts)) } : {}),
    });

    await eventsLogRepo.append({
      generationJobId: fresh.id,
      projectId: fresh.projectId,
      teamId: fresh.teamId,
      eventType: canRetry ? 'retry_scheduled' : 'failed',
      statusAfter: target,
      attempt: fresh.attempts,
      details: {
        reason: input.reason,
        classification: input.classification ?? null,
        workerId: input.workerId ?? null,
      },
    });
    return target;
  });
}

/**
 * Persist a parsed session summary as an observations row with kind='summary'.
 *
 * Wraps the same outbox transition / source-link / audit pipeline as
 * processGeneratedResponse but emits a single 'summary'-kind observation
 * derived from the summary fields. Idempotency is enforced through the same
 * `observations.generation_key` UNIQUE index — re-running the summary job
 * after a restart will collapse to one row.
 */
export async function processSessionSummaryResponse(
  input: ProcessGeneratedResponseInput,
): Promise<ProcessGeneratedResponseOutcome> {
  const { job, rawText } = input;

  if (job.sourceType !== 'session_summary') {
    return { kind: 'parse_error', jobId: job.id, reason: 'session summary processor invoked on non-summary job' };
  }

  if (!rawText.trim()) {
    return { kind: 'empty_response', jobId: job.id, reason: 'provider returned empty content' };
  }

  const parsed = parseAgentXml(rawText, job.id);
  if (!parsed.valid) {
    return { kind: 'parse_error', jobId: job.id, reason: 'parser rejected summary response' };
  }

  const summary = parsed.summary ?? null;
  const skipped = summary?.skipped === true;

  // Defence in depth: a provider that answers with <observation> blocks instead of
  // a <summary> block used to be dropped here silently — parsed.summary was null,
  // the content was judged empty, the job completed and parsed.observations was
  // never looked at. Fold those blocks into the summary body rather than
  // discarding a response the model was billed for.
  const fallbackObservations = !summary && !skipped ? parsed.observations : [];
  const summaryContent = summary
    ? renderSummaryContent(summary)
    : fallbackObservations.map(o => renderObservationContent(o)).join('\n\n');

  const privateContentDetected = skipped || summaryContent.trim().length === 0;
  // `privateContentDetected` cannot tell "the model declined" from "we rendered
  // nothing", and the parser's own skip_reason was being thrown away, so every
  // zero-observation completion looked identical. Keep the reason.
  const skipReason = skipped
    ? (summary?.skip_reason ?? 'model_skipped')
    : summaryContent.trim().length === 0
      ? 'rendered_empty'
      : null;

  const rendered: RenderedObservation[] = privateContentDetected
    ? []
    : [{
        kind: 'summary',
        content: summaryContent,
        metadata: {
          request: summary?.request ?? null,
          investigated: summary?.investigated ?? null,
          learned: summary?.learned ?? null,
          completed: summary?.completed ?? null,
          next_steps: summary?.next_steps ?? null,
          notes: summary?.notes ?? null,
        },
      }];

  return persistGeneratedObservations(input, rendered, privateContentDetected, skipReason);
}

interface RenderedObservation {
  kind: string;
  content: string;
  metadata: Record<string, unknown>;
}

function ownsProcessingAttempt(
  current: PostgresObservationGenerationJob,
  expected: PostgresObservationGenerationJob,
): boolean {
  // Operator retry can reuse an attempt number, and the same worker can claim
  // again. Include the lossless lock timestamp rather than its JS Date value.
  return current.status === 'processing'
    && expected.status === 'processing'
    && expected.lockedAtToken != null
    && current.lockedAtToken === expected.lockedAtToken
    && current.lockedBy === expected.lockedBy
    && current.attempts === expected.attempts;
}

// Shared persist transaction for both the per-event and session-summary
// pipelines: reload + terminal-status check, persist each rendered
// observation (+ source link + observation.created audit), then advance the
// outbox (transitionStatus + lifecycle event + generation_job.completed
// audit). Every side-effect runs inside a single Postgres transaction so
// retries are idempotent.
async function persistGeneratedObservations(
  input: ProcessGeneratedResponseInput,
  rendered: RenderedObservation[],
  privateContentDetected: boolean,
  skipReason: string | null = null,
): Promise<ProcessGeneratedResponseOutcome> {
  const { job } = input;

  // Metadata feeds both the viewer and embedding parts, independently of the
  // rendered content. Apply the same memory-tag boundary before either use.
  rendered = rendered.map(observation => ({
    ...observation,
    metadata: stripMemoryTagsFromJsonStrings(observation.metadata),
  }));

  // Vectors for search by meaning, computed before the transaction opens so
  // the model never holds it, and written beside each row inside it. Null when
  // unavailable: the rows are written anyway and the backfill at the next
  // start embeds them. Index-aligned with `rendered`, not with the
  // rows the loop below writes: a row it skips is embedded and discarded, so
  // the loop's index (which also feeds the generation key) picks each vector.
  const embedded = await embedObservationRows(
    input.pool,
    rendered.map(({ kind, content, metadata }) => ({
      kind,
      content: stripTags(content).stripped,
      metadata,
    })),
  );

  let completedNow = false;
  const outcome = await withPostgresTransaction<ProcessGeneratedResponseOutcome>(input.pool, async (client) => {
    const obsRepo = new PostgresObservationRepository(client);
    const embeddingsRepo = new PostgresObservationEmbeddingsRepository(client);
    const sourcesRepo = new PostgresObservationSourcesRepository(client);
    const jobsRepo = new PostgresObservationGenerationJobRepository(client);
    const eventsLogRepo = new PostgresObservationGenerationJobEventsRepository(client);
    const auditRepo = new PostgresAuthRepository(client);

    // Lock before checking ownership, keeping reclaim/retry/cancellation out
    // until observations, sources, audit and the outbox transition commit.
    const fresh = await jobsRepo.getByIdForScope({
      id: job.id,
      projectId: job.projectId,
      teamId: job.teamId,
      forUpdate: true,
    });
    if (!fresh) {
      throw new Error(`generation job ${job.id} not found in scope`);
    }
    if (fresh.status === 'completed' || fresh.status === 'cancelled' || fresh.status === 'failed') {
      logger.info('SYSTEM', 'generation job already in terminal status; skipping persistence', {
        jobId: fresh.id,
        status: fresh.status,
      });
      return {
        kind: 'completed' as const,
        jobId: fresh.id,
        observations: [],
        privateContentDetected,
      };
    }

    if (!ownsProcessingAttempt(fresh, job)) {
      logger.info('SYSTEM', 'generation attempt superseded; discarding response', { jobId: job.id });
      return { kind: 'superseded', jobId: job.id };
    }

    // Folder label travels on the server_session: the worker derives it from
    // the cwd basename and sends it on session-init. The store stays a single
    // global project; copying the folder onto each observation's metadata lets
    // context injection and search facet by folder without isolating memory.
    const sessionProject = await fetchSessionProject(client, fresh.serverSessionId, fresh.id);

    const persisted: PostgresObservation[] = [];
    for (let index = 0; index < rendered.length; index++) {
      const { kind, content, metadata } = rendered[index]!;
      if (!content || content.trim().length === 0) {
        continue;
      }

      // Defense-in-depth: even if the parser slipped a private-tagged
      // string through, scrub before persisting.
      const scrubbed = stripTags(content);
      if (!scrubbed.stripped || scrubbed.stripped.trim().length === 0) {
        continue;
      }

      const generationKey = buildObservationGenerationKey({
        generationJobId: fresh.id,
        parsedObservationIndex: index,
        content: scrubbed.stripped,
      });

      const observation = await obsRepo.create({
        projectId: fresh.projectId,
        teamId: fresh.teamId,
        serverSessionId: fresh.serverSessionId,
        kind,
        content: scrubbed.stripped,
        generationKey,
        metadata: {
          ...metadata,
          project: sessionProject,
          provider: input.providerLabel,
          model: input.modelId ?? null,
        },
        createdByJobId: fresh.id,
      });
      persisted.push(observation);

      if (embedded) {
        // Vectors are best-effort: a failed insert rolls back to this savepoint
        // and leaves the row to the backfill, instead of aborting the
        // transaction and discarding the generated observations with it.
        await client.query('SAVEPOINT observation_vectors');
        try {
          await embeddingsRepo.upsert({ observationId: observation.id, ...embedded[index]! });
          await client.query('RELEASE SAVEPOINT observation_vectors');
        } catch (error) {
          await client.query('ROLLBACK TO SAVEPOINT observation_vectors');
          logger.warn('SYSTEM', 'observation saved without vectors; the backfill embeds it at the next start', {
            observationId: observation.id,
            error: error instanceof Error ? error.message : String(error),
          });
        }
      }

      await sourcesRepo.addSource({
        observationId: observation.id,
        projectId: fresh.projectId,
        teamId: fresh.teamId,
        sourceType: fresh.sourceType,
        sourceId: fresh.sourceId,
        agentEventId: fresh.agentEventId ?? null,
        generationJobId: fresh.id,
        metadata: {
          provider: input.providerLabel,
          parsedObservationIndex: index,
          // Phase 11 — denormalize identity context for traceability so an
          // operator can answer "which api key produced this observation?"
          // without joining back through generation_job → outbox → key.
          source_adapter: input.sourceAdapter ?? null,
          actor_id: input.actorId ?? null,
          api_key_id: input.apiKeyId ?? null,
        },
      });

      // Phase 11 — audit each generated observation. Using the SAME
      // generation_job_id reference so the audit chain (event_received →
      // generation_job.queued → generation_job.processing → observation.
      // created → observation.read) can be reconstructed.
      const observationAuditEntry = {
        teamId: fresh.teamId,
        projectId: fresh.projectId,
        actorId: input.actorId ?? null,
        apiKeyId: input.apiKeyId ?? null,
        action: 'observation.created',
        resourceType: 'observation',
        resourceId: observation.id,
        details: {
          generationJobId: fresh.id,
          sourceType: fresh.sourceType,
          sourceId: fresh.sourceId,
          provider: input.providerLabel,
          model: input.modelId ?? null,
          sourceAdapter: input.sourceAdapter ?? null,
          parsedObservationIndex: index,
          kind,
        },
      };
      try {
        await auditRepo.createAuditLog(observationAuditEntry);
      } catch (auditError) {
        logger.warn('SYSTEM', 'audit_log observation.created insert failed', {
          observationId: observation.id,
          error: auditError instanceof Error ? auditError.message : String(auditError),
        });
      }
    }

    // Advance outbox status. Phase 1 transitionStatus enforces legal
    // transitions and tenant scope inside its WHERE clause.
    await jobsRepo.transitionStatus({
      id: fresh.id,
      projectId: fresh.projectId,
      teamId: fresh.teamId,
      status: 'completed',
    });
    await eventsLogRepo.append({
      generationJobId: fresh.id,
      projectId: fresh.projectId,
      teamId: fresh.teamId,
      eventType: 'completed',
      statusAfter: 'completed',
      attempt: fresh.attempts,
      details: {
        provider: input.providerLabel,
        model: input.modelId ?? null,
        observationCount: persisted.length,
        privateContentDetected,
        inputEventCount: input.inputEventCount ?? null,
        skipReason,
        workerId: input.workerId ?? null,
        sourceType: fresh.sourceType,
      },
    });

    // Audit log — best-effort; failure here would already be inside the
    // transaction so any insert error rolls everything back. We accept
    // that to keep the pipeline observable end-to-end.
    const jobCompletedAuditEntry = {
      teamId: fresh.teamId,
      projectId: fresh.projectId,
      actorId: input.actorId ?? null,
      apiKeyId: input.apiKeyId ?? null,
      action: 'generation_job.completed',
      resourceType: 'observation_generation_job',
      resourceId: fresh.id,
      details: {
        generationJobId: fresh.id,
        provider: input.providerLabel,
        model: input.modelId ?? null,
        observationCount: persisted.length,
        observationIds: persisted.map(o => o.id),
        sourceAdapter: input.sourceAdapter ?? null,
        sourceType: fresh.sourceType,
      },
    };
    try {
      await auditRepo.createAuditLog(jobCompletedAuditEntry);
    } catch (auditError) {
      // The audit log table may not have a metadata column on older
      // schemas; swallow rather than failing generation.
      logger.warn('SYSTEM', 'audit log insert failed during generation', {
        jobId: fresh.id,
        error: auditError instanceof Error ? auditError.message : String(auditError),
      });
    }

    completedNow = true;
    return {
      kind: 'completed' as const,
      jobId: fresh.id,
      observations: persisted,
      privateContentDetected,
    };
  });

  // Both event and summary jobs consume provider tokens. Meter only the
  // transaction that completed this attempt: a terminal replay also returns
  // `completed`, but must not charge the same response again. Keep writes
  // outside the transaction so a metering failure cannot undo saved memory.
  // The monthly token cap reads the `tokens` rows written here, so a cap counts
  // them even when general metering is off.
  const meteringOn = process.env.CLAUDE_MEM_USAGE_METERING === '1';
  const tokenCapSet = Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP ?? '0') > 0;
  if (completedNow && outcome.kind === 'completed' && (meteringOn || tokenCapSet)) {
    try {
      await recordUsageMetering(input, meteringOn ? outcome.observations.length : 0);
    } catch (usageError) {
      logger.warn('SYSTEM', 'usage metering record failed (post-commit)', {
        jobId: input.job.id,
        error: usageError instanceof Error ? usageError.message : String(usageError),
      });
    }
  }
  return outcome;
}

// Post-commit usage metering writes (tokens + observation counts). Extracted
// so the caller's try block stays narrow; any insert failure surfaces there.
async function recordUsageMetering(
  input: ProcessGeneratedResponseInput,
  observationCount: number,
): Promise<void> {
  const usageRepo = new PostgresUsageRepository(input.pool);
  if (input.tokensUsed && input.tokensUsed > 0) {
    await usageRepo.record({
      teamId: input.job.teamId,
      projectId: input.job.projectId,
      kind: 'tokens',
      quantity: input.tokensUsed,
      metadata: { jobId: input.job.id, provider: input.providerLabel, model: input.modelId ?? null },
    });
  }
  if (observationCount > 0) {
    await usageRepo.record({
      teamId: input.job.teamId,
      projectId: input.job.projectId,
      kind: 'observation',
      quantity: observationCount,
      metadata: { jobId: input.job.id },
    });
  }
}

/**
 * Read the folder/project label for a server session. Returns null when no
 * serverSessionId is provided (legacy jobs) or when the session row no longer
 * exists (e.g. deleted between enqueue and processing). Missing rows are
 * best-effort: the observation is still written with project: null.
 */
async function fetchSessionProject(
  client: PostgresPoolClient,
  serverSessionId: string | null | undefined,
  jobId: string,
): Promise<string | null> {
  if (!serverSessionId) return null;
  const result = await client.query<{ project: string | null }>(
    `SELECT metadata->>'project' AS project FROM server_sessions WHERE id = $1`,
    [serverSessionId],
  );
  if (result.rows.length === 0) {
    logger.debug('SYSTEM', 'session row not found during project lookup; observation will have project: null', {
      jobId,
      serverSessionId,
    });
    return null;
  }
  return result.rows[0]?.project ?? null;
}

function renderSummaryContent(summary: ParsedSummary): string {
  const parts: string[] = [];
  if (summary.request) parts.push(`Request: ${summary.request}`);
  if (summary.investigated) parts.push(`Investigated: ${summary.investigated}`);
  if (summary.learned) parts.push(`Learned: ${summary.learned}`);
  if (summary.completed) parts.push(`Completed: ${summary.completed}`);
  if (summary.next_steps) parts.push(`Next steps: ${summary.next_steps}`);
  if (summary.notes) parts.push(`Notes: ${summary.notes}`);
  return parts.join('\n\n').trim();
}

function renderObservationContent(observation: ParsedObservation): string {
  const parts: string[] = [];
  if (observation.title) parts.push(observation.title);
  if (observation.subtitle) parts.push(observation.subtitle);
  if (observation.narrative) parts.push(observation.narrative);
  if (observation.facts && observation.facts.length > 0) {
    parts.push(observation.facts.map(f => `- ${f}`).join('\n'));
  }
  // The parser treats concepts as content: an observation whose only populated
  // field is <concepts> survives its empty-observation guard. This renderer did
  // not, so that observation rendered to '' and was dropped by the empty-content
  // skip in persistGeneratedObservations - accepted, discarded, job completed.
  // Rendered last-resort only, so responses that carry prose keep the body they
  // already have and no existing content changes shape.
  if (parts.length === 0 && observation.concepts && observation.concepts.length > 0) {
    parts.push(`Concepts: ${observation.concepts.join(', ')}`);
  }
  return parts.join('\n\n').trim();
}

function retryDelayMs(attempts: number): number {
  // Exponential backoff: 5s, 25s, 125s, capped at 10 minutes.
  const base = 5000 * Math.pow(5, Math.max(0, attempts));
  return Math.min(base, 10 * 60 * 1000);
}