|
| 1 | +"""Transcript capture — compresses and stores cycle transcripts via the dashboard API.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import base64 |
| 6 | +import logging |
| 7 | +import os |
| 8 | +from datetime import datetime, timedelta, timezone |
| 9 | +from pathlib import Path |
| 10 | +from typing import TYPE_CHECKING |
| 11 | + |
| 12 | +import httpx |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from .agent import CycleContext |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +CYCLE_RUNS_API = os.environ.get( |
| 20 | + "CYCLE_RUNS_API_URL", "http://localhost:8080/api/cycle-runs" |
| 21 | +) |
| 22 | + |
| 23 | +_WORK_TYPE_TO_CYCLE_TYPE = { |
| 24 | + "new_ticket": "task_work", |
| 25 | + "pr_review": "task_work", |
| 26 | + "ci_fix": "task_work", |
| 27 | + "idle": "idle", |
| 28 | + "memory_housekeeping": "idle", |
| 29 | + "error": "error", |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +def _resolve_cycle_type(work_type: str | None, is_error: bool) -> str: |
| 34 | + if is_error: |
| 35 | + return "error" |
| 36 | + if work_type: |
| 37 | + return _WORK_TYPE_TO_CYCLE_TYPE.get(work_type, "task_work") |
| 38 | + return "triage_only" |
| 39 | + |
| 40 | + |
| 41 | +def _find_transcript(session_id: str, cwd: str) -> Path | None: |
| 42 | + """Locate the Claude session transcript JSONL file.""" |
| 43 | + slug = cwd.replace("/", "-") |
| 44 | + if not slug.startswith("-"): |
| 45 | + slug = "-" + slug |
| 46 | + home = Path.home() |
| 47 | + path = home / ".claude" / "projects" / slug / f"{session_id}.jsonl" |
| 48 | + if path.exists(): |
| 49 | + return path |
| 50 | + # Fallback: scan project dirs for the session file |
| 51 | + projects_dir = home / ".claude" / "projects" |
| 52 | + if projects_dir.is_dir(): |
| 53 | + for candidate in projects_dir.iterdir(): |
| 54 | + f = candidate / f"{session_id}.jsonl" |
| 55 | + if f.exists(): |
| 56 | + return f |
| 57 | + return None |
| 58 | + |
| 59 | + |
| 60 | +def record_transcript( |
| 61 | + label: str, |
| 62 | + result, |
| 63 | + ctx: CycleContext | None = None, |
| 64 | + cwd: str = "", |
| 65 | + instance_id: str | None = None, |
| 66 | +) -> None: |
| 67 | + """Compress and store the cycle transcript + metadata to the dashboard API.""" |
| 68 | + session_id = getattr(result, "session_id", "") |
| 69 | + if not session_id: |
| 70 | + logger.debug("No session_id in result — skipping transcript capture") |
| 71 | + return |
| 72 | + |
| 73 | + usage = getattr(result, "usage", None) or {} |
| 74 | + is_error = getattr(result, "subtype", "") != "success" |
| 75 | + cycle_type = _resolve_cycle_type(ctx.work_type if ctx else None, is_error) |
| 76 | + |
| 77 | + duration_ms = getattr(result, "duration_ms", None) or 0 |
| 78 | + now = datetime.now(timezone.utc) |
| 79 | + started_at = now |
| 80 | + if duration_ms: |
| 81 | + started_at = now - timedelta(milliseconds=duration_ms) |
| 82 | + |
| 83 | + body: dict = { |
| 84 | + "task_id": ctx.task_id if ctx else None, |
| 85 | + "cycle_type": cycle_type, |
| 86 | + "instance_id": instance_id or label, |
| 87 | + "started_at": started_at.isoformat(), |
| 88 | + "finished_at": now.isoformat(), |
| 89 | + "tool_calls": getattr(result, "num_turns", 0), |
| 90 | + "tokens_used": usage.get("input_tokens", 0) + usage.get("output_tokens", 0), |
| 91 | + "progress": { |
| 92 | + "jira_key": ctx.jira_key if ctx else None, |
| 93 | + "repo": ctx.repo if ctx else None, |
| 94 | + "work_type": ctx.work_type if ctx else None, |
| 95 | + "summary": ctx.summary if ctx else None, |
| 96 | + }, |
| 97 | + } |
| 98 | + |
| 99 | + transcript_path = _find_transcript(session_id, cwd) |
| 100 | + if transcript_path: |
| 101 | + try: |
| 102 | + import zstandard as zstd |
| 103 | + |
| 104 | + raw = transcript_path.read_bytes() |
| 105 | + compressor = zstd.ZstdCompressor(level=19) |
| 106 | + compressed = compressor.compress(raw) |
| 107 | + body["transcript_b64"] = base64.b64encode(compressed).decode() |
| 108 | + logger.info( |
| 109 | + "Transcript: %d bytes → %d compressed (%.0f%% savings)", |
| 110 | + len(raw), |
| 111 | + len(compressed), |
| 112 | + (1 - len(compressed) / len(raw)) * 100 if raw else 0, |
| 113 | + ) |
| 114 | + except ImportError: |
| 115 | + logger.warning( |
| 116 | + "zstandard not installed — storing cycle run without transcript" |
| 117 | + ) |
| 118 | + except Exception: |
| 119 | + logger.warning("Failed to read/compress transcript", exc_info=True) |
| 120 | + else: |
| 121 | + logger.debug("Transcript file not found for session %s", session_id) |
| 122 | + |
| 123 | + try: |
| 124 | + httpx.post(CYCLE_RUNS_API, json=body, timeout=10.0) |
| 125 | + except Exception: |
| 126 | + logger.warning("Failed to push cycle run to API", exc_info=True) |
0 commit comments