Back to Opik

Share Diagram

.agents/commands/comet/share-diagram.md

2.0.24-526210.2 KB
Original Source

Share Diagram

Command: cursor share-diagram

Overview

Analyze the current branch's diff and Jira ticket context, then generate a self-contained HTML architecture diagram at {MAIN_REPO_ROOT}/diagrams/opik-{TICKET_NUMBER}-diagram.html.

  • Execution model: Stateless. Each invocation re-checks tool availability (gh preferred, GitHub MCP fallback), re-analyzes the current branch diff and Jira context, then generates a fresh diagram.

This workflow will:

  • Extract Jira ticket context from the current branch
  • Gather the git diff (PR diff if available, otherwise branch diff from main)
  • Analyze changes to understand data flow, architecture, and design decisions
  • Generate a self-contained HTML diagram using the diagram-generation skill
  • Save the diagram under the main repo root's diagrams/ folder (gitignored, local artifact) — even when running inside a worktree, so the diagram survives worktree removal
  • Provide the file path for the user to open in a browser

Inputs

  • Ticket number (optional): Override auto-detection from branch name. E.g., OPIK-4501
  • Focus (optional): What aspect to emphasize — flow, architecture, files, decisions, or all (default: all)

Steps

1. Preflight & Environment Check

  • Check Jira MCP: Test availability by attempting to fetch user info

    If unavailable: warn but continue — diagram can be generated from code diff alone without Jira context.

  • Check GitHub CLI (preferred): Ensure gh is installed and authenticated (gh auth status)
  • GitHub fallback path: If gh is unavailable or unauthenticated, test GitHub MCP availability by fetching repository info for comet-ml/opik.

    If both are unavailable: warn but continue — diagram can be generated from local git diff alone.

  • Check git repository: Verify we're in a git repo with commits.
  • Resolve main repo root: Compute MAIN_REPO_ROOT="$(dirname "$(git rev-parse --path-format=absolute --git-common-dir)")". This returns the main worktree root whether we're currently in the main checkout or in a linked worktree under .claude/worktrees/. All diagram output goes under ${MAIN_REPO_ROOT}/diagrams/ so the files outlive any temporary worktree.
  • Ensure ${MAIN_REPO_ROOT}/diagrams/ directory exists: Create if missing.

2. Extract Context

Ticket Context

  • Parse branch name: Extract OPIK-<number> from current branch (format: <username>/OPIK-<number>-<description>)
  • If ticket not found in branch name (including main, NA branches like user/NA-some-task, or other non-standard formats): Check if a ticket number was provided as input. If not, ask the user for one.
  • If no ticket number available: Skip Jira fetch entirely — generate diagram from code diff alone, using the branch description as the title.
  • Fetch Jira ticket (if ticket found): Get summary, description, issue type, status, priority, labels, comments
  • Build ticket context: Title, type, key requirements, acceptance criteria

Code Changes

  • Check for PR: Use gh pr view --json number,title,url (preferred) or GitHub MCP to find an open PR for the current branch on comet-ml/opik
    • If PR exists: use gh pr diff or GitHub MCP PR diff (preferred — includes review context)
    • If no PR or no GitHub tool available: use git diff main...HEAD for local changes
  • Parse diff: Identify files changed, grouped by component layer:
    • API layer: Resources, endpoints, request/response models
    • Service layer: Business logic, services
    • DAO layer: Database access, SQL, queries
    • Model layer: Domain models, DTOs, enums
    • Migration layer: Database migrations (Liquibase, ClickHouse)
    • Test layer: Unit tests, integration tests
    • Frontend layer: React components, hooks, stores
    • SDK layer: Python/TypeScript SDK changes
  • Identify patterns: New files vs modified, what data flows through the change

3. Analyze & Plan Diagram Sections

Based on the changes, determine which sections to include:

Change TypeSections
New API endpointRequest flow, files changed, design decisions
Bug fixProblem/solution banners, before/after flow, safety guards
New featureData flow, architecture tree, files changed, design decisions
RefactorBefore/after architecture, files changed
Database migrationStorage diagram, data flow, migration notes
Cross-componentFull flow (API → Service → DAO → Storage), files by layer

Always include Files Changed section. Include at most 4 sections total.


4. Generate HTML Diagram

  • Load the diagram-generation skill: Use the style guide and template from .agents/skills/diagram-generation/
  • Fill template sections:
    • Title: OPIK-{TICKET} — {Jira Title}
    • Subtitle: One-line summary of the change
    • Sections: Based on analysis from step 3
  • Apply style guide: Use semantic colors, flow boxes, section labels with dots, and all CSS patterns from the style guide
  • Include "Copy as image" button: Using the Canvas API + Clipboard API script from the template
  • Content safety:
    • NEVER include raw secrets, API keys, tokens, or passwords in diagram content
    • NEVER include customer names unless specifically requested — they should not be public
    • Diagram content should be high-level summaries (component names, flow descriptions, file names) — never raw diff hunks or verbatim Jira comments
  • Content rules:
    • Keep text concise — diagram is visual, not a document
    • Use <b> for component names inside boxes
    • Use for secondary details in boxes
    • Use .code spans for inline code references
    • Use .note for supplementary explanations below flows
    • Max 4 sections per diagram
    • Each flow row should have 3-6 boxes max

5. Save Diagram

  • Output path: ${MAIN_REPO_ROOT}/diagrams/opik-{TICKET_NUMBER}-diagram.html — always under the main repo root, even when the session is running inside a worktree. This keeps the diagram accessible after the worktree is removed.
  • Create ${MAIN_REPO_ROOT}/diagrams/ directory if it doesn't exist
  • Write the HTML file using the Write tool (pass the absolute path)
  • Verify file was written by reading the first few lines back

6. Render PNG Preview (requires Playwright MCP)

Render the diagram to PNG and display it inline in chat.

Note: Playwright MCP blocks file:// URLs, so serve the HTML over a local HTTP server.

  1. Start server: python3 -m http.server 8787 --bind 127.0.0.1 in the ${MAIN_REPO_ROOT}/diagrams/ directory (run in background)
  2. Navigate: browser_navigate to http://localhost:8787/opik-{TICKET_NUMBER}-diagram.html
  3. Hide button: browser_evaluate with document.querySelector('.copy-btn').style.display = 'none' — prevents the fixed-position button from appearing in the screenshot
  4. Snapshot: browser_snapshot to get the element ref for #diagram
  5. Screenshot: browser_take_screenshot targeting the #diagram element ref
    • Use an absolute path for the filename: ${MAIN_REPO_ROOT}/diagrams/opik-{TICKET_NUMBER}-diagram.png
    • Playwright saves relative to its own CWD, so absolute paths ensure the PNG lands in the main repo's diagrams/ folder (not the worktree's)
  6. Close & cleanup: browser_close, then kill the HTTP server process
  7. Display: Use the Read tool on the PNG — it renders as an image inline in the chat

If Playwright MCP is not available, skip this step and fall back to showing the HTML file path.


7. Present Result

  • Show the PNG inline if generated (step 6) — this is the primary visual output
  • Show the HTML file path as a markdown link using the absolute path (e.g., [diagrams/opik-{TICKET}-diagram.html](${MAIN_REPO_ROOT}/diagrams/opik-{TICKET}-diagram.html)). Absolute paths ensure the link is clickable regardless of which folder the IDE has open as its workspace — important when the session is running inside a worktree while the user has the main repo open in VSCode.
  • Summarize sections: Brief description of what each section covers

Error Handling

Jira MCP Failures

  • Connection issues: Check network and authentication
  • Ticket not found: Ask user to verify ticket number
  • No description: Generate diagram from code diff alone, note the gap

GitHub CLI / MCP Failures

  • gh not installed or unauthenticated: Fall back to GitHub MCP
  • Both unavailable: Fall back to local git diff main...HEAD
  • No PR found: Fall back to local git diff main...HEAD
  • PR diff too large: Summarize by file, focus on key changes

Git Failures

  • On main with no ticket: Prompt for ticket number
  • No commits ahead of main: Show error — nothing to diagram
  • Merge conflicts: Warn but generate from available diff

Diagram Generation Failures

  • Changes too small: Generate a minimal diagram with just files changed
  • Changes too large (>30 files): Group by component, show top-level flow only

Success Criteria

The command is successful when:

  1. Jira ticket context was fetched (or gracefully skipped)
  2. Code diff was analyzed and categorized by layer
  3. HTML diagram was generated with correct styling
  4. "Copy as image" button works in the generated HTML
  5. File was saved to ${MAIN_REPO_ROOT}/diagrams/opik-{TICKET_NUMBER}-diagram.html
  6. User was shown the file path (as an absolute-path markdown link) and summary

Notes

  • Diagrams are local artifacts — the main repo's /diagrams/ folder is gitignored
  • Diagrams are always written under the main repo root's diagrams/ folder. When the session runs inside a worktree under .claude/worktrees/, the command resolves MAIN_REPO_ROOT via git rev-parse --git-common-dir so the file lands in the shared diagrams/ folder and survives worktree removal.
  • The diagram-generation logic lives in .agents/skills/diagram-generation/ (shared skill)
  • The "Copy as image" button uses the browser Canvas API — requires opening in a modern browser
  • When run without a PR, the diagram reflects local uncommitted + committed changes vs main
  • Diagrams should be concise and visual — prefer boxes and flows over paragraphs of text

End Command