repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/prune/src/extract.ts

Raw
File outline
/**
 * prune — extract sections from blocks
 */

import type { Block, ExtractOutput, TranscriptEntry } from './types.ts';
import {
  BLOCKER_RE,
  SELF_TALK_PREFIX_RE,
  GOAL_RE,
  SCOPE_CHANGE_RE,
  NOISE_SHORT_RE,
  NON_GOAL_RE,
  TEMPLATE_SIGNAL_RE,
  INTERROGATIVE_RE,
  TRUNCATE_USER,
  TRUNCATE_ASSISTANT,
  PREF_PATTERNS,
  GENERATED_PREF_FALSE_POSITIVE_RE,
} from './constants.ts';

/**
 * Extract structured sections from blocks.
 */
export function extract(blocks: Block[]): ExtractOutput {
  const goals: string[] = [];
  const scopeChanges: string[] = [];
  const modified = new Set<string>();
  const created = new Set<string>();
  const read = new Set<string>();
  const context: string[] = [];
  const preferences: string[] = [];

  let sawInitialGoalBlock = false;

  // First pass: extract goals, scope changes, preferences from user messages
  for (const block of blocks) {
    if (block.kind !== 'user') continue;

    const lines = goalCandidateLines(block.text);
    if (lines.length > 0) {
      if (!sawInitialGoalBlock) {
        for (const line of lines.slice(0, 6)) addUnique(goals, truncate(line, TRUNCATE_USER));
        sawInitialGoalBlock = true;
      } else {
        const leading = block.text.slice(0, 200);
        const isTask = GOAL_RE.test(leading) && lines[0].length > 5;
        const isScopeChange = SCOPE_CHANGE_RE.test(leading);
        if (isScopeChange || isTask) {
          for (const line of lines.slice(0, isScopeChange ? 3 : 2)) {
            addUnique(scopeChanges, truncate(line, TRUNCATE_USER));
          }
        }
      }
    }

    extractPreferences(block.text, preferences);
  }

  // Second pass: extract files and context from tool calls/results
  for (const block of blocks) {
    if (block.kind === 'tool_call' && block.args) {
      extractFileFromArgs(block.name || '', block.args, modified, created, read);
    }
    if (block.kind === 'tool_result' && block.isError) {
      const error = block.name
        ? `[${block.name}] ${truncate(firstLine(block.text), 150)}`
        : truncate(firstLine(block.text), 150);
      addUnique(context, error);
    }
  }

  // Third pass: extract blockers from assistant/user text tail
  for (const block of blocks.slice(-20)) {
    if (block.kind !== 'assistant' && block.kind !== 'user') continue;
    const lines = block.text.split('\n').filter(l => l.trim());
    for (const line of lines) {
      if (BLOCKER_RE.test(line) && line.length > 15) {
        const clean = block.kind === 'user'
          ? `[user] ${truncate(line.trim(), 150)}`
          : truncate(line.trim(), 150);
        addUnique(context, clean);
        break;
      }
    }
  }

  const transcript = buildTranscript(blocks);

  return {
    goals: goals.slice(0, 8),
    scopeChanges: scopeChanges.slice(0, 8),
    files: { modified, created, read },
    context: context.slice(0, 5),
    preferences: preferences.slice(0, 10),
    transcript,
  };
}

function goalCandidateLines(text: string): string[] {
  const raw = nonEmptyLines(text);
  const stop = raw.findIndex(line => TEMPLATE_SIGNAL_RE.test(line));
  const lines = stop >= 0 ? raw.slice(0, stop) : raw;

  return collapseSkillLines(lines)
    .map(stripLeadingBullet)
    .filter(isSubstantiveGoalLine)
    .filter(line => {
      if (!line.endsWith('?')) return true;
      // Questions usually stay transcript-only unless they include a task/action verb.
      return GOAL_RE.test(line) && !INTERROGATIVE_RE.test(line.replace(/^can you\s+/i, ''));
    });
}

function isSubstantiveGoalLine(line: string): boolean {
  const t = line.trim();
  if (t.length <= 5) return false;
  if (t.length > 240) return false;
  if (NOISE_SHORT_RE.test(t)) return false;
  if (NON_GOAL_RE.test(t)) return false;
  return true;
}

function nonEmptyLines(text: string): string[] {
  return text.split('\n').map(l => l.trim()).filter(Boolean);
}

function stripLeadingBullet(line: string): string {
  return line.replace(/^\s*(?:[-*+]|\d+\.)\s+/, '').trim();
}

function collapseSkillLines(lines: string[]): string[] {
  const out: string[] = [];
  let inSkill = false;
  for (const line of lines) {
    if (/^<skill\b/i.test(line)) {
      inSkill = true;
      continue;
    }
    if (/^<\/skill>/i.test(line)) {
      inSkill = false;
      continue;
    }
    if (!inSkill) out.push(line);
  }
  return out;
}

/**
 * Extract file paths from tool args.
 */
function extractFileFromArgs(
  toolName: string,
  args: Record<string, unknown>,
  modified: Set<string>,
  created: Set<string>,
  read: Set<string>,
): void {
  const name = toolName.toLowerCase();

  if (name.includes('edit') || name.includes('write')) {
    extractFilePath(args.path || args.file_path || args.file, modified);
    extractFilePath(args.new_path, created);
  }

  if (name.includes('read')) {
    extractFilePath(args.path || args.file_path || args.file, read);
  }

  if (name.includes('bash')) {
    const cmd = String(args.command || '');
    const pathMatch = cmd.match(/['"]?(\/[\w\/.-]+\.\w+)['"]?/);
    if (pathMatch) {
      modified.add(pathMatch[1]);
    }
  }
}

function extractFilePath(path: unknown, set: Set<string>): void {
  if (typeof path === 'string' && path.trim()) {
    const parts = path.split('/');
    set.add(parts[parts.length - 1]);
  }
}

/**
 * Extract user preferences from text.
 */
function extractPreferences(text: string, prefs: string[]): void {
  const head = text.slice(0, 200);
  let perBlock = 0;

  for (const line of collapseSkillLines(nonEmptyLines(head))) {
    const trimmed = line.trim();
    if (trimmed.length < 5) continue;
    if (trimmed.length > 200) continue;
    if (trimmed.endsWith('?') || trimmed.includes('?...')) continue;
    if (GENERATED_PREF_FALSE_POSITIVE_RE.test(trimmed)) continue;
    if (!PREF_PATTERNS.some(p => p.test(trimmed))) continue;
    addUnique(prefs, truncate(trimmed, 200));
    if (++perBlock >= 1) break;
  }
}

/**
 * Build brief transcript from blocks.
 */
function buildTranscript(blocks: Block[]): TranscriptEntry[] {
  const entries: TranscriptEntry[] = [];

  for (const block of blocks) {
    switch (block.kind) {
      case 'user': {
        const text = truncate(stripSelfTalk(block.text), TRUNCATE_USER);
        if (text) {
          entries.push({ role: 'user', text, ref: `#${block.sourceIndex}` });
        }
        break;
      }
      case 'assistant': {
        const text = truncate(stripSelfTalk(block.text), TRUNCATE_ASSISTANT);
        if (text) {
          entries.push({ role: 'assistant', text, ref: `#${block.sourceIndex}` });
        }
        break;
      }
      case 'tool_call': {
        const tool = block.name || 'unknown';
        const cmd = extractToolCmd(block.args || {});
        entries.push({
          role: 'assistant',
          text: '',
          tool,
          cmd,
          ref: `#${block.sourceIndex}`,
        });
        break;
      }
      case 'tool_result': {
        if (block.isError) {
          const error = block.name ? `[ERROR] ${block.name}` : '[ERROR]';
          entries.push({ role: 'error', text: error, ref: `#${block.sourceIndex}` });
        }
        break;
      }
      case 'thinking':
        break;
    }
  }

  return entries;
}

/**
 * Strip self-talk prefixes from assistant text.
 */
function stripSelfTalk(text: string): string {
  let result = text;
  for (let i = 0; i < 2; i++) {
    const stripped = result.replace(SELF_TALK_PREFIX_RE, '');
    if (stripped === result) break;
    result = stripped;
  }
  return result;
}

/**
 * Extract command from tool args.
 */
function extractToolCmd(args: Record<string, unknown>): string | undefined {
  if (args.command) {
    const cmd = String(args.command);
    return compressBash(cmd);
  }

  if (args.path) return String(args.path);
  if (args.file_path) return String(args.file_path);
  if (args.file) return String(args.file);

  return undefined;
}

function compressBash(raw: string): string {
  let cmd = raw.split('\n').map(l => l.trim()).filter(Boolean)[0] ?? raw;
  cmd = cmd.replace(/^cd\s+\S+\s*&&\s*/, '');
  cmd = cmd.replace(/\s*\|\s*(?:head|tail|sort|wc|column|tr|cut|awk|uniq|node|bun)(?:\s[^|]*)?$/, '');
  return truncate(cmd, 120);
}

function firstLine(text: string): string {
  return text.split('\n')[0]?.trim() || '(no output)';
}

function addUnique(items: string[], item: string): void {
  if (!item.trim()) return;
  if (!items.includes(item)) items.push(item);
}

/**
 * Truncate text to max length.
 */
function truncate(text: string, max: number): string {
  const flat = text.replace(/\s+/g, ' ').trim();
  if (flat.length <= max) return flat;
  return flat.slice(0, max - 3) + '...';
}