All files / src/cli/commands runs.ts

84.25% Statements 305/362
69.95% Branches 142/203
92.5% Functions 37/40
86.66% Lines 286/330

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826                                                            29x   29x 29x   3x   26x               18x 18x 18x 18x                       5x         5x 5x 5x 5x 4x 5x             4x           67x             25x 25x             15x 15x             3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x     3x 3x 3x 3x 3x     4x                   8x 8x 24x 24x   8x             9x                       10x 10x         10x     10x 10x 13x 4x         10x 1x 1x 1x     9x 9x 13x 13x       9x 8x     9x         9x 8x 8x 7x 6x   9x 10x 10x   10x 9x                             7x 7x                               2x     2x               2x 3x                             3x   3x                                       3x 3x 3x 3x 3x 3x 9x   3x   3x                             2x                     2x   18x 27x           2x                 2x     2x   3x                 3x       2x 2x                         2x               2x                     5x   5x 1x 1x 1x       4x 4x   5x 5x 4x 1x 1x 1x 1x       3x       4x 4x 4x 1x       4x 1x 1x       3x 3x     3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x               3x             3x 1x 1x 1x                   3x     5x 5x 1x               1x   2x       3x 3x   3x             3x 3x         3x     3x 3x 3x 3x               3x   3x 1x 1x     2x 2x 2x 2x 2x 2x           2x   2x                 12x 5x 1x 1x   4x       7x 7x 10x 5x       7x 8x 8x   8x 8x       8x 8x 8x   3x 3x     1x   2x 2x                 11x 11x           11x   11x 3x 3x 3x 3x 3x         3x     8x   8x 8x 4x 4x 4x                                                   4x     4x 4x       4x 4x 4x           6x 6x 6x 6x       5x                         12x 12x       12x   12x 12x 2x 2x         2x     10x 7x 7x       10x 10x   10x 10x 29x   10x   33x 33x       33x 33x 33x 33x 4x 4x 4x 1x 1x   3x   32x 32x       32x 14x 14x 14x 14x 14x   14x 18x 18x 18x 18x 17x 17x 18x 4x 4x       33x       10x 10x   7x     7x 23x 23x         7x 18x   7x         7x   7x 7x 7x   7x 7x 7x     7x 7x                                          
import { existsSync, openSync, closeSync, fstatSync, readSync, readdirSync, readFileSync, unlinkSync, watch } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import chalk from 'chalk';
import { loadWardenConfig } from '../../config/loader.js';
import { isExtractionErrorCode, type ConfidenceThreshold, type Severity, type SkillReport } from '../../types/index.js';
import type { CLIOptions, RunsOptions } from '../args.js';
import { getRepoRoot } from '../git.js';
import { findExpiredArtifacts } from '../log-cleanup.js';
import { renderTerminalReport, filterReports } from '../terminal.js';
import type { Reporter } from '../output/reporter.js';
import {
  pluralize,
  formatDuration,
  formatCost,
  totalUsageCost,
  shortRunId,
  parseJsonlReports,
  parseLogMetadata,
  renderJsonlString,
  JsonlChunkRecordSchema,
  JsonlRecordSchema,
  JsonlSummaryRecordSchema,
  type JsonlRunMetadata,
  type LogFileMetadata,
} from '../output/index.js';
 
/**
 * Resolve a log directory path from the repo root.
 */
function resolveLogDir(): { logDir: string; repoPath: string } | undefined {
  const cwd = process.cwd();
  let repoPath: string;
  try {
    repoPath = getRepoRoot(cwd);
  } catch {
    return undefined;
  }
  return { logDir: join(repoPath, '.warden', 'logs'), repoPath };
}
 
/**
 * Recover an ISO timestamp from `{runId8}-{ISO-datetime}.jsonl`.
 * Used as the list sort key for in-progress runs (no summary yet).
 */
function filenameTimestamp(filename: string): string {
  const match = filename.match(/-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)\.jsonl$/);
  const stamp = match?.[1];
  Iif (!stamp) return '';
  return stamp.replace(
    /^(\d{4}-\d{2}-\d{2}T\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/,
    '$1:$2:$3.$4Z',
  );
}
 
/**
 * Resolve a file argument to a full path.
 * If the argument looks like a run ID (no `/` or `.`), look up matching files in .warden/logs/.
 */
function resolveFileArg(arg: string, logDir: string): string[] {
  // If it contains path separators or dots, treat as a file path
  Iif (arg.includes('/') || arg.includes('.')) {
    return [resolve(process.cwd(), arg)];
  }
 
  // Treat as a short run ID — glob for matching files
  try {
    const entries = readdirSync(logDir);
    const matches = entries
      .filter((e) => e.endsWith('.jsonl') && e.startsWith(arg))
      .map((e) => join(logDir, e));
    return matches;
  } catch {
    return [];
  }
}
 
// oxlint-disable-next-line no-control-regex
const ANSI_RE = /\x1b\[[0-9;]*m/g;
 
/**
 * Get the visual width of a string (ignoring ANSI escape codes).
 */
function visualWidth(str: string): number {
  return str.replace(ANSI_RE, '').length;
}
 
/**
 * Pad a string to a visual width, accounting for ANSI codes.
 */
function padToWidth(str: string, width: number): string {
  const pad = width - visualWidth(str);
  return pad > 0 ? str + ' '.repeat(pad) : str;
}
 
/**
 * Right-align a string to a visual width, accounting for ANSI codes.
 */
function rightAlign(str: string, width: number): string {
  const pad = width - visualWidth(str);
  return pad > 0 ? ' '.repeat(pad) + str : str;
}
 
/**
 * Format a date as a human-friendly relative or short absolute string.
 */
function formatRelativeTime(date: Date): string {
  const now = Date.now();
  const diffMs = now - date.getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHr = Math.floor(diffMin / 60);
  const diffDays = Math.floor(diffHr / 24);
 
  Iif (diffSec < 60) return 'just now';
  Iif (diffMin < 60) return `${diffMin}m ago`;
  Iif (diffHr < 24) return `${diffHr}h ago`;
  Iif (diffDays === 1) return 'yesterday';
  Iif (diffDays < 7) return `${diffDays}d ago`;
 
  // Older than a week: show short date
  const month = date.toLocaleString('en-US', { month: 'short' });
  const day = date.getDate();
  const year = date.getFullYear();
  const currentYear = new Date().getFullYear();
  return year === currentYear ? `${month} ${day}` : `${month} ${day}, ${year}`;
}
 
const SEVERITY_COLORS: Record<Severity, (s: string) => string> = {
  high: chalk.red,
  medium: chalk.yellow,
  low: chalk.green,
};
 
/**
 * Format a severity breakdown as colored counts.
 */
function formatSeverityBreakdown(bySeverity: Partial<Record<Severity, number>>): string {
  const severities: Severity[] = ['high', 'medium', 'low'];
  const parts = severities.map((sev) => {
    const count = bySeverity[sev] ?? 0;
    return count > 0 ? SEVERITY_COLORS[sev](String(count)) : chalk.dim('0');
  });
  return parts.join(chalk.dim(' / '));
}
 
/**
 * Get the total rendered cost for a saved run summary.
 */
function getSummaryCostUSD(summary: { usage?: SkillReport['usage']; auxiliaryUsage?: SkillReport['auxiliaryUsage'] }): number | undefined {
  return totalUsageCost(summary.usage, summary.auxiliaryUsage);
}
 
/**
 * List sessions in `.warden/logs/`. Empty (no-file, no-skill) runs
 * are hidden unless `all` is set.
 */
export async function runRunsList(
  options: CLIOptions,
  reporter: Reporter,
  listOptions: { all?: boolean } = {},
): Promise<number> {
  const resolved = resolveLogDir();
  Iif (!resolved) {
    reporter.error('Not a git repository');
    return 1;
  }
 
  const { logDir } = resolved;
 
  let entries: string[];
  try {
    entries = readdirSync(logDir)
      .filter((e) => e.endsWith('.jsonl'))
      .sort((a, b) => filenameTimestamp(b).localeCompare(filenameTimestamp(a)));
  } catch {
    entries = [];
  }
 
  if (entries.length === 0) {
    reporter.warning('No saved sessions found');
    reporter.tip('Run warden to generate sessions in .warden/logs/');
    return 0;
  }
 
  const allLogData: { entry: string; meta: LogFileMetadata | undefined }[] = [];
  for (const entry of entries) {
    const filePath = join(logDir, entry);
    allLogData.push({ entry, meta: parseLogMetadata(filePath) });
  }
  // In-progress runs have no summary; fall back to the run record's
  // timestamp, then to the filename, so they sort to the top.
  const sortKey = (entry: { entry: string; meta: LogFileMetadata | undefined }) =>
    entry.meta?.summary?.run.timestamp ??
    entry.meta?.runMetadata?.timestamp ??
    filenameTimestamp(entry.entry);
  allLogData.sort((a, b) => sortKey(b).localeCompare(sortKey(a)));
 
  // Run-level errors (auth, config) stay visible even with zero files —
  // the error is the point of keeping the record. In-progress runs also
  // stay visible so users can find the active session.
  const isEmptyRun = (entry: { meta: LogFileMetadata | undefined }) => {
    const meta = entry.meta;
    if (!meta || meta.inProgress) return false;
    if (meta.summary?.error) return false;
    return meta.totalFiles === 0 && meta.skills.length === 0;
  };
  const showAll = listOptions.all ?? false;
  const logData = showAll ? allLogData : allLogData.filter((e) => !isEmptyRun(e));
  const hiddenCount = allLogData.length - logData.length;
 
  if (options.json) {
    const results = logData.map(({ entry, meta }) => ({
      file: entry,
      runId: meta?.runMetadata?.runId,
      timestamp: meta?.runMetadata?.timestamp,
      model: meta?.model,
      headSha: meta?.headSha,
      files: meta?.totalFiles,
      findings: meta?.summary?.totalFindings,
      bySeverity: meta?.summary?.bySeverity,
      durationMs: meta?.summary?.run.durationMs,
      costUSD: meta?.summary ? getSummaryCostUSD(meta.summary) : undefined,
      skills: meta?.skills,
      inProgress: meta?.inProgress ?? false,
    }));
 
    process.stdout.write(JSON.stringify(results, null, 2) + '\n');
    return 0;
  }
 
  // Build row data so we can calculate column widths
  interface Row {
    runId: string;
    date: string;
    files: string;
    findings: string;
    time: string;
    cost: string;
    sha: string;
    model: string;
    skills: string;
  }
 
  const rows: Row[] = [];
 
  // Aggregate totals across all runs
  const totals = {
    findings: 0,
    bySeverity: { high: 0, medium: 0, low: 0 } as Record<Severity, number>,
    costUSD: 0,
    durationMs: 0,
    skills: new Set<string>(),
  };
 
  for (const { entry, meta } of logData) {
    Iif (!meta) {
      rows.push({
        runId: entry.slice(0, 8),
        date: '',
        files: '',
        findings: chalk.dim('parse error'),
        time: '',
        cost: '',
        sha: '',
        model: '-',
        skills: '',
      });
      continue;
    }
 
    const { summary, runMetadata, skills, inProgress } = meta;
 
    Iif (inProgress) {
      const ts = runMetadata?.timestamp ?? filenameTimestamp(entry);
      const runId = runMetadata?.runId
        ? shortRunId(runMetadata.runId)
        : entry.slice(0, 8);
      rows.push({
        runId,
        date: ts ? formatRelativeTime(new Date(ts)) : '',
        files: meta.totalFiles > 0 ? String(meta.totalFiles) : '',
        findings: chalk.yellow('running'),
        time: '',
        cost: '',
        sha: meta.headSha ? meta.headSha.slice(0, 7) : '',
        model: meta.model ?? '-',
        skills: skills.join(', '),
      });
      for (const skill of skills) totals.skills.add(skill);
      continue;
    }
 
    Eif (summary) {
      const costUSD = getSummaryCostUSD(summary);
      totals.findings += summary.totalFindings;
      totals.durationMs += summary.run.durationMs;
      totals.costUSD += costUSD ?? 0;
      for (const [sev, count] of Object.entries(summary.bySeverity)) {
        totals.bySeverity[sev as Severity] += count;
      }
      for (const skill of skills) totals.skills.add(skill);
 
      rows.push({
        runId: shortRunId(summary.run.runId),
        date: formatRelativeTime(new Date(summary.run.timestamp)),
        files: meta.totalFiles > 0 ? String(meta.totalFiles) : '',
        findings: formatSeverityBreakdown(summary.bySeverity),
        time: formatDuration(summary.run.durationMs),
        cost: costUSD !== undefined ? formatCost(costUSD) : '',
        sha: meta.headSha ? meta.headSha.slice(0, 7) : '',
        model: meta.model ?? '-',
        skills: skills.join(', '),
      });
    }
  }
 
  // Calculate column widths
  const headers = {
    runId: 'RUN',
    date: 'DATE',
    files: 'FILES',
    findings: 'FINDINGS',
    time: 'TIME',
    cost: 'COST',
    sha: 'SHA',
    model: 'MODEL',
    skills: 'SKILLS',
  };
  const widths = Object.fromEntries(
    Object.keys(headers).map((key) => {
      const col = key as keyof Row;
      return [col, Math.max(headers[col].length, ...rows.map((r) => visualWidth(r[col])))];
    }),
  ) as Record<keyof Row, number>;
 
  // Header row
  const headerLine =
    `  ${padToWidth(headers.runId, widths.runId)}  ` +
    `${padToWidth(headers.date, widths.date)}  ` +
    `${rightAlign(headers.files, widths.files)}  ` +
    `${padToWidth(headers.findings, widths.findings)}  ` +
    `${rightAlign(headers.time, widths.time)}  ` +
    `${rightAlign(headers.cost, widths.cost)}  ` +
    `${padToWidth(headers.sha, widths.sha)}  ` +
    `${padToWidth(headers.model, widths.model)}  ` +
    `${headers.skills}`;
  reporter.text(chalk.dim(headerLine));
 
  // Data rows
  for (const row of rows) {
    const line =
      `  ${padToWidth(chalk.bold(row.runId), widths.runId)}  ` +
      `${padToWidth(chalk.dim(row.date), widths.date)}  ` +
      `${rightAlign(chalk.dim(row.files), widths.files)}  ` +
      `${padToWidth(row.findings, widths.findings)}  ` +
      `${rightAlign(chalk.dim(row.time), widths.time)}  ` +
      `${rightAlign(chalk.dim(row.cost), widths.cost)}  ` +
      `${padToWidth(chalk.dim(row.sha), widths.sha)}  ` +
      `${padToWidth(chalk.dim(row.model), widths.model)}  ` +
      `${chalk.dim(row.skills)}`;
    reporter.text(line);
  }
 
  // Summary footer
  reporter.blank();
  reporter.text(
    chalk.dim(
      `${rows.length} ${pluralize(rows.length, 'run')}  ·  ` +
      `${totals.findings} ${pluralize(totals.findings, 'finding')}  `
    ) +
    formatSeverityBreakdown(totals.bySeverity) +
    chalk.dim(
      `  ·  ${formatDuration(totals.durationMs)}` +
      `  ·  ${formatCost(totals.costUSD)}` +
      `  ·  ${totals.skills.size} ${pluralize(totals.skills.size, 'skill')}`
    )
  );
 
  Iif (hiddenCount > 0) {
    reporter.text(
      chalk.dim(
        `${hiddenCount} empty ${pluralize(hiddenCount, 'session')} hidden — pass --all to show`,
      ),
    );
  }
 
  return 0;
}
 
/**
 * Show results from JSONL log files (replaces `warden replay`).
 */
export async function runRunsShow(
  runsOptions: RunsOptions,
  options: CLIOptions,
  reporter: Reporter,
): Promise<number> {
  const { files: fileArgs } = runsOptions;
 
  if (fileArgs.length === 0) {
    reporter.error('No log files specified');
    reporter.tip('Usage: warden runs show <file.jsonl> [file2.jsonl ...]');
    return 1;
  }
 
  // Resolve file arguments (may be paths or run IDs)
  const resolved = resolveLogDir();
  const logDir = resolved?.logDir;
 
  const resolvedFiles: string[] = [];
  for (const arg of fileArgs) {
    if (logDir) {
      const matches = resolveFileArg(arg, logDir);
      Eif (matches.length > 0) {
        resolvedFiles.push(...matches);
        continue;
      }
    }
    // Fall back to treating as a direct path
    resolvedFiles.push(resolve(process.cwd(), arg));
  }
 
  // Validate all files exist
  const missingFiles: string[] = [];
  for (const file of resolvedFiles) {
    if (!existsSync(file)) {
      missingFiles.push(file);
    }
  }
 
  if (missingFiles.length > 0) {
    reporter.error(`Log ${pluralize(missingFiles.length, 'file')} not found: ${missingFiles.join(', ')}`);
    return 1;
  }
 
  // Parse and merge reports from all files
  const allReports: SkillReport[] = [];
  let totalDurationMs = 0;
  let lastRunMetadata: JsonlRunMetadata | undefined;
 
  for (const file of resolvedFiles) {
    try {
      const content = readFileSync(file, 'utf-8');
      const parsed = parseJsonlReports(content);
      allReports.push(...parsed.reports);
      totalDurationMs += parsed.totalDurationMs;
 
      Eif (parsed.runMetadata) {
        lastRunMetadata = parsed.runMetadata;
        reporter.debug(`Loaded ${parsed.reports.length} ${pluralize(parsed.reports.length, 'skill')} from ${file}`);
        reporter.debug(`  Run ID: ${parsed.runMetadata.runId}`);
        reporter.debug(`  Timestamp: ${parsed.runMetadata.timestamp}`);
      }
    } catch (err) {
      reporter.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : String(err)}`);
      return 1;
    }
  }
 
  Iif (allReports.length === 0) {
    reporter.warning('No skill reports found in log files');
    return 0;
  }
 
  // Load config for minConfidence default (matches main run flow)
  let configMinConfidence: ConfidenceThreshold | undefined;
  if (resolved) {
    try {
      const configPath = resolve(resolved.repoPath, 'warden.toml');
      Iif (existsSync(configPath)) {
        const config = loadWardenConfig(dirname(configPath));
        configMinConfidence = config.defaults?.minConfidence;
      }
    } catch {
      // Use default
    }
  }
 
  // Apply filtering
  const filteredReports = filterReports(allReports, options.reportOn, options.minConfidence ?? configMinConfidence ?? 'medium');
 
  // Output results
  reporter.blank();
  if (options.json) {
    const jsonlContent = renderJsonlString(filteredReports, totalDurationMs, lastRunMetadata ? {
      runId: lastRunMetadata.runId,
      traceId: lastRunMetadata.traceId,
      timestamp: new Date(lastRunMetadata.timestamp),
      model: lastRunMetadata.model,
      headSha: lastRunMetadata.headSha,
      cwd: lastRunMetadata.cwd,
    } : undefined);
    process.stdout.write(jsonlContent);
  } else {
    console.log(renderTerminalReport(filteredReports, reporter.mode, { verbosity: reporter.verbosity }));
  }
 
  // Show summary
  reporter.blank();
  reporter.renderSummary(filteredReports, totalDurationMs);
 
  return 0;
}
 
/**
 * Garbage-collect expired log files.
 */
export async function runRunsGc(_options: CLIOptions, reporter: Reporter): Promise<number> {
  const resolved = resolveLogDir();
  Iif (!resolved) {
    reporter.error('Not a git repository');
    return 1;
  }
 
  const { logDir, repoPath } = resolved;
 
  // Load config for retentionDays
  let retentionDays = 30;
  try {
    const configPath = resolve(repoPath, 'warden.toml');
    Iif (existsSync(configPath)) {
      const config = loadWardenConfig(dirname(configPath));
      retentionDays = config.logs?.retentionDays ?? 30;
    }
  } catch {
    // Use default
  }
 
  const expired = findExpiredArtifacts(logDir, retentionDays);
 
  if (expired.length === 0) {
    reporter.success('Nothing to clean up');
    return 0;
  }
 
  let deleted = 0;
  for (const filePath of expired) {
    try {
      unlinkSync(filePath);
      try { unlinkSync(`${filePath}.done`); } catch { /* sidecar may not exist */ }
      deleted++;
    } catch {
      // Skip files we can't delete
    }
  }
 
  reporter.success(`Removed ${deleted} expired ${pluralize(deleted, 'log file')}`);
 
  return 0;
}
 
/**
 * Resolve a follow target. With no arg, picks the newest session whose
 * file lacks a trailing `summary` record — a reliable proxy for "the
 * run currently happening in another terminal."
 */
function resolveFollowTarget(arg: string | undefined, logDir: string): string | undefined {
  if (arg) {
    if (arg.includes('/') || arg.includes('.')) {
      const path = resolve(process.cwd(), arg);
      return existsSync(path) ? path : undefined;
    }
    return resolveFileArg(arg, logDir)[0];
  }
 
  let entries: string[];
  try {
    entries = readdirSync(logDir)
      .filter((e) => e.endsWith('.jsonl'))
      .sort((a, b) => filenameTimestamp(b).localeCompare(filenameTimestamp(a)));
  } catch {
    return undefined;
  }
  for (const entry of entries) {
    const filePath = join(logDir, entry);
    Iif (!arg && existsSync(`${filePath}.done`)) continue;
    let content: string;
    try {
      content = readFileSync(filePath, 'utf-8');
    } catch {
      continue;
    }
    const lines = content.trim().split('\n').filter((l) => l.trim());
    const last = lines[lines.length - 1];
    if (!last) return filePath;
    let parsed: unknown;
    try {
      parsed = JSON.parse(last);
    } catch {
      // Corrupt tail — treating this as in-progress would hang forever.
      continue;
    }
    Eif ((parsed as { type?: string } | null)?.type !== 'summary') {
      return filePath;
    }
  }
  return undefined;
}
 
/** Render one JSONL line for the human follower. Stops on the summary record. */
function renderFollowLine(line: string, reporter: Reporter): { stop: boolean } {
  let parsed: unknown;
  try {
    parsed = JSON.parse(line);
  } catch {
    reporter.warning(`Skipping malformed line: ${line.slice(0, 80)}`);
    return { stop: false };
  }
 
  const obj = parsed as { type?: string };
 
  if (obj.type === 'summary') {
    const summary = JsonlSummaryRecordSchema.safeParse(obj);
    Eif (summary.success) {
      const { totalFindings, bySeverity } = summary.data;
      reporter.blank();
      reporter.text(
        chalk.dim(`Run finished — ${totalFindings} ${pluralize(totalFindings, 'finding')}  `) +
          formatSeverityBreakdown(bySeverity),
      );
    }
    return { stop: true };
  }
 
  Iif (obj.type === 'fix-evaluation') return { stop: false };
 
  const chunkResult = JsonlChunkRecordSchema.safeParse(obj);
  if (chunkResult.success) {
    const chunk = chunkResult.data;
    Iif (chunk.findings.length === 0 && !chunk.error) return { stop: false };
    console.log(renderTerminalReport([{
      skill: chunk.skill,
      summary: chunk.findings.length > 0
        ? `${chunk.skill}: Found ${chunk.findings.length} ${pluralize(chunk.findings.length, 'issue')}`
        : `${chunk.skill}: chunk failed`,
      findings: chunk.findings,
      durationMs: chunk.durationMs,
      usage: chunk.usage,
      model: chunk.model,
      files: [{
        filename: chunk.chunk.file,
        findings: chunk.findings.length,
        durationMs: chunk.durationMs,
        usage: chunk.usage,
      }],
      error: chunk.error,
      hunkFailures: chunk.error
        ? [{
            type: isExtractionErrorCode(chunk.error.code) ? 'extraction' : 'analysis',
            filename: chunk.chunk.file,
            lineRange: chunk.chunk.lineRange,
            code: chunk.error.code,
            message: chunk.error.message,
          }]
        : undefined,
    }], reporter.mode, { verbosity: reporter.verbosity }));
    return { stop: false };
  }
 
  const skillResult = JsonlRecordSchema.safeParse(obj);
  Iif (!skillResult.success) {
    reporter.warning(`Skipping unrecognized record`);
    return { stop: false };
  }
  const { run: _run, ...report } = skillResult.data;
  console.log(renderTerminalReport([report], reporter.mode, { verbosity: reporter.verbosity }));
  return { stop: false };
}
 
/** `--json` mode: pass the raw line through unmodified for downstream tools. */
function passthroughFollowLine(line: string): { stop: boolean } {
  // One write keeps the line + newline atomic for piped consumers.
  process.stdout.write(line + '\n');
  try {
    const parsed = JSON.parse(line) as { type?: string };
    if (parsed?.type === 'summary') return { stop: true };
  } catch {
    // partial / invalid line; keep waiting for a valid summary
  }
  return { stop: false };
}
 
/**
 * Tail a JSONL session file, rendering each appended record live.
 * Exits 0 on summary record or Ctrl-C — never on findings; this is a
 * viewer, not a build gate.
 */
export async function runRunsFollow(
  runsOptions: RunsOptions,
  options: CLIOptions,
  reporter: Reporter,
): Promise<number> {
  const resolved = resolveLogDir();
  Iif (!resolved) {
    reporter.error('Not a git repository');
    return 1;
  }
  const { logDir } = resolved;
 
  const target = resolveFollowTarget(runsOptions.files[0], logDir);
  if (!target) {
    if (runsOptions.files[0]) {
      reporter.error(`No matching session for ${runsOptions.files[0]}`);
    } else E{
      reporter.error('No active session to follow');
      reporter.tip('Start a run in another terminal, or pass an explicit run id.');
    }
    return 1;
  }
 
  if (!options.json) {
    reporter.dim(`Following: ${target}`);
    reporter.blank();
  }
 
  // Render anything already on disk and remember where we left off.
  let offset = 0;
  let buffer = '';
  let fileIdentity: string | undefined;
  let stopped = false;
  const emittedJsonLines = new Set<string>();
  const targetComplete = () => existsSync(`${target}.done`);
 
  const drainFile = (): void => {
    let fd: number;
    try {
      fd = openSync(target, 'r');
    } catch {
      return;
    }
    try {
      const stat = fstatSync(fd);
      const identity = `${stat.dev}:${stat.ino}`;
      if (fileIdentity && identity !== fileIdentity) {
        fileIdentity = identity;
        buffer = '';
        if (offset > 0 && !options.json) {
          offset = stat.size;
          return;
        }
        offset = 0;
      }
      fileIdentity = identity;
      Iif (stat.size < offset) {
        buffer = '';
        offset = 0;
      }
      if (stat.size <= offset) return;
      const len = stat.size - offset;
      const buf = Buffer.alloc(len);
      readSync(fd, buf, 0, len, offset);
      offset = stat.size;
      buffer += buf.toString('utf-8');
      let nl: number;
      while ((nl = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, nl);
        buffer = buffer.slice(nl + 1);
        Iif (!line.trim()) continue;
        if (options.json && emittedJsonLines.has(line)) continue;
        if (options.json) emittedJsonLines.add(line);
        const result = options.json ? passthroughFollowLine(line) : renderFollowLine(line, reporter);
        if (result.stop) {
          stopped = true;
          return;
        }
      }
    } finally {
      try { closeSync(fd); } catch { /* ignore */ }
    }
  };
 
  drainFile();
  if (stopped || targetComplete()) return 0;
 
  return new Promise<number>((resolvePromise) => {
    let watcher: ReturnType<typeof watch> | undefined;
 
    const tick = () => {
      drainFile();
      if (stopped || targetComplete()) finish(0);
    };
 
    // fs.watch is best-effort across platforms; the 1s poll below is the
    // real correctness guarantee.
    try {
      watcher = watch(target, { persistent: true }, () => tick());
      // FSWatcher 'error' would crash the process otherwise (file deleted, inotify limit, ...).
      watcher.on('error', () => {
        try { watcher?.close(); } catch { /* ignore */ }
        watcher = undefined;
      });
    } catch { /* polling alone is fine */ }
    const pollTimer = setInterval(tick, 1000);
 
    const finish = (code: number) => {
      Eif (watcher) {
        try { watcher.close(); } catch { /* ignore */ }
      }
      clearInterval(pollTimer);
      process.off('SIGINT', onSigint);
      resolvePromise(code);
    };
 
    const onSigint = () => finish(0);
    process.on('SIGINT', onSigint);
  });
}
 
/** Dispatch to the appropriate `runs` subcommand. */
export async function runRuns(
  runsOptions: RunsOptions,
  options: CLIOptions,
  reporter: Reporter,
): Promise<number> {
  switch (runsOptions.subcommand) {
    case 'list':
      return runRunsList(options, reporter, { all: runsOptions.all });
    case 'show':
      return runRunsShow(runsOptions, options, reporter);
    case 'gc':
      return runRunsGc(options, reporter);
    case 'follow':
      return runRunsFollow(runsOptions, options, reporter);
  }
}