⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat: Add Observability skill - real-time agent monitoring dashboard
Daniel Miesslerab97c3630648
diff --git a/.claude/skills/observability/.gitignore b/.claude/skills/observability/.gitignorenew file mode 100644index 00000000..c19ce206--- /dev/null+++ b/.claude/skills/observability/.gitignore@@ -0,0 +1,6 @@+node_modules/+.vite/+dist/+*.log+.DS_Store+.tmp/diff --git a/.claude/skills/observability/SKILL.md b/.claude/skills/observability/SKILL.mdnew file mode 100644index 00000000..05b7e026--- /dev/null+++ b/.claude/skills/observability/SKILL.md@@ -0,0 +1,160 @@+---+name: Observability+description: Real-time monitoring dashboard for PAI multi-agent activity. USE WHEN user says 'start observability', 'stop dashboard', 'restart observability', 'monitor agents', 'show agent activity', or needs to debug multi-agent workflows.+---++# Agent Observability Dashboard++Real-time monitoring of PAI multi-agent activity with WebSocket streaming.++## Quick Start++```bash+# Start server and dashboard+~/.claude/skills/observability/manage.sh start++# Stop everything+~/.claude/skills/observability/manage.sh stop++# Restart both+~/.claude/skills/observability/manage.sh restart++# Check status+~/.claude/skills/observability/manage.sh status+```++## Access Points++- **Dashboard UI**: http://localhost:5172+- **Server API**: http://localhost:4000+- **WebSocket Stream**: ws://localhost:4000/stream++## What It Monitors++### Real-Time Tracking+- Agent session starts/ends+- Tool calls across all agents+- Hook event execution+- Session timelines and traces+- WebSocket live updates++### Data Sources+- **Primary**: `~/.claude/history/raw-outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl`+- **Format**: JSONL with structured event data+- **Hooks**: Events logged automatically by PAI hook system++## Architecture++**Stack:**+- Server: Bun + Express + TypeScript+- Client: Vite + Vue + TypeScript+- Storage: In-memory streaming (no database)+- Protocol: WebSocket for real-time updates++**Key Features:**+- Watch filesystem with automatic reload+- Tail-follow for today's event file+- Cache events in-memory+- Broadcast WebSocket to all clients+- No persistence (fresh start each launch)++## When to Activate This Skill++- "Start observability"+- "Stop the dashboard"+- "Restart observability"+- "Monitor agents"+- "Show agent activity"+- "Observability status"+- "Debug agent workflow"++## Examples++**Example 1: Start monitoring agents**+```+User: "start observability"+→ Launches server on port 4000+→ Starts dashboard on port 5172+→ Opens browser to live agent activity view+```++**Example 2: Debug a stuck workflow**+```+User: "something's weird with my agents, show me what's happening"+→ Opens observability dashboard+→ Shows real-time tool calls across all agents+→ Reveals which agent is blocked or looping+```++**Example 3: Check dashboard status**+```+User: "is observability running?"+→ Runs manage.sh status+→ Reports server and client running state+→ Shows access URLs if active+```++## Development++### Server+```bash+cd ~/.claude/skills/observability/apps/server+bun install+bun run dev+```++### Client+```bash+cd ~/.claude/skills/observability/apps/client+bun install+bun run dev+```++## Troubleshooting++### Dashboard not loading+- Check server is running: `curl http://localhost:4000/health`+- Check client is running: `curl http://localhost:5172`+- Restart: `./manage.sh restart`++### No events showing+- Verify events file exists: `~/.claude/history/raw-outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl`+- Check hooks are configured in `~/.claude/settings.json`+- Try triggering an event (use any tool or agent)++### Port conflicts+- Server uses: 4000+- Client uses: 5172+- Check nothing else is using these ports++## Files++```+~/.claude/skills/observability/+├── SKILL.md # This file+├── manage.sh # Control script+├── apps/+│ ├── server/ # Backend (Bun + Express)+│ │ ├── src/index.ts+│ │ └── package.json+│ └── client/ # Frontend (Vite + Vue)+│ ├── src/+│ ├── package.json+│ └── vite.config.ts+└── scripts/ # Utility scripts+```++## Key Principles++1. **Real-time** - Events stream as they happen+2. **Ephemeral** - No persistence, in-memory only+3. **Simple** - No database, no configuration+4. **Transparent** - Full visibility into agent activity+5. **Unobtrusive** - Doesn't interfere with PAI operation++## Hook Integration++For the observability dashboard to receive events, configure your PAI hooks to log to:+`~/.claude/history/raw-outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl`++The `capture-all-events.ts` hook in `~/.claude/hooks/` handles this automatically.diff --git a/.claude/skills/observability/apps/client/README.md b/.claude/skills/observability/apps/client/README.mdnew file mode 100644index 00000000..33895ab2--- /dev/null+++ b/.claude/skills/observability/apps/client/README.md@@ -0,0 +1,5 @@+# Vue 3 + TypeScript + Vite++This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.++Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).diff --git a/.claude/skills/observability/apps/client/index.html b/.claude/skills/observability/apps/client/index.htmlnew file mode 100644index 00000000..3e68f0c3--- /dev/null+++ b/.claude/skills/observability/apps/client/index.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <link rel="icon" type="image/svg+xml" href="/binoculars.svg" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Agents</title>+ </head>+ <body>+ <div id="app"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/.claude/skills/observability/apps/client/package.json b/.claude/skills/observability/apps/client/package.jsonnew file mode 100644index 00000000..47a52214--- /dev/null+++ b/.claude/skills/observability/apps/client/package.json@@ -0,0 +1,26 @@+{+ "name": "multi-agent-observability-client",+ "private": true,+ "version": "1.2.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vue-tsc -b && vite build",+ "preview": "vite preview"+ },+ "dependencies": {+ "lucide-vue-next": "^0.548.0",+ "vue": "^3.5.17"+ },+ "devDependencies": {+ "@types/node": "^22.11.2",+ "@vitejs/plugin-vue": "^6.0.0",+ "@vue/tsconfig": "^0.7.0",+ "autoprefixer": "^10.4.20",+ "postcss": "^8.5.3",+ "tailwindcss": "^3.4.16",+ "typescript": "~5.8.3",+ "vite": "^7.0.4",+ "vue-tsc": "^2.2.12"+ }+}diff --git a/.claude/skills/observability/apps/client/postcss.config.js b/.claude/skills/observability/apps/client/postcss.config.jsnew file mode 100644index 00000000..e99ebc2c--- /dev/null+++ b/.claude/skills/observability/apps/client/postcss.config.js@@ -0,0 +1,6 @@+export default {+ plugins: {+ tailwindcss: {},+ autoprefixer: {},+ },+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/public/binoculars.svg b/.claude/skills/observability/apps/client/public/binoculars.svgnew file mode 100644index 00000000..64302261--- /dev/null+++ b/.claude/skills/observability/apps/client/public/binoculars.svg@@ -0,0 +1,16 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <!-- Left barrel -->+ <rect x="3" y="6" width="6" height="12" rx="3" fill="#a855f7" stroke="#9333ea" stroke-width="1.5"/>+ <!-- Right barrel -->+ <rect x="15" y="6" width="6" height="12" rx="3" fill="#a855f7" stroke="#9333ea" stroke-width="1.5"/>+ <!-- Bridge connecting the two barrels -->+ <path d="M9 11h6" stroke="#9333ea" stroke-width="2"/>+ <!-- Left eyepiece -->+ <circle cx="6" cy="6" r="2.5" fill="#c084fc" stroke="#9333ea" stroke-width="1.5"/>+ <!-- Right eyepiece -->+ <circle cx="18" cy="6" r="2.5" fill="#c084fc" stroke="#9333ea" stroke-width="1.5"/>+ <!-- Left objective lens -->+ <circle cx="6" cy="18" r="2.5" fill="#7c3aed" stroke="#9333ea" stroke-width="1.5"/>+ <!-- Right objective lens -->+ <circle cx="18" cy="18" r="2.5" fill="#7c3aed" stroke="#9333ea" stroke-width="1.5"/>+</svg>diff --git a/.claude/skills/observability/apps/client/public/vite.svg b/.claude/skills/observability/apps/client/public/vite.svgnew file mode 100644index 00000000..e7b8dfb1--- /dev/null+++ b/.claude/skills/observability/apps/client/public/vite.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/App.vue b/.claude/skills/observability/apps/client/src/App.vuenew file mode 100644index 00000000..7df531ff--- /dev/null+++ b/.claude/skills/observability/apps/client/src/App.vue@@ -0,0 +1,203 @@+<template>+ <div class="compact-mode h-screen flex flex-col theme-tokyo-night dashboard-modern">+ <!-- Background gradient overlay -->+ <div class="fixed inset-0 bg-gradient-to-br from-[#1a1b26] via-[#16161e] to-[#0f0f14] -z-10"></div>+ <div class="fixed inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiM3YWEyZjciIGZpbGwtb3BhY2l0eT0iMC4wMiI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMSIvPjwvZz48L2c+PC9zdmc+')] -z-10 opacity-50"></div>++ <!-- Filters -->+ <FilterPanel+ v-if="showFilters"+ class="short:hidden glass-panel-elevated mx-4 mt-4 rounded-2xl"+ :filters="filters"+ @update:filters="filters = $event"+ />++ <!-- Live Pulse Chart - Glass Panel -->+ <div class="mx-4 mt-4 mobile:mx-2 mobile:mt-2">+ <div class="glass-panel rounded-2xl overflow-hidden">+ <LivePulseChart+ :events="events"+ :filters="filters"+ :time-range="currentTimeRange"+ @update-unique-apps="uniqueAppNames = $event"+ @update-all-apps="allAppNames = $event"+ @update-time-range="currentTimeRange = $event"+ @update-heat-level="heatLevel = $event"+ @update-events-per-minute="eventsPerMinute = $event"+ @update-agent-counts="agentCounts = $event"+ @clear-events="handleClearClick"+ @toggle-filters="showFilters = !showFilters"+ />+ </div>+ </div>++ <!-- Agent Swim Lane Container - Glass Panel -->+ <div v-if="selectedAgentLanes.length > 0" class="mx-4 mt-4 mobile:mx-2 mobile:mt-2">+ <div class="glass-panel rounded-2xl p-4 mobile:p-2">+ <AgentSwimLaneContainer+ :selected-agents="selectedAgentLanes"+ :events="events"+ :time-range="currentTimeRange"+ @update:selected-agents="selectedAgentLanes = $event"+ />+ </div>+ </div>++ <!-- Timeline - Glass Panel -->+ <div class="flex flex-col flex-1 overflow-hidden mx-4 my-4 mobile:mx-2 mobile:my-2">+ <div class="glass-panel rounded-2xl flex-1 overflow-hidden">+ <EventTimeline+ :events="events"+ :filters="filters"+ :unique-app-names="uniqueAppNames"+ :all-app-names="allAppNames"+ :heat-level="heatLevel"+ :agent-counts="agentCounts"+ :events-per-minute="eventsPerMinute"+ :time-range="currentTimeRange"+ :time-ranges="['1M', '2M', '4M', '8M', '16M']"+ v-model:stick-to-bottom="stickToBottom"+ @select-agent="toggleAgentLane"+ @set-time-range="setTimeRangeFromTimeline"+ />+ </div>+ </div>++ <!-- Stick to bottom button - Glass styling -->+ <StickScrollButton+ class="short:hidden glass-button"+ :stick-to-bottom="stickToBottom"+ @toggle="stickToBottom = !stickToBottom"+ />++ <!-- Error message - Glass styling -->+ <div+ v-if="error"+ class="fixed bottom-6 left-6 mobile:bottom-4 mobile:left-4 mobile:right-4 glass-panel-elevated rounded-xl px-4 py-3 mobile:px-3 mobile:py-2 border-l-4 border-[var(--theme-accent-error)]"+ >+ <span class="text-[var(--theme-accent-error)] font-medium">{{ error }}</span>+ </div>++ <!-- Theme Manager -->+ <ThemeManager+ :is-open="showThemeManager"+ @close="showThemeManager = false"+ />++ <!-- Toast Notifications -->+ <ToastNotification+ v-for="(toast, index) in toasts"+ :key="toast.id"+ :index="index"+ :agent-name="toast.agentName"+ :agent-color="toast.agentColor"+ @dismiss="dismissToast(toast.id)"+ />+ </div>+</template>++<script setup lang="ts">+import { ref, watch } from 'vue';+import type { TimeRange } from './types';+import { useWebSocket } from './composables/useWebSocket';+import { useThemes } from './composables/useThemes';+import { useEventColors } from './composables/useEventColors';+import EventTimeline from './components/EventTimeline.vue';+import FilterPanel from './components/FilterPanel.vue';+import StickScrollButton from './components/StickScrollButton.vue';+import LivePulseChart from './components/LivePulseChart.vue';+import ThemeManager from './components/ThemeManager.vue';+import ToastNotification from './components/ToastNotification.vue';+import AgentSwimLaneContainer from './components/AgentSwimLaneContainer.vue';++// WebSocket connection+const { events, isConnected, error, clearEvents } = useWebSocket('ws://localhost:4000/stream');++// Theme management (sets up theme system)+useThemes();++// Event colors+const { getHexColorForApp } = useEventColors();++// Filters+const filters = ref({+ sourceApp: '',+ sessionId: '',+ eventType: ''+});++// UI state+const stickToBottom = ref(true);+const showThemeManager = ref(false);+const showFilters = ref(false);+const uniqueAppNames = ref<string[]>([]); // Apps active in current time window+const allAppNames = ref<string[]>([]); // All apps ever seen in session+const selectedAgentLanes = ref<string[]>([]);+const currentTimeRange = ref<TimeRange>('1M'); // Current time range from LivePulseChart+const heatLevel = ref({ intensity: 0, color: '#565f89', label: 'Low' });+const agentCounts = ref<Record<string, number>>({});+const eventsPerMinute = ref(0);++// Toast notifications+interface Toast {+ id: number;+ agentName: string;+ agentColor: string;+}+const toasts = ref<Toast[]>([]);+let toastIdCounter = 0;+const seenAgents = new Set<string>();++// Watch for new agents and show toast+watch(uniqueAppNames, (newAppNames) => {+ // Find agents that are new (not in seenAgents set)+ newAppNames.forEach(appName => {+ if (!seenAgents.has(appName)) {+ seenAgents.add(appName);+ // Show toast for new agent+ const toast: Toast = {+ id: toastIdCounter++,+ agentName: appName,+ agentColor: getHexColorForApp(appName)+ };+ toasts.value.push(toast);+ }+ });+}, { deep: true });++const dismissToast = (id: number) => {+ const index = toasts.value.findIndex(t => t.id === id);+ if (index !== -1) {+ toasts.value.splice(index, 1);+ }+};++// Handle agent tag clicks for swim lanes+const toggleAgentLane = (agentName: string) => {+ const index = selectedAgentLanes.value.indexOf(agentName);+ if (index >= 0) {+ // Remove from comparison+ selectedAgentLanes.value.splice(index, 1);+ } else {+ // Add to comparison+ selectedAgentLanes.value.push(agentName);+ }+};++// Handle clear button click+const handleClearClick = () => {+ clearEvents();+ selectedAgentLanes.value = [];+};++// Handle time range change from EventTimeline+const setTimeRangeFromTimeline = (range: TimeRange) => {+ currentTimeRange.value = range;+};++// Debug handler for theme manager+const handleThemeManagerClick = () => {+ console.log('Theme manager button clicked!');+ showThemeManager.value = true;+};+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/assets/fonts.css b/.claude/skills/observability/apps/client/src/assets/fonts.cssnew file mode 100644index 00000000..3f1e02e5--- /dev/null+++ b/.claude/skills/observability/apps/client/src/assets/fonts.css@@ -0,0 +1,68 @@+@font-face {+ font-family: 'concourse-t3';+ src: url('./fonts/concourse_t3_regular-webfont.woff') format('woff');+ font-style: normal;+ font-weight: normal;+ font-stretch: normal;+ font-display: swap;+}++@font-face {+ font-family: 'concourse-c3';+ src: url('./fonts/concourse_c3_regular.woff') format('woff');+ font-style: normal;+ font-weight: normal;+ font-stretch: normal;+ font-display: swap;+}++@font-face {+ font-family: 'equity-text-b';+ src: url('./fonts/equity_text_b_regular-webfont.woff') format('woff');+ font-style: normal;+ font-weight: normal;+ font-stretch: normal;+ font-display: swap;+}++@font-face {+ font-family: 'advocate';+ font-style: normal;+ font-weight: normal;+ font-stretch: normal;+ font-display: swap;+ src: url('./fonts/advocate_14_cond_reg.woff2') format('woff2');+}++/* Valkyrie text fonts */+@font-face {+ font-family: 'valkyrie-text';+ src: url('./fonts/valkyrie_a_regular.woff2') format('woff2');+ font-weight: normal;+ font-style: normal;+ font-display: swap;+}++@font-face {+ font-family: 'valkyrie-text';+ src: url('./fonts/valkyrie_a_bold.woff2') format('woff2');+ font-weight: bold;+ font-style: normal;+ font-display: swap;+}++@font-face {+ font-family: 'valkyrie-text';+ src: url('./fonts/valkyrie_a_italic.woff2') format('woff2');+ font-weight: normal;+ font-style: italic;+ font-display: swap;+}++@font-face {+ font-family: 'valkyrie-text';+ src: url('./fonts/valkyrie_a_bold_italic.woff2') format('woff2');+ font-weight: bold;+ font-style: italic;+ font-display: swap;+}diff --git a/.claude/skills/observability/apps/client/src/assets/fonts/advocate_14_cond_reg.woff2 b/.claude/skills/observability/apps/client/src/assets/fonts/advocate_14_cond_reg.woff2new file mode 100644index 00000000..dda43184Binary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/advocate_14_cond_reg.woff2 differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/concourse_c3_regular.woff b/.claude/skills/observability/apps/client/src/assets/fonts/concourse_c3_regular.woffnew file mode 100644index 00000000..c102a6e9Binary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/concourse_c3_regular.woff differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/concourse_t3_regular-webfont.woff b/.claude/skills/observability/apps/client/src/assets/fonts/concourse_t3_regular-webfont.woffnew file mode 100644index 00000000..be11d447Binary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/concourse_t3_regular-webfont.woff differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/equity_text_b_regular-webfont.woff b/.claude/skills/observability/apps/client/src/assets/fonts/equity_text_b_regular-webfont.woffnew file mode 100644index 00000000..9a42b5afBinary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/equity_text_b_regular-webfont.woff differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold.woff2 b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold.woff2new file mode 100644index 00000000..35d8ea2dBinary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold.woff2 differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold_italic.woff2 b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold_italic.woff2new file mode 100644index 00000000..c2ccba3cBinary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_bold_italic.woff2 differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_italic.woff2 b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_italic.woff2new file mode 100644index 00000000..0af16d45Binary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_italic.woff2 differdiff --git a/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_regular.woff2 b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_regular.woff2new file mode 100644index 00000000..4387da7eBinary files /dev/null and b/.claude/skills/observability/apps/client/src/assets/fonts/valkyrie_a_regular.woff2 differdiff --git a/.claude/skills/observability/apps/client/src/assets/vue.svg b/.claude/skills/observability/apps/client/src/assets/vue.svgnew file mode 100644index 00000000..770e9d33--- /dev/null+++ b/.claude/skills/observability/apps/client/src/assets/vue.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/AgentSwimLane.vue b/.claude/skills/observability/apps/client/src/components/AgentSwimLane.vuenew file mode 100644index 00000000..6ea81dbf--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/AgentSwimLane.vue@@ -0,0 +1,728 @@+<template>+ <div class="agent-swim-lane">+ <div class="lane-header">+ <div class="header-left">+ <div class="agent-label-container">+ <span+ class="agent-label-app-only"+ :style="{+ backgroundColor: getHexColorForApp(appName),+ borderColor: getHexColorForApp(appName)+ }"+ >+ <span class="font-mono text-xs">{{ appName }}</span>+ </span>+ </div>+ <div+ v-if="modelName"+ class="model-badge"+ :title="`Model: ${modelName}`"+ >+ <Brain :size="14" :stroke-width="2.5" />+ <span class="text-xs font-bold">{{ formatModelName(modelName) }}</span>+ </div>+ <div+ class="event-count-badge"+ @mouseover="hoveredEventCount = true"+ @mouseleave="hoveredEventCount = false"+ :title="`Total events in the last ${timeRange === '1m' ? '1 minute' : timeRange === '3m' ? '3 minutes' : '5 minutes'}`"+ >+ <Zap :size="14" :stroke-width="2.5" class="flex-shrink-0" />+ <span class="text-xs font-bold" :class="hoveredEventCount ? 'min-w-[65px]' : ''">+ {{ hoveredEventCount ? `${totalEventCount} Events` : totalEventCount }}+ </span>+ </div>+ <div+ class="tool-call-badge"+ @mouseover="hoveredToolCount = true"+ @mouseleave="hoveredToolCount = false"+ :title="`Tool calls in the last ${timeRange === '1m' ? '1 minute' : timeRange === '3m' ? '3 minutes' : '5 minutes'}`"+ >+ <Wrench :size="14" :stroke-width="2.5" class="flex-shrink-0" />+ <span class="text-xs font-bold" :class="hoveredToolCount ? 'min-w-[75px]' : ''">+ {{ hoveredToolCount ? `${toolCallCount} Tool Calls` : toolCallCount }}+ </span>+ </div>+ <div+ class="avg-time-badge flex items-center gap-1.5 px-2 py-2 bg-[var(--theme-bg-tertiary)] rounded-lg border border-[var(--theme-border-primary)] shadow-sm min-h-[28px]"+ @mouseover="hoveredAvgTime = true"+ @mouseleave="hoveredAvgTime = false"+ :title="`Average time between events in the last ${timeRange === '1m' ? '1 minute' : timeRange === '3m' ? '3 minutes' : '5 minutes'}`"+ >+ <Clock :size="16" :stroke-width="2.5" class="flex-shrink-0" />+ <span class="text-sm font-bold text-[var(--theme-text-primary)]" :class="hoveredAvgTime ? 'min-w-[90px]' : ''">+ {{ hoveredAvgTime ? `Avg Gap: ${formatGap(agentEventTimingMetrics.avgGap)}` : formatGap(agentEventTimingMetrics.avgGap) }}+ </span>+ </div>+ </div>+ <button @click="emit('close')" class="close-btn" title="Remove this swim lane">+ <X :size="16" :stroke-width="2.5" />+ </button>+ </div>+ <div ref="chartContainer" class="chart-wrapper">+ <canvas+ ref="canvas"+ class="w-full cursor-crosshair"+ :style="{ height: chartHeight + 'px' }"+ @mousemove="handleMouseMove"+ @mouseleave="handleMouseLeave"+ @click="handleCanvasClick"+ role="img"+ :aria-label="chartAriaLabel"+ ></canvas>+ <div+ v-if="tooltip.visible"+ class="absolute bg-gradient-to-r from-[var(--theme-primary)] to-[var(--theme-primary-dark)] text-white px-2 py-1.5 rounded-lg text-xs pointer-events-none z-10 shadow-lg border border-[var(--theme-primary-light)] font-bold drop-shadow-md"+ :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"+ >+ {{ tooltip.text }}+ </div>+ <div+ v-if="!hasData"+ class="absolute inset-0 flex items-center justify-center"+ >+ <p class="flex items-center gap-2 text-[var(--theme-text-tertiary)] text-sm font-semibold">+ <Loader2 :size="16" :stroke-width="2.5" class="animate-spin" />+ Waiting for events...+ </p>+ </div>+ </div>+ <!-- Cluster Expansion Panel -->+ <div v-if="expandedCluster" class="cluster-details">+ <div class="cluster-details-header">+ <span class="font-bold">Cluster Details</span>+ <button @click="expandedCluster = null" class="close-btn-small">+ <X :size="14" :stroke-width="2.5" />+ </button>+ </div>+ <div class="cluster-details-body">+ <div v-for="(point, index) in getChartData().filter(p => p.clusterId === expandedCluster)" :key="index">+ <div class="cluster-summary">+ <span class="font-bold">{{ point.summaryText || 'Event Cluster' }}</span>+ <span class="text-xs text-[var(--theme-text-tertiary)]">{{ point.count }} events</span>+ </div>+ <div class="event-list">+ <div v-for="(event, eventIndex) in point.rawEvents?.slice(0, 10)" :key="eventIndex" class="event-item">+ <span class="event-type">{{ event.hook_event_type }}</span>+ <span class="event-app">{{ event.source_app ? event.source_app.charAt(0).toUpperCase() + event.source_app.slice(1) : event.source_app }}</span>+ <span class="event-time">{{ new Date(event.timestamp || 0).toLocaleTimeString() }}</span>+ </div>+ <div v-if="(point.rawEvents?.length || 0) > 10" class="text-xs text-[var(--theme-text-tertiary)] mt-2">+ ... and {{ (point.rawEvents?.length || 0) - 10 }} more events+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, onMounted, onUnmounted, watch, computed } from 'vue';+import type { HookEvent, TimeRange, ChartConfig } from '../types';+import { useAgentChartData } from '../composables/useAgentChartData';+import { createChartRenderer, type ChartDimensions } from '../utils/chartRenderer';+import { useEventEmojis } from '../composables/useEventEmojis';+import { useEventColors } from '../composables/useEventColors';+import { Brain, Wrench, Clock, X, Zap, Loader2 } from 'lucide-vue-next';++const props = defineProps<{+ agentName: string; // Format: "agent:session" (e.g., "pentester:a1b2c3d4")+ events: HookEvent[];+ timeRange: TimeRange;+}>();++const emit = defineEmits<{+ close: [];+}>();++const canvas = ref<HTMLCanvasElement>();+const chartContainer = ref<HTMLDivElement>();+const chartHeight = 80;+const hoveredEventCount = ref(false);+const hoveredToolCount = ref(false);+const hoveredAvgTime = ref(false);++// Format gap time in ms to readable string (e.g., "125ms" or "1.2s")+const formatGap = (gapMs: number): string => {+ if (gapMs === 0) return '—';+ if (gapMs < 1000) {+ return `${Math.round(gapMs)}ms`;+ }+ return `${(gapMs / 1000).toFixed(1)}s`;+};++// Extract app name and session ID from agent ID for display+const appName = computed(() => props.agentName.split(':')[0]);+const sessionId = computed(() => props.agentName.split(':')[1]);++// Get model name from most recent event for this agent+const modelName = computed(() => {+ const [targetAgent, targetSession] = props.agentName.split(':');+ const agentEvents = props.events+ .filter(e => {+ // PAI uses agent_name field (if available) or falls back to source_app+ const eventAgent = e.agent_name || e.source_app;+ return eventAgent === targetAgent && e.session_id.slice(0, 8) === targetSession;+ })+ .filter(e => e.model_name); // Only events with model_name++ if (agentEvents.length === 0) return null;++ // Get most recent event's model name+ const mostRecent = agentEvents[agentEvents.length - 1];+ return mostRecent.model_name;+});++// Format model name for display (e.g., "claude-haiku-4-5-20251001" -> "haiku-4-5")+const formatModelName = (name: string | null | undefined): string => {+ if (!name) return '';++ // Extract model family and version+ // "claude-haiku-4-5-20251001" -> "haiku-4-5"+ // "claude-sonnet-4-5-20250929" -> "sonnet-4-5"+ const parts = name.split('-');+ if (parts.length >= 4) {+ return `${parts[1]}-${parts[2]}-${parts[3]}`;+ }+ return name;+};++// Format event type names for user-friendly display (matching EventRow.vue)+const formatEventType = (eventType: string): string => {+ const displayNames: Record<string, string> = {+ 'PreToolUse': 'Pre-Tool',+ 'PostToolUse': 'Post-Tool',+ 'UserPromptSubmit': 'Prompt',+ 'SessionStart': 'Session Start',+ 'SessionEnd': 'Session End',+ 'Stop': 'Stop',+ 'SubagentStop': 'Subagent Stop',+ 'PreCompact': 'Pre-Compact',+ 'Notification': 'Notification',+ 'Completed': 'Completed'+ };+ return displayNames[eventType] || eventType;+};++const {+ dataPoints,+ addEvent,+ getChartData,+ setTimeRange,+ cleanup: cleanupChartData,+ eventTimingMetrics: agentEventTimingMetrics+} = useAgentChartData(props.agentName);++let renderer: ReturnType<typeof createChartRenderer> | null = null;+let resizeObserver: ResizeObserver | null = null;+let animationFrame: number | null = null;+const processedEventIds = new Set<string>();++const { formatEventTypeLabel } = useEventEmojis();+const { getHexColorForApp, getHexColorForSession } = useEventColors();++const hasData = computed(() => dataPoints.value.some(dp => dp.count > 0));++const totalEventCount = computed(() => {+ return dataPoints.value.reduce((sum, dp) => sum + dp.count, 0);+});++const toolCallCount = computed(() => {+ return dataPoints.value.reduce((sum, dp) => {+ return sum + (dp.eventTypes?.['PreToolUse'] || 0);+ }, 0);+});++const chartAriaLabel = computed(() => {+ const [app, session] = props.agentName.split(':');+ return `Activity chart for ${app} (session: ${session}) showing ${totalEventCount.value} events`;+});++const tooltip = ref({+ visible: false,+ x: 0,+ y: 0,+ text: ''+});++const getThemeColor = (property: string): string => {+ const style = getComputedStyle(document.documentElement);+ const color = style.getPropertyValue(`--theme-${property}`).trim();+ return color || '#3B82F6';+};++const getActiveConfig = (): ChartConfig => {+ return {+ maxDataPoints: 60,+ animationDuration: 300,+ barWidth: 3,+ barGap: 1,+ colors: {+ primary: getThemeColor('primary'),+ glow: getThemeColor('primary-light'),+ axis: getThemeColor('border-primary'),+ text: getThemeColor('text-tertiary')+ }+ };+};++const getDimensions = (): ChartDimensions => {+ const width = chartContainer.value?.offsetWidth || 800;+ return {+ width,+ height: chartHeight,+ padding: {+ top: 7,+ right: 7,+ bottom: 15, // Minimal padding now that labels are inline with icons+ left: 7+ }+ };+};++const render = () => {+ if (!renderer || !canvas.value) return;++ const data = getChartData();+ const maxValue = Math.max(...data.map(d => d.count), 1);++ renderer.clear();+ renderer.drawBackground();+ renderer.drawAxes();+ renderer.drawTimeLabels(props.timeRange);+ renderer.drawBars(data, maxValue, 1, formatEventTypeLabel, getHexColorForSession, getHexColorForApp);+};++const animateNewEvent = (x: number, y: number) => {+ let radius = 0;+ let opacity = 0.8;++ const animate = () => {+ if (!renderer) return;++ render();+ renderer.drawPulseEffect(x, y, radius, opacity);++ radius += 2;+ opacity -= 0.02;++ if (opacity > 0) {+ animationFrame = requestAnimationFrame(animate);+ } else {+ animationFrame = null;+ }+ };++ animate();+};++const handleResize = () => {+ if (!renderer || !canvas.value) return;++ const dimensions = getDimensions();+ renderer.resize(dimensions);+ render();+};++const processNewEvents = () => {+ const currentEvents = props.events;+ const newEventsToProcess: HookEvent[] = [];++ // Find events that haven't been processed yet+ currentEvents.forEach(event => {+ const eventKey = `${event.id}-${event.timestamp}`;+ if (!processedEventIds.has(eventKey)) {+ processedEventIds.add(eventKey);+ newEventsToProcess.push(event);+ }+ });++ // Parse agent ID to get agent name and session+ const [targetAgent, targetSession] = props.agentName.split(':');++ // Process new events (filter by agent ID: agent_name:session)+ newEventsToProcess.forEach(event => {+ if (+ event.hook_event_type !== 'refresh' &&+ event.hook_event_type !== 'initial'+ ) {+ // PAI uses agent_name field (if available) or falls back to source_app+ const eventAgent = event.agent_name || event.source_app;++ if (+ eventAgent === targetAgent &&+ event.session_id.slice(0, 8) === targetSession+ ) {+ addEvent(event);++ // Trigger pulse animation for new event+ if (renderer && canvas.value) {+ const chartArea = getDimensions();+ const x = chartArea.width - chartArea.padding.right - 10;+ const y = chartArea.height / 2;+ animateNewEvent(x, y);+ }+ }+ }+ });++ // Clean up old event IDs to prevent memory leak+ const currentEventIds = new Set(currentEvents.map(e => `${e.id}-${e.timestamp}`));+ processedEventIds.forEach(id => {+ if (!currentEventIds.has(id)) {+ processedEventIds.delete(id);+ }+ });++ render();+};++// Watch for new events - immediate: true ensures we process existing events on mount+watch(() => props.events, processNewEvents, { deep: true, immediate: true });++// Watch for time range changes - update internal timeRange and trigger reaggregation+watch(() => props.timeRange, (newRange) => {+ setTimeRange(newRange);+ render();+}, { immediate: true });++const handleMouseMove = (event: MouseEvent) => {+ if (!canvas.value || !chartContainer.value) return;++ const rect = canvas.value.getBoundingClientRect();+ const x = event.clientX - rect.left;+ const y = event.clientY - rect.top;++ const data = getChartData();+ const dimensions = getDimensions();+ const chartArea = {+ x: dimensions.padding.left,+ y: dimensions.padding.top,+ width: dimensions.width - dimensions.padding.left - dimensions.padding.right,+ height: dimensions.height - dimensions.padding.top - dimensions.padding.bottom+ };++ const barWidth = chartArea.width / data.length;+ const barIndex = Math.floor((x - chartArea.x) / barWidth);++ if (barIndex >= 0 && barIndex < data.length && y >= chartArea.y && y <= chartArea.y + chartArea.height) {+ const point = data[barIndex];+ if (point.count > 0) {+ const eventTypesText = Object.entries(point.eventTypes || {})+ .map(([type, count]) => `${formatEventType(type)}: ${count}`)+ .join(', ');++ tooltip.value = {+ visible: true,+ x: event.clientX - rect.left,+ y: event.clientY - rect.top - 30,+ text: `${point.count} events${eventTypesText ? ` (${eventTypesText})` : ''}`+ };+ return;+ }+ }++ tooltip.value.visible = false;+};++const handleMouseLeave = () => {+ tooltip.value.visible = false;+};++const expandedCluster = ref<string | null>(null);++const handleCanvasClick = (event: MouseEvent) => {+ if (!canvas.value || !chartContainer.value) return;++ const rect = canvas.value.getBoundingClientRect();+ const x = event.clientX - rect.left;++ const data = getChartData();+ const dimensions = getDimensions();+ const chartArea = {+ x: dimensions.padding.left,+ y: dimensions.padding.top,+ width: dimensions.width - dimensions.padding.left - dimensions.padding.right,+ height: dimensions.height - dimensions.padding.top - dimensions.padding.bottom+ };++ const barWidth = chartArea.width / data.length;+ const barIndex = Math.floor((x - chartArea.x) / barWidth);++ if (barIndex >= 0 && barIndex < data.length) {+ const point = data[barIndex];+ if (point.isCluster && point.clusterId) {+ // Toggle expansion+ if (expandedCluster.value === point.clusterId) {+ expandedCluster.value = null;+ } else {+ expandedCluster.value = point.clusterId;+ }+ }+ }+};++// Watch for theme changes+const themeObserver = new MutationObserver(() => {+ if (renderer) {+ render();+ }+});++onMounted(() => {+ if (!canvas.value || !chartContainer.value) return;++ const dimensions = getDimensions();+ const config = getActiveConfig();++ renderer = createChartRenderer(canvas.value, dimensions, config);++ // Set up resize observer+ resizeObserver = new ResizeObserver(handleResize);+ resizeObserver.observe(chartContainer.value);++ // Observe theme changes+ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class']+ });++ // Initial render+ render();++ // Start optimized render loop with FPS limiting+ let lastRenderTime = 0;+ const targetFPS = 30;+ const frameInterval = 1000 / targetFPS;++ const renderLoop = (currentTime: number) => {+ const deltaTime = currentTime - lastRenderTime;++ if (deltaTime >= frameInterval) {+ render();+ lastRenderTime = currentTime - (deltaTime % frameInterval);+ }++ requestAnimationFrame(renderLoop);+ };+ requestAnimationFrame(renderLoop);+});++onUnmounted(() => {+ cleanupChartData();++ if (renderer) {+ renderer.stopAnimation();+ }++ if (resizeObserver && chartContainer.value) {+ resizeObserver.disconnect();+ }++ if (animationFrame) {+ cancelAnimationFrame(animationFrame);+ }++ themeObserver.disconnect();+});+</script>++<style scoped>+.agent-swim-lane {+ width: 100%;+ background: transparent;+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin-bottom: 12px; /* Add spacing to prevent label overlap with next swimlane */+}++.lane-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ font-size: 12px;+ font-weight: 600;+ padding: 0 7px;+ gap: 8px;+}++.header-left {+ display: flex;+ align-items: center;+ gap: 6px;+}++.agent-label-container {+ display: flex;+ align-items: center;+ gap: 0;+ white-space: nowrap;+}++.agent-label-app-only {+ padding: 8px 8px;+ border-radius: 8px;+ border: 1px solid currentColor;+ color: white;+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ display: inline-flex;+ align-items: center;+ min-height: 28px;+}++.model-badge,+.event-count-badge,+.tool-call-badge {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 8px 8px;+ background: var(--theme-bg-tertiary);+ border: 1px solid var(--theme-border-primary);+ border-radius: 8px;+ color: var(--theme-text-primary);+ font-size: 11px;+ white-space: nowrap;+ cursor: pointer;+ transition: all 0.2s ease;+ user-select: none;+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);+ min-height: 28px;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);+}++.model-badge {+ cursor: default;+}++.event-count-badge:hover,+.tool-call-badge:hover,+.model-badge:hover {+ background: var(--theme-bg-quaternary);+ border-color: var(--theme-primary);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+}++.avg-time-badge {+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);+}++.close-btn {+ background: none;+ border: none;+ cursor: pointer;+ font-size: 14px;+ color: var(--theme-text-tertiary);+ padding: 0;+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 3px;+ transition: all 0.2s;+ flex-shrink: 0;+}++.close-btn:hover {+ background: var(--theme-bg-quaternary);+ color: var(--theme-text-primary);+ transform: scale(1.1);+}++.chart-wrapper {+ position: relative;+ width: 100%;+ border: 1px solid var(--theme-border-primary);+ border-radius: 6px;+ overflow: hidden;+ background: var(--theme-bg-tertiary);+}++.cluster-details {+ margin-top: 8px;+ background: var(--theme-bg-tertiary);+ border: 1px solid var(--theme-border-primary);+ border-radius: 6px;+ overflow: hidden;+}++.cluster-details-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 8px 12px;+ background: var(--theme-bg-quaternary);+ border-bottom: 1px solid var(--theme-border-primary);+ font-size: 12px;+}++.close-btn-small {+ background: none;+ border: none;+ cursor: pointer;+ color: var(--theme-text-tertiary);+ padding: 2px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 3px;+ transition: all 0.2s;+}++.close-btn-small:hover {+ background: var(--theme-bg-tertiary);+ color: var(--theme-text-primary);+}++.cluster-details-body {+ padding: 12px;+ max-height: 300px;+ overflow-y: auto;+}++.cluster-summary {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 8px;+ font-size: 13px;+}++.event-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.event-item {+ display: grid;+ grid-template-columns: 150px 150px 1fr;+ gap: 12px;+ padding: 6px 8px;+ background: var(--theme-bg-primary);+ border-radius: 4px;+ font-size: 11px;+ font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;+}++.event-type {+ color: var(--theme-text-primary);+ font-weight: 600;+}++.event-app {+ color: var(--theme-primary);+ font-weight: 600;+}++.event-time {+ color: var(--theme-text-tertiary);+ text-align: right;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/AgentSwimLaneContainer.vue b/.claude/skills/observability/apps/client/src/components/AgentSwimLaneContainer.vuenew file mode 100644index 00000000..a1cb05be--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/AgentSwimLaneContainer.vue@@ -0,0 +1,59 @@+<template>+ <div v-if="selectedAgents.length > 0" class="swim-lane-container">+ <div class="lanes-wrapper">+ <AgentSwimLane+ v-for="agent in selectedAgents"+ :key="agent"+ :agent-name="agent"+ :events="events"+ :time-range="timeRange"+ @close="removeAgent(agent)"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import type { HookEvent, TimeRange } from '../types';+import AgentSwimLane from './AgentSwimLane.vue';++const props = defineProps<{+ selectedAgents: string[];+ events: HookEvent[];+ timeRange: TimeRange;+}>();++const emit = defineEmits<{+ 'update:selectedAgents': [agents: string[]];+}>();++function removeAgent(agent: string) {+ const updated = props.selectedAgents.filter(a => a !== agent);+ emit('update:selectedAgents', updated);+}+</script>++<style scoped>+.swim-lane-container {+ width: 100%;+ animation: slideIn 0.3s ease;+}++@keyframes slideIn {+ from {+ opacity: 0;+ transform: translateY(-10px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++.lanes-wrapper {+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: 100%;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/ChatTranscript.vue b/.claude/skills/observability/apps/client/src/components/ChatTranscript.vuenew file mode 100644index 00000000..b66bc296--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/ChatTranscript.vue@@ -0,0 +1,320 @@+<template>+ <div class="bg-white dark:bg-gray-800 rounded-lg p-4 h-full overflow-y-auto space-y-3 border-2 border-gray-300 dark:border-gray-600">+ <div v-for="(item, index) in chatItems" :key="index">+ <!-- User Message -->+ <div v-if="item.type === 'user' && item.message"+ class="p-3 rounded-lg bg-blue-50 dark:bg-blue-900/30">+ <div class="flex items-start justify-between">+ <div class="flex items-start space-x-3 flex-1">+ <span class="text-lg font-semibold px-3 py-1 rounded-full flex-shrink-0 bg-blue-500 text-white">+ User+ </span>+ <div class="flex-1">+ <!-- Handle string content -->+ <p v-if="typeof item.message.content === 'string'"+ class="prose text-lg text-gray-800 dark:text-gray-100 whitespace-pre-wrap font-medium">+ {{ item.message.content.includes('<command-') ? cleanCommandContent(item.message.content) : item.message.content }}+ </p>+ <!-- Handle array content -->+ <div v-else-if="Array.isArray(item.message.content)" class="space-y-2">+ <div v-for="(content, cIndex) in item.message.content" :key="cIndex">+ <!-- Text content -->+ <p v-if="content.type === 'text'"+ class="prose text-lg text-gray-800 dark:text-gray-100 whitespace-pre-wrap font-medium">+ {{ content.text }}+ </p>+ <!-- Tool result -->+ <div v-else-if="content.type === 'tool_result'"+ class="bg-gray-100 dark:bg-gray-900 p-2 rounded">+ <span class="text-sm font-mono text-gray-600 dark:text-gray-400">Tool Result:</span>+ <pre class="text-sm text-gray-700 dark:text-gray-300 mt-1">{{ content.content }}</pre>+ </div>+ </div>+ </div>+ <!-- Metadata -->+ <div v-if="item.timestamp" class="mt-2 text-xs text-gray-500 dark:text-gray-400">+ {{ formatTimestamp(item.timestamp) }}+ </div>+ </div>+ </div>+ <!-- Action Buttons -->+ <div class="flex items-center space-x-1 ml-2">+ <!-- Show Details Button -->+ <button+ @click="toggleDetails(index)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"+ >+ {{ isDetailsExpanded(index) ? 'Hide' : 'Show' }} Details+ </button>+ <!-- Copy Button -->+ <button+ @click="copyMessage(index, item.type || item.role)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors flex items-center"+ :title="'Copy message'"+ >+ {{ getCopyButtonText(index) }}+ </button>+ </div>+ </div>+ <!-- Details Section -->+ <div v-if="isDetailsExpanded(index)" class="mt-3 p-3 bg-gray-100 dark:bg-gray-900 rounded-lg">+ <pre class="text-xs text-gray-700 dark:text-gray-300 overflow-x-auto">{{ JSON.stringify(getObfuscatedItem(index), null, 2) }}</pre>+ </div>+ </div>++ <!-- Assistant Message -->+ <div v-else-if="item.type === 'assistant' && item.message"+ class="p-3 rounded-lg bg-gray-50 dark:bg-gray-900/30">+ <div class="flex items-start justify-between">+ <div class="flex items-start space-x-3 flex-1">+ <span class="text-lg font-semibold px-3 py-1 rounded-full flex-shrink-0 bg-gray-500 text-white">+ Assistant+ </span>+ <div class="flex-1">+ <!-- Handle content array -->+ <div v-if="Array.isArray(item.message.content)" class="space-y-2">+ <div v-for="(content, cIndex) in item.message.content" :key="cIndex">+ <!-- Text content -->+ <p v-if="content.type === 'text'"+ class="prose text-lg text-gray-800 dark:text-gray-100 whitespace-pre-wrap font-medium">+ {{ content.text }}+ </p>+ <!-- Tool use -->+ <div v-else-if="content.type === 'tool_use'"+ class="bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded border border-yellow-200 dark:border-yellow-800">+ <div class="flex items-center space-x-2 mb-2">+ <Wrench :size="20" :stroke-width="2.5" class="text-yellow-600 dark:text-yellow-400" />+ <span class="font-semibold text-yellow-800 dark:text-yellow-200">{{ content.name }}</span>+ </div>+ <pre class="text-sm text-gray-700 dark:text-gray-300 overflow-x-auto">{{ JSON.stringify(content.input, null, 2) }}</pre>+ </div>+ </div>+ </div>+ <!-- Usage info -->+ <div v-if="item.message.usage" class="mt-2 text-xs text-gray-500 dark:text-gray-400">+ Tokens: {{ item.message.usage.input_tokens }} in / {{ item.message.usage.output_tokens }} out+ </div>+ <!-- Timestamp -->+ <div v-if="item.timestamp" class="mt-1 text-xs text-gray-500 dark:text-gray-400">+ {{ formatTimestamp(item.timestamp) }}+ </div>+ </div>+ </div>+ <!-- Action Buttons -->+ <div class="flex items-center space-x-1 ml-2">+ <!-- Show Details Button -->+ <button+ @click="toggleDetails(index)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"+ >+ {{ isDetailsExpanded(index) ? 'Hide' : 'Show' }} Details+ </button>+ <!-- Copy Button -->+ <button+ @click="copyMessage(index, item.type || item.role)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors flex items-center"+ :title="'Copy message'"+ >+ {{ getCopyButtonText(index) }}+ </button>+ </div>+ </div>+ <!-- Details Section -->+ <div v-if="isDetailsExpanded(index)" class="mt-3 p-3 bg-gray-100 dark:bg-gray-900 rounded-lg">+ <pre class="text-xs text-gray-700 dark:text-gray-300 overflow-x-auto">{{ JSON.stringify(getObfuscatedItem(index), null, 2) }}</pre>+ </div>+ </div>++ <!-- System Message -->+ <div v-else-if="item.type === 'system'"+ class="p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">+ <div class="flex items-start justify-between">+ <div class="flex items-start space-x-3 flex-1">+ <span class="text-lg font-semibold px-3 py-1 rounded-full flex-shrink-0 bg-amber-600 text-white">+ System+ </span>+ <div class="flex-1">+ <p class="text-lg text-gray-800 dark:text-gray-100 font-medium">+ {{ cleanSystemContent(item.content || '') }}+ </p>+ <!-- Tool use ID if present -->+ <div v-if="item.toolUseID" class="mt-1 text-xs text-gray-500 dark:text-gray-400 font-mono">+ Tool ID: {{ item.toolUseID }}+ </div>+ <!-- Timestamp -->+ <div v-if="item.timestamp" class="mt-1 text-xs text-gray-500 dark:text-gray-400">+ {{ formatTimestamp(item.timestamp) }}+ </div>+ </div>+ </div>+ <!-- Action Buttons -->+ <div class="flex items-center space-x-1 ml-2">+ <!-- Show Details Button -->+ <button+ @click="toggleDetails(index)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"+ >+ {{ isDetailsExpanded(index) ? 'Hide' : 'Show' }} Details+ </button>+ <!-- Copy Button -->+ <button+ @click="copyMessage(index, item.type || item.role)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors flex items-center"+ :title="'Copy message'"+ >+ {{ getCopyButtonText(index) }}+ </button>+ </div>+ </div>+ <!-- Details Section -->+ <div v-if="isDetailsExpanded(index)" class="mt-3 p-3 bg-gray-100 dark:bg-gray-900 rounded-lg">+ <pre class="text-xs text-gray-700 dark:text-gray-300 overflow-x-auto">{{ JSON.stringify(getObfuscatedItem(index), null, 2) }}</pre>+ </div>+ </div>++ <!-- Fallback for simple chat format -->+ <div v-else-if="item.role"+ class="p-3 rounded-lg"+ :class="item.role === 'user' ? 'bg-blue-50 dark:bg-blue-900/30' : 'bg-gray-50 dark:bg-gray-900/30'">+ <div class="flex items-start justify-between">+ <div class="flex items-start space-x-3 flex-1">+ <span class="text-lg font-semibold px-3 py-1 rounded-full flex-shrink-0"+ :class="item.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-500 text-white'">+ {{ item.role === 'user' ? 'User' : 'Assistant' }}+ </span>+ <div class="flex-1">+ <p class="prose text-lg text-gray-800 dark:text-gray-100 whitespace-pre-wrap font-medium">+ {{ item.content }}+ </p>+ </div>+ </div>+ <!-- Action Buttons -->+ <div class="flex items-center space-x-1 ml-2">+ <!-- Show Details Button -->+ <button+ @click="toggleDetails(index)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"+ >+ {{ isDetailsExpanded(index) ? 'Hide' : 'Show' }} Details+ </button>+ <!-- Copy Button -->+ <button+ @click="copyMessage(index, item.type || item.role)"+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors flex items-center"+ :title="'Copy message'"+ >+ {{ getCopyButtonText(index) }}+ </button>+ </div>+ </div>+ <!-- Details Section -->+ <div v-if="isDetailsExpanded(index)" class="mt-3 p-3 bg-gray-100 dark:bg-gray-900 rounded-lg">+ <pre class="text-xs text-gray-700 dark:text-gray-300 overflow-x-auto">{{ JSON.stringify(getObfuscatedItem(index), null, 2) }}</pre>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from 'vue';+import { Wrench } from 'lucide-vue-next';+import { obfuscateObject, obfuscateString } from '../utils/obfuscate';++const props = defineProps<{+ chat: any[];+}>();++// Track which items have details expanded+const expandedDetails = ref<Set<number>>(new Set());++const toggleDetails = (index: number) => {+ if (expandedDetails.value.has(index)) {+ expandedDetails.value.delete(index);+ } else {+ expandedDetails.value.add(index);+ }+ // Force reactivity+ expandedDetails.value = new Set(expandedDetails.value);+};++const isDetailsExpanded = (index: number) => {+ return expandedDetails.value.has(index);+};++const chatItems = computed(() => {+ // Handle both simple chat format and complex claude-code format+ if (props.chat.length > 0 && props.chat[0].type) {+ // Complex format from chat.json+ return props.chat;+ } else {+ // Simple format with role/content+ return props.chat;+ }+});++// Obfuscated version for displaying in details sections+const getObfuscatedItem = (index: number) => {+ const item = chatItems.value[index];+ return obfuscateObject(item);+};++const formatTimestamp = (timestamp: string) => {+ const date = new Date(timestamp);+ return date.toLocaleTimeString();+};++// const cleanContent = (content: string) => {+// // Remove command message tags+// return content+// .replace(/<command-message>.*?<\/command-message>/gs, '')+// .replace(/<command-name>.*?<\/command-name>/gs, '')+// .trim();+// };++const cleanSystemContent = (content: string) => {+ // Remove ANSI escape codes+ return content.replace(/\u001b\[[0-9;]*m/g, '');+};++const cleanCommandContent = (content: string) => {+ // Remove command tags and clean content+ return content+ .replace(/<command-message>.*?<\/command-message>/gs, '')+ .replace(/<command-name>(.*?)<\/command-name>/gs, '$1')+ .trim();+};++// Track copy button states+const copyButtonStates = ref<Map<number, string>>(new Map());++const getCopyButtonText = (index: number) => {+ return copyButtonStates.value.get(index) || 'Copy';+};++const copyMessage = async (index: number, _type: string) => {+ const item = chatItems.value[index];++ try {+ // Obfuscate sensitive data before copying+ const obfuscatedItem = obfuscateObject(item);+ const jsonPayload = JSON.stringify(obfuscatedItem, null, 2);+ await navigator.clipboard.writeText(jsonPayload);++ copyButtonStates.value.set(index, 'Copied!');+ setTimeout(() => {+ copyButtonStates.value.delete(index);+ copyButtonStates.value = new Map(copyButtonStates.value);+ }, 2000);+ } catch (err) {+ console.error('Failed to copy:', err);+ copyButtonStates.value.set(index, 'Failed');+ setTimeout(() => {+ copyButtonStates.value.delete(index);+ copyButtonStates.value = new Map(copyButtonStates.value);+ }, 2000);+ }+ // Force reactivity+ copyButtonStates.value = new Map(copyButtonStates.value);+};+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/ChatTranscriptModal.vue b/.claude/skills/observability/apps/client/src/components/ChatTranscriptModal.vuenew file mode 100644index 00000000..db378c5b--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/ChatTranscriptModal.vue@@ -0,0 +1,361 @@+<template>+ <Teleport to="body">+ <div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 mobile:p-0">+ <!-- Backdrop -->+ <div+ class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"+ @click="close"+ ></div>++ <!-- Modal -->+ <div+ class="relative bg-white dark:bg-gray-800 rounded-lg mobile:rounded-none shadow-xl flex flex-col overflow-hidden z-10 mobile:w-full mobile:h-full mobile:fixed mobile:inset-0"+ :style="{ width: '85vw', height: '85vh' }"+ :class="{ 'mobile:!w-full mobile:!h-full': true }"+ @click.stop+ >+ <!-- Header -->+ <div class="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-6 mobile:p-3">+ <div class="flex items-center justify-between mb-4 mobile:mb-2">+ <h2 class="flex items-center gap-2 text-3xl mobile:text-lg font-semibold text-gray-900 dark:text-white">+ <MessageSquare :size="28" :stroke-width="2.5" />+ Chat Transcript+ </h2>+ <button+ @click="close"+ class="p-2 mobile:p-3 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"+ >+ <svg class="w-6 h-6 mobile:w-5 mobile:h-5 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />+ </svg>+ </button>+ </div>++ <!-- Search and Filters -->+ <div class="space-y-4">+ <!-- Search Input -->+ <div class="flex gap-2">+ <div class="relative flex-1">+ <input+ v-model="searchQuery"+ @keyup.enter="executeSearch"+ type="text"+ placeholder="Search transcript..."+ class="w-full px-4 py-2 mobile:px-3 mobile:py-2 pl-10 mobile:pl-8 text-lg mobile:text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"+ >+ <svg class="absolute left-3 top-3 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />+ </svg>+ </div>+ <button+ @click="executeSearch"+ class="px-4 py-2 mobile:px-3 mobile:py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors text-base mobile:text-sm min-w-[44px] min-h-[44px] flex items-center justify-center"+ >+ Search+ </button>+ <button+ @click="copyAllMessages"+ class="px-4 py-2 mobile:px-3 mobile:py-2 bg-gray-500 hover:bg-gray-600 text-white font-medium rounded-lg transition-colors text-base mobile:text-sm min-w-[44px] min-h-[44px] flex items-center justify-center"+ title="Copy all messages as JSON"+ >+ {{ copyAllButtonText }}+ </button>+ </div>++ <!-- Filters -->+ <div class="flex flex-wrap gap-2 mobile:gap-1 max-h-24 mobile:max-h-32 overflow-y-auto p-2 mobile:p-1 bg-gray-50 dark:bg-gray-900/50 rounded-lg mobile:overflow-x-auto mobile:pb-2">+ <button+ v-for="filter in filters"+ :key="filter.type"+ @click="toggleFilter(filter.type)"+ class="px-4 py-2 mobile:px-3 mobile:py-1.5 rounded-full text-sm mobile:text-xs font-medium transition-colors min-h-[44px] mobile:min-h-[36px] flex items-center whitespace-nowrap"+ :class="activeFilters.includes(filter.type)+ ? 'bg-blue-500 text-white'+ : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'"+ >+ <component :is="filter.icon" :size="14" :stroke-width="2.5" class="mr-1" />+ {{ filter.label }}+ </button>++ <!-- Clear Filters -->+ <button+ v-if="searchQuery || activeSearchQuery || activeFilters.length > 0"+ @click="clearSearch"+ class="px-4 py-2 mobile:px-3 mobile:py-1.5 rounded-full text-sm mobile:text-xs font-medium bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-900/50 min-h-[44px] mobile:min-h-[36px] flex items-center whitespace-nowrap"+ >+ Clear All+ </button>+ </div>++ <!-- Results Count -->+ <div v-if="activeSearchQuery || activeFilters.length > 0" class="text-sm mobile:text-xs text-gray-500 dark:text-gray-400">+ Showing {{ filteredChat.length }} of {{ chat.length }} messages+ <span v-if="activeSearchQuery" class="ml-2 font-medium mobile:block mobile:ml-0 mobile:mt-1">+ (searching for "{{ activeSearchQuery }}")+ </span>+ </div>+ </div>+ </div>++ <!-- Content -->+ <div class="flex-1 p-6 mobile:p-3 overflow-hidden flex flex-col">+ <ChatTranscript :chat="filteredChat" />+ </div>+ </div>+ </div>+ </Teleport>+</template>++<script setup lang="ts">+import { ref, computed, watch, onMounted, onUnmounted } from 'vue';+import ChatTranscript from './ChatTranscript.vue';+import { obfuscateObject } from '../utils/obfuscate';+import { MessageSquare, Copy, CheckCircle, X, User, Bot, Settings, Wrench, FileText, PenTool, Edit, Search } from 'lucide-vue-next';++const props = defineProps<{+ isOpen: boolean;+ chat: any[];+}>();++const emit = defineEmits<{+ close: [];+}>();++const searchQuery = ref('');+const activeSearchQuery = ref('');+const activeFilters = ref<string[]>([]);+const copyAllButtonText = ref('Copy All');++const filters = [+ // Message types+ { type: 'user', label: 'User', icon: User },+ { type: 'assistant', label: 'Assistant', icon: Bot },+ { type: 'system', label: 'System', icon: Settings },++ // Tool actions+ { type: 'tool_use', label: 'Tool Use', icon: Wrench },+ { type: 'tool_result', label: 'Tool Result', icon: CheckCircle },++ // Specific tools+ { type: 'Read', label: 'Read', icon: FileText },+ { type: 'Write', label: 'Write', icon: PenTool },+ { type: 'Edit', label: 'Edit', icon: Edit },+ { type: 'Glob', label: 'Glob', icon: Search },+];++const toggleFilter = (type: string) => {+ const index = activeFilters.value.indexOf(type);+ if (index > -1) {+ activeFilters.value.splice(index, 1);+ } else {+ activeFilters.value.push(type);+ }+};++const executeSearch = () => {+ activeSearchQuery.value = searchQuery.value;+};++const clearSearch = () => {+ searchQuery.value = '';+ activeSearchQuery.value = '';+ activeFilters.value = [];+};++const close = () => {+ emit('close');+};++const copyAllMessages = async () => {+ try {+ // Obfuscate sensitive data before copying+ const obfuscatedChat = obfuscateObject(props.chat);+ const jsonPayload = JSON.stringify(obfuscatedChat, null, 2);+ await navigator.clipboard.writeText(jsonPayload);++ copyAllButtonText.value = 'Copied!';+ setTimeout(() => {+ copyAllButtonText.value = 'Copy All';+ }, 2000);+ } catch (err) {+ console.error('Failed to copy all messages:', err);+ copyAllButtonText.value = 'Failed';+ setTimeout(() => {+ copyAllButtonText.value = 'Copy All';+ }, 2000);+ }+};++const matchesSearch = (item: any, query: string): boolean => {+ const lowerQuery = query.toLowerCase().trim();++ // Check direct content (for system messages and simple chat)+ if (typeof item.content === 'string') {+ // Remove ANSI codes before searching+ const cleanContent = item.content.replace(/\u001b\[[0-9;]*m/g, '').toLowerCase();+ if (cleanContent.includes(lowerQuery)) {+ return true;+ }+ }++ // Check role in simple format+ if (item.role && item.role.toLowerCase().includes(lowerQuery)) {+ return true;+ }++ // Check message object (complex format)+ if (item.message) {+ // Check message role+ if (item.message.role && item.message.role.toLowerCase().includes(lowerQuery)) {+ return true;+ }++ // Check message content+ if (item.message.content) {+ if (typeof item.message.content === 'string' && item.message.content.toLowerCase().includes(lowerQuery)) {+ return true;+ }+ // Check array content+ if (Array.isArray(item.message.content)) {+ for (const content of item.message.content) {+ if (content.text && content.text.toLowerCase().includes(lowerQuery)) {+ return true;+ }+ if (content.name && content.name.toLowerCase().includes(lowerQuery)) {+ return true;+ }+ if (content.input && JSON.stringify(content.input).toLowerCase().includes(lowerQuery)) {+ return true;+ }+ if (content.content && typeof content.content === 'string' && content.content.toLowerCase().includes(lowerQuery)) {+ return true;+ }+ }+ }+ }+ }++ // Check type+ if (item.type && item.type.toLowerCase().includes(lowerQuery)) {+ return true;+ }++ // Check parentUuid, uuid, sessionId+ if (item.uuid && item.uuid.toLowerCase().includes(lowerQuery)) {+ return true;+ }+ if (item.sessionId && item.sessionId.toLowerCase().includes(lowerQuery)) {+ return true;+ }++ // Check toolUseResult+ if (item.toolUseResult) {+ if (JSON.stringify(item.toolUseResult).toLowerCase().includes(lowerQuery)) {+ return true;+ }+ }++ return false;+};++const matchesFilters = (item: any): boolean => {+ if (activeFilters.value.length === 0) return true;++ // Check message type+ if (item.type && activeFilters.value.includes(item.type)) {+ return true;+ }++ // Check role (simple format)+ if (item.role && activeFilters.value.includes(item.role)) {+ return true;+ }++ // Check for system messages with hook types+ if (item.type === 'system' && item.content) {+ // Extract hook type from system content (e.g., "PreToolUse:Read")+ const hookMatch = item.content.match(/([A-Za-z]+):/)?.[1];+ if (hookMatch && activeFilters.value.includes(hookMatch)) {+ return true;+ }+ // Also check if content contains "Running"+ if (item.content.includes('Running') && activeFilters.value.includes('Running')) {+ return true;+ }+ // Check for specific tool names in system messages+ const toolNames = ['Read', 'Write', 'Edit', 'Glob'];+ for (const tool of toolNames) {+ if (item.content.includes(tool) && activeFilters.value.includes(tool)) {+ return true;+ }+ }+ }++ // Check for command messages+ if (item.message?.content && typeof item.message.content === 'string') {+ if (item.message.content.includes('<command-') && activeFilters.value.includes('command')) {+ return true;+ }+ }++ // Check for meta messages+ if (item.isMeta && activeFilters.value.includes('meta')) {+ return true;+ }++ // Check for tool use in content+ if (item.message?.content && Array.isArray(item.message.content)) {+ for (const content of item.message.content) {+ if (content.type === 'tool_use') {+ if (activeFilters.value.includes('tool_use')) {+ return true;+ }+ // Check for specific tool names+ if (content.name && activeFilters.value.includes(content.name)) {+ return true;+ }+ }+ if (content.type === 'tool_result' && activeFilters.value.includes('tool_result')) {+ return true;+ }+ }+ }++ return false;+};++const filteredChat = computed(() => {+ if (!activeSearchQuery.value && activeFilters.value.length === 0) {+ return props.chat;+ }++ return props.chat.filter(item => {+ const matchesQueryCondition = !activeSearchQuery.value || matchesSearch(item, activeSearchQuery.value);+ const matchesFilterCondition = matchesFilters(item);+ return matchesQueryCondition && matchesFilterCondition;+ });+});++// Handle ESC key+const handleKeydown = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && props.isOpen) {+ close();+ }+};++onMounted(() => {+ document.addEventListener('keydown', handleKeydown);+});++onUnmounted(() => {+ document.removeEventListener('keydown', handleKeydown);+});++// Reset search when modal closes+watch(() => props.isOpen, (newVal) => {+ if (!newVal) {+ clearSearch();+ }+});++</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/EventRow.vue b/.claude/skills/observability/apps/client/src/components/EventRow.vuenew file mode 100644index 00000000..09f8671c--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/EventRow.vue@@ -0,0 +1,668 @@+<template>+ <div>+ <!-- HITL Question Section (NEW) -->+ <div+ v-if="event.humanInTheLoop && (event.humanInTheLoopStatus?.status === 'pending' || hasSubmittedResponse)"+ class="mb-4 p-4 rounded-lg border-2 shadow-lg"+ :class="hasSubmittedResponse || event.humanInTheLoopStatus?.status === 'responded' ? 'border-green-500 bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20' : 'border-yellow-500 bg-gradient-to-r from-yellow-50 to-yellow-100 dark:from-yellow-900/20 dark:to-yellow-800/20 animate-pulse-slow'"+ @click.stop+ >+ <!-- Question Header -->+ <div class="mb-3">+ <div class="flex items-center justify-between mb-2">+ <div class="flex items-center space-x-2">+ <component :is="hitlTypeIcon" :size="24" :stroke-width="2.5" :class="hasSubmittedResponse || event.humanInTheLoopStatus?.status === 'responded' ? 'text-green-600 dark:text-green-400' : 'text-yellow-600 dark:text-yellow-400'" />+ <h3 class="text-lg font-bold" :class="hasSubmittedResponse || event.humanInTheLoopStatus?.status === 'responded' ? 'text-green-900 dark:text-green-100' : 'text-yellow-900 dark:text-yellow-100'">+ {{ hitlTypeLabel }}+ </h3>+ <span v-if="permissionType" class="text-xs font-mono font-semibold px-2 py-1 rounded border-2 bg-blue-50 dark:bg-blue-900/20 border-blue-500 text-blue-900 dark:text-blue-100">+ {{ permissionType }}+ </span>+ </div>+ <span v-if="!hasSubmittedResponse && event.humanInTheLoopStatus?.status !== 'responded'" class="flex items-center gap-1.5 text-xs font-semibold text-yellow-700 dark:text-yellow-300">+ <Clock :size="12" :stroke-width="2.5" />+ Waiting for response...+ </span>+ </div>+ <div class="flex items-center space-x-2 ml-9">+ <div+ class="text-xs font-bold px-2 py-0.5 rounded-full border-2 shadow-lg flex items-center gap-1 text-[var(--theme-text-primary)] bg-[var(--theme-bg-tertiary)]"+ :style="{+ borderColor: appHexColor,+ backgroundColor: appHexColor + '33'+ }"+ >+ <span class="font-mono text-xs">{{ agentId }}</span>+ </div>+ <span class="text-xs text-[var(--theme-text-tertiary)] font-medium">+ {{ formatTime(event.timestamp) }}+ </span>+ </div>+ </div>++ <!-- Question Text -->+ <div class="mb-4 p-3 bg-white dark:bg-gray-800 rounded-lg border" :class="hasSubmittedResponse || event.humanInTheLoopStatus?.status === 'responded' ? 'border-green-300' : 'border-yellow-300'">+ <p class="prose text-base font-medium text-gray-900 dark:text-gray-100">+ {{ event.humanInTheLoop.question }}+ </p>+ </div>++ <!-- Inline Response Display (Optimistic UI) -->+ <div v-if="localResponse || (event.humanInTheLoopStatus?.status === 'responded' && event.humanInTheLoopStatus.response)" class="mb-4 p-3 bg-white dark:bg-gray-800 rounded-lg border border-green-400">+ <div class="flex items-center gap-2 mb-2">+ <CheckCircle :size="18" :stroke-width="2.5" class="text-green-600" />+ <strong class="text-green-900 dark:text-green-100">Your Response:</strong>+ </div>+ <div v-if="(localResponse?.response || event.humanInTheLoopStatus?.response?.response)" class="text-gray-900 dark:text-gray-100 ml-7">+ {{ localResponse?.response || event.humanInTheLoopStatus?.response?.response }}+ </div>+ <div v-if="(localResponse?.permission !== undefined || event.humanInTheLoopStatus?.response?.permission !== undefined)" class="flex items-center gap-1.5 text-gray-900 dark:text-gray-100 ml-7">+ <component :is="(localResponse?.permission ?? event.humanInTheLoopStatus?.response?.permission) ? CheckCircle : X" :size="16" :stroke-width="2.5" :class="(localResponse?.permission ?? event.humanInTheLoopStatus?.response?.permission) ? 'text-green-600' : 'text-red-600'" />+ {{ (localResponse?.permission ?? event.humanInTheLoopStatus?.response?.permission) ? 'Approved' : 'Denied' }}+ </div>+ <div v-if="(localResponse?.choice || event.humanInTheLoopStatus?.response?.choice)" class="text-gray-900 dark:text-gray-100 ml-7">+ {{ localResponse?.choice || event.humanInTheLoopStatus?.response?.choice }}+ </div>+ </div>++ <!-- Response UI -->+ <div v-if="event.humanInTheLoop.type === 'question'">+ <!-- Text Input for Questions -->+ <textarea+ v-model="responseText"+ class="w-full p-3 border-2 border-yellow-500 rounded-lg focus:ring-2 focus:ring-yellow-500 focus:border-transparent resize-none"+ rows="3"+ placeholder="Type your response here..."+ @click.stop+ ></textarea>+ <div class="flex justify-end space-x-2 mt-2">+ <button+ @click.stop="submitResponse"+ :disabled="!responseText.trim() || isSubmitting || hasSubmittedResponse"+ class="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105 disabled:transform-none disabled:cursor-not-allowed"+ >+ <component :is="isSubmitting ? Loader2 : CheckCircle" :size="16" :stroke-width="2.5" :class="isSubmitting ? 'animate-spin' : ''" />+ {{ isSubmitting ? 'Sending...' : 'Submit Response' }}+ </button>+ </div>+ </div>++ <div v-else-if="event.humanInTheLoop.type === 'permission'">+ <!-- Yes/No Buttons for Permissions -->+ <div class="flex justify-end items-center space-x-3">+ <div v-if="hasSubmittedResponse || event.humanInTheLoopStatus?.status === 'responded'" class="flex items-center px-3 py-2 bg-green-100 dark:bg-green-900/30 rounded-lg border border-green-500">+ <span class="text-sm font-bold text-green-900 dark:text-green-100">Responded</span>+ </div>+ <button+ @click.stop="submitPermission(false)"+ :disabled="isSubmitting || hasSubmittedResponse"+ class="flex items-center gap-2 px-6 py-2 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105"+ :class="hasSubmittedResponse ? 'opacity-40 cursor-not-allowed' : ''"+ >+ <component :is="isSubmitting ? Loader2 : X" :size="16" :stroke-width="2.5" :class="isSubmitting ? 'animate-spin' : ''" />+ Deny+ </button>+ <button+ @click.stop="submitPermission(true)"+ :disabled="isSubmitting || hasSubmittedResponse"+ class="flex items-center gap-2 px-6 py-2 bg-green-600 hover:bg-green-700 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105"+ :class="hasSubmittedResponse ? 'opacity-40 cursor-not-allowed' : ''"+ >+ <component :is="isSubmitting ? Loader2 : CheckCircle" :size="16" :stroke-width="2.5" :class="isSubmitting ? 'animate-spin' : ''" />+ Approve+ </button>+ </div>+ </div>++ <div v-else-if="event.humanInTheLoop.type === 'choice'">+ <!-- Multiple Choice Buttons -->+ <div class="flex flex-wrap gap-2 justify-end">+ <button+ v-for="choice in event.humanInTheLoop.choices"+ :key="choice"+ @click.stop="submitChoice(choice)"+ :disabled="isSubmitting || hasSubmittedResponse"+ class="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105 disabled:transform-none"+ >+ <Loader2 v-if="isSubmitting" :size="16" :stroke-width="2.5" class="animate-spin" />+ {{ choice }}+ </button>+ </div>+ </div>+ </div>++ <!-- Original Event Row Content (skip if HITL with humanInTheLoop) -->+ <div+ v-if="!event.humanInTheLoop"+ class="group relative p-3 mobile:p-2 rounded-xl glass-card cursor-pointer"+ :class="{ 'ring-1 ring-[var(--theme-primary)]/50 glow-primary': isExpanded }"+ @click="toggleExpanded"+ >+ <div class="ml-1">+ <!-- Single Row Layout - All Platforms -->+ <div class="flex items-center justify-between gap-3">+ <div class="flex items-center gap-2.5 flex-1 min-w-0">+ <!-- Agent Badge - More refined -->+ <div+ class="text-xs font-medium px-2.5 py-1 rounded-lg border flex items-center gap-1.5 shrink-0 transition-smooth"+ :style="{+ borderColor: appHexColor + '50',+ backgroundColor: appHexColor + '15'+ }"+ >+ <span class="font-mono text-xs whitespace-nowrap text-[var(--theme-text-primary)]">{{ agentId }}</span>+ </div>++ <!-- Event Type Badge (Hook) -->+ <span+ class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium"+ :style="{+ backgroundColor: eventTypeColor + '12',+ color: eventTypeColor+ }"+ >+ <component :is="hookIcon" :size="12" :stroke-width="2" />+ {{ formatEventType(event.hook_event_type) }}+ </span>++ <!-- Tool info - Inline on same row -->+ <span v-if="toolInfo" class="flex items-center gap-1.5 min-w-0">+ <span+ v-if="toolInfo.tool"+ class="text-xs font-medium px-2 py-1 rounded-lg inline-flex items-center gap-1 shrink-0"+ :style="{+ backgroundColor: toolTypeColor + '10',+ color: toolTypeColor+ }"+ >+ <component :is="getToolIcon(toolInfo.tool)" :size="11" :stroke-width="2" />+ {{ toolInfo.tool }}+ </span>+ <span+ v-if="toolInfo.detail"+ class="text-sm truncate max-w-md text-[var(--theme-text-secondary)]"+ :class="{+ 'italic': event.hook_event_type === 'UserPromptSubmit',+ 'font-medium': event.hook_event_type === 'Completed'+ }"+ :style="{+ color: event.hook_event_type === 'UserPromptSubmit' ? '#7dcfff' :+ event.hook_event_type === 'Completed' ? '#9ece6a' :+ undefined+ }"+ >{{ toolInfo.detail }}</span>+ </span>++ <!-- Summary - Inline on same row -->+ <span v-if="event.summary" class="inline-flex items-center gap-1.5 text-xs text-[var(--theme-text-primary)] font-medium px-2.5 py-1 bg-[var(--theme-primary)]/8 rounded-lg min-w-0 max-w-sm">+ <FileText :size="11" :stroke-width="2" class="text-[var(--theme-primary)] shrink-0" />+ <span class="truncate">{{ event.summary }}</span>+ </span>+ </div>++ <!-- Timestamp -->+ <span class="text-xs text-[var(--theme-text-quaternary)] font-medium whitespace-nowrap">+ {{ formatTime(event.timestamp) }}+ </span>+ </div>++ <!-- Expanded content - Glass panel nested -->+ <div v-if="isExpanded" class="mt-3 pt-3 border-t border-[var(--glass-border)] space-y-3">+ <!-- Payload -->+ <div>+ <div class="flex items-center justify-between mb-2">+ <h4 class="text-sm font-medium text-[var(--theme-text-secondary)] flex items-center gap-1.5">+ <Package :size="14" :stroke-width="2" />+ Payload+ </h4>+ <button+ @click.stop="copyPayload"+ class="glass-button px-3 py-1.5 mobile:px-2 mobile:py-1 text-xs font-medium rounded-lg flex items-center gap-1.5 text-[var(--theme-text-secondary)] hover:text-[var(--theme-text-primary)]"+ >+ <Copy :size="12" :stroke-width="2" />+ <span>{{ copyButtonText }}</span>+ </button>+ </div>+ <pre class="text-xs text-[var(--theme-text-primary)] glass-panel-subtle p-3 mobile:p-2 rounded-xl overflow-x-auto max-h-64 overflow-y-auto font-mono">{{ formattedPayload }}</pre>+ </div>++ <!-- Chat transcript button -->+ <div v-if="event.chat && event.chat.length > 0" class="flex justify-end">+ <button+ @click.stop="!isMobile && (showChatModal = true)"+ :class="[+ 'px-4 py-2 mobile:px-3 mobile:py-1.5 font-medium rounded-xl transition-smooth flex items-center gap-2',+ isMobile+ ? 'glass-panel-subtle cursor-not-allowed opacity-40 text-[var(--theme-text-quaternary)]'+ : 'bg-[var(--theme-primary)] hover:bg-[var(--theme-primary-hover)] text-white'+ ]"+ :disabled="isMobile"+ >+ <MessageSquare :size="14" :stroke-width="2" />+ <span class="text-sm mobile:text-xs">+ {{ isMobile ? 'Not available' : `Chat (${event.chat.length})` }}+ </span>+ </button>+ </div>+ </div>+ </div>+ </div>+ <!-- Chat Modal -->+ <ChatTranscriptModal+ v-if="event.chat && event.chat.length > 0"+ :is-open="showChatModal"+ :chat="event.chat"+ @close="showChatModal = false"+ />+ </div>+</template>++<script setup lang="ts">+import { ref, computed } from 'vue';+import type { HookEvent, HumanInTheLoopResponse } from '../types';+import { useMediaQuery } from '../composables/useMediaQuery';+import { useEventColors } from '../composables/useEventColors';+import { obfuscateObject, obfuscateString } from '../utils/obfuscate';+import {+ Wrench,+ CheckCircle,+ Bell,+ StopCircle,+ Users,+ Package,+ MessageSquare,+ Rocket,+ Flag,+ FileText,+ Copy,+ HelpCircle,+ Lock,+ Target,+ Clock,+ Loader2,+ X,+ UserCheck,+ Eye,+ FilePlus,+ Edit3,+ Terminal,+ Search,+ FolderSearch,+ Globe,+ Compass,+ Zap,+ Command,+ CheckSquare,+ MessageCircleQuestion,+ BookOpen,+ Code,+ type LucideIcon+} from 'lucide-vue-next';+import ChatTranscriptModal from './ChatTranscriptModal.vue';++const props = defineProps<{+ event: HookEvent;+ gradientClass: string;+ colorClass: string;+ appGradientClass: string;+ appColorClass: string;+ appHexColor: string;+}>();++// Get color functions+const { getEventTypeColor, getToolTypeColor } = useEventColors();++const emit = defineEmits<{+ (e: 'response-submitted', response: HumanInTheLoopResponse): void;+}>();++// Existing refs+const isExpanded = ref(false);+const showChatModal = ref(false);+const copyButtonText = ref('Copy');++// New refs for HITL+const responseText = ref('');+const isSubmitting = ref(false);+const hasSubmittedResponse = ref(false);+const localResponse = ref<HumanInTheLoopResponse | null>(null); // Optimistic UI++// Media query for responsive design+const { isMobile } = useMediaQuery();++const toggleExpanded = () => {+ isExpanded.value = !isExpanded.value;+};++const sessionIdShort = computed(() => {+ return props.event.session_id.slice(0, 8);+});++const agentId = computed(() => {+ // For UserPromptSubmit events, show "User" as the source+ if (props.event.hook_event_type === 'UserPromptSubmit') {+ return 'User';+ }+ // Capitalize the agent name+ const name = props.event.source_app;+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : name;+});++const hookIcon = computed<LucideIcon>(() => {+ const iconMap: Record<string, LucideIcon> = {+ 'PreToolUse': Wrench,+ 'PostToolUse': CheckCircle,+ 'Notification': Bell,+ 'Stop': StopCircle,+ 'SubagentStop': UserCheck,+ 'PreCompact': Package,+ 'UserPromptSubmit': MessageSquare,+ 'SessionStart': Rocket,+ 'SessionEnd': Flag,+ 'Completed': CheckCircle+ };+ return iconMap[props.event.hook_event_type] || MessageSquare;+});++// Color for the event type badge+const eventTypeColor = computed(() => {+ return getEventTypeColor(props.event.hook_event_type);+});++// Color for the tool name badge+const toolTypeColor = computed(() => {+ if (toolInfo.value?.tool) {+ return getToolTypeColor(toolInfo.value.tool);+ }+ return '#7aa2f7'; // Default Tokyo Night blue+});++const formattedPayload = computed(() => {+ // Obfuscate sensitive data in the payload before displaying+ const obfuscated = obfuscateObject(props.event.payload);+ return JSON.stringify(obfuscated, null, 2);+});++const toolInfo = computed(() => {+ const payload = props.event.payload;++ // Handle Completed events (synthetic completion events)+ if (props.event.hook_event_type === 'Completed') {+ return {+ tool: '',+ detail: payload.task || props.event.summary || 'Task completed'+ };+ }++ // Handle UserPromptSubmit events+ if (props.event.hook_event_type === 'UserPromptSubmit' && payload.prompt) {+ const promptPreview = payload.prompt.slice(0, 300);+ const obfuscatedPrompt = obfuscateString(promptPreview);+ return {+ tool: 'Prompt:',+ detail: `"${obfuscatedPrompt}${payload.prompt.length > 300 ? '...' : ''}"`+ };+ }++ // Handle PreCompact events+ if (props.event.hook_event_type === 'PreCompact') {+ const trigger = payload.trigger || 'unknown';+ return {+ tool: 'Compaction:',+ detail: trigger === 'manual' ? 'Manual compaction' : 'Auto-compaction (full context)'+ };+ }++ // Handle SessionStart events+ if (props.event.hook_event_type === 'SessionStart') {+ const source = payload.source || 'unknown';+ const sourceLabels: Record<string, string> = {+ 'startup': 'New session',+ 'resume': 'Resuming session',+ 'clear': 'Fresh session'+ };+ return {+ tool: 'Session:',+ detail: sourceLabels[source] || source+ };+ }++ // Handle tool-based events+ if (payload.tool_name) {+ const info: { tool: string; detail?: string } = { tool: payload.tool_name };++ if (payload.tool_input) {+ if (payload.tool_input.command) {+ const commandPreview = payload.tool_input.command.slice(0, 200);+ const obfuscatedCommand = obfuscateString(commandPreview);+ info.detail = obfuscatedCommand + (payload.tool_input.command.length > 200 ? '...' : '');+ } else if (payload.tool_input.file_path) {+ // Show more of the file path (last 3 segments or full if shorter)+ const parts = payload.tool_input.file_path.split('/');+ const filePath = parts.length > 3 ? '.../' + parts.slice(-3).join('/') : payload.tool_input.file_path;+ // Obfuscate in case file path contains sensitive info+ info.detail = obfuscateString(filePath);+ } else if (payload.tool_input.pattern) {+ info.detail = obfuscateString(payload.tool_input.pattern);+ }+ }++ return info;+ }++ return null;+});++const formatTime = (timestamp?: number) => {+ if (!timestamp) return '';+ const date = new Date(timestamp);+ return date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });+};++// Format event type names for user-friendly display+const formatEventType = (eventType: string): string => {+ const displayNames: Record<string, string> = {+ 'PreToolUse': 'Pre-Tool',+ 'PostToolUse': 'Post-Tool',+ 'UserPromptSubmit': 'UserPromptSubmit',+ 'SessionStart': 'SessionStart',+ 'SessionEnd': 'SessionEnd',+ 'Stop': 'Stop',+ 'SubagentStop': 'SubagentStop',+ 'PreCompact': 'PreCompact',+ 'Notification': 'Notification',+ 'Completed': 'Completed'+ };+ return displayNames[eventType] || eventType;+};++// Get icon for tool type (matching TopToolsWidget)+const getToolIcon = (toolName: string): LucideIcon => {+ const toolIcons: Record<string, LucideIcon> = {+ 'Read': Eye,+ 'Write': FilePlus,+ 'Edit': Edit3,+ 'Bash': Terminal,+ 'Grep': Search,+ 'Glob': FolderSearch,+ 'Task': Users,+ 'WebFetch': Globe,+ 'WebSearch': Compass,+ 'Skill': Zap,+ 'SlashCommand': Command,+ 'TodoWrite': CheckSquare,+ 'AskUserQuestion': MessageCircleQuestion,+ 'NotebookEdit': BookOpen,+ 'NotebookRead': FileText,+ 'BashOutput': Terminal,+ 'KillShell': Terminal,+ 'ExitPlanMode': CheckCircle,+ };+ return toolIcons[toolName] || Code;+};++const copyPayload = async () => {+ try {+ await navigator.clipboard.writeText(formattedPayload.value);+ copyButtonText.value = 'Copied!';+ setTimeout(() => {+ copyButtonText.value = 'Copy';+ }, 2000);+ } catch (err) {+ console.error('Failed to copy:', err);+ copyButtonText.value = 'Failed';+ setTimeout(() => {+ copyButtonText.value = 'Copy';+ }, 2000);+ }+};++// New computed properties for HITL+const hitlTypeIcon = computed<LucideIcon>(() => {+ if (!props.event.humanInTheLoop) return HelpCircle;+ const iconMap: Record<string, LucideIcon> = {+ question: HelpCircle,+ permission: Lock,+ choice: Target+ };+ return iconMap[props.event.humanInTheLoop.type] || HelpCircle;+});++const hitlTypeLabel = computed(() => {+ if (!props.event.humanInTheLoop) return '';+ const labelMap = {+ question: 'Agent Question',+ permission: 'Permission Request',+ choice: 'Choice Required'+ };+ return labelMap[props.event.humanInTheLoop.type] || 'Question';+});++const permissionType = computed(() => {+ return props.event.payload?.permission_type || null;+});++// Methods for HITL responses+const submitResponse = async () => {+ if (!responseText.value.trim() || !props.event.id) return;++ const response: HumanInTheLoopResponse = {+ response: responseText.value.trim(),+ hookEvent: props.event,+ respondedAt: Date.now()+ };++ // Optimistic UI: Show response immediately+ localResponse.value = response;+ hasSubmittedResponse.value = true;+ const savedText = responseText.value;+ responseText.value = '';+ isSubmitting.value = true;++ try {+ const res = await fetch(`http://localhost:4000/events/${props.event.id}/respond`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(response)+ });++ if (!res.ok) throw new Error('Failed to submit response');++ emit('response-submitted', response);+ } catch (error) {+ console.error('Error submitting response:', error);+ // Rollback optimistic update+ localResponse.value = null;+ hasSubmittedResponse.value = false;+ responseText.value = savedText;+ alert('Failed to submit response. Please try again.');+ } finally {+ isSubmitting.value = false;+ }+};++const submitPermission = async (approved: boolean) => {+ if (!props.event.id) return;++ const response: HumanInTheLoopResponse = {+ permission: approved,+ hookEvent: props.event,+ respondedAt: Date.now()+ };++ // Optimistic UI: Show response immediately+ localResponse.value = response;+ hasSubmittedResponse.value = true;+ isSubmitting.value = true;++ try {+ const res = await fetch(`http://localhost:4000/events/${props.event.id}/respond`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(response)+ });++ if (!res.ok) throw new Error('Failed to submit permission');++ emit('response-submitted', response);+ } catch (error) {+ console.error('Error submitting permission:', error);+ // Rollback optimistic update+ localResponse.value = null;+ hasSubmittedResponse.value = false;+ alert('Failed to submit permission. Please try again.');+ } finally {+ isSubmitting.value = false;+ }+};++const submitChoice = async (choice: string) => {+ if (!props.event.id) return;++ const response: HumanInTheLoopResponse = {+ choice,+ hookEvent: props.event,+ respondedAt: Date.now()+ };++ // Optimistic UI: Show response immediately+ localResponse.value = response;+ hasSubmittedResponse.value = true;+ isSubmitting.value = true;++ try {+ const res = await fetch(`http://localhost:4000/events/${props.event.id}/respond`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(response)+ });++ if (!res.ok) throw new Error('Failed to submit choice');++ emit('response-submitted', response);+ } catch (error) {+ console.error('Error submitting choice:', error);+ // Rollback optimistic update+ localResponse.value = null;+ hasSubmittedResponse.value = false;+ alert('Failed to submit choice. Please try again.');+ } finally {+ isSubmitting.value = false;+ }+};+</script>++<style scoped>+@keyframes pulse-slow {+ 0%, 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.95;+ }+}++.animate-pulse-slow {+ animation: pulse-slow 2s ease-in-out infinite;+}+</style>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/EventTimeline.vue b/.claude/skills/observability/apps/client/src/components/EventTimeline.vuenew file mode 100644index 00000000..a3b9eed2--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/EventTimeline.vue@@ -0,0 +1,194 @@+<template>+ <div class="flex-1 mobile:h-[50vh] overflow-hidden flex flex-col">+ <!-- Intensity Bar - Activity Heat Indicator -->+ <IntensityBar+ v-if="heatLevel"+ :intensity="heatLevel.intensity"+ :color="heatLevel.color"+ :label="heatLevel.label"+ :events-per-minute="eventsPerMinute ?? 0"+ :show-tooltip="true"+ :time-range="timeRange"+ :time-ranges="timeRanges"+ @set-time-range="$emit('setTimeRange', $event)"+ />++ <!-- Scrollable Event List - More breathing room -->+ <div+ ref="scrollContainer"+ class="flex-1 overflow-y-auto px-5 py-4 mobile:px-3 mobile:py-2"+ @scroll="handleScroll"+ >+ <!-- Column Headers -->+ <div class="flex items-center justify-between gap-3 px-4 py-2 mb-2 text-xs font-medium text-[#565f89] uppercase tracking-wide">+ <div class="flex items-center gap-2.5 flex-1 min-w-0">+ <span class="w-20">Agent</span>+ <span class="w-24">Hook</span>+ <span class="w-20">Tool</span>+ <span class="flex-1">Details</span>+ </div>+ <span class="w-16 text-right">Time</span>+ </div>+ <TransitionGroup+ name="event"+ tag="div"+ class="space-y-2 mobile:space-y-1.5 divide-y divide-[#565f89]/10"+ >+ <EventRow+ v-for="event in filteredEvents"+ :key="`${event.id}-${event.timestamp}`"+ :event="event"+ :gradient-class="getGradientForSession(event.session_id)"+ :color-class="getColorForSession(event.session_id)"+ :app-gradient-class="getGradientForApp(event.agent_name || event.source_app)"+ :app-color-class="getColorForApp(event.agent_name || event.source_app)"+ :app-hex-color="getHexColorForApp(event.agent_name || event.source_app)"+ />+ </TransitionGroup>++ <!-- Empty State - Modern styling -->+ <div v-if="filteredEvents.length === 0" class="flex flex-col items-center justify-center py-16 mobile:py-10">+ <div class="glass-panel-subtle p-6 rounded-2xl mb-4">+ <Box :size="40" class="text-[var(--theme-text-quaternary)]" />+ </div>+ <p class="text-base mobile:text-sm font-medium text-[var(--theme-text-secondary)] mb-1">No events yet</p>+ <p class="text-sm mobile:text-xs text-[var(--theme-text-quaternary)]">Events will appear here as they stream in</p>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, computed, watch, nextTick, shallowRef } from 'vue';+import type { HookEvent } from '../types';+import { Sparkles, Moon, Box } from 'lucide-vue-next';+import EventRow from './EventRow.vue';+import IntensityBar from './IntensityBar.vue';+import { useEventColors } from '../composables/useEventColors';++const props = defineProps<{+ events: HookEvent[];+ filters: {+ sourceApp: string;+ sessionId: string;+ eventType: string;+ };+ stickToBottom: boolean;+ uniqueAppNames?: string[]; // Agent IDs (app:session) active in current time window+ allAppNames?: string[]; // All agent IDs (app:session) ever seen in session+ heatLevel?: { intensity: number; color: string; label: string };+ agentCounts?: Record<string, number>; // Count of instances per agent type+ eventsPerMinute?: number; // Events per minute for heat bar display+ timeRange?: string; // Current time range+ timeRanges?: string[]; // Available time ranges+}>();++const emit = defineEmits<{+ 'update:stickToBottom': [value: boolean];+ selectAgent: [agentName: string];+ setTimeRange: [range: string];+}>();++const scrollContainer = ref<HTMLElement>();+const { getGradientForSession, getColorForSession, getGradientForApp, getColorForApp, getHexColorForApp } = useEventColors();++// Stable list of app names - only grows, never shrinks (prevents flashing)+const seenAppNames = shallowRef<Set<string>>(new Set());++// Get unique app names from current data+const displayedAppNames = computed(() => {+ const allAgentIds = props.allAppNames?.length ? props.allAppNames : (props.uniqueAppNames || []);+ const uniqueApps = new Set<string>();+ allAgentIds.forEach(agentId => {+ const appName = agentId.split(':')[0];+ uniqueApps.add(appName);+ });+ return Array.from(uniqueApps);+});++// Stable app names - accumulates all seen apps, sorted alphabetically+const stableAppNames = computed(() => {+ // Add any new apps to the seen set+ displayedAppNames.value.forEach(app => seenAppNames.value.add(app));+ return Array.from(seenAppNames.value).sort();+});++// Check if an app is currently active (any instance has events in current time window)+const isAppActive = (appName: string): boolean => {+ return (props.uniqueAppNames || []).some(agentId => agentId.split(':')[0] === appName);+};++// Get instance count for an app type+const getAppInstanceCount = (appName: string): number => {+ return props.agentCounts?.[appName] || 0;+};++const filteredEvents = computed(() => {+ const filtered = props.events.filter(event => {+ if (props.filters.sourceApp && event.source_app !== props.filters.sourceApp) {+ return false;+ }+ if (props.filters.sessionId && event.session_id !== props.filters.sessionId) {+ return false;+ }+ if (props.filters.eventType && event.hook_event_type !== props.filters.eventType) {+ return false;+ }+ return true;+ });++ // Reverse array so newest events appear at top+ return filtered.slice().reverse();+});++const scrollToTop = () => {+ if (scrollContainer.value) {+ scrollContainer.value.scrollTop = 0;+ }+};++const handleScroll = () => {+ if (!scrollContainer.value) return;++ const { scrollTop } = scrollContainer.value;+ const isAtTop = scrollTop < 50;++ if (isAtTop !== props.stickToBottom) {+ emit('update:stickToBottom', isAtTop);+ }+};++watch(() => props.events.length, async () => {+ if (props.stickToBottom) {+ await nextTick();+ scrollToTop();+ }+});++watch(() => props.stickToBottom, (shouldStick) => {+ if (shouldStick) {+ scrollToTop();+ }+});+</script>++<style scoped>+.event-enter-active {+ transition: all 0.3s ease;+}++.event-enter-from {+ opacity: 0;+ transform: translateY(-20px);+}++.event-leave-active {+ transition: all 0.3s ease;+}++.event-leave-to {+ opacity: 0;+ transform: translateY(20px);+}++</style>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/FilterPanel.vue b/.claude/skills/observability/apps/client/src/components/FilterPanel.vuenew file mode 100644index 00000000..5b456ba0--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/FilterPanel.vue@@ -0,0 +1,120 @@+<template>+ <div class="bg-gradient-to-r from-[var(--theme-bg-primary)] to-[var(--theme-bg-secondary)] border-b-2 border-[var(--theme-primary)] px-3 py-4 mobile:py-2 shadow-lg">+ <div class="flex flex-wrap gap-3 items-center mobile:flex-col mobile:items-stretch">+ <div class="flex-1 min-w-0 mobile:w-full">+ <label class="block text-base mobile:text-sm font-bold text-[var(--theme-primary)] mb-1.5 drop-shadow-sm">+ Source App+ </label>+ <select+ v-model="localFilters.sourceApp"+ @change="updateFilters"+ class="w-full px-4 py-2 mobile:px-2 mobile:py-1.5 text-base mobile:text-sm border border-[var(--theme-primary)] rounded-lg focus:ring-2 focus:ring-[var(--theme-primary)]/30 focus:border-[var(--theme-primary-dark)] bg-[var(--theme-bg-primary)] text-[var(--theme-text-primary)] shadow-md hover:shadow-lg transition-all duration-200"+ >+ <option value="">All Sources</option>+ <option v-for="app in filterOptions.source_apps" :key="app" :value="app">+ {{ app }}+ </option>+ </select>+ </div>++ <div class="flex-1 min-w-0 mobile:w-full">+ <label class="block text-base mobile:text-sm font-bold text-[var(--theme-primary)] mb-1.5 drop-shadow-sm">+ Session ID+ </label>+ <select+ v-model="localFilters.sessionId"+ @change="updateFilters"+ class="w-full px-4 py-2 mobile:px-2 mobile:py-1.5 text-base mobile:text-sm border border-[var(--theme-primary)] rounded-lg focus:ring-2 focus:ring-[var(--theme-primary)]/30 focus:border-[var(--theme-primary-dark)] bg-[var(--theme-bg-primary)] text-[var(--theme-text-primary)] shadow-md hover:shadow-lg transition-all duration-200"+ >+ <option value="">All Sessions</option>+ <option v-for="session in filterOptions.session_ids" :key="session" :value="session">+ {{ session.slice(0, 8) }}...+ </option>+ </select>+ </div>++ <div class="flex-1 min-w-0 mobile:w-full">+ <label class="block text-base mobile:text-sm font-bold text-[var(--theme-primary)] mb-1.5 drop-shadow-sm">+ Event Type+ </label>+ <select+ v-model="localFilters.eventType"+ @change="updateFilters"+ class="w-full px-4 py-2 mobile:px-2 mobile:py-1.5 text-base mobile:text-sm border border-[var(--theme-primary)] rounded-lg focus:ring-2 focus:ring-[var(--theme-primary)]/30 focus:border-[var(--theme-primary-dark)] bg-[var(--theme-bg-primary)] text-[var(--theme-text-primary)] shadow-md hover:shadow-lg transition-all duration-200"+ >+ <option value="">All Types</option>+ <option v-for="type in filterOptions.hook_event_types" :key="type" :value="type">+ {{ type }}+ </option>+ </select>+ </div>++ <button+ v-if="hasActiveFilters"+ @click="clearFilters"+ class="px-4 py-2 mobile:px-2 mobile:py-1.5 mobile:w-full text-base mobile:text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"+ >+ Clear Filters+ </button>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, computed, onMounted } from 'vue';+import type { FilterOptions } from '../types';++const props = defineProps<{+ filters: {+ sourceApp: string;+ sessionId: string;+ eventType: string;+ };+}>();++const emit = defineEmits<{+ 'update:filters': [filters: typeof props.filters];+}>();++const filterOptions = ref<FilterOptions>({+ source_apps: [],+ session_ids: [],+ hook_event_types: []+});++const localFilters = ref({ ...props.filters });++const hasActiveFilters = computed(() => {+ return localFilters.value.sourceApp || localFilters.value.sessionId || localFilters.value.eventType;+});++const updateFilters = () => {+ emit('update:filters', { ...localFilters.value });+};++const clearFilters = () => {+ localFilters.value = {+ sourceApp: '',+ sessionId: '',+ eventType: ''+ };+ updateFilters();+};++const fetchFilterOptions = async () => {+ try {+ const response = await fetch('http://localhost:4000/events/filter-options');+ if (response.ok) {+ filterOptions.value = await response.json();+ }+ } catch (error) {+ console.error('Failed to fetch filter options:', error);+ }+};++onMounted(() => {+ fetchFilterOptions();+ // Refresh filter options periodically+ setInterval(fetchFilterOptions, 10000);+});+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/HelloWorld.vue b/.claude/skills/observability/apps/client/src/components/HelloWorld.vuenew file mode 100644index 00000000..b58e52b9--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/HelloWorld.vue@@ -0,0 +1,41 @@+<script setup lang="ts">+import { ref } from 'vue'++defineProps<{ msg: string }>()++const count = ref(0)+</script>++<template>+ <h1>{{ msg }}</h1>++ <div class="card">+ <button type="button" @click="count++">count is {{ count }}</button>+ <p>+ Edit+ <code>components/HelloWorld.vue</code> to test HMR+ </p>+ </div>++ <p>+ Check out+ <a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"+ >create-vue</a+ >, the official Vue + Vite starter+ </p>+ <p>+ Learn more about IDE Support for Vue in the+ <a+ href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"+ target="_blank"+ >Vue Docs Scaling up Guide</a+ >.+ </p>+ <p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>+</template>++<style scoped>+.read-the-docs {+ color: #888;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/IntensityBar.vue b/.claude/skills/observability/apps/client/src/components/IntensityBar.vuenew file mode 100644index 00000000..fc0f2992--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/IntensityBar.vue@@ -0,0 +1,211 @@+<template>+ <div class="intensity-bar-wrapper">+ <!-- Events per minute counter -->+ <div class="events-counter" :style="{ color: color }">+ <span class="events-value">{{ eventsPerMinute }}</span>+ <span class="events-label">ev/min</span>+ </div>++ <!-- The intensity bar -->+ <div class="intensity-bar-container">+ <div+ class="intensity-bar"+ :style="{ backgroundColor: color, width: `${Math.max(5, intensity * 100)}%` }"+ :title="`Activity: ${label} (${Math.round(intensity * 100)}%)`"+ >+ <!-- Gradient overlay for depth -->+ <div class="intensity-gradient"></div>+ </div>++ <!-- Optional label tooltip on hover -->+ <div class="intensity-tooltip" v-if="showTooltip">+ <span class="intensity-value">{{ Math.round(intensity * 100) }}%</span>+ <span class="intensity-label">{{ label }}</span>+ </div>+ </div>++ <!-- Time Range Selector -->+ <div v-if="timeRanges && timeRanges.length > 0" class="time-range-selector">+ <button+ v-for="range in timeRanges"+ :key="range"+ @click="$emit('setTimeRange', range)"+ class="time-range-btn"+ :class="{ active: timeRange === range }"+ :style="timeRange === range ? { backgroundColor: color, color: getContrastColor(color) } : {}"+ >+ {{ range }}+ </button>+ </div>+ </div>+</template>++<script setup lang="ts">+import { toRefs } from 'vue';++const props = withDefaults(defineProps<{+ intensity: number; // 0.0 to 1.0+ color: string; // Hex color+ label: string; // "Cold", "Cool", "Warm", "Hot", "Fire", "Inferno"+ eventsPerMinute: number; // Events per minute count+ showTooltip?: boolean;+ timeRange?: string; // Current time range (e.g., '1M', '2M')+ timeRanges?: string[]; // Available time ranges+}>(), {+ showTooltip: false,+ eventsPerMinute: 0,+ timeRange: '1M',+ timeRanges: () => []+});++defineEmits<{+ (e: 'setTimeRange', range: string): void;+}>();++const { intensity, color, label, eventsPerMinute, timeRange, timeRanges } = toRefs(props);++// Get contrasting text color for readability+function getContrastColor(hexColor: string): string {+ // Convert hex to RGB+ const r = parseInt(hexColor.slice(1, 3), 16);+ const g = parseInt(hexColor.slice(3, 5), 16);+ const b = parseInt(hexColor.slice(5, 7), 16);++ // Calculate luminance+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;++ // Return white for dark backgrounds, dark for light backgrounds+ return luminance > 0.5 ? '#1a1b26' : '#ffffff';+}+</script>++<style scoped>+.intensity-bar-wrapper {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 0 16px;+}++.events-counter {+ display: flex;+ align-items: center;+ gap: 4px;+ flex-shrink: 0;+ transition: color 2s ease-in-out;+}++.events-value {+ font-size: 16px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+}++.events-label {+ font-size: 11px;+ font-weight: 600;+ opacity: 0.7;+ text-transform: uppercase;+}++.intensity-bar-container {+ position: relative;+ flex: 1;+ height: 4px;+ background: var(--theme-bg-tertiary, #1a1b26);+ overflow: hidden;+ border-radius: 2px;+}++.intensity-bar {+ position: absolute;+ top: 0;+ left: 0;+ height: 100%;+ transition: background-color 2s ease-in-out, width 0.5s ease-out;+ border-radius: 2px;+}++.intensity-gradient {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: linear-gradient(+ to right,+ transparent 0%,+ rgba(255, 255, 255, 0.1) 50%,+ transparent 100%+ );+ animation: shimmer 3s ease-in-out infinite;+}++@keyframes shimmer {+ 0%, 100% {+ opacity: 0.3;+ }+ 50% {+ opacity: 0.6;+ }+}++.intensity-tooltip {+ position: absolute;+ top: 8px;+ right: 8px;+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: var(--theme-bg-secondary, #24283b);+ border: 1px solid var(--theme-border-primary, #414868);+ border-radius: 4px;+ font-size: 11px;+ opacity: 0;+ transition: opacity 0.2s ease;+ pointer-events: none;+}++.intensity-bar-container:hover .intensity-tooltip {+ opacity: 1;+}++.intensity-value {+ font-weight: 600;+ color: var(--theme-text-primary, #c0caf5);+}++.intensity-label {+ color: var(--theme-text-secondary, #565f89);+}++.time-range-selector {+ display: flex;+ align-items: center;+ gap: 4px;+ flex-shrink: 0;+}++.time-range-btn {+ padding: 4px 12px;+ font-size: 14px;+ font-weight: 700;+ border-radius: 4px;+ border: none;+ background: transparent;+ color: var(--theme-text-tertiary, #565f89);+ cursor: pointer;+ transition: all 0.2s ease;+}++.time-range-btn:hover {+ color: var(--theme-text-secondary, #9aa5ce);+ background: var(--theme-bg-tertiary, #1a1b26);+}++.time-range-btn.active {+ /* Color set dynamically via :style binding */+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/LivePulseChart.vue b/.claude/skills/observability/apps/client/src/components/LivePulseChart.vuenew file mode 100644index 00000000..41e13392--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/LivePulseChart.vue@@ -0,0 +1,947 @@+<template>+ <div class="modern-dashboard">+ <!-- Header Bar -->+ <div class="agent-bar px-5 py-2 mobile:px-3 mobile:py-1.5 border-b border-white/[0.03] bg-[var(--theme-bg-primary)]">+ <!-- Skills, Workflows, Tools row (with Tokens/Cost right-justified) -->+ <div class="flex items-center gap-4 flex-wrap">+ <!-- Skills -->+ <div class="flex items-center gap-2 flex-shrink-0">+ <span class="text-sm text-[var(--theme-text-tertiary)] font-medium uppercase">SKILLS:</span>+ <div v-if="skillsAndWorkflows.filter(sw => sw.type === 'skill').length === 0" class="flex items-center gap-2">+ <!-- Grayed out Core placeholder -->+ <div class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm bg-[#565f89]/20">+ <Settings2 :size="14" class="text-[#565f89]" />+ <span class="font-medium text-[#565f89]">Core</span>+ </div>+ </div>+ <div v-else class="flex items-center gap-2">+ <div+ v-for="item in skillsAndWorkflows.filter(sw => sw.type === 'skill').slice(0, 3)"+ :key="item.name"+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm bg-[#bb9af7]/10"+ :title="`Skill: ${item.name}`"+ >+ <Settings2 :size="14" class="text-[#bb9af7]" />+ <span class="font-medium text-[#bb9af7]">{{ item.name }}</span>+ </div>+ </div>+ </div>++ <span class="text-[var(--theme-text-quaternary)]">|</span>++ <!-- Workflows -->+ <div class="flex items-center gap-2 flex-shrink-0">+ <span class="text-sm text-[var(--theme-text-tertiary)] font-medium uppercase">WORKFLOWS:</span>+ <div v-if="skillsAndWorkflows.filter(sw => sw.type === 'workflow').length === 0" class="flex items-center gap-2">+ <!-- Grayed out None placeholder -->+ <div class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm bg-[#565f89]/20">+ <Hammer :size="14" class="text-[#565f89]" />+ <span class="font-medium text-[#565f89]">None</span>+ </div>+ </div>+ <div v-else class="flex items-center gap-2">+ <div+ v-for="item in skillsAndWorkflows.filter(sw => sw.type === 'workflow').slice(0, 3)"+ :key="item.name"+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm bg-[#7aa2f7]/10"+ :title="`Workflow: ${item.name}`"+ >+ <Hammer :size="14" class="text-[#7aa2f7]" />+ <span class="font-medium text-[#7aa2f7]">{{ item.name }}</span>+ </div>+ </div>+ </div>++ <span class="text-[var(--theme-text-quaternary)]">|</span>++ <!-- Tools -->+ <div class="flex items-center gap-2 flex-shrink-0">+ <span class="text-sm text-[var(--theme-text-tertiary)] font-medium uppercase">TOOLS:</span>+ <div v-if="topTools.length === 0" class="flex items-center gap-2">+ <!-- Grayed out placeholder tools: Read, Edit, Bash -->+ <div+ v-for="placeholderTool in ['Read', 'Edit', 'Bash']"+ :key="placeholderTool"+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm bg-[#565f89]/20"+ >+ <component :is="getToolIcon(placeholderTool)" :size="14" class="text-[#565f89]" />+ <span class="font-medium text-[#565f89]">{{ placeholderTool }}</span>+ </div>+ </div>+ <div v-else class="flex items-center gap-2">+ <div+ v-for="tool in topTools.slice(0, 4)"+ :key="tool.tool"+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm"+ :class="getToolStyle(tool.tool).bgClass"+ :title="`${tool.tool}: ${tool.count} calls${tool.skill ? ` (${tool.skill})` : ''}`"+ >+ <component :is="getToolIcon(tool.tool)" :size="14" :class="getToolStyle(tool.tool).iconClass" />+ <span class="font-medium" :class="getToolStyle(tool.tool).textClass">{{ tool.tool }}</span>+ <span class="font-bold" :class="getToolStyle(tool.tool).countClass">{{ tool.count }}</span>+ </div>+ </div>+ </div>++ <!-- Spacer to push pricing to the right -->+ <div class="flex-1"></div>++ <!-- Tokens -->+ <div+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm flex-shrink-0"+ style="background-color: rgba(224, 175, 104, 0.15)"+ :title="`Input: ${formatTokens(totalTokens.input)} | Output: ${formatTokens(totalTokens.output)}`"+ >+ <Cpu :size="14" class="text-[#e0af68]" />+ <span class="font-medium text-[#e0af68]">{{ formatTokens(totalTokens.input) }}/{{ formatTokens(totalTokens.output) }}</span>+ </div>++ <!-- Cost - green dollar sign and price -->+ <div+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm flex-shrink-0"+ style="background-color: rgba(158, 206, 106, 0.15)"+ :title="`Estimated cost based on Claude Opus pricing`"+ >+ <DollarSign :size="14" class="text-[#9ece6a]" />+ <span class="font-medium text-[#9ece6a]">${{ estimatedCost.toFixed(2) }}</span>+ </div>+ </div>++ <!-- Activities row - separate line below Tools -->+ <div class="flex items-center gap-2 mt-2 pt-2 border-t border-white/[0.03]">+ <span class="text-sm text-[var(--theme-text-tertiary)] font-medium flex-shrink-0 uppercase">ACTIVITIES:</span>+ <div v-if="currentActivities.length > 0" class="flex items-center gap-2 flex-wrap flex-1">+ <div+ v-for="(activity, idx) in currentActivities.slice(0, 16)"+ :key="idx"+ class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-sm"+ style="background-color: rgba(125, 207, 255, 0.12)"+ :title="`${activity.agent}: ${activity.activity}`"+ >+ <Sparkles :size="11" class="text-[#7dcfff] flex-shrink-0 animate-pulse" />+ <span class="text-[var(--theme-text-secondary)]">{{ truncateToWords(activity.activity, 8) }}...</span>+ </div>+ </div>+ <span v-else class="text-sm text-[var(--theme-text-quaternary)] italic">Waiting...</span>+ </div>++ <!-- Agent Pills Bar - Above timeline -->+ <div class="flex gap-2 min-h-[32px] mt-2 pt-2 border-t border-white/[0.03]">+ <button+ v-for="appName in stableAgentNames"+ :key="appName"+ class="agent-pill-top flex-1 min-w-0 text-xs font-medium px-3 py-1.5 rounded-lg border transition-all duration-200 cursor-pointer flex items-center gap-2 justify-center"+ :class="[+ isAgentActive(appName)+ ? 'text-[var(--theme-text-primary)]'+ : 'text-[var(--theme-text-secondary)] opacity-40 hover:opacity-70'+ ]"+ :style="{+ borderColor: getHexColorForApp(appName) + (isAgentActive(appName) ? '60' : '20'),+ backgroundColor: getHexColorForApp(appName) + (isAgentActive(appName) ? '20' : '05')+ }"+ :title="`${appName}: ${getAgentInstanceCount(appName)} instance${getAgentInstanceCount(appName) !== 1 ? 's' : ''}`"+ >+ <Sparkles v-if="isAgentActive(appName)" :size="10" class="flex-shrink-0" :style="{ color: getHexColorForApp(appName) }" />+ <Moon v-else :size="10" class="flex-shrink-0 opacity-50" />+ <span class="font-mono truncate">{{ appName }}</span>+ <span+ v-if="getAgentInstanceCount(appName) >= 1"+ class="px-1.5 py-0.5 text-[14px] font-bold rounded min-w-[20px] text-center flex-shrink-0"+ :style="getAgentInstanceCount(appName) > 1+ ? { backgroundColor: '#7aa2f7', color: '#1a1b26' }+ : { backgroundColor: '#1a1b26', color: '#c0caf5' }"+ >+ {{ getAgentInstanceCount(appName) }}+ </span>+ </button>+ <!-- Grayed out placeholder agents when none active: User and Kai -->+ <template v-if="stableAgentNames.length === 0">+ <div+ v-for="placeholderAgent in ['User', 'Kai']"+ :key="placeholderAgent"+ class="agent-pill-top flex-1 min-w-0 text-xs font-medium px-3 py-1.5 rounded-lg transition-all duration-200 flex items-center gap-2 justify-center bg-[#565f89]/20"+ >+ <Moon :size="10" class="flex-shrink-0 text-[#565f89]" />+ <span class="font-mono truncate text-[#565f89]">{{ placeholderAgent }}</span>+ </div>+ </template>+ </div>+ </div>++ <!-- Chart Section -->+ <div class="chart-section px-5 py-4 mobile:px-3 mobile:py-3">+ <div ref="chartContainer" class="relative rounded-xl overflow-hidden">+ <canvas+ ref="canvas"+ class="w-full cursor-crosshair"+ :style="{ height: chartHeight + 'px' }"+ @mousemove="handleMouseMove"+ @mouseleave="handleMouseLeave"+ role="img"+ :aria-label="chartAriaLabel"+ ></canvas>+ <div+ v-if="tooltip.visible"+ class="absolute glass-panel-elevated text-[var(--theme-text-primary)] px-3 py-2 mobile:px-3 mobile:py-2 rounded-xl text-xs mobile:text-sm pointer-events-none z-10 font-medium"+ :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"+ >+ {{ tooltip.text }}+ </div>+ <div+ v-if="!hasData"+ class="absolute inset-0 flex items-center justify-center"+ >+ <div class="flex items-center gap-3 text-[var(--theme-text-tertiary)] mobile:text-sm text-base">+ <Loader2 :size="20" :stroke-width="2" class="animate-spin text-[var(--theme-primary)]" />+ <span class="font-medium">Waiting for events...</span>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, onMounted, onUnmounted, watch, computed } from 'vue';+import type { HookEvent, TimeRange, ChartConfig } from '../types';+import { useChartData } from '../composables/useChartData';+import { useAdvancedMetrics } from '../composables/useAdvancedMetrics';+import { useHeatLevel } from '../composables/useHeatLevel';+import { createChartRenderer, type ChartDimensions } from '../utils/chartRenderer';+import { useEventEmojis } from '../composables/useEventEmojis';+import { useEventColors } from '../composables/useEventColors';+import {+ Trash2, BarChart3, Users, Zap, Wrench, Clock, Loader2, Activity, Cpu, TrendingUp, Brain, Sparkles, Timer, FolderOpen, Terminal, Layers, DollarSign, Moon,+ // Tool icons+ FileText, FileEdit, FilePlus, Search, FolderSearch, Globe, Send, GitBranch, Package, Code, Database, Eye, MessageSquare, Cog, Play, type LucideIcon,+ // Skill/Workflow icons+ Settings2, Workflow, Hammer+} from 'lucide-vue-next';+import StatBadge from './stats/StatBadge.vue';+import { useKaiContext } from '../composables/useKaiContext';++const props = defineProps<{+ events: HookEvent[];+ filters: {+ sourceApp: string;+ sessionId: string;+ eventType: string;+ };+ timeRange?: TimeRange;+}>();++const emit = defineEmits<{+ updateUniqueApps: [appNames: string[]];+ updateAllApps: [appNames: string[]];+ updateTimeRange: [timeRange: TimeRange];+ updateHeatLevel: [data: { intensity: number; color: string; label: string }];+ updateEventsPerMinute: [count: number];+ updateAgentCounts: [counts: Record<string, number>];+ clearEvents: [];+ toggleFilters: [];+}>();++const canvas = ref<HTMLCanvasElement>();+const chartContainer = ref<HTMLDivElement>();+const windowHeight = ref(typeof window !== 'undefined' ? window.innerHeight : 600);+const chartHeight = computed(() => windowHeight.value <= 400 ? 240 : 260);++const timeRanges: TimeRange[] = ['1M', '2M', '4M', '8M', '16M'];++const {+ timeRange,+ dataPoints,+ addEvent,+ getChartData,+ setTimeRange,+ cleanup: cleanupChartData,+ clearData,+ uniqueAgentCount,+ uniqueAgentIdsInWindow,+ allUniqueAgentIds,+ toolCallCount,+ eventTimingMetrics,+ allEvents,+ currentConfig+} = useChartData();++// Initialize advanced metrics+const {+ eventsPerMinute,+ totalTokens,+ activeSessions,+ topTools,+ skillsAndWorkflows,+ agentActivity,+ eventTypeBreakdown,+ eventsPerMinuteDelta+} = useAdvancedMetrics(allEvents, dataPoints, timeRange, currentConfig);++// Initialize heat level based on activity+const activeAgentCount = computed(() => agentActivity.value.length);+const {+ intensity: heatIntensity,+ color: heatColor,+ label: heatLabel+} = useHeatLevel(eventsPerMinute, activeAgentCount);++// Compute agent instance counts (how many ACTIVE instances of each agent type exist)+// Uses uniqueAgentIdsInWindow to count only agents with events in current time window+const agentInstanceCounts = computed(() => {+ const counts: Record<string, number> = {};+ uniqueAgentIdsInWindow.value.forEach(agentId => {+ // Extract base agent name (before any session suffix) and capitalize+ const rawName = agentId.split(':')[0];+ const baseName = rawName.charAt(0).toUpperCase() + rawName.slice(1);+ counts[baseName] = (counts[baseName] || 0) + 1;+ });+ return counts;+});++// Stable agent names for the top pills bar (accumulates all seen agents)+const seenAgentNames = ref<Set<string>>(new Set());++// Check if the user has submitted prompts in this session+const hasUserEvents = computed(() => {+ return allEvents.value.some(event => event.hook_event_type === 'UserPromptSubmit');+});++// Check if user is currently active (has UserPromptSubmit in current time window)+const isUserActive = computed(() => {+ const now = Date.now();+ const windowMs = 30000; // 30 second window+ return allEvents.value.some(event =>+ event.hook_event_type === 'UserPromptSubmit' &&+ event.timestamp &&+ (now - event.timestamp) < windowMs+ );+});++// Capitalize first letter of agent name+const capitalizeAgentName = (name: string): string => {+ if (!name) return name;+ return name.charAt(0).toUpperCase() + name.slice(1);+};++const stableAgentNames = computed(() => {+ // Add "User" if there are UserPromptSubmit events+ if (hasUserEvents.value) {+ seenAgentNames.value.add('User');+ }++ // Extract unique app names from all agent IDs and capitalize them+ allUniqueAgentIds.value.forEach(agentId => {+ const appName = capitalizeAgentName(agentId.split(':')[0]);+ seenAgentNames.value.add(appName);+ });+ return Array.from(seenAgentNames.value).sort();+});++// Check if an agent is currently active (has events in current time window)+const isAgentActive = (appName: string): boolean => {+ // Special case for User+ if (appName === 'User') {+ return isUserActive.value;+ }+ // Compare capitalized names+ return uniqueAgentIdsInWindow.value.some(agentId => {+ const rawName = agentId.split(':')[0];+ const capitalizedName = rawName.charAt(0).toUpperCase() + rawName.slice(1);+ return capitalizedName === appName;+ });+};++// Get instance count for an agent type+const getAgentInstanceCount = (appName: string): number => {+ // User is always a single "instance"+ if (appName === 'User') {+ return hasUserEvents.value ? 1 : 0;+ }+ return agentInstanceCounts.value[appName] || 0;+};++// Format gap time in ms to readable string (e.g., "125ms" or "1.2s")+const formatGap = (gapMs: number): string => {+ if (gapMs === 0) return '—';+ if (gapMs < 1000) {+ return `${Math.round(gapMs)}ms`;+ }+ return `${(gapMs / 1000).toFixed(1)}s`;+};++// Format tokens with K/M suffixes (with tilde to indicate estimation)+const formatTokens = (tokens: number): string => {+ if (tokens === 0) return '~0';+ if (tokens >= 1000000) {+ return `~${(tokens / 1000000).toFixed(1)}M`;+ }+ if (tokens >= 10000) {+ return `~${Math.round(tokens / 1000)}K`;+ }+ if (tokens >= 1000) {+ return `~${(tokens / 1000).toFixed(1)}K`;+ }+ return `~${tokens.toString()}`;+};++// Truncate text to N words (no ellipsis - added in template)+const truncateToWords = (text: string, maxWords: number): string => {+ const words = text.split(/\s+/);+ if (words.length <= maxWords) return text;+ return words.slice(0, maxWords).join(' ');+};++// Watch uniqueAgentIdsInWindow and emit updates (for active agents in time window)+watch(uniqueAgentIdsInWindow, (agentIds) => {+ emit('updateUniqueApps', agentIds);+}, { immediate: true });++// Watch allUniqueAgentIds and emit updates (for all agents ever seen)+watch(allUniqueAgentIds, (agentIds) => {+ emit('updateAllApps', agentIds);+}, { immediate: true });++// Watch timeRange and emit updates+watch(timeRange, (range) => {+ emit('updateTimeRange', range);+}, { immediate: true });++// Watch heat level and emit updates+watch([heatIntensity, heatColor, heatLabel], () => {+ emit('updateHeatLevel', {+ intensity: heatIntensity.value,+ color: heatColor.value,+ label: heatLabel.value+ });+}, { immediate: true });++// Watch agent counts and emit updates+watch(agentInstanceCounts, (counts) => {+ emit('updateAgentCounts', counts);+}, { immediate: true, deep: true });++// Watch events per minute and emit updates+watch(eventsPerMinute, (count) => {+ emit('updateEventsPerMinute', count);+}, { immediate: true });++// Real-time activities from Kitty tab titles (sent by update-tab-title.ts hook)+interface AgentActivityItem {+ agent: string;+ activity: string;+ timestamp: number;+}++// Store for real-time activities (updated via polling)+const realTimeActivities = ref<AgentActivityItem[]>([]);++// Fetch activities from Kitty tabs+const fetchActivities = async () => {+ try {+ const response = await fetch('http://localhost:4000/api/activities');+ if (response.ok) {+ const activities = await response.json();+ // Replace entire array with fresh data from API+ realTimeActivities.value = activities.map((act: any) => ({+ agent: act.agent,+ activity: act.activity,+ timestamp: new Date(act.timestamp).getTime()+ }));+ }+ } catch {+ // Server might not be running+ }+};++// Computed property that shows ONLY real-time activities from Kitty tab titles+// These are the semantic "Verb-ing noun noun" summaries from update-tab-title.ts+const currentActivities = computed((): AgentActivityItem[] => {+ // Return all activities from the server (Kitty tab titles)+ return realTimeActivities.value+ .sort((a, b) => b.timestamp - a.timestamp)+ .slice(0, 16);+});++let renderer: ReturnType<typeof createChartRenderer> | null = null;+let resizeObserver: ResizeObserver | null = null;+let animationFrame: number | null = null;+let activityPollInterval: ReturnType<typeof setInterval> | null = null;+const processedEventIds = new Set<string>();++const { formatEventTypeLabel } = useEventEmojis();+const { getHexColorForSession, getHexColorForApp } = useEventColors();++// Kai context (learnings, active skill, session duration)+const { context: kaiContext, formatDuration } = useKaiContext();++const hasData = computed(() => dataPoints.value.some(dp => dp.count > 0));++const totalEventCount = computed(() => {+ return dataPoints.value.reduce((sum, dp) => sum + dp.count, 0);+});++// Estimate cost based on Claude Opus 4 pricing+// Input: $15/1M tokens, Output: $75/1M tokens+const estimatedCost = computed(() => {+ const inputCostPerMillion = 15;+ const outputCostPerMillion = 75;+ const inputCost = (totalTokens.value.input / 1_000_000) * inputCostPerMillion;+ const outputCost = (totalTokens.value.output / 1_000_000) * outputCostPerMillion;+ return inputCost + outputCost;+});++// Tool icon mapping - returns icon component based on tool name+const getToolIcon = (toolName: string): LucideIcon => {+ const toolIcons: Record<string, LucideIcon> = {+ // File operations - cyan theme+ 'Read': FileText,+ 'Write': FilePlus,+ 'Edit': FileEdit,+ 'MultiEdit': FileEdit,+ // Search operations - purple theme+ 'Grep': Search,+ 'Glob': FolderSearch,+ // Shell operations - green theme+ 'Bash': Terminal,+ 'BashOutput': Terminal,+ // Web operations - orange theme+ 'WebFetch': Globe,+ 'WebSearch': Globe,+ // Task/Agent operations - pink theme+ 'Task': Send,+ 'TodoWrite': MessageSquare,+ // Code operations - blue theme+ 'NotebookEdit': Code,+ 'NotebookRead': Code,+ // System operations - yellow theme+ 'Skill': Cog,+ 'SlashCommand': Play,+ };+ return toolIcons[toolName] || Wrench;+};++// Tool style mapping - returns color classes based on tool category+interface ToolStyle {+ bgClass: string;+ iconClass: string;+ textClass: string;+ countClass: string;+}++const getToolStyle = (toolName: string): ToolStyle => {+ // File operations - cyan/blue+ if (['Read', 'Write', 'Edit', 'MultiEdit'].includes(toolName)) {+ return {+ bgClass: 'bg-[#7dcfff]/10',+ iconClass: 'text-[#7dcfff]',+ textClass: 'text-[#7dcfff]',+ countClass: 'text-[#7dcfff]'+ };+ }+ // Search operations - purple+ if (['Grep', 'Glob'].includes(toolName)) {+ return {+ bgClass: 'bg-[#bb9af7]/10',+ iconClass: 'text-[#bb9af7]',+ textClass: 'text-[#bb9af7]',+ countClass: 'text-[#bb9af7]'+ };+ }+ // Shell operations - green+ if (['Bash', 'BashOutput'].includes(toolName)) {+ return {+ bgClass: 'bg-[#9ece6a]/10',+ iconClass: 'text-[#9ece6a]',+ textClass: 'text-[#9ece6a]',+ countClass: 'text-[#9ece6a]'+ };+ }+ // Web operations - orange+ if (['WebFetch', 'WebSearch'].includes(toolName)) {+ return {+ bgClass: 'bg-[#ff9e64]/10',+ iconClass: 'text-[#ff9e64]',+ textClass: 'text-[#ff9e64]',+ countClass: 'text-[#ff9e64]'+ };+ }+ // Task/Agent operations - pink+ if (['Task', 'TodoWrite'].includes(toolName)) {+ return {+ bgClass: 'bg-[#f7768e]/10',+ iconClass: 'text-[#f7768e]',+ textClass: 'text-[#f7768e]',+ countClass: 'text-[#f7768e]'+ };+ }+ // Default - neutral gray+ return {+ bgClass: 'bg-[#565f89]/10',+ iconClass: 'text-[#a9b1d6]',+ textClass: 'text-[#a9b1d6]',+ countClass: 'text-[#c0caf5]'+ };+};++const chartAriaLabel = computed(() => {+ const rangeText = timeRange.value === '1M' ? '1 minute' : timeRange.value === '2M' ? '2 minutes' : timeRange.value === '4M' ? '4 minutes' : timeRange.value === '8M' ? '8 minutes' : '16 minutes';+ return `Activity chart showing ${totalEventCount.value} events over the last ${rangeText}`;+});++const tooltip = ref({+ visible: false,+ x: 0,+ y: 0,+ text: ''+});++const getThemeColor = (property: string): string => {+ const style = getComputedStyle(document.documentElement);+ const color = style.getPropertyValue(`--theme-${property}`).trim();+ return color || '#3B82F6'; // fallback+};++const getActiveConfig = (): ChartConfig => {+ return {+ maxDataPoints: 60,+ animationDuration: 300,+ barWidth: 3,+ barGap: 1,+ colors: {+ primary: getThemeColor('primary'),+ glow: getThemeColor('primary-light'),+ axis: getThemeColor('border-primary'),+ text: getThemeColor('text-tertiary')+ }+ };+};++const getDimensions = (): ChartDimensions => {+ const width = chartContainer.value?.offsetWidth || 800;+ return {+ width,+ height: chartHeight.value,+ padding: {+ top: 15,+ right: 15,+ bottom: 35, // More space for time labels+ left: 15+ }+ };+};++const render = () => {+ if (!renderer || !canvas.value) return;++ const data = getChartData();+ const maxValue = Math.max(...data.map(d => d.count), 1);++ renderer.clear();+ renderer.drawBackground();+ renderer.drawAxes();+ renderer.drawTimeLabels(timeRange.value);+ renderer.drawBars(data, maxValue, 1, formatEventTypeLabel, getHexColorForApp);+};++const animateNewEvent = (x: number, y: number) => {+ let radius = 0;+ let opacity = 0.8;++ const animate = () => {+ if (!renderer) return;++ render();+ renderer.drawPulseEffect(x, y, radius, opacity);++ radius += 2;+ opacity -= 0.02;++ if (opacity > 0) {+ animationFrame = requestAnimationFrame(animate);+ } else {+ animationFrame = null;+ }+ };++ animate();+};++const handleWindowResize = () => {+ windowHeight.value = window.innerHeight;+};++const handleResize = () => {+ if (!renderer || !canvas.value) return;++ const dimensions = getDimensions();+ renderer.resize(dimensions);+ render();+};++const isEventFiltered = (event: HookEvent): boolean => {+ if (props.filters.sourceApp && event.source_app !== props.filters.sourceApp) {+ return false;+ }+ if (props.filters.sessionId && event.session_id !== props.filters.sessionId) {+ return false;+ }+ if (props.filters.eventType && event.hook_event_type !== props.filters.eventType) {+ return false;+ }+ return true;+};++const processNewEvents = () => {+ const currentEvents = props.events;+ const newEventsToProcess: HookEvent[] = [];++ // Find events that haven't been processed yet+ currentEvents.forEach(event => {+ const eventKey = `${event.id}-${event.timestamp}`;+ if (!processedEventIds.has(eventKey)) {+ processedEventIds.add(eventKey);+ newEventsToProcess.push(event);+ }+ });++ // Process new events+ newEventsToProcess.forEach(event => {+ if (event.hook_event_type !== 'refresh' && event.hook_event_type !== 'initial' && isEventFiltered(event)) {+ addEvent(event);++ // Trigger pulse animation for new event+ if (renderer && canvas.value) {+ const chartArea = getDimensions();+ const x = chartArea.width - chartArea.padding.right - 10;+ const y = chartArea.height / 2;+ animateNewEvent(x, y);+ }+ }+ });++ // Clean up old event IDs to prevent memory leak+ // Keep only IDs from current events+ const currentEventIds = new Set(currentEvents.map(e => `${e.id}-${e.timestamp}`));+ processedEventIds.forEach(id => {+ if (!currentEventIds.has(id)) {+ processedEventIds.delete(id);+ }+ });++ render();+};++// Watch for new events+watch(() => props.events, (newEvents) => {+ // If events array is empty, clear all internal state+ if (newEvents.length === 0) {+ clearData();+ processedEventIds.clear();+ render();+ return;+ }+ processNewEvents();+}, { deep: true });++// Watch for filter changes+watch(() => props.filters, () => {+ // Reset and reprocess all events with new filters+ dataPoints.value = [];+ processedEventIds.clear();+ processNewEvents();+}, { deep: true });++// Watch for time range changes (internal)+watch(timeRange, () => {+ // Need to re-process all events when time range changes+ // because bucket sizes are different+ render();+});++// Watch for time range prop changes (from parent, e.g., IntensityBar buttons)+watch(() => props.timeRange, (newRange) => {+ if (newRange && newRange !== timeRange.value) {+ setTimeRange(newRange);+ }+});++// Watch for chart height changes+watch(chartHeight, () => {+ handleResize();+});++const handleMouseMove = (event: MouseEvent) => {+ if (!canvas.value || !chartContainer.value) return;++ const rect = canvas.value.getBoundingClientRect();+ const x = event.clientX - rect.left;+ const y = event.clientY - rect.top;++ const data = getChartData();+ const dimensions = getDimensions();+ const chartArea = {+ x: dimensions.padding.left,+ y: dimensions.padding.top,+ width: dimensions.width - dimensions.padding.left - dimensions.padding.right,+ height: dimensions.height - dimensions.padding.top - dimensions.padding.bottom+ };++ const barWidth = chartArea.width / data.length;+ const barIndex = Math.floor((x - chartArea.x) / barWidth);++ if (barIndex >= 0 && barIndex < data.length && y >= chartArea.y && y <= chartArea.y + chartArea.height) {+ const point = data[barIndex];+ if (point.count > 0) {+ const eventTypesText = Object.entries(point.eventTypes || {})+ .map(([type, count]) => `${type}: ${count}`)+ .join(', ');++ tooltip.value = {+ visible: true,+ x: event.clientX - rect.left,+ y: event.clientY - rect.top - 30,+ text: `${point.count} events${eventTypesText ? ` (${eventTypesText})` : ''}`+ };+ return;+ }+ }++ tooltip.value.visible = false;+};++const handleMouseLeave = () => {+ tooltip.value.visible = false;+};++const handleTimeRangeKeyDown = (event: KeyboardEvent, currentIndex: number) => {+ let newIndex = currentIndex;++ switch (event.key) {+ case 'ArrowLeft':+ newIndex = Math.max(0, currentIndex - 1);+ break;+ case 'ArrowRight':+ newIndex = Math.min(timeRanges.length - 1, currentIndex + 1);+ break;+ case 'Home':+ newIndex = 0;+ break;+ case 'End':+ newIndex = timeRanges.length - 1;+ break;+ default:+ return;+ }++ if (newIndex !== currentIndex) {+ event.preventDefault();+ setTimeRange(timeRanges[newIndex]);+ // Focus the new button+ const buttons = (event.currentTarget as HTMLElement)?.parentElement?.querySelectorAll('button');+ if (buttons && buttons[newIndex]) {+ (buttons[newIndex] as HTMLButtonElement).focus();+ }+ }+};++// Watch for theme changes+const themeObserver = new MutationObserver(() => {+ if (renderer) {+ render();+ }+});++onMounted(() => {+ if (!canvas.value || !chartContainer.value) return;++ const dimensions = getDimensions();+ const config = getActiveConfig();++ renderer = createChartRenderer(canvas.value, dimensions, config);++ // Fetch initial activities from server+ fetchActivities();++ // Poll for activities every 2 seconds (stored globally for cleanup)+ activityPollInterval = setInterval(fetchActivities, 2000);++ // Set up resize observer+ resizeObserver = new ResizeObserver(handleResize);+ resizeObserver.observe(chartContainer.value);++ // Observe theme changes+ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class']+ });++ // Listen for window height changes+ window.addEventListener('resize', handleWindowResize);++ // Initial render+ render();++ // Start optimized render loop with FPS limiting+ let lastRenderTime = 0;+ const targetFPS = 30;+ const frameInterval = 1000 / targetFPS;++ const renderLoop = (currentTime: number) => {+ const deltaTime = currentTime - lastRenderTime;++ if (deltaTime >= frameInterval) {+ render();+ lastRenderTime = currentTime - (deltaTime % frameInterval);+ }++ requestAnimationFrame(renderLoop);+ };+ requestAnimationFrame(renderLoop);+});++onUnmounted(() => {+ cleanupChartData();++ if (renderer) {+ renderer.stopAnimation();+ }++ if (resizeObserver && chartContainer.value) {+ resizeObserver.disconnect();+ }++ if (animationFrame) {+ cancelAnimationFrame(animationFrame);+ }++ // Clean up activity polling interval+ if (activityPollInterval) {+ clearInterval(activityPollInterval);+ }++ themeObserver.disconnect();++ // Remove window resize listener+ window.removeEventListener('resize', handleWindowResize);+});+</script>++<style scoped>+/* Modern Dashboard Layout */+.modern-dashboard {+ display: flex;+ flex-direction: column;+}++/* Tools Bar - Horizontal list of active tools */+.tools-bar {+ /* border removed */+}++/* Chart Section - Clean with breathing room */+.chart-section {+ /* Clean styling inherited from parent glass panel */+}++</style>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/StickScrollButton.vue b/.claude/skills/observability/apps/client/src/components/StickScrollButton.vuenew file mode 100644index 00000000..7a25974c--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/StickScrollButton.vue@@ -0,0 +1,44 @@+<template>+ <button+ @click="$emit('toggle')"+ class="fixed bottom-6 right-6 mobile:bottom-4 mobile:right-4 p-4 mobile:p-3 rounded-full shadow-lg hover:shadow-xl transition-all duration-200 min-w-[44px] min-h-[44px] flex items-center justify-center border-2 transform hover:scale-110"+ :class="[+ stickToBottom+ ? 'bg-gradient-to-r from-[var(--theme-primary)] to-[var(--theme-primary-light)] text-white border-[var(--theme-primary-dark)] drop-shadow-md'+ : 'bg-[var(--theme-bg-primary)] hover:bg-[var(--theme-bg-secondary)] text-[var(--theme-text-primary)] border-[var(--theme-border-primary)] hover:border-[var(--theme-primary)]'+ ]"+ :title="stickToBottom ? 'Disable auto-scroll to top' : 'Enable auto-scroll to top'"+ >+ <svg+ class="w-6 h-6 mobile:w-5 mobile:h-5 drop-shadow-sm"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ v-if="stickToBottom"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ d="M5 10l7-7m0 0l7 7m-7-7v18"+ />+ <path+ v-else+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6v.01"+ />+ </svg>+ </button>+</template>++<script setup lang="ts">+defineProps<{+ stickToBottom: boolean;+}>();++defineEmits<{+ toggle: [];+}>();+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/ThemeManager.vue b/.claude/skills/observability/apps/client/src/components/ThemeManager.vuenew file mode 100644index 00000000..880cd7d1--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/ThemeManager.vue@@ -0,0 +1,125 @@+<template>+ <Teleport to="body">+ <div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4">+ <!-- Backdrop -->+ <div+ class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"+ @click="close"+ ></div>++ <!-- Modal -->+ <div+ class="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl flex flex-col overflow-hidden z-10"+ style="width: 75vw; height: 75vh"+ @click.stop+ >+ <!-- Header -->+ <div class="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-6">+ <div class="flex items-center justify-between mb-4">+ <h2 class="text-3xl font-semibold text-gray-900 dark:text-white">+ 🎨 Theme Manager+ </h2>+ <button+ @click="close"+ class="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"+ >+ <svg class="w-6 h-6 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />+ </svg>+ </button>+ </div>+ </div>++ <!-- Content -->+ <div class="flex-1 p-6 overflow-y-auto">+ <!-- Theme Grid -->+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">+ <div+ v-for="theme in predefinedThemes"+ :key="theme.name"+ @click="selectTheme(theme.name)"+ :class="[+ 'cursor-pointer rounded-lg border-2 p-4 transition-all hover:shadow-md',+ currentTheme === theme.name+ ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'+ : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'+ ]"+ >+ <!-- Theme Preview -->+ <div class="flex h-16 rounded-md overflow-hidden mb-3">+ <div+ class="flex-1"+ :style="{ backgroundColor: theme.preview.primary }"+ ></div>+ <div+ class="flex-1"+ :style="{ backgroundColor: theme.preview.secondary }"+ ></div>+ <div+ class="flex-1"+ :style="{ backgroundColor: theme.preview.accent }"+ ></div>+ </div>++ <!-- Theme Info -->+ <h3 class="font-medium text-gray-900 dark:text-white">{{ theme.displayName }}</h3>+ <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">{{ theme.description }}</p>++ <!-- Current indicator -->+ <div v-if="currentTheme === theme.name" class="mt-2">+ <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300">+ <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />+ </svg>+ Current+ </span>+ </div>+ </div>+ </div>++ <!-- Actions -->+ <div class="flex justify-between items-center pt-4 border-t border-gray-200 dark:border-gray-700">+ <div class="text-sm text-gray-500 dark:text-gray-400">+ {{ predefinedThemes.length }} themes available+ </div>+ <button+ @click="close"+ class="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"+ >+ Close+ </button>+ </div>+ </div>+ </div>+ </div>+ </Teleport>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import { useThemes } from '../composables/useThemes';++defineProps<{+ isOpen: boolean;+}>();++const emit = defineEmits<{+ close: [];+}>();++// Theme management+const { state, predefinedThemes, setTheme } = useThemes();++// Computed properties+const currentTheme = computed(() => state.value.currentTheme);++// Methods+const selectTheme = (themeName: string) => {+ setTheme(themeName);+ close();+};++const close = () => {+ emit('close');+};+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/ThemePreview.vue b/.claude/skills/observability/apps/client/src/components/ThemePreview.vuenew file mode 100644index 00000000..5030bde6--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/ThemePreview.vue@@ -0,0 +1,293 @@+<template>+ <div class="bg-gray-100 dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700">+ <div class="flex items-center justify-between mb-4">+ <h4 class="text-lg font-medium text-gray-900 dark:text-white">Live Preview</h4>+ <button+ @click="$emit('apply')"+ class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"+ >+ Apply Preview+ </button>+ </div>++ <!-- Preview Window -->+ <div class="border-2 border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden">+ <!-- Mini header simulation -->+ <div+ class="px-4 py-3 border-b"+ :style="{+ backgroundColor: theme.colors?.bgPrimary || '#ffffff',+ borderColor: theme.colors?.borderPrimary || '#e5e7eb'+ }"+ >+ <div class="flex items-center justify-between">+ <h3+ class="font-semibold"+ :style="{ color: theme.colors?.textPrimary || '#111827' }"+ >+ {{ theme.displayName || 'Theme Preview' }}+ </h3>+ <div class="flex items-center space-x-2">+ <div+ class="w-3 h-3 rounded-full"+ :style="{ backgroundColor: theme.colors?.accentSuccess || '#10b981' }"+ ></div>+ <span+ class="text-sm"+ :style="{ color: theme.colors?.textTertiary || '#6b7280' }"+ >+ Connected+ </span>+ </div>+ </div>+ </div>++ <!-- Content area simulation -->+ <div+ class="p-4 space-y-4"+ :style="{ backgroundColor: theme.colors?.bgSecondary || '#f9fafb' }"+ >+ <!-- Simulated event card -->+ <div+ class="rounded-lg p-4 border shadow-sm"+ :style="{+ backgroundColor: theme.colors?.bgPrimary || '#ffffff',+ borderColor: theme.colors?.borderPrimary || '#e5e7eb'+ }"+ >+ <div class="flex items-center justify-between mb-2">+ <div class="flex items-center space-x-3">+ <span+ class="px-3 py-1 rounded-full text-sm font-medium border-2"+ :style="{+ backgroundColor: (theme.colors?.primary || '#3b82f6') + '20',+ color: theme.colors?.primary || '#3b82f6',+ borderColor: theme.colors?.primary || '#3b82f6'+ }"+ >+ demo-app+ </span>+ <span+ class="px-2 py-1 rounded-full text-sm border"+ :style="{+ color: theme.colors?.textSecondary || '#374151',+ borderColor: theme.colors?.borderSecondary || '#d1d5db'+ }"+ >+ abc123+ </span>+ <span+ class="flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium"+ :style="{+ backgroundColor: (theme.colors?.accentInfo || '#3b82f6') + '20',+ color: theme.colors?.accentInfo || '#3b82f6'+ }"+ >+ <Wrench :size="14" :stroke-width="2.5" />+ PreToolUse+ </span>+ </div>+ <span+ class="text-sm"+ :style="{ color: theme.colors?.textQuaternary || '#9ca3af' }"+ >+ 2:34 PM+ </span>+ </div>++ <div class="flex items-center justify-between">+ <div>+ <span+ class="font-medium"+ :style="{ color: theme.colors?.textSecondary || '#374151' }"+ >+ Bash+ </span>+ <span+ class="ml-2"+ :style="{ color: theme.colors?.textTertiary || '#6b7280' }"+ >+ ls -la+ </span>+ </div>+ <div+ class="flex items-center gap-1.5 px-3 py-1 rounded-lg"+ :style="{+ backgroundColor: theme.colors?.bgTertiary || '#f3f4f6'+ }"+ >+ <FileText :size="14" :stroke-width="2.5" :style="{ color: theme.colors?.textSecondary || '#374151' }" />+ <span+ class="text-sm"+ :style="{ color: theme.colors?.textSecondary || '#374151' }"+ >+ Summary available+ </span>+ </div>+ </div>+ </div>++ <!-- Simulated filter panel -->+ <div+ class="rounded-lg p-3 border"+ :style="{+ backgroundColor: theme.colors?.bgTertiary || '#f3f4f6',+ borderColor: theme.colors?.borderSecondary || '#d1d5db'+ }"+ >+ <div class="flex items-center space-x-4">+ <select+ class="px-3 py-1 rounded border text-sm"+ :style="{+ backgroundColor: theme.colors?.bgPrimary || '#ffffff',+ borderColor: theme.colors?.borderPrimary || '#e5e7eb',+ color: theme.colors?.textSecondary || '#374151'+ }"+ >+ <option>All Apps</option>+ <option>demo-app</option>+ </select>+ <select+ class="px-3 py-1 rounded border text-sm"+ :style="{+ backgroundColor: theme.colors?.bgPrimary || '#ffffff',+ borderColor: theme.colors?.borderPrimary || '#e5e7eb',+ color: theme.colors?.textSecondary || '#374151'+ }"+ >+ <option>All Events</option>+ <option>PreToolUse</option>+ </select>+ <button+ class="px-3 py-1 rounded text-sm font-medium text-white transition-colors"+ :style="{+ backgroundColor: theme.colors?.primary || '#3b82f6'+ }"+ @mouseover="handleHover"+ @mouseleave="handleHoverEnd"+ >+ Apply Filters+ </button>+ </div>+ </div>++ <!-- Color palette display -->+ <div class="grid grid-cols-8 gap-2">+ <div+ v-for="(color, key) in displayColors"+ :key="key"+ class="h-8 rounded border relative group cursor-pointer"+ :style="{ backgroundColor: color, borderColor: theme.colors?.borderPrimary || '#e5e7eb' }"+ :title="`${formatColorLabel(key)}: ${color}`"+ >+ <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-10 rounded transition-all duration-200"></div>+ </div>+ </div>++ <!-- Status indicators -->+ <div class="flex items-center justify-between text-sm">+ <div class="flex items-center space-x-4">+ <div class="flex items-center space-x-2">+ <div+ class="w-2 h-2 rounded-full"+ :style="{ backgroundColor: theme.colors?.accentSuccess || '#10b981' }"+ ></div>+ <span :style="{ color: theme.colors?.textSecondary || '#374151' }">+ Success+ </span>+ </div>+ <div class="flex items-center space-x-2">+ <div+ class="w-2 h-2 rounded-full"+ :style="{ backgroundColor: theme.colors?.accentWarning || '#f59e0b' }"+ ></div>+ <span :style="{ color: theme.colors?.textSecondary || '#374151' }">+ Warning+ </span>+ </div>+ <div class="flex items-center space-x-2">+ <div+ class="w-2 h-2 rounded-full"+ :style="{ backgroundColor: theme.colors?.accentError || '#ef4444' }"+ ></div>+ <span :style="{ color: theme.colors?.textSecondary || '#374151' }">+ Error+ </span>+ </div>+ </div>+ <span :style="{ color: theme.colors?.textTertiary || '#6b7280' }">+ 156 events+ </span>+ </div>+ </div>+ </div>++ <!-- Theme info -->+ <div class="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700">+ <div class="flex items-start space-x-3">+ <svg class="w-5 h-5 text-blue-500 mt-0.5" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />+ </svg>+ <div>+ <p class="text-sm font-medium text-blue-800 dark:text-blue-200">+ Live Preview Active+ </p>+ <p class="text-sm text-blue-600 dark:text-blue-300">+ This is how your theme will look in the application. Changes are applied in real-time.+ </p>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import type { CustomTheme, CreateThemeFormData } from '../types/theme';+import { Wrench, FileText } from 'lucide-vue-next';++interface Props {+ theme: CustomTheme | CreateThemeFormData;+}++const props = defineProps<Props>();++defineEmits<{+ apply: [];+}>();++// Extract only the visible colors for the palette display+const displayColors = computed(() => {+ const colors = props.theme.colors;+ if (!colors) return {};++ return {+ primary: colors.primary,+ bgPrimary: colors.bgPrimary,+ bgSecondary: colors.bgSecondary,+ bgTertiary: colors.bgTertiary,+ textPrimary: colors.textPrimary,+ textSecondary: colors.textSecondary,+ accentSuccess: colors.accentSuccess,+ accentError: colors.accentError+ };+});++const formatColorLabel = (key: string) => {+ return key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());+};++const handleHover = (event: Event) => {+ const button = event.target as HTMLElement;+ if (props.theme.colors?.primaryHover) {+ button.style.backgroundColor = props.theme.colors.primaryHover;+ }+};++const handleHoverEnd = (event: Event) => {+ const button = event.target as HTMLElement;+ if (props.theme.colors?.primary) {+ button.style.backgroundColor = props.theme.colors.primary;+ }+};+</script>\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/components/ToastNotification.vue b/.claude/skills/observability/apps/client/src/components/ToastNotification.vuenew file mode 100644index 00000000..633640f3--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/ToastNotification.vue@@ -0,0 +1,97 @@+<template>+ <Transition name="toast">+ <div+ v-if="isVisible"+ class="fixed left-1/2 transform -translate-x-1/2 z-50 flex items-center gap-3 px-4 py-3 bg-gray-900 text-white rounded-lg border-2 font-semibold drop-shadow-2xl transition-all duration-300"+ :style="{+ top: `${16 + (index * 68)}px`,+ borderColor: agentColor,+ boxShadow: `0 10px 40px -10px rgba(0, 0, 0, 0.5), 0 20px 50px -15px rgba(0, 0, 0, 0.3), 0 0 0 3px ${agentColor}33`+ }"+ >+ <div+ class="w-3 h-3 rounded-full"+ :style="{ backgroundColor: agentColor }"+ ></div>+ <span class="text-sm" :style="{ color: agentColor }">+ New Agent <span class="font-bold px-2 py-0.5 rounded" :style="{ backgroundColor: agentColor, color: '#1a1b26' }">"{{ agentName }}"</span> Joined+ </span>+ <button+ @click="dismiss"+ class="ml-2 text-white hover:text-white/80 transition-colors duration-200 font-bold text-lg leading-none"+ aria-label="Dismiss notification"+ >+ ×+ </button>+ </div>+ </Transition>+</template>++<script setup lang="ts">+import { ref, onMounted, onUnmounted } from 'vue';++const props = defineProps<{+ agentName: string;+ agentColor: string;+ index: number;+ duration?: number;+}>();++const emit = defineEmits<{+ dismiss: [];+}>();++const isVisible = ref(false);+let dismissTimer: number | null = null;++const dismiss = () => {+ isVisible.value = false;+ if (dismissTimer !== null) {+ clearTimeout(dismissTimer);+ dismissTimer = null;+ }+ // Wait for animation to complete before emitting+ setTimeout(() => {+ emit('dismiss');+ }, 300);+};++onMounted(() => {+ // Show toast with slight delay for animation+ requestAnimationFrame(() => {+ isVisible.value = true;+ });++ // Auto-dismiss after duration (default 4s)+ const totalDuration = props.duration || 4000;+ dismissTimer = window.setTimeout(() => {+ dismiss();+ }, totalDuration);+});++onUnmounted(() => {+ if (dismissTimer !== null) {+ clearTimeout(dismissTimer);+ }+});+</script>++<style scoped>+.toast-enter-active {+ transition: all 0.3s ease-out;+}++.toast-leave-active {+ transition: all 0.3s ease-in;+}++.toast-enter-from {+ opacity: 0;+ transform: translate(-50%, -20px);+}++.toast-leave-to {+ opacity: 0;+ transform: translate(-50%, -20px);+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/stats/StatBadge.vue b/.claude/skills/observability/apps/client/src/components/stats/StatBadge.vuenew file mode 100644index 00000000..84defc07--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/stats/StatBadge.vue@@ -0,0 +1,318 @@+<template>+ <div+ class="stat-badge-enhanced"+ :class="[+ `variant-${variant}`,+ health && `health-${health}`+ ]"+ :data-health="health"+ role="status"+ :aria-label="ariaLabel"+ >+ <component+ :is="icon"+ class="badge-icon"+ :size="12"+ :stroke-width="2.5"+ aria-hidden="true"+ />+ <span class="badge-value">{{ formattedValue }}</span>+ <span class="badge-label">{{ label }}</span>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import type { Component } from '@vue/runtime-core';++export interface StatBadgeProps {+ icon: Component;+ value: number | string;+ label: string;+ delta?: {+ value: string;+ state: 'positive' | 'negative' | 'neutral';+ };+ sparklineData?: number[];+ health?: 'excellent' | 'good' | 'warning' | 'critical';+ variant?: 'primary' | 'secondary';+}++const props = withDefaults(defineProps<StatBadgeProps>(), {+ variant: 'secondary'+});++const sparklineWidth = 40;+const sparklineHeight = 16;++// Format number with appropriate suffix+const formatNumber = (value: number | string): string => {+ if (typeof value === 'string') return value;+ if (value >= 1000000) return `${(value / 1000000).toFixed(1)}M`;+ if (value >= 10000) return `${(value / 1000).toFixed(0)}K`;+ if (value >= 1000) return `${(value / 1000).toFixed(1)}K`;+ return value.toString();+};++const formattedValue = computed(() => formatNumber(props.value));++// Generate smooth bezier curve path for sparkline+const generateSparklinePath = (+ data: number[],+ width: number = sparklineWidth,+ height: number = sparklineHeight+): string => {+ if (!data || data.length < 2) return '';++ const maxValue = Math.max(...data);+ const minValue = Math.min(...data);+ const range = maxValue - minValue || 1;++ const points = data.map((value, index) => ({+ x: (index / (data.length - 1)) * width,+ y: height - ((value - minValue) / range) * height+ }));++ // Create smooth bezier curve+ let path = `M ${points[0].x},${points[0].y}`;++ for (let i = 1; i < points.length; i++) {+ const prev = points[i - 1];+ const curr = points[i];+ const cpx = (prev.x + curr.x) / 2;+ path += ` Q ${cpx},${prev.y} ${cpx},${(prev.y + curr.y) / 2}`;+ path += ` Q ${cpx},${curr.y} ${curr.x},${curr.y}`;+ }++ return path;+};++const sparklinePath = computed(() => {+ if (!props.sparklineData || props.sparklineData.length === 0) {+ return '';+ }+ return generateSparklinePath(props.sparklineData, sparklineWidth, sparklineHeight);+});++// Describe trend for accessibility+const trendDescription = computed(() => {+ if (!props.sparklineData || props.sparklineData.length < 2) {+ return 'no data';+ }++ const firstValue = props.sparklineData[0];+ const lastValue = props.sparklineData[props.sparklineData.length - 1];++ if (lastValue > firstValue) {+ return 'upward trend';+ } else if (lastValue < firstValue) {+ return 'downward trend';+ }+ return 'stable trend';+});++// ARIA label for screen readers+const ariaLabel = computed(() => {+ let description = `${props.label}: ${formattedValue.value}`;++ if (props.delta) {+ description += `, ${props.delta.state} change of ${props.delta.value}`;+ }++ if (props.health) {+ description += `, health status: ${props.health}`;+ }++ if (props.sparklineData && props.sparklineData.length > 0) {+ description += `, ${trendDescription.value}`;+ }++ return description;+});+</script>++<style scoped>+.stat-badge-enhanced {+ display: flex;+ flex-direction: row;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ min-height: 28px;+ border-radius: 8px;+ background: linear-gradient(135deg,+ var(--theme-bg-tertiary),+ var(--theme-bg-quaternary)+ );+ border: 1px solid var(--theme-border-primary);+ box-shadow: 0 1px 3px var(--theme-shadow);+ transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);+ cursor: default;+ user-select: none;+ will-change: transform, opacity;+}++.stat-badge-enhanced:hover {+ border-color: var(--theme-primary);+ box-shadow: 0 4px 12px var(--theme-shadow-lg);+ transform: translateY(-1px);+}++.stat-badge-enhanced:focus-visible {+ outline: 2px solid var(--theme-primary);+ outline-offset: 2px;+}++/* Primary variant (existing metrics) */+.variant-primary {+ background: linear-gradient(135deg,+ color-mix(in srgb, var(--theme-primary) 10%, transparent),+ color-mix(in srgb, var(--theme-primary-light) 10%, transparent)+ );+ border: 1px solid color-mix(in srgb, var(--theme-primary) 30%, transparent);+}++.variant-primary:hover {+ border-color: var(--theme-primary);+ box-shadow: 0 4px 12px color-mix(in srgb, var(--theme-primary) 20%, transparent);+}++/* Secondary variant (default) */+.variant-secondary {+ background: linear-gradient(135deg,+ var(--theme-bg-tertiary),+ var(--theme-bg-quaternary)+ );+}++/* Health states */+.health-excellent {+ border-color: var(--theme-accent-success);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--theme-accent-success) 20%, transparent),+ 0 1px 3px var(--theme-shadow);+}++.health-excellent:hover {+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--theme-accent-success) 30%, transparent),+ 0 4px 12px var(--theme-shadow-lg);+}++.health-good {+ border-color: color-mix(in srgb, var(--theme-accent-success) 60%, transparent);+}++.health-warning {+ border-color: var(--theme-accent-warning);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--theme-accent-warning) 20%, transparent),+ 0 1px 3px var(--theme-shadow);+}++.health-warning:hover {+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--theme-accent-warning) 30%, transparent),+ 0 4px 12px var(--theme-shadow-lg);+}++.health-critical {+ border-color: var(--theme-accent-error);+ animation: badge-pulse-warning 2s infinite;+}++@keyframes badge-pulse-warning {+ 0%, 100% {+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--theme-accent-error) 20%, transparent),+ 0 1px 3px var(--theme-shadow);+ }+ 50% {+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--theme-accent-error) 30%, transparent),+ 0 2px 8px var(--theme-shadow-lg);+ }+}++.badge-icon {+ flex-shrink: 0;+ color: var(--theme-primary);+ opacity: 0.8;+ transition: opacity 0.2s ease;+}++.stat-badge-enhanced:hover .badge-icon {+ opacity: 1;+}++.badge-value {+ font-family: 'concourse-c3', monospace;+ font-size: 12px;+ font-weight: 700;+ line-height: 1;+ color: var(--theme-text-primary);+ letter-spacing: -0.02em;+ white-space: nowrap;+}++.badge-label {+ font-family: 'concourse-t3', sans-serif;+ font-size: 9px;+ font-weight: 600;+ line-height: 1;+ color: var(--theme-text-tertiary);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ white-space: nowrap;+}++/* Mobile responsive adjustments */+@media (max-width: 640px) {+ .stat-badge-enhanced {+ padding: 3px 6px;+ gap: 3px;+ }++ .badge-value {+ font-size: 11px;+ }++ .badge-label {+ font-size: 8px;+ }+}++/* Touch-friendly hover states */+@media (hover: none) and (pointer: coarse) {+ .stat-badge-enhanced:hover {+ transform: none;+ }++ .stat-badge-enhanced:active {+ transform: scale(0.98);+ opacity: 0.9;+ }+}++/* Reduced motion support */+@media (prefers-reduced-motion: reduce) {+ .stat-badge-enhanced {+ transition: none;+ }++ .health-critical {+ animation: none;+ }++ .badge-icon,+ .badge-delta,+ .badge-sparkline {+ transition: none;+ }+}++/* High contrast mode support */+@media (prefers-contrast: high) {+ .stat-badge-enhanced {+ border-width: 2px;+ }++ .badge-value {+ font-weight: 800;+ }+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/AgentActivityWidget.vue b/.claude/skills/observability/apps/client/src/components/widgets/AgentActivityWidget.vuenew file mode 100644index 00000000..3bedebac--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/AgentActivityWidget.vue@@ -0,0 +1,130 @@+<template>+ <div class="mini-widget">+ <div class="widget-header">+ <h3 class="widget-title">Agent Activity</h3>+ <Users :size="14" :stroke-width="2.5" class="widget-icon" />+ </div>+ <div class="widget-body">+ <div class="agent-list">+ <div+ v-for="(agent, index) in agentActivity.slice(0, 6)"+ :key="agent.agent"+ class="agent-col"+ >+ <div class="agent-header">+ <div class="agent-label">{{ agent.agent }}</div>+ <div class="agent-count">{{ agent.count }}</div>+ </div>+ <div class="agent-bar">+ <div+ class="agent-bar-fill"+ :class="`bar-color-${index % 5}`"+ :style="{ width: `${agent.percentage}%` }"+ ></div>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { Users } from 'lucide-vue-next';+import type { AgentActivity } from '../../composables/useAdvancedMetrics';++const props = defineProps<{+ agentActivity: AgentActivity[];+}>();+</script>++<style scoped>+@import './widget-base.css';++.agent-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ height: 100%;+ justify-content: space-around;+}++.agent-col {+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.agent-header {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ gap: 4px;+}++.agent-label {+ font-size: 9px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex: 1;+}++.agent-bar {+ height: 10px;+ background: var(--theme-bg-tertiary);+ border-radius: 5px;+ overflow: hidden;+}++.agent-bar-fill {+ height: 100%;+ border-radius: 5px;+ transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);+ animation: shimmer 2s ease-in-out infinite;+}++.bar-color-0 {+ background: linear-gradient(90deg, rgba(122, 162, 247, 0.6) 0%, rgba(187, 154, 247, 0.5) 100%);+ box-shadow: 0 0 4px rgba(122, 162, 247, 0.2);+}++.bar-color-1 {+ background: linear-gradient(90deg, rgba(158, 206, 106, 0.6) 0%, rgba(115, 218, 202, 0.5) 100%);+ box-shadow: 0 0 4px rgba(158, 206, 106, 0.2);+}++.bar-color-2 {+ background: linear-gradient(90deg, rgba(247, 118, 142, 0.6) 0%, rgba(255, 158, 100, 0.5) 100%);+ box-shadow: 0 0 4px rgba(247, 118, 142, 0.2);+}++.bar-color-3 {+ background: linear-gradient(90deg, rgba(224, 175, 104, 0.6) 0%, rgba(255, 158, 100, 0.5) 100%);+ box-shadow: 0 0 4px rgba(224, 175, 104, 0.2);+}++.bar-color-4 {+ background: linear-gradient(90deg, rgba(187, 154, 247, 0.6) 0%, rgba(192, 202, 245, 0.5) 100%);+ box-shadow: 0 0 4px rgba(187, 154, 247, 0.2);+}++@keyframes shimmer {+ 0%, 100% {+ filter: brightness(1);+ }+ 50% {+ filter: brightness(1.1);+ }+}++.agent-count {+ font-size: 10px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ flex-shrink: 0;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/EventTypesWidget.vue b/.claude/skills/observability/apps/client/src/components/widgets/EventTypesWidget.vuenew file mode 100644index 00000000..e6f6041f--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/EventTypesWidget.vue@@ -0,0 +1,129 @@+<template>+ <div class="mini-widget">+ <div class="widget-header">+ <h3 class="widget-title">Active Skills</h3>+ <Layers :size="14" :stroke-width="2.5" class="widget-icon" />+ </div>+ <div class="widget-body">+ <div class="skills-list">+ <div+ v-for="skill in activeSkills"+ :key="skill.name"+ class="skill-item"+ >+ <div class="skill-icon">{{ skill.icon }}</div>+ <span class="skill-name">{{ skill.name }}</span>+ <span class="skill-count">{{ skill.count }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import { Layers } from 'lucide-vue-next';++const props = defineProps<{+ events: any[];+}>();++// Skill icons mapping+const skillIcons: Record<string, string> = {+ 'system': '⚙️',+ 'research': '🔍',+ 'writing': '✍️',+ 'blogging': '📝',+ 'social': '📱',+ 'development': '💻',+ 'media': '🎨',+ 'business': '💼',+ 'be-creative': '✨',+ 'personal': '👤',+ 'telos': '🎯',+ 'security': '🔒',+ 'default': '🔧'+};++// Extract active skills from events+const activeSkills = computed(() => {+ const skillCounts = new Map<string, number>();++ // Count events per skill+ props.events.forEach(event => {+ // Try multiple ways to extract skill information+ const skill =+ event.payload?.skill ||+ 'core';++ if (skill && skill !== 'unknown') {+ skillCounts.set(skill, (skillCounts.get(skill) || 0) + 1);+ }+ });++ // Convert to array and sort by count+ return Array.from(skillCounts.entries())+ .map(([name, count]) => ({+ name,+ count,+ icon: skillIcons[name] || skillIcons['default']+ }))+ .sort((a, b) => b.count - a.count)+ .slice(0, 8);+});+</script>++<style scoped>+@import './widget-base.css';++.skills-list {+ display: flex;+ flex-direction: column;+ gap: 3px;+ height: 100%;+ overflow-y: auto;+}++.skill-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 4px 6px;+ border-radius: 4px;+ background: var(--theme-bg-secondary);+ border: 1px solid var(--theme-border-primary);+ transition: all 0.2s ease;+}++.skill-item:hover {+ background: var(--theme-bg-tertiary);+ border-color: color-mix(in srgb, var(--theme-primary) 50%, transparent);+ transform: translateX(2px);+}++.skill-icon {+ font-size: 14px;+ line-height: 1;+ flex-shrink: 0;+}++.skill-name {+ font-size: 10px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex: 1;+ min-width: 0;+}++.skill-count {+ font-size: 10px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-primary);+ flex-shrink: 0;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/SessionTimelineWidget.vue b/.claude/skills/observability/apps/client/src/components/widgets/SessionTimelineWidget.vuenew file mode 100644index 00000000..03385db0--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/SessionTimelineWidget.vue@@ -0,0 +1,169 @@+<template>+ <div class="mini-widget">+ <div class="widget-header">+ <h3 class="widget-title">Buffer Stats</h3>+ <Activity :size="14" :stroke-width="2.5" class="widget-icon" />+ </div>+ <div class="widget-body">+ <div class="stats-grid">+ <div class="stat-item">+ <span class="stat-label">Events</span>+ <span class="stat-value">{{ bufferStats.totalEvents }}</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">Time Span</span>+ <span class="stat-value">{{ bufferStats.timeSpan }}</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">Oldest</span>+ <span class="stat-value">{{ bufferStats.oldestAge }}</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">Rate</span>+ <span class="stat-value">{{ bufferStats.eventRate }}/min</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">Sessions</span>+ <span class="stat-value">{{ bufferStats.sessionCount }}</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">Buffer</span>+ <span class="stat-value" :class="bufferStats.bufferHealthClass">{{ bufferStats.bufferHealth }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import { Activity } from 'lucide-vue-next';++const props = defineProps<{+ activeSessions: number;+ events: any[];+}>();++// Format duration string+function formatDuration(milliseconds: number): string {+ const seconds = Math.floor(milliseconds / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);++ if (hours > 0) return `${hours}h`;+ if (minutes > 0) return `${minutes}m`;+ return `${seconds}s`;+}++// Calculate buffer statistics+const bufferStats = computed(() => {+ const totalEvents = props.events.length;++ if (totalEvents === 0) {+ return {+ totalEvents: 0,+ timeSpan: '-',+ oldestAge: '-',+ eventRate: '0.0',+ sessionCount: 0,+ bufferHealth: 'Empty',+ bufferHealthClass: 'health-warning'+ };+ }++ // Get oldest and newest timestamps+ const timestamps = props.events.map(e => e.timestamp).filter(Boolean);+ const oldestTimestamp = Math.min(...timestamps);+ const newestTimestamp = Math.max(...timestamps);++ const timeSpanMs = newestTimestamp - oldestTimestamp;+ const oldestAgeMs = Date.now() - oldestTimestamp;++ // Calculate event rate (events per minute over the time span)+ const timeSpanMinutes = timeSpanMs / (60 * 1000);+ const eventRate = timeSpanMinutes > 0+ ? (totalEvents / timeSpanMinutes).toFixed(1)+ : '0.0';++ // Count unique sessions+ const uniqueSessions = new Set(+ props.events.map(e => e.session_id).filter(Boolean)+ );++ // Determine buffer health+ let bufferHealth = 'Good';+ let bufferHealthClass = 'health-good';++ if (totalEvents > 8000) {+ bufferHealth = 'Full';+ bufferHealthClass = 'health-critical';+ } else if (totalEvents > 5000) {+ bufferHealth = 'High';+ bufferHealthClass = 'health-warning';+ }++ return {+ totalEvents: totalEvents.toLocaleString(),+ timeSpan: formatDuration(timeSpanMs),+ oldestAge: formatDuration(oldestAgeMs),+ eventRate,+ sessionCount: uniqueSessions.size,+ bufferHealth,+ bufferHealthClass+ };+});+</script>++<style scoped>+@import './widget-base.css';++.stats-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 4px;+ height: 100%;+}++.stat-item {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 4px 6px;+ border-radius: 4px;+ background: var(--theme-bg-secondary);+ transition: background 0.2s ease;+}++.stat-item:hover {+ background: var(--theme-bg-tertiary);+}++.stat-label {+ font-size: 7px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+ text-transform: uppercase;+ letter-spacing: 0.3px;+}++.stat-value {+ font-size: 11px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ line-height: 1;+}++.health-good {+ color: rgba(158, 206, 106, 1);+}++.health-warning {+ color: rgba(224, 175, 104, 1);+}++.health-critical {+ color: rgba(247, 118, 142, 1);+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/TokenUsageWidget.vue b/.claude/skills/observability/apps/client/src/components/widgets/TokenUsageWidget.vuenew file mode 100644index 00000000..d3eed647--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/TokenUsageWidget.vue@@ -0,0 +1,513 @@+<template>+ <div class="mini-widget">+ <div class="widget-header">+ <h3 class="widget-title">Token Usage</h3>+ <div class="header-controls">+ <select v-model="selectedTimeRange" class="time-range-selector">+ <option value="1h">1h</option>+ <option value="24h">24h</option>+ <option value="7d">7d</option>+ <option value="30d">30d</option>+ <option value="all">All</option>+ </select>+ <Coins :size="14" :stroke-width="2.5" class="widget-icon" />+ </div>+ </div>++ <div class="widget-body">+ <!-- Loading State -->+ <div v-if="loading" class="loading-state">+ <Loader2 :size="16" class="spinner" />+ <span>Loading...</span>+ </div>++ <!-- Error State -->+ <div v-else-if="error" class="error-state">+ <AlertCircle :size="16" />+ <span>{{ error }}</span>+ </div>++ <!-- Empty State -->+ <div v-else-if="isEmpty" class="empty-state">+ <Info :size="16" />+ <span>No token usage data yet</span>+ </div>++ <!-- Stats Display -->+ <div v-else class="stats-container">+ <!-- Summary Cards -->+ <div class="summary-cards">+ <div class="summary-card">+ <div class="summary-label">Total Tokens</div>+ <div class="summary-value">{{ formatNumber(stats.totalTokens) }}</div>+ <div class="summary-breakdown">+ <span class="breakdown-item">+ <ArrowDown :size="10" />+ {{ formatNumber(stats.totalInputTokens) }}+ </span>+ <span class="breakdown-item">+ <ArrowUp :size="10" />+ {{ formatNumber(stats.totalOutputTokens) }}+ </span>+ </div>+ </div>++ <div class="summary-card cost-card">+ <div class="summary-label">Total Cost</div>+ <div class="summary-value cost-value">${{ formatCost(stats.totalCost) }}</div>+ <div class="summary-breakdown">+ <span class="breakdown-item">+ {{ stats.entryCount }} request{{ stats.entryCount !== 1 ? 's' : '' }}+ </span>+ </div>+ </div>+ </div>++ <!-- By Service -->+ <div class="section">+ <div class="section-header">+ <Server :size="10" />+ <span>By Service</span>+ </div>+ <div class="service-list">+ <div+ v-for="([service, data], index) in sortedServices"+ :key="service"+ class="service-item"+ >+ <div class="service-header">+ <span class="service-name">{{ service }}</span>+ <span class="service-cost">${{ formatCost(data.cost) }}</span>+ </div>+ <div class="service-bar">+ <div+ class="service-bar-fill"+ :style="{+ width: `${(data.cost / stats.totalCost) * 100}%`,+ backgroundColor: getServiceColor(service, index)+ }"+ ></div>+ </div>+ <div class="service-meta">+ <span class="service-tokens">{{ formatNumber(data.tokens) }} tokens</span>+ <span class="service-count">{{ data.count }} calls</span>+ </div>+ </div>+ </div>+ </div>++ <!-- By Agent -->+ <div v-if="hasAgentData" class="section">+ <div class="section-header">+ <Bot :size="10" />+ <span>By Agent</span>+ </div>+ <div class="agent-list">+ <div+ v-for="([agent, data], index) in sortedAgents"+ :key="agent"+ class="agent-item"+ >+ <div class="agent-header">+ <span class="agent-name">{{ agent }}</span>+ <span class="agent-cost">${{ formatCost(data.cost) }}</span>+ </div>+ <div class="agent-meta">+ <span class="agent-tokens">{{ formatNumber(data.tokens) }} tokens</span>+ <span class="agent-count">{{ data.count }} calls</span>+ </div>+ </div>+ </div>+ </div>++ <!-- Top Models -->+ <div class="section">+ <div class="section-header">+ <Cpu :size="10" />+ <span>Top Models</span>+ </div>+ <div class="model-list">+ <div+ v-for="[model, data] in sortedModels.slice(0, 5)"+ :key="model"+ class="model-item"+ >+ <span class="model-name">{{ model }}</span>+ <span class="model-count">{{ data.count }}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, computed, onMounted, watch } from 'vue';+import {+ Coins,+ Loader2,+ AlertCircle,+ Info,+ ArrowDown,+ ArrowUp,+ Server,+ Bot,+ Cpu+} from 'lucide-vue-next';++// Time range selection+const selectedTimeRange = ref<string>('24h');+const loading = ref(false);+const error = ref<string | null>(null);++// Stats data+interface Stats {+ totalTokens: number;+ totalInputTokens: number;+ totalOutputTokens: number;+ totalCost: number;+ byService: Record<string, { tokens: number; cost: number; count: number }>;+ byModel: Record<string, { tokens: number; cost: number; count: number }>;+ byAgent: Record<string, { tokens: number; cost: number; count: number }>;+ entryCount: number;+}++const stats = ref<Stats>({+ totalTokens: 0,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalCost: 0,+ byService: {},+ byModel: {},+ byAgent: {},+ entryCount: 0+});++// Service colors+const serviceColors = [+ '#7aa2f7', // Blue+ '#9ece6a', // Green+ '#e0af68', // Yellow+ '#bb9af7', // Purple+ '#f7768e', // Red+ '#73daca', // Teal+ '#ff9e64', // Orange+];++function getServiceColor(service: string, index: number): string {+ return serviceColors[index % serviceColors.length];+}++// Computed properties+const isEmpty = computed(() => stats.value.entryCount === 0);++const hasAgentData = computed(() => Object.keys(stats.value.byAgent).length > 0);++const sortedServices = computed(() => {+ return Object.entries(stats.value.byService)+ .sort(([, a], [, b]) => b.cost - a.cost);+});++const sortedAgents = computed(() => {+ return Object.entries(stats.value.byAgent)+ .sort(([, a], [, b]) => b.cost - a.cost)+ .slice(0, 5); // Top 5 agents+});++const sortedModels = computed(() => {+ return Object.entries(stats.value.byModel)+ .sort(([, a], [, b]) => b.count - a.count);+});++// Format numbers+function formatNumber(num: number): string {+ if (num >= 1_000_000) {+ return (num / 1_000_000).toFixed(1) + 'M';+ } else if (num >= 1_000) {+ return (num / 1_000).toFixed(1) + 'K';+ }+ return num.toString();+}++// Format cost+function formatCost(cost: number): string {+ if (cost === 0) return '0.00';+ if (cost < 0.01) return cost.toFixed(4);+ if (cost < 1) return cost.toFixed(3);+ return cost.toFixed(2);+}++// Fetch stats from API+async function fetchStats() {+ loading.value = true;+ error.value = null;++ try {+ const timeRangeParam = selectedTimeRange.value === 'all'+ ? ''+ : `?timeRange=${selectedTimeRange.value}`;++ const response = await fetch(`http://localhost:4000/api/token-usage/stats${timeRangeParam}`);++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const result = await response.json();++ if (result.success) {+ stats.value = result.data;+ } else {+ error.value = result.error || 'Failed to fetch stats';+ }+ } catch (err) {+ console.error('Error fetching token usage stats:', err);+ error.value = 'Failed to connect to server';+ } finally {+ loading.value = false;+ }+}++// Watch time range changes+watch(selectedTimeRange, () => {+ fetchStats();+});++// Initial load+onMounted(() => {+ fetchStats();++ // Refresh every 30 seconds+ const interval = setInterval(fetchStats, 30000);++ // Cleanup on unmount+ return () => clearInterval(interval);+});+</script>++<style scoped>+@import './widget-base.css';++.header-controls {+ display: flex;+ align-items: center;+ gap: 6px;+}++.time-range-selector {+ font-size: 9px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ background: var(--theme-bg-tertiary);+ border: 1px solid var(--theme-border-primary);+ color: var(--theme-text-primary);+ padding: 2px 6px;+ border-radius: 4px;+ cursor: pointer;+ outline: none;+ transition: all 0.2s ease;+}++.time-range-selector:hover {+ background: var(--theme-bg-quaternary);+ border-color: var(--theme-primary);+}++.time-range-selector:focus {+ border-color: var(--theme-primary);+ box-shadow: 0 0 0 2px rgba(122, 162, 247, 0.1);+}++.loading-state,+.error-state,+.empty-state {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 16px;+ font-size: 10px;+ color: var(--theme-text-tertiary);+}++.spinner {+ animation: spin 1s linear infinite;+}++@keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+}++.error-state {+ color: rgba(247, 118, 142, 1);+}++.stats-container {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.summary-cards {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 6px;+}++.summary-card {+ background: var(--theme-bg-tertiary);+ border: 1px solid var(--theme-border-primary);+ border-radius: 6px;+ padding: 6px 8px;+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.summary-card.cost-card {+ background: linear-gradient(135deg, rgba(122, 162, 247, 0.05) 0%, rgba(158, 206, 106, 0.05) 100%);+ border-color: rgba(122, 162, 247, 0.3);+}++.summary-label {+ font-size: 8px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.summary-value {+ font-size: 16px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ line-height: 1;+}++.summary-value.cost-value {+ color: var(--theme-primary);+}++.summary-breakdown {+ display: flex;+ gap: 8px;+ margin-top: 2px;+}++.breakdown-item {+ display: flex;+ align-items: center;+ gap: 2px;+ font-size: 8px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+}++.section {+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.section-header {+ display: flex;+ align-items: center;+ gap: 4px;+ font-size: 9px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-secondary);+ text-transform: uppercase;+ letter-spacing: 0.5px;+ padding-bottom: 2px;+ border-bottom: 1px solid var(--theme-border-secondary);+}++.service-list,+.agent-list,+.model-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.service-item,+.agent-item,+.model-item {+ padding: 4px 6px;+ border-radius: 4px;+ transition: background 0.2s ease;+}++.service-item:hover,+.agent-item:hover,+.model-item:hover {+ background: var(--theme-bg-tertiary);+}++.service-header,+.agent-header,+.model-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 6px;+}++.service-name,+.agent-name,+.model-name {+ font-size: 9px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ text-transform: capitalize;+}++.service-cost,+.agent-cost {+ font-size: 9px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-primary);+}++.service-bar {+ height: 3px;+ background: var(--theme-bg-quaternary);+ border-radius: 2px;+ overflow: hidden;+ margin: 2px 0;+}++.service-bar-fill {+ height: 100%;+ transition: width 0.3s ease;+}++.service-meta,+.agent-meta {+ display: flex;+ justify-content: space-between;+ align-items: center;+ font-size: 7px;+ font-weight: 500;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+}++.model-count {+ font-size: 9px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-secondary);+ background: var(--theme-bg-tertiary);+ padding: 2px 6px;+ border-radius: 3px;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/TopToolsWidget.vue b/.claude/skills/observability/apps/client/src/components/widgets/TopToolsWidget.vuenew file mode 100644index 00000000..20908715--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/TopToolsWidget.vue@@ -0,0 +1,246 @@+<template>+ <div class="mini-widget">+ <div class="widget-header">+ <h3 class="widget-title">Tool Performance</h3>+ <Wrench :size="14" :stroke-width="2.5" class="widget-icon" />+ </div>+ <div class="widget-body">+ <div class="tool-grid">+ <div+ v-for="tool in topTools"+ :key="tool.tool"+ class="tool-item"+ :class="{+ 'has-errors': tool.hasErrors,+ 'is-slow': tool.isSlow+ }"+ :title="getToolTitle(tool)"+ >+ <component+ :is="getToolIcon(tool.tool)"+ :size="12"+ :stroke-width="2"+ class="tool-icon"+ />+ <div class="tool-info">+ <span class="tool-name">{{ tool.tool }}</span>+ <span v-if="tool.skill" class="tool-skill">{{ tool.skill }}</span>+ </div>+ <component+ v-if="tool.healthIndicator && getHealthIcon(tool.healthIndicator)"+ :is="getHealthIcon(tool.healthIndicator)"+ :size="11"+ :stroke-width="2"+ class="tool-health-icon"+ :class="{+ 'health-error': tool.hasErrors,+ 'health-slow': tool.isSlow+ }"+ />+ <span class="tool-count">{{ tool.count }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue';+import type { Component } from '@vue/runtime-core';+import {+ Wrench,+ FileText,+ PenTool,+ Edit3,+ Terminal,+ Search,+ FolderSearch,+ Users,+ Globe,+ Compass,+ Zap,+ Command,+ CheckSquare,+ MessageCircleQuestion,+ BookOpen,+ Settings,+ Play,+ CheckCircle2,+ AlertTriangle,+ Clock,+ Code,+ FileCode,+ FilePlus,+ Eye,+ Package+} from 'lucide-vue-next';+import type { ToolUsage } from '../../composables/useAdvancedMetrics';++const props = defineProps<{+ topTools: ToolUsage[];+}>();++// Icon mapping for each tool+const toolIcons: Record<string, Component> = {+ 'Read': Eye,+ 'Write': FilePlus,+ 'Edit': Edit3,+ 'Bash': Terminal,+ 'Grep': Search,+ 'Glob': FolderSearch,+ 'Task': Users,+ 'WebFetch': Globe,+ 'WebSearch': Compass,+ 'Skill': Zap,+ 'SlashCommand': Command,+ 'TodoWrite': CheckSquare,+ 'AskUserQuestion': MessageCircleQuestion,+ 'NotebookEdit': BookOpen,+ 'NotebookRead': FileText,+ 'BashOutput': Terminal,+ 'KillShell': Terminal,+ 'ExitPlanMode': CheckCircle2,+ 'mcp__Chrome__take_snapshot': Eye,+ 'mcp__Chrome__click': Package,+ 'mcp__Chrome__navigate_page': Globe,+ 'mcp__Apify__search-actors': Search,+ 'mcp__content__find_post': FileText,+ 'default': Code+};++// Health indicator icons+const healthIcons = {+ '✅': CheckCircle2,+ '⚠️': AlertTriangle,+ '🐌': Clock+};++const maxToolCount = computed(() =>+ Math.max(...props.topTools.map(t => t.count), 1)+);++// Get icon component for a tool+function getToolIcon(toolName: string): Component {+ return toolIcons[toolName] || toolIcons['default'];+}++// Get health icon component+function getHealthIcon(indicator: string): Component | null {+ return healthIcons[indicator] || null;+}++// Generate detailed tooltip for each tool+function getToolTitle(tool: ToolUsage): string {+ const parts = [tool.tool];++ if (tool.skill) {+ parts.push(`Skill: ${tool.skill}`);+ }++ parts.push(`Count: ${tool.count}`);++ if (tool.successRate !== undefined) {+ parts.push(`Success: ${tool.successRate}%`);+ }++ if (tool.hasErrors) {+ parts.push('Has errors');+ }++ if (tool.isSlow) {+ parts.push('Slow performance');+ }++ return parts.join(' • ');+}+</script>++<style scoped>+@import './widget-base.css';++.tool-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 2px 6px;+ height: 100%;+ align-content: start;+}++.tool-item {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 2px 4px;+ border-radius: 4px;+ transition: all 0.2s ease;+}++.tool-item:hover {+ background: var(--theme-bg-tertiary);+}++.tool-item.has-errors {+ background: rgba(247, 118, 142, 0.1);+ border: 1px solid rgba(247, 118, 142, 0.2);+}++.tool-item.is-slow {+ background: rgba(224, 175, 104, 0.1);+ border: 1px solid rgba(224, 175, 104, 0.2);+}++.tool-icon {+ flex-shrink: 0;+ color: var(--theme-text-tertiary);+ opacity: 0.8;+}++.tool-health-icon {+ flex-shrink: 0;+ margin-left: auto;+}++.tool-health-icon.health-error {+ color: rgba(247, 118, 142, 1);+}++.tool-health-icon.health-slow {+ color: rgba(224, 175, 104, 1);+}++.tool-info {+ display: flex;+ flex-direction: column;+ gap: 1px;+ flex: 1;+ min-width: 0;+}++.tool-name {+ font-size: 9px;+ font-weight: 600;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.tool-skill {+ font-size: 7px;+ font-weight: 500;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-text-tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.tool-count {+ font-size: 10px;+ font-weight: 700;+ font-family: 'concourse-c3', monospace;+ color: var(--theme-primary);+ flex-shrink: 0;+}+</style>diff --git a/.claude/skills/observability/apps/client/src/components/widgets/widget-base.css b/.claude/skills/observability/apps/client/src/components/widgets/widget-base.cssnew file mode 100644index 00000000..317a5ead--- /dev/null+++ b/.claude/skills/observability/apps/client/src/components/widgets/widget-base.css@@ -0,0 +1,69 @@+.mini-widget {+ background: linear-gradient(135deg,+ var(--theme-bg-primary) 0%,+ var(--theme-bg-secondary) 100%+ );+ border: 1px solid var(--theme-border-primary);+ border-radius: 12px;+ padding: 12px;+ box-shadow: inset 0 1px 2px var(--theme-shadow);+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);+ height: 120px;+ display: flex;+ flex-direction: column;+}++.mini-widget:hover {+ border-color: color-mix(in srgb, var(--theme-primary) 50%, transparent);+ box-shadow:+ inset 0 1px 2px var(--theme-shadow),+ 0 4px 12px var(--theme-shadow-lg);+ transform: scale(1.02);+}++.widget-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 8px;+}++.widget-title {+ font-size: 11px;+ font-weight: 700;+ font-family: 'concourse-t3', sans-serif;+ color: var(--theme-text-secondary);+ text-transform: uppercase;+ letter-spacing: 0.08em;+}++.widget-icon {+ color: var(--theme-primary);+ opacity: 0.7;+}++.widget-body {+ flex: 1;+ position: relative;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ padding-right: 4px;+}++.widget-body::-webkit-scrollbar {+ width: 4px;+}++.widget-body::-webkit-scrollbar-track {+ background: transparent;+}++.widget-body::-webkit-scrollbar-thumb {+ background: var(--theme-border-primary);+ border-radius: 2px;+}++.widget-body::-webkit-scrollbar-thumb:hover {+ background: var(--theme-text-tertiary);+}diff --git a/.claude/skills/observability/apps/client/src/composables/ADVANCED_METRICS_INTEGRATION.md b/.claude/skills/observability/apps/client/src/composables/ADVANCED_METRICS_INTEGRATION.mdnew file mode 100644index 00000000..70625173--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/ADVANCED_METRICS_INTEGRATION.md@@ -0,0 +1,245 @@+# Advanced Metrics Integration Guide++## Overview++The `useAdvancedMetrics` composable provides comprehensive analytics beyond basic chart data, including:++- **Events Per Minute** - Real-time throughput rate+- **Total Tokens** - Token consumption tracking (input/output/total)+- **Active Sessions** - Count of unique sessions+- **Success Rate** - Percentage of successful events+- **Top Tools** - Most frequently used tools (top 5)+- **Agent Activity** - Distribution across agents+- **Event Type Breakdown** - Event type distribution+- **Delta Calculations** - Change from previous window++## Integration with LivePulseChart.vue++### Step 1: Import the Composable++```typescript+import { useAdvancedMetrics } from '../composables/useAdvancedMetrics';+```++### Step 2: Extract Required Data from useChartData++```typescript+const {+ timeRange,+ dataPoints,+ addEvent,+ getChartData,+ setTimeRange,+ cleanup: cleanupChartData,+ clearData,+ uniqueAgentCount,+ uniqueAgentIdsInWindow,+ allUniqueAgentIds,+ toolCallCount,+ eventTimingMetrics,+ allEvents, // <-- Need this for advanced metrics+ currentConfig // <-- Need this for advanced metrics+} = useChartData();+```++**Note:** The current `useChartData` composable needs to expose `allEvents` and `currentConfig` in its return value.++### Step 3: Initialize Advanced Metrics++```typescript+const {+ eventsPerMinute,+ totalTokens,+ activeSessions,+ successRate,+ topTools,+ agentActivity,+ eventTypeBreakdown,+ eventsPerMinuteDelta+} = useAdvancedMetrics(allEvents, dataPoints, timeRange, currentConfig);+```++### Step 4: Use Metrics in Template++```vue+<template>+ <!-- Events Per Minute with Delta -->+ <div class="metric-card">+ <div class="metric-value">{{ eventsPerMinute }} events/min</div>+ <div class="metric-delta" :class="{ positive: eventsPerMinuteDelta.delta > 0 }">+ {{ eventsPerMinuteDelta.delta > 0 ? '+' : '' }}{{ eventsPerMinuteDelta.delta }}+ ({{ eventsPerMinuteDelta.deltaPercent }}%)+ </div>+ </div>++ <!-- Token Consumption -->+ <div class="metric-card">+ <div class="metric-label">Tokens</div>+ <div class="metric-value">{{ totalTokens.total.toLocaleString() }}</div>+ <div class="metric-breakdown">+ Input: {{ totalTokens.input.toLocaleString() }} |+ Output: {{ totalTokens.output.toLocaleString() }}+ </div>+ </div>++ <!-- Active Sessions -->+ <div class="metric-card">+ <div class="metric-label">Active Sessions</div>+ <div class="metric-value">{{ activeSessions }}</div>+ </div>++ <!-- Success Rate -->+ <div class="metric-card">+ <div class="metric-label">Success Rate</div>+ <div class="metric-value">{{ successRate }}%</div>+ </div>++ <!-- Top Tools -->+ <div class="metric-card">+ <div class="metric-label">Top Tools</div>+ <div v-for="tool in topTools" :key="tool.tool" class="tool-item">+ <span>{{ tool.tool }}</span>+ <span>{{ tool.count }}</span>+ </div>+ </div>++ <!-- Agent Activity Distribution -->+ <div class="metric-card">+ <div class="metric-label">Agent Activity</div>+ <div v-for="agent in agentActivity" :key="agent.agent" class="agent-item">+ <span>{{ agent.agent }}</span>+ <span>{{ agent.count }} ({{ agent.percentage }}%)</span>+ </div>+ </div>++ <!-- Event Type Breakdown -->+ <div class="metric-card">+ <div class="metric-label">Event Types</div>+ <div v-for="type in eventTypeBreakdown" :key="type.type" class="type-item">+ <span>{{ type.type }}</span>+ <span>{{ type.count }} ({{ type.percentage }}%)</span>+ </div>+ </div>+</template>+```++## Required Modification to useChartData.ts++To make this integration work, `useChartData.ts` must expose two additional properties:++```typescript+// In useChartData.ts, add these to the return statement:+return {+ timeRange,+ dataPoints,+ addEvent,+ getChartData,+ setTimeRange,+ cleanup,+ clearData,+ currentConfig, // <-- Add this+ uniqueAgentCount,+ uniqueAgentIdsInWindow,+ allUniqueAgentIds,+ toolCallCount,+ eventTimingMetrics,+ allEvents // <-- Add this+};+```++## Standalone Usage Example++You can also use `useAdvancedMetrics` in a completely new component:++```vue+<script setup lang="ts">+import { ref, computed } from 'vue';+import type { HookEvent, ChartDataPoint, TimeRange } from '../types';+import { useChartData } from '../composables/useChartData';+import { useAdvancedMetrics } from '../composables/useAdvancedMetrics';++// Initialize base chart data+const chartData = useChartData();++// Initialize advanced metrics+const metrics = useAdvancedMetrics(+ chartData.allEvents,+ chartData.dataPoints,+ chartData.timeRange,+ chartData.currentConfig+);++// All metrics are reactive and will update automatically+</script>++<template>+ <div class="metrics-dashboard">+ <h2>Advanced Metrics</h2>++ <!-- Display all metrics -->+ <div class="metrics-grid">+ <MetricCard+ title="Events/Min"+ :value="metrics.eventsPerMinute.value"+ :delta="metrics.eventsPerMinuteDelta.value"+ />++ <MetricCard+ title="Success Rate"+ :value="`${metrics.successRate.value}%`"+ />++ <MetricCard+ title="Total Tokens"+ :value="metrics.totalTokens.value.total"+ />++ <MetricCard+ title="Active Sessions"+ :value="metrics.activeSessions.value"+ />+ </div>++ <!-- Tool usage chart -->+ <ToolUsageChart :tools="metrics.topTools.value" />++ <!-- Agent distribution chart -->+ <AgentDistributionChart :agents="metrics.agentActivity.value" />++ <!-- Event type breakdown -->+ <EventTypeChart :types="metrics.eventTypeBreakdown.value" />+ </div>+</template>+```++## Performance Notes++- All calculations use Vue's `computed` properties for automatic memoization+- No loops over full event history - reuses existing `dataPoints` where possible+- Calculations are only re-run when dependencies change+- Efficient filtering using timestamps and Set operations++## Type Safety++All return values are fully typed:++```typescript+import type {+ TokenMetrics,+ ToolUsage,+ AgentActivity,+ EventTypeDistribution,+ DeltaMetrics,+ AdvancedMetrics+} from '../composables/useAdvancedMetrics';+```++## Error Handling++The composable handles missing or malformed data gracefully:++- Returns safe defaults (0, [], null) for missing data+- Uses optional chaining for nested properties+- Checks for division by zero+- Filters out invalid timestamps+- Doesn't crash if event structure variesdiff --git a/.claude/skills/observability/apps/client/src/composables/__tests__/useAdvancedMetrics.example.ts b/.claude/skills/observability/apps/client/src/composables/__tests__/useAdvancedMetrics.example.tsnew file mode 100644index 00000000..81f600d1--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/__tests__/useAdvancedMetrics.example.ts@@ -0,0 +1,184 @@+/**+ * Example usage and validation of useAdvancedMetrics composable+ *+ * This file demonstrates how to use the advanced metrics composable+ * and validates that all metrics are correctly calculated.+ */++import { ref } from 'vue';+import type { HookEvent, ChartDataPoint, TimeRange } from '../../types';+import { useAdvancedMetrics } from '../useAdvancedMetrics';++// Example: Create mock data+const createMockEvents = (): HookEvent[] => [+ {+ id: 1,+ source_app: 'kai',+ agent_name: 'kai',+ session_id: 'session-001',+ hook_event_type: 'PostToolUse',+ payload: {+ tool_name: 'Read',+ usage: { input_tokens: 1000, output_tokens: 500 }+ },+ timestamp: Date.now() - 30000 // 30 seconds ago+ },+ {+ id: 2,+ source_app: 'kai',+ agent_name: 'engineer',+ session_id: 'session-002',+ hook_event_type: 'PostToolUse',+ payload: {+ tool_name: 'Write',+ usage: { input_tokens: 800, output_tokens: 300 }+ },+ timestamp: Date.now() - 20000 // 20 seconds ago+ },+ {+ id: 3,+ source_app: 'kai',+ agent_name: 'kai',+ session_id: 'session-001',+ hook_event_type: 'PreToolUse',+ payload: { tool_name: 'Read' },+ timestamp: Date.now() - 10000 // 10 seconds ago+ },+ {+ id: 4,+ source_app: 'kai',+ agent_name: 'engineer',+ session_id: 'session-002',+ hook_event_type: 'error',+ payload: { error: 'Something went wrong' },+ timestamp: Date.now() - 5000 // 5 seconds ago+ }+];++const createMockDataPoints = (): ChartDataPoint[] => [+ {+ timestamp: Date.now() - 60000,+ count: 10,+ eventTypes: { 'PostToolUse': 6, 'PreToolUse': 4 },+ sessions: { 'session-001': 7, 'session-002': 3 },+ apps: { 'kai': 10 }+ },+ {+ timestamp: Date.now() - 30000,+ count: 15,+ eventTypes: { 'PostToolUse': 8, 'PreToolUse': 5, 'error': 2 },+ sessions: { 'session-001': 8, 'session-002': 7 },+ apps: { 'kai': 12, 'engineer': 3 }+ }+];++// Example: Initialize the composable+export function exampleUsage() {+ // Create refs with mock data+ const allEvents = ref<HookEvent[]>(createMockEvents());+ const dataPoints = ref<ChartDataPoint[]>(createMockDataPoints());+ const timeRange = ref<TimeRange>('1m');+ const currentConfig = ref({+ duration: 60 * 1000, // 1 minute+ bucketSize: 1000,+ maxPoints: 60+ });++ // Initialize advanced metrics+ const metrics = useAdvancedMetrics(+ allEvents,+ dataPoints,+ timeRange,+ currentConfig+ );++ // Example: Access metrics+ console.log('Events Per Minute:', metrics.eventsPerMinute.value);+ // Expected: ~25 events/min (25 total events / 1 minute)++ console.log('Total Tokens:', metrics.totalTokens.value);+ // Expected: { input: 1800, output: 800, total: 2600 }++ console.log('Active Sessions:', metrics.activeSessions.value);+ // Expected: 2 (session-001 and session-002)++ console.log('Success Rate:', metrics.successRate.value);+ // Expected: 75% (3 successful events out of 4)++ console.log('Top Tools:', metrics.topTools.value);+ // Expected: [{ tool: 'Read', count: 2 }, { tool: 'Write', count: 1 }]++ console.log('Agent Activity:', metrics.agentActivity.value);+ // Expected: [+ // { agent: 'kai', count: 2, percentage: 50 },+ // { agent: 'engineer', count: 2, percentage: 50 }+ // ]++ console.log('Event Type Breakdown:', metrics.eventTypeBreakdown.value);+ // Expected: [+ // { type: 'PostToolUse', count: 2, percentage: 50 },+ // { type: 'PreToolUse', count: 1, percentage: 25 },+ // { type: 'error', count: 1, percentage: 25 }+ // ]++ console.log('Events Per Minute Delta:', metrics.eventsPerMinuteDelta.value);+ // Expected: Comparison between current and previous time window++ return metrics;+}++// Example: Integration with LivePulseChart+export function integrateWithComponent() {+ // Assuming you have useChartData initialized+ const chartData = {+ allEvents: ref<HookEvent[]>([]),+ dataPoints: ref<ChartDataPoint[]>([]),+ timeRange: ref<TimeRange>('1m'),+ currentConfig: ref({+ duration: 60 * 1000,+ bucketSize: 1000,+ maxPoints: 60+ })+ };++ // Initialize advanced metrics with chart data+ const advancedMetrics = useAdvancedMetrics(+ chartData.allEvents,+ chartData.dataPoints,+ chartData.timeRange,+ chartData.currentConfig+ );++ // All metrics are reactive and will update automatically+ return advancedMetrics;+}++// Example: Validation function+export function validateMetrics() {+ const metrics = exampleUsage();++ const validations = {+ eventsPerMinute: metrics.eventsPerMinute.value >= 0,+ totalTokensHasProperties:+ typeof metrics.totalTokens.value.input === 'number' &&+ typeof metrics.totalTokens.value.output === 'number' &&+ typeof metrics.totalTokens.value.total === 'number',+ activeSessionsIsNumber: typeof metrics.activeSessions.value === 'number',+ successRateInRange:+ metrics.successRate.value >= 0 && metrics.successRate.value <= 100,+ topToolsIsArray: Array.isArray(metrics.topTools.value),+ agentActivityIsArray: Array.isArray(metrics.agentActivity.value),+ eventTypeBreakdownIsArray: Array.isArray(metrics.eventTypeBreakdown.value),+ deltaHasAllProperties:+ typeof metrics.eventsPerMinuteDelta.value.current === 'number' &&+ typeof metrics.eventsPerMinuteDelta.value.previous === 'number' &&+ typeof metrics.eventsPerMinuteDelta.value.delta === 'number' &&+ typeof metrics.eventsPerMinuteDelta.value.deltaPercent === 'number'+ };++ const allValid = Object.values(validations).every(v => v === true);+ console.log('All metrics valid:', allValid);+ console.log('Validation details:', validations);++ return allValid;+}diff --git a/.claude/skills/observability/apps/client/src/composables/useAdvancedMetrics.ts b/.claude/skills/observability/apps/client/src/composables/useAdvancedMetrics.tsnew file mode 100644index 00000000..476d3ff1--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useAdvancedMetrics.ts@@ -0,0 +1,534 @@+import { computed, ref, type Ref } from 'vue';+import type { HookEvent, ChartDataPoint, TimeRange } from '../types';++/**+ * Interface for token consumption metrics+ */+export interface TokenMetrics {+ input: number;+ output: number;+ total: number;+}++/**+ * Interface for tool usage tracking+ */+export interface ToolUsage {+ tool: string;+ count: number;+ skill?: string;+ successRate?: number;+ hasErrors?: boolean;+ isSlow?: boolean;+ healthIndicator?: string;+}++/**+ * Interface for skill/workflow usage tracking+ */+export interface SkillWorkflowUsage {+ name: string;+ type: 'skill' | 'workflow';+ count: number;+}++/**+ * Interface for agent activity tracking+ */+export interface AgentActivity {+ agent: string;+ count: number;+ percentage: number;+}++/**+ * Interface for event type distribution+ */+export interface EventTypeDistribution {+ type: string;+ count: number;+ percentage: number;+}++/**+ * Interface for delta calculations between time windows+ */+export interface DeltaMetrics {+ current: number;+ previous: number;+ delta: number;+ deltaPercent: number;+}++/**+ * Interface for the complete advanced metrics return value+ */+export interface AdvancedMetrics {+ eventsPerMinute: Ref<number>;+ totalTokens: Ref<TokenMetrics>;+ activeSessions: Ref<number>;+ successRate: Ref<number>;+ topTools: Ref<ToolUsage[]>;+ skillsAndWorkflows: Ref<SkillWorkflowUsage[]>;+ agentActivity: Ref<AgentActivity[]>;+ eventTypeBreakdown: Ref<EventTypeDistribution[]>;+ eventsPerMinuteDelta: Ref<DeltaMetrics>;+}++/**+ * Advanced metrics composable for Kai observability dashboard+ *+ * Provides comprehensive analytics and calculations beyond basic chart data:+ * - Real-time throughput (events per minute)+ * - Token consumption tracking (input/output/total)+ * - Active session counting+ * - Success rate analysis+ * - Tool usage statistics+ * - Agent activity distribution+ * - Event type breakdown+ * - Delta calculations vs previous window+ *+ * @param allEvents - Ref containing all events in memory (from useChartData)+ * @param dataPoints - Ref containing aggregated chart data points+ * @param timeRange - Ref containing current time range setting+ * @param currentConfig - Ref containing current time range configuration+ * @returns Object with computed reactive metrics+ */+export function useAdvancedMetrics(+ allEvents: Ref<HookEvent[]>,+ dataPoints: Ref<ChartDataPoint[]>,+ timeRange: Ref<TimeRange>,+ currentConfig: Ref<{ duration: number; bucketSize: number; maxPoints: number }>+): AdvancedMetrics {++ /**+ * Calculate events per minute based on current time window+ * Uses total events in dataPoints divided by time range duration+ */+ const eventsPerMinute = computed<number>(() => {+ const totalEvents = dataPoints.value.reduce((sum, dp) => sum + dp.count, 0);+ const durationMinutes = currentConfig.value.duration / (60 * 1000);++ // Debug logging for event counting+ if (totalEvents > 0) {+ console.log(`[useAdvancedMetrics] Events/min calculation:`, {+ totalEvents,+ durationMinutes: durationMinutes.toFixed(2),+ eventsPerMinute: (totalEvents / durationMinutes).toFixed(2),+ dataPointsCount: dataPoints.value.length+ });+ }++ if (durationMinutes === 0) return 0;+ return Number((totalEvents / durationMinutes).toFixed(2));+ });++ /**+ * Estimate token consumption based on event types+ * Since Claude Code hooks don't expose actual token usage data,+ * we estimate based on typical token consumption per event type+ */+ const totalTokens = computed<TokenMetrics>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ // Filter events in current time window+ const windowEvents = allEvents.value.filter(+ event => event.timestamp && event.timestamp >= cutoffTime+ );++ // Token estimation heuristics (rough averages)+ const TOKEN_ESTIMATES = {+ 'PostToolUse': 2000, // Tool responses are typically verbose+ 'PostAgentMessage': 1500, // Agent messages/responses+ 'UserPromptSubmit': 500, // User prompts are typically shorter+ 'PreToolUse': 300, // Tool setup/preparation+ 'SessionStart': 1000, // Session initialization with context+ 'SessionEnd': 200, // Session cleanup+ 'default': 100 // Fallback for unknown events+ };++ // Estimate tokens based on event types+ let estimatedInput = 0;+ let estimatedOutput = 0;++ windowEvents.forEach(event => {+ const eventType = event.hook_event_type || 'default';+ const estimate = TOKEN_ESTIMATES[eventType] || TOKEN_ESTIMATES['default'];++ // Distribute estimate across input/output (typical 40/60 split)+ estimatedInput += Math.floor(estimate * 0.4);+ estimatedOutput += Math.floor(estimate * 0.6);+ });++ return {+ input: estimatedInput,+ output: estimatedOutput,+ total: estimatedInput + estimatedOutput+ };+ });++ /**+ * Count unique active sessions in current time window+ * Tracks distinct session IDs from events+ */+ const activeSessions = computed<number>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const uniqueSessions = new Set<string>();++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ uniqueSessions.add(event.session_id);+ }+ });++ return uniqueSessions.size;+ });++ /**+ * Calculate success rate as percentage of successful events+ * Successful events: PostToolUse with no errors+ * Failed events: Events with error in type or payload+ * Returns percentage 0-100+ */+ const successRate = computed<number>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const windowEvents = allEvents.value.filter(+ event => event.timestamp && event.timestamp >= cutoffTime+ );++ if (windowEvents.length === 0) return 100; // Default to 100% if no events++ let successCount = 0;+ let totalCount = 0;++ windowEvents.forEach(event => {+ totalCount++;++ // Consider an event successful if:+ // - Not an error event type+ // - No error in payload+ const isError =+ event.hook_event_type.toLowerCase().includes('error') ||+ event.payload?.error ||+ event.payload?.status === 'error';++ if (!isError) {+ successCount++;+ }+ });++ if (totalCount === 0) return 100;+ return Number(((successCount / totalCount) * 100).toFixed(2));+ });++ /**+ * Track all frequently used tools with performance metrics+ * Analyzes PostToolUse and PreToolUse events to extract tool names and health status+ */+ const topTools = computed<ToolUsage[]>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const toolData = new Map<string, {+ count: number;+ skill?: string;+ errors: number;+ totalDuration: number;+ callCount: number;+ }>();++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ // Check for tool usage events+ if (+ event.hook_event_type === 'PostToolUse' ||+ event.hook_event_type === 'PreToolUse'+ ) {+ // Extract tool name from payload+ const toolName =+ event.payload?.tool_name ||+ event.payload?.tool ||+ event.payload?.name ||+ 'unknown';++ // Extract skill information if available+ const skillName = event.payload?.skill;++ if (!toolData.has(toolName)) {+ toolData.set(toolName, {+ count: 0,+ skill: skillName,+ errors: 0,+ totalDuration: 0,+ callCount: 0+ });+ }++ const data = toolData.get(toolName)!;+ data.count++;++ // Track errors+ if (+ event.hook_event_type?.toLowerCase().includes('error') ||+ event.payload?.error ||+ event.payload?.status === 'error'+ ) {+ data.errors++;+ }++ // Track duration for performance (if available)+ if (event.payload?.duration) {+ data.totalDuration += event.payload.duration;+ data.callCount++;+ }++ // Update skill if we didn't have it before+ if (!data.skill && skillName) {+ data.skill = skillName;+ }+ }+ }+ });++ // Convert to array with health indicators+ return Array.from(toolData.entries())+ .map(([tool, data]) => {+ const successRate = data.count > 0+ ? Number(((data.count - data.errors) / data.count * 100).toFixed(1))+ : 100;++ const avgDuration = data.callCount > 0+ ? data.totalDuration / data.callCount+ : 0;++ const hasErrors = data.errors > 0;+ const isSlow = avgDuration > 2000; // Consider slow if avg > 2 seconds++ // Determine health indicator+ let healthIndicator = '✅';+ if (hasErrors && successRate < 90) {+ healthIndicator = '⚠️';+ } else if (isSlow) {+ healthIndicator = '🐌';+ } else if (hasErrors) {+ healthIndicator = '⚠️';+ }++ return {+ tool,+ count: data.count,+ skill: data.skill,+ successRate,+ hasErrors,+ isSlow,+ healthIndicator+ };+ })+ .sort((a, b) => b.count - a.count);+ });++ /**+ * Track skills and workflows invoked in the current time window+ * Detects Skill tool calls and workflow executions from events+ */+ const skillsAndWorkflows = computed<SkillWorkflowUsage[]>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const usageMap = new Map<string, { type: 'skill' | 'workflow'; count: number }>();++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ // Check for Skill tool invocations+ // Payload structure: { tool_name: "Skill", tool_input: { skill: "SkillName" } }+ const toolName = event.payload?.tool_name;+ if (+ (event.hook_event_type === 'PostToolUse' || event.hook_event_type === 'PreToolUse') &&+ toolName === 'Skill'+ ) {+ const skillName = event.payload?.tool_input?.skill || 'unknown';+ if (skillName !== 'unknown') {+ const key = `skill:${skillName}`;+ if (!usageMap.has(key)) {+ usageMap.set(key, { type: 'skill', count: 0 });+ }+ usageMap.get(key)!.count++;+ }+ }++ // Check for workflow executions (from skill-workflow-notification script)+ // Payload structure: { tool_name: "Bash", tool_input: { command: "~/.claude/tools/skill-workflow-notification WORKFLOWNAME SKILLNAME" } }+ if (event.hook_event_type === 'PostToolUse' && event.payload?.tool_name === 'Bash') {+ const command = event.payload?.tool_input?.command || '';+ // Match skill-workflow-notification calls: ~/.claude/tools/skill-workflow-notification WORKFLOWNAME SKILLNAME+ const wfMatch = command.match(/\/skill-workflow-notification\s+(\w+)\s+(\w+)/);+ if (wfMatch) {+ const workflowName = wfMatch[1];+ const skillName = wfMatch[2];++ // Add the workflow+ const workflowKey = `workflow:${workflowName}`;+ if (!usageMap.has(workflowKey)) {+ usageMap.set(workflowKey, { type: 'workflow', count: 0 });+ }+ usageMap.get(workflowKey)!.count++;++ // Also add the skill that contains this workflow+ const skillKey = `skill:${skillName}`;+ if (!usageMap.has(skillKey)) {+ usageMap.set(skillKey, { type: 'skill', count: 0 });+ }+ usageMap.get(skillKey)!.count++;+ }+ }++ // Also detect SlashCommand invocations as potential workflows+ // Payload structure: { tool_name: "SlashCommand", tool_input: { command: "/commandName args..." } }+ if (+ (event.hook_event_type === 'PostToolUse' || event.hook_event_type === 'PreToolUse') &&+ event.payload?.tool_name === 'SlashCommand'+ ) {+ const fullCommand = event.payload?.tool_input?.command || '';+ // Extract just the command name (first word after the slash)+ const commandMatch = fullCommand.match(/^\/(\w+)/);+ const commandName = commandMatch ? commandMatch[1] : null;+ if (commandName) {+ const key = `workflow:${commandName}`;+ if (!usageMap.has(key)) {+ usageMap.set(key, { type: 'workflow', count: 0 });+ }+ usageMap.get(key)!.count++;+ }+ }+ }+ });++ // Convert to array+ return Array.from(usageMap.entries())+ .map(([key, data]) => {+ const [type, name] = key.split(':');+ return {+ name,+ type: type as 'skill' | 'workflow',+ count: data.count+ };+ })+ .sort((a, b) => b.count - a.count);+ });++ /**+ * Calculate agent activity distribution+ * Shows event count and percentage for each agent in time window+ */+ const agentActivity = computed<AgentActivity[]>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const agentCounts = new Map<string, number>();+ let totalEvents = 0;++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ // Use agent_name if available, fallback to source_app+ const agentKey = event.agent_name || event.source_app || 'unknown';+ agentCounts.set(agentKey, (agentCounts.get(agentKey) || 0) + 1);+ totalEvents++;+ }+ });++ // Convert to array with percentages+ return Array.from(agentCounts.entries())+ .map(([agent, count]) => ({+ agent,+ count,+ percentage: totalEvents > 0 ? Number(((count / totalEvents) * 100).toFixed(2)) : 0+ }))+ .sort((a, b) => b.count - a.count);+ });++ /**+ * Calculate event type distribution+ * Shows breakdown of all event types with counts and percentages+ */+ const eventTypeBreakdown = computed<EventTypeDistribution[]>(() => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const typeCounts = new Map<string, number>();+ let totalEvents = 0;++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ typeCounts.set(+ event.hook_event_type,+ (typeCounts.get(event.hook_event_type) || 0) + 1+ );+ totalEvents++;+ }+ });++ // Convert to array with percentages+ return Array.from(typeCounts.entries())+ .map(([type, count]) => ({+ type,+ count,+ percentage: totalEvents > 0 ? Number(((count / totalEvents) * 100).toFixed(2)) : 0+ }))+ .sort((a, b) => b.count - a.count);+ });++ /**+ * Calculate delta metrics for events per minute+ * Compares current window to previous window of same duration+ */+ const eventsPerMinuteDelta = computed<DeltaMetrics>(() => {+ const now = Date.now();+ const duration = currentConfig.value.duration;++ // Current window+ const currentCutoff = now - duration;+ const currentEvents = allEvents.value.filter(+ event => event.timestamp && event.timestamp >= currentCutoff+ ).length;++ // Previous window (same duration, immediately before current)+ const previousStart = currentCutoff - duration;+ const previousEnd = currentCutoff;+ const previousEvents = allEvents.value.filter(+ event =>+ event.timestamp &&+ event.timestamp >= previousStart &&+ event.timestamp < previousEnd+ ).length;++ const durationMinutes = duration / (60 * 1000);+ const current = durationMinutes > 0 ? Number((currentEvents / durationMinutes).toFixed(2)) : 0;+ const previous = durationMinutes > 0 ? Number((previousEvents / durationMinutes).toFixed(2)) : 0;+ const delta = Number((current - previous).toFixed(2));+ const deltaPercent = previous > 0 ? Number(((delta / previous) * 100).toFixed(2)) : 0;++ return {+ current,+ previous,+ delta,+ deltaPercent+ };+ });++ return {+ eventsPerMinute,+ totalTokens,+ activeSessions,+ successRate,+ topTools,+ skillsAndWorkflows,+ agentActivity,+ eventTypeBreakdown,+ eventsPerMinuteDelta+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useAgentChartData.ts b/.claude/skills/observability/apps/client/src/composables/useAgentChartData.tsnew file mode 100644index 00000000..e02080f8--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useAgentChartData.ts@@ -0,0 +1,12 @@+import { useChartData } from './useChartData';++/**+ * Composable for rendering chart data specific to a single agent.+ * Delegates to useChartData with agent filtering applied.+ *+ * @param agentName - The specific agent/source_app to track (format: "app:session")+ * @returns All chart data methods with agent filtering applied+ */+export function useAgentChartData(agentName: string) {+ return useChartData(agentName);+}diff --git a/.claude/skills/observability/apps/client/src/composables/useChartData.ts b/.claude/skills/observability/apps/client/src/composables/useChartData.tsnew file mode 100644index 00000000..3b1ae8d5--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useChartData.ts@@ -0,0 +1,385 @@+import { ref, computed } from 'vue';+import type { HookEvent, ChartDataPoint, TimeRange } from '../types';++export function useChartData(agentIdFilter?: string) {+ const timeRange = ref<TimeRange>('1M');+ const dataPoints = ref<ChartDataPoint[]>([]);++ // Parse agent ID filter (format: "app:session")+ const parseAgentId = (agentId: string): { app: string; session: string } | null => {+ const parts = agentId.split(':');+ if (parts.length === 2) {+ return { app: parts[0], session: parts[1] };+ }+ return null;+ };++ const agentIdParsed = agentIdFilter ? parseAgentId(agentIdFilter) : null;++ // Store all events for re-aggregation when time range changes+ const allEvents = ref<HookEvent[]>([]);++ // Debounce for high-frequency events+ let eventBuffer: HookEvent[] = [];+ let debounceTimer: number | null = null;+ const DEBOUNCE_DELAY = 50; // 50ms debounce++ const timeRangeConfig = {+ '1M': {+ duration: 60 * 1000, // 1 minute in ms+ bucketSize: 1000, // 1 second buckets+ maxPoints: 60+ },+ '2M': {+ duration: 2 * 60 * 1000, // 2 minutes in ms+ bucketSize: 2000, // 2 second buckets+ maxPoints: 60+ },+ '4M': {+ duration: 4 * 60 * 1000, // 4 minutes in ms+ bucketSize: 4000, // 4 second buckets+ maxPoints: 60+ },+ '8M': {+ duration: 8 * 60 * 1000, // 8 minutes in ms+ bucketSize: 8000, // 8 second buckets+ maxPoints: 60+ },+ '16M': {+ duration: 16 * 60 * 1000, // 16 minutes in ms+ bucketSize: 16000, // 16 second buckets+ maxPoints: 60+ }+ };++ const currentConfig = computed(() => timeRangeConfig[timeRange.value]);++ const getBucketTimestamp = (timestamp: number): number => {+ const config = currentConfig.value;+ return Math.floor(timestamp / config.bucketSize) * config.bucketSize;+ };++ const processEventBuffer = () => {+ const eventsToProcess = [...eventBuffer];+ eventBuffer = [];++ // Debug: Log event processing+ if (eventsToProcess.length > 0) {+ console.log(`[useChartData] Processing ${eventsToProcess.length} new events`);+ }++ // Add events to our complete list+ allEvents.value.push(...eventsToProcess);++ eventsToProcess.forEach(event => {+ if (!event.timestamp) return;++ // Skip if event doesn't match agent ID filter (check both app and session)+ if (agentIdParsed) {+ if (event.source_app !== agentIdParsed.app) {+ return;+ }+ // Check if session ID matches (first 8 chars)+ if (event.session_id.slice(0, 8) !== agentIdParsed.session) {+ return;+ }+ }++ const bucketTime = getBucketTimestamp(event.timestamp);++ // Find existing bucket or create new one+ let bucket = dataPoints.value.find(dp => dp.timestamp === bucketTime);+ if (bucket) {+ bucket.count++;+ // Track event types+ if (!bucket.eventTypes) {+ bucket.eventTypes = {};+ }+ bucket.eventTypes[event.hook_event_type] = (bucket.eventTypes[event.hook_event_type] || 0) + 1;+ // Track sessions+ if (!bucket.sessions) {+ bucket.sessions = {};+ }+ bucket.sessions[event.session_id] = (bucket.sessions[event.session_id] || 0) + 1;+ // Track apps (prefer agent_name over source_app)+ if (!bucket.apps) {+ bucket.apps = {};+ }+ const appKey = event.agent_name || event.source_app || 'unknown';+ bucket.apps[appKey] = (bucket.apps[appKey] || 0) + 1;+ // Track raw events (for tool name extraction in timeline)+ if (!bucket.rawEvents) {+ bucket.rawEvents = [];+ }+ bucket.rawEvents.push(event);+ } else {+ const appKey = event.agent_name || event.source_app || 'unknown';+ dataPoints.value.push({+ timestamp: bucketTime,+ count: 1,+ eventTypes: { [event.hook_event_type]: 1 },+ sessions: { [event.session_id]: 1 },+ apps: { [appKey]: 1 },+ rawEvents: [event] // Add raw events for tool name extraction+ });+ }+ });++ // Clean old data once after processing all events+ cleanOldData();+ cleanOldEvents();+ };++ const addEvent = (event: HookEvent) => {+ eventBuffer.push(event);++ // Clear existing timer+ if (debounceTimer !== null) {+ clearTimeout(debounceTimer);+ }++ // Set new timer+ debounceTimer = window.setTimeout(() => {+ processEventBuffer();+ debounceTimer = null;+ }, DEBOUNCE_DELAY);+ };++ const cleanOldData = () => {+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ const beforeCount = dataPoints.value.length;+ dataPoints.value = dataPoints.value.filter(dp => dp.timestamp >= cutoffTime);+ const afterCount = dataPoints.value.length;++ // Ensure we don't exceed max points+ if (dataPoints.value.length > currentConfig.value.maxPoints) {+ dataPoints.value = dataPoints.value.slice(-currentConfig.value.maxPoints);+ }++ // Debug: Log cleanup summary (throttled to avoid spam)+ if (beforeCount !== afterCount && Math.random() < 0.1) { // Only log 10% of the time+ const totalEvents = dataPoints.value.reduce((sum, dp) => sum + dp.count, 0);+ console.log(`[useChartData] Cleaned old data: ${beforeCount} → ${afterCount} data points, ${totalEvents} total events`);+ }+ };++ const cleanOldEvents = () => {+ const now = Date.now();+ const cutoffTime = now - 5 * 60 * 1000; // Keep events for max 5 minutes++ allEvents.value = allEvents.value.filter(event =>+ event.timestamp && event.timestamp >= cutoffTime+ );+ };++ const getChartData = (): ChartDataPoint[] => {+ const now = Date.now();+ const config = currentConfig.value;+ const startTime = now - config.duration;++ // Create array of all time buckets in range+ const buckets: ChartDataPoint[] = [];+ for (let time = startTime; time <= now; time += config.bucketSize) {+ const bucketTime = getBucketTimestamp(time);+ const existingBucket = dataPoints.value.find(dp => dp.timestamp === bucketTime);+ buckets.push({+ timestamp: bucketTime,+ count: existingBucket?.count || 0,+ eventTypes: existingBucket?.eventTypes || {},+ sessions: existingBucket?.sessions || {},+ apps: existingBucket?.apps || {},+ rawEvents: existingBucket?.rawEvents || []+ });+ }++ // Return only the last maxPoints buckets+ return buckets.slice(-config.maxPoints);+ };++ const setTimeRange = (range: TimeRange) => {+ timeRange.value = range;+ // Re-aggregate data for new bucket size+ reaggregateData();+ };++ const reaggregateData = () => {+ // Clear current data points+ dataPoints.value = [];++ // Re-process all events with new bucket size+ const now = Date.now();+ const cutoffTime = now - currentConfig.value.duration;++ // Filter events within the time range and by agent ID if specified+ let relevantEvents = allEvents.value.filter(event =>+ event.timestamp && event.timestamp >= cutoffTime+ );++ if (agentIdParsed) {+ relevantEvents = relevantEvents.filter(event =>+ event.source_app === agentIdParsed.app &&+ event.session_id.slice(0, 8) === agentIdParsed.session+ );+ }++ // Re-aggregate all relevant events+ relevantEvents.forEach(event => {+ if (!event.timestamp) return;++ const bucketTime = getBucketTimestamp(event.timestamp);++ // Find existing bucket or create new one+ let bucket = dataPoints.value.find(dp => dp.timestamp === bucketTime);+ if (bucket) {+ bucket.count++;+ bucket.eventTypes[event.hook_event_type] = (bucket.eventTypes[event.hook_event_type] || 0) + 1;+ bucket.sessions[event.session_id] = (bucket.sessions[event.session_id] || 0) + 1;+ // Track raw events (for tool name extraction in timeline)+ if (!bucket.rawEvents) {+ bucket.rawEvents = [];+ }+ bucket.rawEvents.push(event);+ } else {+ dataPoints.value.push({+ timestamp: bucketTime,+ count: 1,+ eventTypes: { [event.hook_event_type]: 1 },+ sessions: { [event.session_id]: 1 },+ apps: { [event.source_app || 'unknown']: 1 },+ rawEvents: [event] // Add raw events for tool name extraction+ });+ }+ });++ // Clean up+ cleanOldData();+ };++ // Auto-clean old data every second+ const cleanupInterval = setInterval(() => {+ cleanOldData();+ cleanOldEvents();+ }, 1000);++ // Cleanup on unmount+ const cleanup = () => {+ clearInterval(cleanupInterval);+ if (debounceTimer !== null) {+ clearTimeout(debounceTimer);+ processEventBuffer(); // Process any remaining events+ }+ };++ // Clear all data (for when user clicks clear button)+ const clearData = () => {+ dataPoints.value = [];+ allEvents.value = [];+ eventBuffer = [];+ if (debounceTimer !== null) {+ clearTimeout(debounceTimer);+ debounceTimer = null;+ }+ };++ // Helper to create unique agent ID from source_app + session_id+ const createAgentId = (sourceApp: string, sessionId: string): string => {+ return `${sourceApp}:${sessionId.slice(0, 8)}`;+ };++ // Compute unique agent IDs (source_app:session_id) within the current time window+ const uniqueAgentIdsInWindow = computed(() => {+ const now = Date.now();+ const config = currentConfig.value;+ const cutoffTime = now - config.duration;++ // Get all unique (source_app, session_id) combos from events in the time window+ const uniqueAgents = new Set<string>();++ allEvents.value.forEach(event => {+ if (event.timestamp && event.timestamp >= cutoffTime) {+ const agentId = createAgentId(event.source_app, event.session_id);+ uniqueAgents.add(agentId);+ }+ });++ return Array.from(uniqueAgents);+ });++ // Compute ALL unique agent IDs ever seen in the session (not just in current window)+ const allUniqueAgentIds = computed(() => {+ const uniqueAgents = new Set<string>();++ allEvents.value.forEach(event => {+ const agentId = createAgentId(event.source_app, event.session_id);+ uniqueAgents.add(agentId);+ });++ return Array.from(uniqueAgents);+ });++ // Compute unique agent count based on current time window+ const uniqueAgentCount = computed(() => {+ return uniqueAgentIdsInWindow.value.length;+ });++ // Compute total tool calls (PreToolUse events) based on current time window+ const toolCallCount = computed(() => {+ return dataPoints.value.reduce((sum, dp) => {+ return sum + (dp.eventTypes?.['PreToolUse'] || 0);+ }, 0);+ });++ // Compute event timing metrics (min, max, average gap between events in ms)+ const eventTimingMetrics = computed(() => {+ const now = Date.now();+ const config = currentConfig.value;+ const cutoffTime = now - config.duration;++ // Get all events in current time window, sorted by timestamp+ const windowEvents = allEvents.value+ .filter(e => e.timestamp && e.timestamp >= cutoffTime)+ .sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));++ if (windowEvents.length < 2) {+ return { minGap: 0, maxGap: 0, avgGap: 0 };+ }++ // Calculate gaps between consecutive events+ const gaps: number[] = [];+ for (let i = 1; i < windowEvents.length; i++) {+ const gap = (windowEvents[i].timestamp || 0) - (windowEvents[i - 1].timestamp || 0);+ if (gap > 0) {+ gaps.push(gap);+ }+ }++ if (gaps.length === 0) {+ return { minGap: 0, maxGap: 0, avgGap: 0 };+ }++ const minGap = Math.min(...gaps);+ const maxGap = Math.max(...gaps);+ const avgGap = gaps.reduce((a, b) => a + b, 0) / gaps.length;++ return { minGap, maxGap, avgGap };+ });++ return {+ timeRange,+ dataPoints,+ addEvent,+ getChartData,+ setTimeRange,+ cleanup,+ clearData,+ currentConfig,+ uniqueAgentCount,+ uniqueAgentIdsInWindow,+ allUniqueAgentIds,+ toolCallCount,+ eventTimingMetrics,+ allEvents // Exposed for useAdvancedMetrics integration+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/composables/useEventColors.ts b/.claude/skills/observability/apps/client/src/composables/useEventColors.tsnew file mode 100644index 00000000..b1ca3109--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useEventColors.ts@@ -0,0 +1,202 @@++export function useEventColors() {+ // Agent color definitions from /agents/*.md files+ const agentColors: Record<string, string> = {+ 'user': '#C084FC', // bright purple (for UserPromptSubmit events)+ 'pentester': '#EF4444', // red+ 'engineer': '#22C55E', // green+ 'principal-engineer': '#3B82F6', // blue+ 'designer': '#A855F7', // purple+ 'architect': '#A855F7', // purple+ 'intern': '#06B6D4', // cyan+ 'artist': '#06B6D4', // cyan+ 'perplexity-researcher': '#EAB308', // yellow+ 'claude-researcher': '#EAB308', // yellow+ 'gemini-researcher': '#EAB308', // yellow+ 'grok-researcher': '#EAB308', // yellow+ 'qatester': '#EAB308', // yellow+ 'claude-code': '#3B82F6', // blue (default for main agent)+ };++ const colorPalette = [+ 'bg-blue-500',+ 'bg-green-500',+ 'bg-yellow-500',+ 'bg-purple-500',+ 'bg-pink-500',+ 'bg-indigo-500',+ 'bg-red-500',+ 'bg-orange-500',+ 'bg-teal-500',+ 'bg-cyan-500',+ ];++ // Improved hash function with better distribution+ const hashString = (str: string): number => {+ let hash = 7151;+ for (let i = 0; i < str.length; i++) {+ hash = ((hash << 5) + hash) + str.charCodeAt(i);+ }+ return Math.abs(hash >>> 0); // Use unsigned 32-bit integer+ };++ const getColorForSession = (sessionId: string): string => {+ const hash = hashString(sessionId);+ const index = hash % colorPalette.length;+ return colorPalette[index];+ };++ const getColorForApp = (appName: string): string => {+ const hash = hashString(appName);+ const index = hash % colorPalette.length;+ return colorPalette[index];+ };++ const getGradientForSession = (sessionId: string): string => {+ const baseColor = getColorForSession(sessionId);++ // Map base colors to gradient classes+ const gradientMap: Record<string, string> = {+ 'bg-blue-500': 'from-blue-500 to-blue-600',+ 'bg-green-500': 'from-green-500 to-green-600',+ 'bg-yellow-500': 'from-yellow-500 to-yellow-600',+ 'bg-purple-500': 'from-purple-500 to-purple-600',+ 'bg-pink-500': 'from-pink-500 to-pink-600',+ 'bg-indigo-500': 'from-indigo-500 to-indigo-600',+ 'bg-red-500': 'from-red-500 to-red-600',+ 'bg-orange-500': 'from-orange-500 to-orange-600',+ 'bg-teal-500': 'from-teal-500 to-teal-600',+ 'bg-cyan-500': 'from-cyan-500 to-cyan-600',+ };++ return `bg-gradient-to-r ${gradientMap[baseColor] || 'from-gray-500 to-gray-600'}`;+ };++ const getGradientForApp = (appName: string): string => {+ const baseColor = getColorForApp(appName);++ // Map base colors to gradient classes+ const gradientMap: Record<string, string> = {+ 'bg-blue-500': 'from-blue-500 to-blue-600',+ 'bg-green-500': 'from-green-500 to-green-600',+ 'bg-yellow-500': 'from-yellow-500 to-yellow-600',+ 'bg-purple-500': 'from-purple-500 to-purple-600',+ 'bg-pink-500': 'from-pink-500 to-pink-600',+ 'bg-indigo-500': 'from-indigo-500 to-indigo-600',+ 'bg-red-500': 'from-red-500 to-red-600',+ 'bg-orange-500': 'from-orange-500 to-orange-600',+ 'bg-teal-500': 'from-teal-500 to-teal-600',+ 'bg-cyan-500': 'from-cyan-500 to-cyan-600',+ };++ return `bg-gradient-to-r ${gradientMap[baseColor] || 'from-gray-500 to-gray-600'}`;+ };++ const tailwindToHex = (tailwindClass: string): string => {+ const colorMap: Record<string, string> = {+ 'bg-blue-500': '#3B82F6',+ 'bg-green-500': '#22C55E',+ 'bg-yellow-500': '#EAB308',+ 'bg-purple-500': '#A855F7',+ 'bg-pink-500': '#EC4899',+ 'bg-indigo-500': '#6366F1',+ 'bg-red-500': '#EF4444',+ 'bg-orange-500': '#F97316',+ 'bg-teal-500': '#14B8A6',+ 'bg-cyan-500': '#06B6D4',+ };+ return colorMap[tailwindClass] || '#3B82F6'; // Default to blue+ };++ const getHexColorForSession = (sessionId: string): string => {+ const tailwindClass = getColorForSession(sessionId);+ return tailwindToHex(tailwindClass);+ };++ const getHexColorForApp = (appName: string): string => {+ // Extract agent name before colon (e.g., "kai:58a240f7" -> "kai")+ const agentName = appName.split(':')[0].toLowerCase();++ // Special case: 'kai' and 'claude-code' should be blue (not in map, but explicit)+ if (agentName === 'kai') {+ return '#3B82F6';+ }++ // Check if app has a predefined color from agent definitions+ if (agentColors[agentName]) {+ return agentColors[agentName];+ }++ // Fallback to hash-based color for unknown apps+ const hash = hashString(appName);+ const hue = hash % 360;+ return `hsl(${hue}, 70%, 50%)`;+ };++ // Tokyo Night color palette for event types+ const tokyoNightColors = {+ purple: '#bb9af7', // Skills+ cyan: '#7dcfff', // Prompts+ blue: '#7aa2f7', // Sessions+ magenta: '#bb9af7', // Sub-agents+ green: '#9ece6a', // File operations+ yellow: '#e0af68', // Search/Find+ orange: '#ff9e64', // Execution/Bash+ red: '#f7768e', // Errors/Stop+ teal: '#1abc9c', // Compaction+ };++ // Get color for hook event types+ const getEventTypeColor = (hookEventType: string): string => {+ const colorMap: Record<string, string> = {+ 'UserPromptSubmit': tokyoNightColors.cyan,+ 'SessionStart': tokyoNightColors.blue,+ 'SessionEnd': tokyoNightColors.blue,+ 'Stop': tokyoNightColors.red,+ 'SubagentStop': tokyoNightColors.magenta,+ 'PreCompact': tokyoNightColors.teal,+ 'PreToolUse': tokyoNightColors.yellow,+ 'PostToolUse': tokyoNightColors.orange, // Orange for post-tool+ 'Notification': tokyoNightColors.orange,+ 'Completed': tokyoNightColors.green, // Green for completions+ };+ return colorMap[hookEventType] || tokyoNightColors.blue;+ };++ // Get color for tool types+ const getToolTypeColor = (toolName: string): string => {+ // File operations+ if (['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(toolName)) {+ return tokyoNightColors.green;+ }+ // Search/Find operations+ if (['Glob', 'Grep', 'WebSearch', 'WebFetch'].includes(toolName)) {+ return tokyoNightColors.yellow;+ }+ // Execution+ if (['Bash', 'BashOutput', 'KillShell'].includes(toolName)) {+ return tokyoNightColors.orange;+ }+ // Task/Agent operations+ if (['Task', 'Skill', 'SlashCommand'].includes(toolName)) {+ return tokyoNightColors.purple;+ }+ // User interaction+ if (['AskUserQuestion', 'TodoWrite'].includes(toolName)) {+ return tokyoNightColors.cyan;+ }+ // Default+ return tokyoNightColors.blue;+ };++ return {+ getColorForSession,+ getColorForApp,+ getGradientForSession,+ getGradientForApp,+ getHexColorForSession,+ getHexColorForApp,+ getEventTypeColor,+ getToolTypeColor+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/composables/useEventEmojis.ts b/.claude/skills/observability/apps/client/src/composables/useEventEmojis.tsnew file mode 100644index 00000000..be192b4b--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useEventEmojis.ts@@ -0,0 +1,41 @@+const eventTypeToEmoji: Record<string, string> = {+ 'PreToolUse': '🔧',+ 'PostToolUse': '✅',+ 'Notification': '🔔',+ 'Stop': '🛑',+ 'SubagentStop': '👥',+ 'PreCompact': '📦',+ 'UserPromptSubmit': '💬',+ 'SessionStart': '🚀',+ 'SessionEnd': '🏁',+ // Default+ 'default': '❓'+};++export function useEventEmojis() {+ const getEmojiForEventType = (eventType: string): string => {+ return eventTypeToEmoji[eventType] || eventTypeToEmoji.default;+ };++ const formatEventTypeLabel = (eventTypes: Record<string, number>): string => {+ const entries = Object.entries(eventTypes)+ .sort((a, b) => b[1] - a[1]); // Sort by count descending++ if (entries.length === 0) return '';++ // Show up to 3 most frequent event types+ const topEntries = entries.slice(0, 3);++ return topEntries+ .map(([type, count]) => {+ const emoji = getEmojiForEventType(type);+ return count > 1 ? `${emoji}×${count}` : emoji;+ })+ .join('');+ };++ return {+ getEmojiForEventType,+ formatEventTypeLabel+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/composables/useEventSearch.ts b/.claude/skills/observability/apps/client/src/composables/useEventSearch.tsnew file mode 100644index 00000000..e73756c3--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useEventSearch.ts@@ -0,0 +1,138 @@+import { ref, computed } from 'vue';+import type { HookEvent } from '../types';++export function useEventSearch() {+ const searchPattern = ref<string>('');+ const searchError = ref<string>('');++ // Validate regex pattern+ const validateRegex = (pattern: string): { valid: boolean; error?: string } => {+ if (!pattern || pattern.trim() === '') {+ return { valid: true };+ }++ try {+ new RegExp(pattern);+ return { valid: true };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Invalid regex pattern';+ return { valid: false, error: errorMessage };+ }+ };++ // Extract searchable text from event+ const getSearchableText = (event: HookEvent): string => {+ const parts: string[] = [];++ // Event type+ if (event.hook_event_type) {+ parts.push(event.hook_event_type);+ }++ // Source app and session+ if (event.source_app) {+ parts.push(event.source_app);+ }+ if (event.session_id) {+ parts.push(event.session_id);+ }++ // Model name+ if (event.model) {+ parts.push(event.model);+ }++ // Tool information+ if (event.tool_name) {+ parts.push(event.tool_name);+ }+ if (event.tool_command) {+ parts.push(event.tool_command);+ }+ if (event.tool_file && event.tool_file.path) {+ parts.push(event.tool_file.path);+ }++ // Summary text+ if (event.summary) {+ parts.push(event.summary);+ }++ // HITL information+ if (event.hitl_question) {+ parts.push(event.hitl_question);+ }+ if (event.hitl_permission) {+ parts.push(event.hitl_permission);+ }++ return parts.join(' ').toLowerCase();+ };++ // Check if event matches pattern+ const matchesPattern = (event: HookEvent, pattern: string): boolean => {+ if (!pattern || pattern.trim() === '') {+ return true;+ }++ const validation = validateRegex(pattern);+ if (!validation.valid) {+ return false;+ }++ try {+ const regex = new RegExp(pattern, 'i'); // Case-insensitive+ const searchableText = getSearchableText(event);+ return regex.test(searchableText);+ } catch {+ return false;+ }+ };++ // Filter events by pattern+ const searchEvents = (events: HookEvent[], pattern: string): HookEvent[] => {+ if (!pattern || pattern.trim() === '') {+ return events;+ }++ return events.filter(event => matchesPattern(event, pattern));+ };++ // Computed property for current error+ const hasError = computed(() => searchError.value.length > 0);++ // Update search pattern and validate+ const updateSearchPattern = (pattern: string) => {+ searchPattern.value = pattern;++ if (!pattern || pattern.trim() === '') {+ searchError.value = '';+ return;+ }++ const validation = validateRegex(pattern);+ if (!validation.valid) {+ searchError.value = validation.error || 'Invalid regex pattern';+ } else {+ searchError.value = '';+ }+ };++ // Clear search+ const clearSearch = () => {+ searchPattern.value = '';+ searchError.value = '';+ };++ return {+ searchPattern,+ searchError,+ hasError,+ validateRegex,+ matchesPattern,+ searchEvents,+ updateSearchPattern,+ clearSearch,+ getSearchableText+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useHITLNotifications.ts b/.claude/skills/observability/apps/client/src/composables/useHITLNotifications.tsnew file mode 100644index 00000000..d6b9bab0--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useHITLNotifications.ts@@ -0,0 +1,37 @@+import { ref } from 'vue';+import type { HookEvent } from '../types';++export function useHITLNotifications() {+ const hasPermission = ref(false);++ // Request notification permission+ const requestPermission = async () => {+ if ('Notification' in window) {+ const permission = await Notification.requestPermission();+ hasPermission.value = permission === 'granted';+ }+ };++ // Show notification for HITL request+ const notifyHITLRequest = (event: HookEvent) => {+ if (!hasPermission.value || !event.humanInTheLoop) return;++ const notification = new Notification('Agent Needs Your Input', {+ body: event.humanInTheLoop.question.slice(0, 100),+ icon: '/vite.svg',+ tag: `hitl-${event.id}`,+ requireInteraction: true+ });++ notification.onclick = () => {+ window.focus();+ notification.close();+ };+ };++ return {+ hasPermission,+ requestPermission,+ notifyHITLRequest+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useHeatLevel.ts b/.claude/skills/observability/apps/client/src/composables/useHeatLevel.tsnew file mode 100644index 00000000..938486f0--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useHeatLevel.ts@@ -0,0 +1,179 @@+import { computed, type Ref } from 'vue';++/**+ * Heat level intensity indicator composable+ *+ * Provides a 0-1 intensity value based on real-time activity metrics.+ * Uses events per minute with logarithmic thresholds: 4, 8, 16, 32, 64, 128+ *+ * Color scale (Tokyo Night compatible, accessible):+ * - Cold: #565f89 (storm gray) - 0-4 ev/min+ * - Cool: #7aa2f7 (blue) - 4-8 ev/min+ * - Warm: #9d7cd8 (purple) - 8-16 ev/min+ * - Hot: #e0af68 (amber) - 16-32 ev/min+ * - Fire: #f7768e (red) - 32-64 ev/min+ * - Inferno:#ff5555 (bright red) - 64-128+ ev/min+ */++export interface HeatLevelConfig {+ // Thresholds for active agents+ activeAgentsLow: number;+ activeAgentsHigh: number;+}++export interface HeatLevel {+ intensity: Ref<number>; // 0.0 to 1.0+ color: Ref<string>; // Current hex color+ label: Ref<string>; // Human readable label+ eventsContribution: Ref<number>; // How much events/min contributes (0-1)+ agentsContribution: Ref<number>; // How much active agents contributes (0-1)+}++const DEFAULT_CONFIG: HeatLevelConfig = {+ activeAgentsLow: 1,+ activeAgentsHigh: 5,+};++// Logarithmic thresholds: 4, 8, 16, 32, 64, 128+const HEAT_THRESHOLDS = [4, 8, 16, 32, 64, 128];++// Tokyo Night color scale for heat levels+const HEAT_COLORS = {+ cold: '#565f89', // Storm gray (0-4)+ cool: '#7aa2f7', // Blue (4-8)+ warm: '#9d7cd8', // Purple (8-16)+ hot: '#e0af68', // Amber (16-32)+ fire: '#f7768e', // Red (32-64)+ inferno: '#ff5555', // Bright red (64-128+)+};++/**+ * Interpolate between two hex colors+ */+function interpolateColor(color1: string, color2: string, factor: number): string {+ const c1 = hexToRgb(color1);+ const c2 = hexToRgb(color2);++ const r = Math.round(c1.r + (c2.r - c1.r) * factor);+ const g = Math.round(c1.g + (c2.g - c1.g) * factor);+ const b = Math.round(c1.b + (c2.b - c1.b) * factor);++ return rgbToHex(r, g, b);+}++function hexToRgb(hex: string): { r: number; g: number; b: number } {+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);+ return result ? {+ r: parseInt(result[1], 16),+ g: parseInt(result[2], 16),+ b: parseInt(result[3], 16),+ } : { r: 0, g: 0, b: 0 };+}++function rgbToHex(r: number, g: number, b: number): string {+ return '#' + [r, g, b].map(x => {+ const hex = x.toString(16);+ return hex.length === 1 ? '0' + hex : hex;+ }).join('');+}++/**+ * Get heat level index based on events per minute+ * Thresholds: 4, 8, 16, 32, 64, 128+ */+function getHeatIndex(epm: number): number {+ for (let i = 0; i < HEAT_THRESHOLDS.length; i++) {+ if (epm < HEAT_THRESHOLDS[i]) return i;+ }+ return HEAT_THRESHOLDS.length; // Above 128+}++/**+ * Get color array for interpolation+ */+const COLOR_ARRAY = [+ HEAT_COLORS.cold, // 0-4+ HEAT_COLORS.cool, // 4-8+ HEAT_COLORS.warm, // 8-16+ HEAT_COLORS.hot, // 16-32+ HEAT_COLORS.fire, // 32-64+ HEAT_COLORS.inferno, // 64-128++];++/**+ * Calculate heat level based on activity metrics+ *+ * @param eventsPerMinute - Current events per minute (from useAdvancedMetrics)+ * @param activeAgentCount - Number of active agents (from agentActivity.length)+ * @param config - Optional threshold configuration+ */+export function useHeatLevel(+ eventsPerMinute: Ref<number>,+ activeAgentCount: Ref<number>,+ config: Partial<HeatLevelConfig> = {}+): HeatLevel {+ const cfg = { ...DEFAULT_CONFIG, ...config };++ // Calculate events contribution based on logarithmic thresholds+ const eventsContribution = computed(() => {+ const epm = eventsPerMinute.value;+ if (epm <= 0) return 0;+ if (epm >= 128) return 1;+ // Logarithmic scale: 4, 8, 16, 32, 64, 128+ return Math.log2(Math.max(1, epm)) / Math.log2(128);+ });++ // Calculate agents contribution (0-1)+ const agentsContribution = computed(() => {+ const agents = activeAgentCount.value;+ if (agents <= cfg.activeAgentsLow) return 0;+ if (agents >= cfg.activeAgentsHigh) return 1;+ return (agents - cfg.activeAgentsLow) / (cfg.activeAgentsHigh - cfg.activeAgentsLow);+ });++ // Combined intensity (weighted: 85% events, 15% agents for faster color change)+ const intensity = computed(() => {+ const combined = (eventsContribution.value * 0.85) + (agentsContribution.value * 0.15);+ return Math.min(1, Math.max(0, combined));+ });++ // Map events per minute to color using thresholds+ const color = computed(() => {+ const epm = eventsPerMinute.value;+ const idx = getHeatIndex(epm);++ if (idx === 0) {+ // Below first threshold - cold+ const factor = epm / HEAT_THRESHOLDS[0];+ return interpolateColor(HEAT_COLORS.cold, HEAT_COLORS.cool, factor);+ } else if (idx >= COLOR_ARRAY.length) {+ // Above max threshold - inferno+ return HEAT_COLORS.inferno;+ } else {+ // Interpolate between thresholds+ const lowerThreshold = HEAT_THRESHOLDS[idx - 1];+ const upperThreshold = HEAT_THRESHOLDS[idx];+ const factor = (epm - lowerThreshold) / (upperThreshold - lowerThreshold);+ return interpolateColor(COLOR_ARRAY[idx - 1], COLOR_ARRAY[idx], factor);+ }+ });++ // Human readable label based on thresholds+ const label = computed(() => {+ const epm = eventsPerMinute.value;+ if (epm < 4) return 'Cold';+ if (epm < 8) return 'Cool';+ if (epm < 16) return 'Warm';+ if (epm < 32) return 'Hot';+ if (epm < 64) return 'Fire';+ return 'Inferno';+ });++ return {+ intensity,+ color,+ label,+ eventsContribution,+ agentsContribution,+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useKaiContext.ts b/.claude/skills/observability/apps/client/src/composables/useKaiContext.tsnew file mode 100644index 00000000..befad4db--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useKaiContext.ts@@ -0,0 +1,69 @@+import { ref, onMounted, onUnmounted } from 'vue';++export interface KaiContext {+ activeSkill: string | null;+ currentProject: {+ name: string;+ root: string;+ type: string;+ } | null;+ learningsToday: number;+ recentLearnings: { title: string; timestamp: string }[];+ sessionsToday: number;+ skillCount: number;+ sessionDuration: number;+ lastUpdate: string | null;+}++export function useKaiContext() {+ const context = ref<KaiContext | null>(null);+ const loading = ref(true);+ const error = ref<string | null>(null);++ let pollInterval: ReturnType<typeof setInterval> | null = null;++ const fetchContext = async () => {+ try {+ const response = await fetch('http://localhost:4000/api/kai/context');+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ context.value = await response.json();+ error.value = null;+ } catch (err) {+ error.value = err instanceof Error ? err.message : 'Unknown error';+ } finally {+ loading.value = false;+ }+ };++ // Format session duration as human readable+ const formatDuration = (ms: number): string => {+ if (ms < 60000) return '<1m';+ const minutes = Math.floor(ms / 60000);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ const remainingMinutes = minutes % 60;+ return `${hours}h ${remainingMinutes}m`;+ };++ onMounted(() => {+ fetchContext();+ // Poll every 30 seconds for updates+ pollInterval = setInterval(fetchContext, 30000);+ });++ onUnmounted(() => {+ if (pollInterval) {+ clearInterval(pollInterval);+ }+ });++ return {+ context,+ loading,+ error,+ formatDuration,+ refresh: fetchContext+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useMediaQuery.ts b/.claude/skills/observability/apps/client/src/composables/useMediaQuery.tsnew file mode 100644index 00000000..471920dd--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useMediaQuery.ts@@ -0,0 +1,84 @@+import { ref, computed, onMounted, onUnmounted } from 'vue';++/**+ * Reactive media query composable for detecting screen size changes+ * Provides mobile detection for < 700px screens with debouncing+ */+export function useMediaQuery() {+ const windowWidth = ref(0);+ let resizeTimeout: number | null = null;+ let mediaQuery: MediaQueryList | null = null;++ // Define mobile breakpoint at 700px+ const MOBILE_BREAKPOINT = 700;++ // Computed properties for different screen sizes+ const isMobile = computed(() => windowWidth.value < MOBILE_BREAKPOINT);+ const isTablet = computed(() => windowWidth.value >= MOBILE_BREAKPOINT && windowWidth.value < 1024);+ const isDesktop = computed(() => windowWidth.value >= 1024);++ // Debounced resize handler+ const handleResize = () => {+ if (resizeTimeout) {+ clearTimeout(resizeTimeout);+ }+ resizeTimeout = window.setTimeout(() => {+ windowWidth.value = window.innerWidth;+ }, 100);+ };++ // Media query change handler+ const handleMediaQueryChange = (_event: MediaQueryListEvent) => {+ windowWidth.value = window.innerWidth;+ };++ onMounted(() => {+ // Check if we're in a browser environment (SSR compatibility)+ if (typeof window !== 'undefined') {+ // Set initial width+ windowWidth.value = window.innerWidth;++ // Set up media query listener for better performance+ mediaQuery = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);++ // Use the newer addEventListener if available, fallback to addListener+ if (mediaQuery.addEventListener) {+ mediaQuery.addEventListener('change', handleMediaQueryChange);+ } else {+ // Fallback for older browsers+ mediaQuery.addListener(handleMediaQueryChange);+ }++ // Also listen to resize events as backup+ window.addEventListener('resize', handleResize);+ }+ });++ onUnmounted(() => {+ // Clean up event listeners+ if (resizeTimeout) {+ clearTimeout(resizeTimeout);+ }++ if (mediaQuery) {+ if (mediaQuery.removeEventListener) {+ mediaQuery.removeEventListener('change', handleMediaQueryChange);+ } else {+ // Fallback for older browsers+ mediaQuery.removeListener(handleMediaQueryChange);+ }+ }++ if (typeof window !== 'undefined') {+ window.removeEventListener('resize', handleResize);+ }+ });++ return {+ windowWidth: computed(() => windowWidth.value),+ isMobile,+ isTablet,+ isDesktop,+ MOBILE_BREAKPOINT+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/composables/useThemes.ts b/.claude/skills/observability/apps/client/src/composables/useThemes.tsnew file mode 100644index 00000000..2bac2657--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useThemes.ts@@ -0,0 +1,848 @@+import { ref, computed, onMounted, readonly } from 'vue';+import type {+ ThemeName,+ CustomTheme,+ PredefinedTheme,+ ThemeState,+ ThemeManagerState,+ CreateThemeFormData,+ ThemeColors,+ ThemeValidationResult,+ ThemeImportExport,+ ThemeApiResponse+} from '../types/theme';+import { PREDEFINED_THEME_NAMES, COLOR_REGEX, RGBA_REGEX } from '../types/theme';++// Predefined themes configuration+const PREDEFINED_THEMES: Record<ThemeName, PredefinedTheme> = {+ light: {+ name: 'light',+ displayName: 'Light',+ description: 'Clean and bright theme with high contrast',+ cssClass: 'theme-light',+ preview: { primary: '#ffffff', secondary: '#f9fafb', accent: '#3b82f6' },+ colors: {+ primary: '#3b82f6',+ primaryHover: '#2563eb',+ primaryLight: '#dbeafe',+ primaryDark: '#1e40af',+ bgPrimary: '#ffffff',+ bgSecondary: '#f9fafb',+ bgTertiary: '#f3f4f6',+ bgQuaternary: '#e5e7eb',+ textPrimary: '#111827',+ textSecondary: '#374151',+ textTertiary: '#6b7280',+ textQuaternary: '#9ca3af',+ borderPrimary: '#e5e7eb',+ borderSecondary: '#d1d5db',+ borderTertiary: '#9ca3af',+ accentSuccess: '#10b981',+ accentWarning: '#f59e0b',+ accentError: '#ef4444',+ accentInfo: '#3b82f6',+ shadow: 'rgba(0, 0, 0, 0.1)',+ shadowLg: 'rgba(0, 0, 0, 0.25)',+ hoverBg: 'rgba(0, 0, 0, 0.05)',+ activeBg: 'rgba(0, 0, 0, 0.1)',+ focusRing: '#3b82f6'+ }+ },+ dark: {+ name: 'dark',+ displayName: 'Dark',+ description: 'Dark theme with reduced eye strain',+ cssClass: 'theme-dark',+ preview: { primary: '#111827', secondary: '#1f2937', accent: '#60a5fa' },+ colors: {+ primary: '#60a5fa',+ primaryHover: '#3b82f6',+ primaryLight: '#1e3a8a',+ primaryDark: '#1d4ed8',+ bgPrimary: '#111827',+ bgSecondary: '#1f2937',+ bgTertiary: '#374151',+ bgQuaternary: '#4b5563',+ textPrimary: '#f9fafb',+ textSecondary: '#e5e7eb',+ textTertiary: '#d1d5db',+ textQuaternary: '#9ca3af',+ borderPrimary: '#374151',+ borderSecondary: '#4b5563',+ borderTertiary: '#6b7280',+ accentSuccess: '#34d399',+ accentWarning: '#fbbf24',+ accentError: '#f87171',+ accentInfo: '#60a5fa',+ shadow: 'rgba(0, 0, 0, 0.5)',+ shadowLg: 'rgba(0, 0, 0, 0.75)',+ hoverBg: 'rgba(255, 255, 255, 0.05)',+ activeBg: 'rgba(255, 255, 255, 0.1)',+ focusRing: '#60a5fa'+ }+ },+ modern: {+ name: 'modern',+ displayName: 'Modern',+ description: 'Sleek modern theme with blue accents',+ cssClass: 'theme-modern',+ preview: { primary: '#f8fafc', secondary: '#f1f5f9', accent: '#0ea5e9' },+ colors: {+ primary: '#0ea5e9',+ primaryHover: '#0284c7',+ primaryLight: '#e0f2fe',+ primaryDark: '#0c4a6e',+ bgPrimary: '#f8fafc',+ bgSecondary: '#f1f5f9',+ bgTertiary: '#e2e8f0',+ bgQuaternary: '#cbd5e1',+ textPrimary: '#0f172a',+ textSecondary: '#334155',+ textTertiary: '#64748b',+ textQuaternary: '#94a3b8',+ borderPrimary: '#e2e8f0',+ borderSecondary: '#cbd5e1',+ borderTertiary: '#94a3b8',+ accentSuccess: '#059669',+ accentWarning: '#d97706',+ accentError: '#dc2626',+ accentInfo: '#0ea5e9',+ shadow: 'rgba(15, 23, 42, 0.1)',+ shadowLg: 'rgba(15, 23, 42, 0.25)',+ hoverBg: 'rgba(15, 23, 42, 0.05)',+ activeBg: 'rgba(15, 23, 42, 0.1)',+ focusRing: '#0ea5e9'+ }+ },+ earth: {+ name: 'earth',+ displayName: 'Earth',+ description: 'Natural theme with warm earth tones',+ cssClass: 'theme-earth',+ preview: { primary: '#f5f5dc', secondary: '#d2b48c', accent: '#8b4513' },+ colors: {+ primary: '#8b4513',+ primaryHover: '#a0522d',+ primaryLight: '#deb887',+ primaryDark: '#654321',+ bgPrimary: '#f5f5dc',+ bgSecondary: '#f0e68c',+ bgTertiary: '#daa520',+ bgQuaternary: '#cd853f',+ textPrimary: '#2f1b14',+ textSecondary: '#5d4e37',+ textTertiary: '#8b4513',+ textQuaternary: '#a0522d',+ borderPrimary: '#deb887',+ borderSecondary: '#d2b48c',+ borderTertiary: '#cd853f',+ accentSuccess: '#228b22',+ accentWarning: '#ff8c00',+ accentError: '#dc143c',+ accentInfo: '#4682b4',+ shadow: 'rgba(139, 69, 19, 0.15)',+ shadowLg: 'rgba(139, 69, 19, 0.3)',+ hoverBg: 'rgba(139, 69, 19, 0.08)',+ activeBg: 'rgba(139, 69, 19, 0.15)',+ focusRing: '#8b4513'+ }+ },+ glass: {+ name: 'glass',+ displayName: 'Glass',+ description: 'Frosted glass theme with vibrant purple accents',+ cssClass: 'theme-glass',+ preview: { primary: '#e6e6fa', secondary: '#dda0dd', accent: '#9370db' },+ colors: {+ primary: '#9370db',+ primaryHover: '#8a2be2',+ primaryLight: '#e6e6fa',+ primaryDark: '#4b0082',+ bgPrimary: '#f8f8ff',+ bgSecondary: '#e6e6fa',+ bgTertiary: '#dda0dd',+ bgQuaternary: '#d8bfd8',+ textPrimary: '#2e1065',+ textSecondary: '#5b21b6',+ textTertiary: '#7c3aed',+ textQuaternary: '#8b5cf6',+ borderPrimary: '#dda0dd',+ borderSecondary: '#d8bfd8',+ borderTertiary: '#c8a2c8',+ accentSuccess: '#32cd32',+ accentWarning: '#ffa500',+ accentError: '#ff1493',+ accentInfo: '#9370db',+ shadow: 'rgba(147, 112, 219, 0.2)',+ shadowLg: 'rgba(147, 112, 219, 0.4)',+ hoverBg: 'rgba(147, 112, 219, 0.1)',+ activeBg: 'rgba(147, 112, 219, 0.2)',+ focusRing: '#9370db'+ }+ },+ 'high-contrast': {+ name: 'high-contrast',+ displayName: 'High Contrast',+ description: 'Maximum contrast theme for accessibility',+ cssClass: 'theme-high-contrast',+ preview: { primary: '#ffffff', secondary: '#f0f0f0', accent: '#000000' },+ colors: {+ primary: '#000000',+ primaryHover: '#333333',+ primaryLight: '#f0f0f0',+ primaryDark: '#000000',+ bgPrimary: '#ffffff',+ bgSecondary: '#f0f0f0',+ bgTertiary: '#e0e0e0',+ bgQuaternary: '#d0d0d0',+ textPrimary: '#000000',+ textSecondary: '#000000',+ textTertiary: '#333333',+ textQuaternary: '#666666',+ borderPrimary: '#000000',+ borderSecondary: '#333333',+ borderTertiary: '#666666',+ accentSuccess: '#008000',+ accentWarning: '#ff8c00',+ accentError: '#ff0000',+ accentInfo: '#0000ff',+ shadow: 'rgba(0, 0, 0, 0.3)',+ shadowLg: 'rgba(0, 0, 0, 0.6)',+ hoverBg: 'rgba(0, 0, 0, 0.1)',+ activeBg: 'rgba(0, 0, 0, 0.2)',+ focusRing: '#000000'+ }+ },+ 'dark-blue': {+ name: 'dark-blue',+ displayName: 'Dark Blue',+ description: 'Deep blue theme with navy accents',+ cssClass: 'theme-dark-blue',+ preview: { primary: '#000033', secondary: '#000066', accent: '#0099ff' },+ colors: {+ primary: '#0099ff',+ primaryHover: '#0077cc',+ primaryLight: '#33aaff',+ primaryDark: '#0066cc',+ bgPrimary: '#000033',+ bgSecondary: '#000066',+ bgTertiary: '#000099',+ bgQuaternary: '#0000cc',+ textPrimary: '#e6f2ff',+ textSecondary: '#ccddff',+ textTertiary: '#99bbff',+ textQuaternary: '#6699ff',+ borderPrimary: '#003366',+ borderSecondary: '#004499',+ borderTertiary: '#0066cc',+ accentSuccess: '#00ff88',+ accentWarning: '#ffaa00',+ accentError: '#ff3366',+ accentInfo: '#0099ff',+ shadow: 'rgba(0, 0, 51, 0.7)',+ shadowLg: 'rgba(0, 0, 51, 0.9)',+ hoverBg: 'rgba(0, 153, 255, 0.15)',+ activeBg: 'rgba(0, 153, 255, 0.25)',+ focusRing: '#0099ff'+ }+ },+ 'colorblind-friendly': {+ name: 'colorblind-friendly',+ displayName: 'Colorblind Friendly',+ description: 'High contrast colors safe for color vision deficiency',+ cssClass: 'theme-colorblind-friendly',+ preview: { primary: '#ffffcc', secondary: '#ffcc99', accent: '#993366' },+ colors: {+ primary: '#993366',+ primaryHover: '#663344',+ primaryLight: '#cc6699',+ primaryDark: '#661144',+ bgPrimary: '#ffffcc',+ bgSecondary: '#ffcc99',+ bgTertiary: '#ffaa88',+ bgQuaternary: '#ff9966',+ textPrimary: '#331122',+ textSecondary: '#442233',+ textTertiary: '#553344',+ textQuaternary: '#664455',+ borderPrimary: '#cc9966',+ borderSecondary: '#996633',+ borderTertiary: '#663300',+ accentSuccess: '#117733',+ accentWarning: '#cc6633',+ accentError: '#882233',+ accentInfo: '#993366',+ shadow: 'rgba(51, 17, 34, 0.15)',+ shadowLg: 'rgba(51, 17, 34, 0.3)',+ hoverBg: 'rgba(153, 51, 102, 0.08)',+ activeBg: 'rgba(153, 51, 102, 0.15)',+ focusRing: '#993366'+ }+ },+ ocean: {+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Bright tropical ocean with turquoise and coral accents',+ cssClass: 'theme-ocean',+ preview: { primary: '#cceeff', secondary: '#66ccff', accent: '#0088cc' },+ colors: {+ primary: '#0088cc',+ primaryHover: '#006699',+ primaryLight: '#33aadd',+ primaryDark: '#005588',+ bgPrimary: '#cceeff',+ bgSecondary: '#99ddff',+ bgTertiary: '#66ccff',+ bgQuaternary: '#33bbff',+ textPrimary: '#003344',+ textSecondary: '#004455',+ textTertiary: '#005566',+ textQuaternary: '#006677',+ borderPrimary: '#66bbdd',+ borderSecondary: '#4499cc',+ borderTertiary: '#2288bb',+ accentSuccess: '#00cc66',+ accentWarning: '#ff9933',+ accentError: '#ff3333',+ accentInfo: '#0088cc',+ shadow: 'rgba(0, 136, 204, 0.15)',+ shadowLg: 'rgba(0, 136, 204, 0.3)',+ hoverBg: 'rgba(0, 136, 204, 0.08)',+ activeBg: 'rgba(0, 136, 204, 0.15)',+ focusRing: '#0088cc'+ }+ },+ 'midnight-purple': {+ name: 'midnight-purple',+ displayName: 'Midnight Purple',+ description: 'Deep purples with neon accents for a modern, low-light friendly theme',+ cssClass: 'theme-midnight-purple',+ preview: { primary: '#0f0a1a', secondary: '#1a1333', accent: '#a78bfa' },+ colors: {+ primary: '#a78bfa',+ primaryHover: '#c4b5fd',+ primaryLight: '#2e1065',+ primaryDark: '#6d28d9',+ bgPrimary: '#0f0a1a',+ bgSecondary: '#1a1333',+ bgTertiary: '#2d1b4e',+ bgQuaternary: '#3f2766',+ textPrimary: '#f3e8ff',+ textSecondary: '#e9d5ff',+ textTertiary: '#d8b4fe',+ textQuaternary: '#c084fc',+ borderPrimary: '#6d28d9',+ borderSecondary: '#7e22ce',+ borderTertiary: '#a855f7',+ accentSuccess: '#34d399',+ accentWarning: '#fbbf24',+ accentError: '#f472b6',+ accentInfo: '#a78bfa',+ shadow: 'rgba(0, 0, 0, 0.6)',+ shadowLg: 'rgba(0, 0, 0, 0.8)',+ hoverBg: 'rgba(167, 139, 250, 0.1)',+ activeBg: 'rgba(167, 139, 250, 0.2)',+ focusRing: '#a78bfa'+ }+ },+ 'sunset-orange': {+ name: 'sunset-orange',+ displayName: 'Sunset Orange',+ description: 'Warm oranges and neutral tones for high contrast and distinctive appearance',+ cssClass: 'theme-sunset-orange',+ preview: { primary: '#f5ede4', secondary: '#fce4d6', accent: '#ea580c' },+ colors: {+ primary: '#ea580c',+ primaryHover: '#c2410c',+ primaryLight: '#fed7aa',+ primaryDark: '#9a3412',+ bgPrimary: '#f5ede4',+ bgSecondary: '#fce4d6',+ bgTertiary: '#fbdcc3',+ bgQuaternary: '#f8d4af',+ textPrimary: '#1f1208',+ textSecondary: '#3e2109',+ textTertiary: '#5d2d0e',+ textQuaternary: '#7c3a14',+ borderPrimary: '#fbdcc3',+ borderSecondary: '#f8c9a8',+ borderTertiary: '#f5a842',+ accentSuccess: '#16a34a',+ accentWarning: '#f59e0b',+ accentError: '#dc2626',+ accentInfo: '#ea580c',+ shadow: 'rgba(218, 74, 13, 0.15)',+ shadowLg: 'rgba(218, 74, 13, 0.3)',+ hoverBg: 'rgba(234, 88, 12, 0.08)',+ activeBg: 'rgba(234, 88, 12, 0.15)',+ focusRing: '#ea580c'+ }+ },+ 'mint-fresh': {+ name: 'mint-fresh',+ displayName: 'Mint Fresh',+ description: 'Cool mint greens with slate neutrals for a calming, professional appearance',+ cssClass: 'theme-mint-fresh',+ preview: { primary: '#f0fdfa', secondary: '#d1fae5', accent: '#0d9488' },+ colors: {+ primary: '#0d9488',+ primaryHover: '#0f766e',+ primaryLight: '#ccfbf1',+ primaryDark: '#134e4a',+ bgPrimary: '#f0fdfa',+ bgSecondary: '#d1fae5',+ bgTertiary: '#a7f3d0',+ bgQuaternary: '#7ee8c9',+ textPrimary: '#0d3b36',+ textSecondary: '#145352',+ textTertiary: '#1b6b67',+ textQuaternary: '#2d827d',+ borderPrimary: '#a7f3d0',+ borderSecondary: '#7ee8c9',+ borderTertiary: '#5eead4',+ accentSuccess: '#059669',+ accentWarning: '#d97706',+ accentError: '#dc2626',+ accentInfo: '#0d9488',+ shadow: 'rgba(13, 148, 136, 0.12)',+ shadowLg: 'rgba(13, 148, 136, 0.25)',+ hoverBg: 'rgba(13, 148, 136, 0.08)',+ activeBg: 'rgba(13, 148, 136, 0.15)',+ focusRing: '#0d9488'+ }+ },+ 'tokyo-night': {+ name: 'tokyo-night',+ displayName: 'Tokyo Night',+ description: 'Deep dark theme with vibrant blue and purple accents inspired by Tokyo at night',+ cssClass: 'theme-tokyo-night',+ preview: { primary: '#1a1b26', secondary: '#24283b', accent: '#7aa2f7' },+ colors: {+ primary: '#7aa2f7',+ primaryHover: '#89b4fa',+ primaryLight: '#3d59a1',+ primaryDark: '#565f89',+ bgPrimary: '#1a1b26',+ bgSecondary: '#16161e',+ bgTertiary: '#24283b',+ bgQuaternary: '#292e42',+ textPrimary: '#c0caf5',+ textSecondary: '#a9b1d6',+ textTertiary: '#787c99',+ textQuaternary: '#565f89',+ borderPrimary: '#414868',+ borderSecondary: '#545c7e',+ borderTertiary: '#565f89',+ accentSuccess: '#9ece6a',+ accentWarning: '#e0af68',+ accentError: '#f7768e',+ accentInfo: '#7aa2f7',+ shadow: 'rgba(0, 0, 0, 0.5)',+ shadowLg: 'rgba(0, 0, 0, 0.75)',+ hoverBg: '#292e42',+ activeBg: '#3b4261',+ focusRing: '#7aa2f7'+ }+ }+};++export function useThemes() {+ // State+ const state = ref<ThemeState>({+ currentTheme: 'light',+ customThemes: [],+ isCustomTheme: false,+ isLoading: false,+ error: null+ });++ const managerState = ref<ThemeManagerState>({+ isOpen: false,+ activeTab: 'predefined',+ previewTheme: null,+ editingTheme: null+ });++ // Computed properties+ const currentThemeData = computed(() => {+ if (state.value.isCustomTheme) {+ return state.value.customThemes.find(t => t.id === state.value.currentTheme);+ }+ return PREDEFINED_THEMES[state.value.currentTheme as ThemeName];+ });++ const predefinedThemes = computed(() => Object.values(PREDEFINED_THEMES));++ // Core theme management+ const setTheme = (theme: ThemeName | string) => {+ const isCustom = !PREDEFINED_THEME_NAMES.includes(theme as ThemeName);++ if (isCustom) {+ const customTheme = state.value.customThemes.find(t => t.id === theme);+ if (!customTheme) {+ console.error(`Custom theme not found: ${theme}`);+ return;+ }+ applyCustomTheme(customTheme);+ } else {+ applyPredefinedTheme(theme as ThemeName);+ }++ state.value.currentTheme = theme;+ state.value.isCustomTheme = isCustom;++ // Save to localStorage+ localStorage.setItem('theme', theme);+ localStorage.setItem('isCustomTheme', isCustom.toString());+ };++ const applyPredefinedTheme = (themeName: ThemeName) => {+ // Remove all theme classes (including those with hyphens)+ document.documentElement.className = document.documentElement.className+ .replace(/theme-[\w-]+/g, '');++ // Add new theme class+ const themeData = PREDEFINED_THEMES[themeName];+ if (themeData) {+ document.documentElement.classList.add(themeData.cssClass);++ // For backward compatibility with existing dark mode+ if (themeName === 'dark') {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }+ }+ };++ const applyCustomTheme = (theme: CustomTheme) => {+ // Remove all theme classes (including those with hyphens)+ document.documentElement.className = document.documentElement.className+ .replace(/theme-[\w-]+/g, '');++ // Apply custom CSS variables+ const root = document.documentElement;+ Object.entries(theme.colors).forEach(([key, value]) => {+ const cssVar = camelToKebab(key);+ root.style.setProperty(`--theme-${cssVar}`, value);+ });++ // Add custom theme class+ root.classList.add('theme-custom');+ };++ // Theme validation+ const validateTheme = (colors: Partial<ThemeColors>): ThemeValidationResult => {+ const errors: string[] = [];+ const warnings: string[] = [];++ Object.entries(colors).forEach(([key, value]) => {+ if (!value) {+ errors.push(`${key} is required`);+ return;+ }++ if (!isValidColor(value)) {+ errors.push(`${key} must be a valid color (hex, rgb, or rgba)`);+ }+ });++ // Check contrast ratios (simplified)+ if (colors.textPrimary && colors.bgPrimary) {+ const contrast = calculateContrast(colors.textPrimary, colors.bgPrimary);+ if (contrast < 4.5) {+ warnings.push('Primary text and background may not meet accessibility contrast requirements');+ }+ }++ return {+ isValid: errors.length === 0,+ errors,+ warnings+ };+ };++ // Custom theme management+ const createCustomTheme = async (formData: CreateThemeFormData): Promise<CustomTheme | null> => {+ const validation = validateTheme(formData.colors as ThemeColors);+ if (!validation.isValid) {+ state.value.error = validation.errors.join(', ');+ return null;+ }++ const theme: CustomTheme = {+ id: generateId(),+ name: formData.name,+ displayName: formData.displayName,+ description: formData.description,+ colors: formData.colors as ThemeColors,+ isCustom: true,+ isPublic: formData.isPublic,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ tags: formData.tags+ };++ // Save locally+ state.value.customThemes.push(theme);+ saveCustomThemes();++ // Save to server if requested+ if (formData.isPublic) {+ try {+ await saveThemeToServer(theme);+ } catch (error) {+ console.warn('Failed to save theme to server:', error);+ }+ }++ return theme;+ };++ const updateCustomTheme = (themeId: string, updates: Partial<CustomTheme>) => {+ const index = state.value.customThemes.findIndex(t => t.id === themeId);+ if (index !== -1) {+ state.value.customThemes[index] = {+ ...state.value.customThemes[index],+ ...updates,+ updatedAt: new Date().toISOString()+ };+ saveCustomThemes();+ }+ };++ const deleteCustomTheme = (themeId: string) => {+ const index = state.value.customThemes.findIndex(t => t.id === themeId);+ if (index !== -1) {+ state.value.customThemes.splice(index, 1);+ saveCustomThemes();++ // Switch to default theme if current theme was deleted+ if (state.value.currentTheme === themeId) {+ setTheme('light');+ }+ }+ };++ // Import/Export+ const exportTheme = (themeId: string): ThemeImportExport | null => {+ const theme = state.value.customThemes.find(t => t.id === themeId);+ if (!theme) return null;++ return {+ version: '1.0.0',+ theme,+ exportedAt: new Date().toISOString(),+ exportedBy: 'observability-system'+ };+ };++ const importTheme = (importData: ThemeImportExport): boolean => {+ try {+ const theme = importData.theme;++ // Validate theme structure+ const validation = validateTheme(theme.colors);+ if (!validation.isValid) {+ state.value.error = `Invalid theme: ${validation.errors.join(', ')}`;+ return false;+ }++ // Generate new ID to avoid conflicts+ const newTheme: CustomTheme = {+ ...theme,+ id: generateId(),+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ };++ state.value.customThemes.push(newTheme);+ saveCustomThemes();+ return true;+ } catch (error) {+ state.value.error = 'Failed to import theme';+ return false;+ }+ };++ // Server API functions+ const saveThemeToServer = async (theme: CustomTheme): Promise<void> => {+ const response = await fetch('http://localhost:4000/api/themes', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(theme)+ });++ if (!response.ok) {+ const result = await response.json();+ throw new Error(result.error || 'Failed to save theme to server');+ }+ };++ const loadThemesFromServer = async (): Promise<CustomTheme[]> => {+ try {+ const response = await fetch('http://localhost:4000/api/themes?isPublic=true');+ if (!response.ok) return [];++ const result: ThemeApiResponse<CustomTheme[]> = await response.json();+ if (result.success && result.data) {+ // Convert server themes to custom theme format+ return result.data.map(theme => ({+ ...theme,+ isCustom: true+ }));+ }+ return [];+ } catch (error) {+ console.warn('Failed to load themes from server:', error);+ return [];+ }+ };+++ // Utility functions+ const camelToKebab = (str: string) => {+ return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();+ };++ const generateId = () => {+ return Math.random().toString(36).substr(2, 9);+ };++ const isValidColor = (color: string): boolean => {+ return COLOR_REGEX.test(color) || RGBA_REGEX.test(color) || CSS.supports('color', color);+ };++ const calculateContrast = (_color1: string, _color2: string): number => {+ // Simplified contrast calculation+ // In a real implementation, you'd use a proper color contrast library+ return 4.5; // Placeholder+ };++ // localStorage functions+ const saveCustomThemes = () => {+ localStorage.setItem('customThemes', JSON.stringify(state.value.customThemes));+ };++ const loadCustomThemes = () => {+ try {+ const stored = localStorage.getItem('customThemes');+ if (stored) {+ state.value.customThemes = JSON.parse(stored);+ }+ } catch (error) {+ console.warn('Failed to load custom themes from localStorage:', error);+ state.value.customThemes = [];+ }+ };++ // Initialization+ const initializeTheme = () => {+ loadCustomThemes();++ // Load saved theme+ const savedTheme = localStorage.getItem('theme');++ if (savedTheme) {+ setTheme(savedTheme);+ } else {+ // Default to Tokyo Night theme for compact dark aesthetic+ setTheme('tokyo-night');+ }+ };++ // Manager state functions+ const openThemeManager = () => {+ console.log('Opening theme manager...', managerState.value.isOpen);+ managerState.value.isOpen = true;+ console.log('Theme manager state after:', managerState.value.isOpen);+ };++ const closeThemeManager = () => {+ managerState.value.isOpen = false;+ managerState.value.previewTheme = null;+ managerState.value.editingTheme = null;+ };++ const setActiveTab = (tab: ThemeManagerState['activeTab']) => {+ managerState.value.activeTab = tab;+ };++ const previewTheme = (theme: ThemeName | CustomTheme) => {+ managerState.value.previewTheme = theme;++ // Apply preview temporarily+ if (typeof theme === 'string') {+ applyPredefinedTheme(theme);+ } else {+ applyCustomTheme(theme);+ }+ };++ const cancelPreview = () => {+ managerState.value.previewTheme = null;++ // Restore current theme+ if (state.value.isCustomTheme) {+ const customTheme = state.value.customThemes.find(t => t.id === state.value.currentTheme);+ if (customTheme) {+ applyCustomTheme(customTheme);+ }+ } else {+ applyPredefinedTheme(state.value.currentTheme as ThemeName);+ }+ };++ const applyPreview = () => {+ if (managerState.value.previewTheme) {+ const theme = typeof managerState.value.previewTheme === 'string'+ ? managerState.value.previewTheme+ : managerState.value.previewTheme.id;++ setTheme(theme);+ managerState.value.previewTheme = null;+ }+ };++ // Initialize on mount+ onMounted(() => {+ initializeTheme();+ });++ return {+ // State+ state: readonly(state),+ managerState,++ // Computed+ currentThemeData,+ predefinedThemes,++ // Core functions+ setTheme,+ validateTheme,++ // Custom theme management+ createCustomTheme,+ updateCustomTheme,+ deleteCustomTheme,++ // Import/Export+ exportTheme,+ importTheme,++ // Manager functions+ openThemeManager,+ closeThemeManager,+ setActiveTab,+ previewTheme,+ cancelPreview,+ applyPreview,++ // Server functions+ loadThemesFromServer,++ // Utility+ initializeTheme+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/composables/useTimelineIntelligence.ts b/.claude/skills/observability/apps/client/src/composables/useTimelineIntelligence.tsnew file mode 100644index 00000000..155ec59e--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useTimelineIntelligence.ts@@ -0,0 +1,198 @@+/**+ * Timeline Intelligence Composable+ * Aggregates events into time windows and provides intelligent summarization+ * Uses Haiku for fast, cheap summarization of event clusters+ */++import { ref, computed } from 'vue';+import type { HookEvent } from '../types';+import { summarizeEvents, type EventSummary, isHaikuConfigured } from '../utils/haiku';++export interface EventCluster {+ id: string;+ summary: EventSummary;+ events: HookEvent[];+ windowStart: number;+ windowEnd: number;+ expanded: boolean;+}++const SAMPLING_WINDOW_MS = 2500; // 2.5 seconds+const SUMMARIZATION_THRESHOLD = 3; // Summarize if ≥3 events in window+const MAX_EVENTS_BEFORE_COLLAPSE = 5; // Always collapse beyond 5++export function useTimelineIntelligence() {+ const clusters = ref<EventCluster[]>([]);+ const isProcessing = ref(false);+ const hasClusters = computed(() => clusters.value.length > 0);++ /**+ * Process new events and create/update clusters+ */+ async function processEvents(events: HookEvent[]) {+ if (events.length === 0) return;++ isProcessing.value = true;++ try {+ // Group events by time windows+ const windows = groupEventsIntoWindows(events);++ // Process each window+ for (const windowEvents of windows) {+ if (windowEvents.length === 0) continue;++ const shouldCluster =+ windowEvents.length >= SUMMARIZATION_THRESHOLD ||+ windowEvents.length > MAX_EVENTS_BEFORE_COLLAPSE;++ if (shouldCluster && isHaikuConfigured()) {+ // Create a cluster with Haiku summarization+ const summary = await summarizeEvents(windowEvents);+ const clusterId = generateClusterId(windowEvents);++ // Check if cluster already exists+ const existingClusterIndex = clusters.value.findIndex(c => c.id === clusterId);+ if (existingClusterIndex >= 0) {+ // Update existing cluster+ clusters.value[existingClusterIndex].events = windowEvents;+ clusters.value[existingClusterIndex].summary = summary;+ } else {+ // Create new cluster+ clusters.value.push({+ id: clusterId,+ summary,+ events: windowEvents,+ windowStart: Math.min(...windowEvents.map(e => e.timestamp || Date.now())),+ windowEnd: Math.max(...windowEvents.map(e => e.timestamp || Date.now())),+ expanded: false+ });+ }+ } else {+ // Keep events individual (below threshold or no Haiku)+ for (const event of windowEvents) {+ const clusterId = `single-${event.id}-${event.timestamp}`;+ const existingClusterIndex = clusters.value.findIndex(c => c.id === clusterId);++ if (existingClusterIndex < 0) {+ const summary = await summarizeEvents([event]);+ clusters.value.push({+ id: clusterId,+ summary,+ events: [event],+ windowStart: event.timestamp || Date.now(),+ windowEnd: event.timestamp || Date.now(),+ expanded: false+ });+ }+ }+ }+ }++ // Clean old clusters (keep last 5 minutes)+ const cutoff = Date.now() - 5 * 60 * 1000;+ clusters.value = clusters.value.filter(c => c.windowEnd >= cutoff);++ // Sort by timestamp+ clusters.value.sort((a, b) => a.windowStart - b.windowStart);+ } finally {+ isProcessing.value = false;+ }+ }++ /**+ * Group events into time windows+ */+ function groupEventsIntoWindows(events: HookEvent[]): HookEvent[][] {+ if (events.length === 0) return [];++ // Sort by timestamp+ const sortedEvents = [...events].sort((a, b) =>+ (a.timestamp || 0) - (b.timestamp || 0)+ );++ const windows: HookEvent[][] = [];+ let currentWindow: HookEvent[] = [];+ let windowStart = sortedEvents[0].timestamp || Date.now();++ for (const event of sortedEvents) {+ const eventTime = event.timestamp || Date.now();+ const timeSinceWindowStart = eventTime - windowStart;++ if (timeSinceWindowStart <= SAMPLING_WINDOW_MS) {+ // Add to current window+ currentWindow.push(event);+ } else {+ // Start new window+ if (currentWindow.length > 0) {+ windows.push(currentWindow);+ }+ currentWindow = [event];+ windowStart = eventTime;+ }+ }++ // Add final window+ if (currentWindow.length > 0) {+ windows.push(currentWindow);+ }++ return windows;+ }++ /**+ * Generate unique cluster ID based on window and events+ */+ function generateClusterId(events: HookEvent[]): string {+ const timestamps = events.map(e => e.timestamp || 0).sort();+ const start = timestamps[0];+ const end = timestamps[timestamps.length - 1];+ const eventIds = events.map(e => e.id).join('-');+ return `cluster-${start}-${end}-${eventIds.substring(0, 20)}`;+ }++ /**+ * Toggle cluster expansion+ */+ function toggleCluster(clusterId: string) {+ const cluster = clusters.value.find(c => c.id === clusterId);+ if (cluster) {+ cluster.expanded = !cluster.expanded;+ }+ }++ /**+ * Get clusters for a specific agent+ */+ function getClustersForAgent(agentId: string): EventCluster[] {+ const [targetApp, targetSession] = agentId.split(':');+ return clusters.value.filter(cluster =>+ cluster.events.some(e =>+ e.source_app === targetApp &&+ e.session_id.slice(0, 8) === targetSession+ )+ );+ }++ /**+ * Clear all clusters+ */+ function clearClusters() {+ clusters.value = [];+ }++ return {+ clusters,+ isProcessing,+ hasClusters,+ processEvents,+ toggleCluster,+ getClustersForAgent,+ clearClusters,+ config: {+ samplingWindowMs: SAMPLING_WINDOW_MS,+ summarizationThreshold: SUMMARIZATION_THRESHOLD,+ maxEventsBeforeCollapse: MAX_EVENTS_BEFORE_COLLAPSE+ }+ };+}diff --git a/.claude/skills/observability/apps/client/src/composables/useWebSocket.ts b/.claude/skills/observability/apps/client/src/composables/useWebSocket.tsnew file mode 100644index 00000000..5e7dc87d--- /dev/null+++ b/.claude/skills/observability/apps/client/src/composables/useWebSocket.ts@@ -0,0 +1,99 @@+import { ref, onMounted, onUnmounted } from 'vue';+import type { HookEvent, WebSocketMessage } from '../types';++export function useWebSocket(url: string) {+ const events = ref<HookEvent[]>([]);+ const isConnected = ref(false);+ const error = ref<string | null>(null);++ let ws: WebSocket | null = null;+ let reconnectTimeout: number | null = null;++ // Get max events from environment variable or use default+ const maxEvents = parseInt(import.meta.env.VITE_MAX_EVENTS_TO_DISPLAY || '100');++ const connect = () => {+ try {+ ws = new WebSocket(url);++ ws.onopen = () => {+ console.log('WebSocket connected');+ isConnected.value = true;+ error.value = null;+ };++ ws.onmessage = (event) => {+ try {+ const message: WebSocketMessage = JSON.parse(event.data);++ if (message.type === 'initial') {+ const initialEvents = Array.isArray(message.data) ? message.data : [];+ // Only keep the most recent events up to maxEvents+ events.value = initialEvents.slice(-maxEvents);+ } else if (message.type === 'event') {+ const newEvent = message.data as HookEvent;+ events.value.push(newEvent);++ // Limit events array to maxEvents, removing the oldest when exceeded+ if (events.value.length > maxEvents) {+ // Remove the oldest events (first 10) when limit is exceeded+ events.value = events.value.slice(events.value.length - maxEvents + 10);+ }+ }+ } catch (err) {+ console.error('Failed to parse WebSocket message:', err);+ }+ };++ ws.onerror = (err) => {+ console.error('WebSocket error:', err);+ error.value = 'WebSocket connection error';+ };++ ws.onclose = () => {+ console.log('WebSocket disconnected');+ isConnected.value = false;++ // Attempt to reconnect after 3 seconds+ reconnectTimeout = window.setTimeout(() => {+ console.log('Attempting to reconnect...');+ connect();+ }, 3000);+ };+ } catch (err) {+ console.error('Failed to connect:', err);+ error.value = 'Failed to connect to server';+ }+ };++ const disconnect = () => {+ if (reconnectTimeout) {+ clearTimeout(reconnectTimeout);+ reconnectTimeout = null;+ }++ if (ws) {+ ws.close();+ ws = null;+ }+ };++ onMounted(() => {+ connect();+ });++ onUnmounted(() => {+ disconnect();+ });++ const clearEvents = () => {+ events.value = [];+ };++ return {+ events,+ isConnected,+ error,+ clearEvents+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/main.ts b/.claude/skills/observability/apps/client/src/main.tsnew file mode 100644index 00000000..064c7a19--- /dev/null+++ b/.claude/skills/observability/apps/client/src/main.ts@@ -0,0 +1,8 @@+import { createApp } from 'vue'+import './assets/fonts.css'+import './styles/main.css'+import './styles/themes.css'+import './styles/compact.css'+import App from './App.vue'++createApp(App).mount('#app')diff --git a/.claude/skills/observability/apps/client/src/style.css b/.claude/skills/observability/apps/client/src/style.cssnew file mode 100644index 00000000..41e43884--- /dev/null+++ b/.claude/skills/observability/apps/client/src/style.css@@ -0,0 +1,104 @@+:root {+ font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;+ line-height: 1.5;+ font-weight: 400;++ color-scheme: light dark;+ color: rgba(255, 255, 255, 0.87);+ background-color: #242424;++ font-synthesis: none;+ text-rendering: optimizeLegibility;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+}++a {+ font-weight: 500;+ color: #646cff;+ text-decoration: inherit;+}+a:hover {+ color: #535bf2;+}++body {+ margin: 0;+ display: flex;+ place-items: center;+ min-width: 320px;+ min-height: 100vh;+ overflow-x: hidden; /* Prevent horizontal scrolling on mobile */+}++h1 {+ font-size: 3.2em;+ line-height: 1.1;+}++button {+ border-radius: 8px;+ border: 1px solid transparent;+ padding: 0.6em 1.2em;+ font-size: 1em;+ font-weight: 500;+ font-family: inherit;+ background-color: #1a1a1a;+ cursor: pointer;+ transition: border-color 0.25s;+}+button:hover {+ border-color: #646cff;+}+button:focus,+button:focus-visible {+ outline: 4px auto -webkit-focus-ring-color;+}++.card {+ padding: 2em;+}++#app {+ max-width: 1280px;+ margin: 0 auto;+ padding: 2rem;+ text-align: center;+}++@media (prefers-color-scheme: light) {+ :root {+ color: #213547;+ background-color: #ffffff;+ }+ a:hover {+ color: #747bff;+ }+ button {+ background-color: #f9f9f9;+ }+}++/* Mobile optimizations */+@media (max-width: 699px) {+ body {+ place-items: stretch; /* Allow full width on mobile */+ }++ #app {+ max-width: none; /* Remove max-width constraint on mobile */+ padding: 0; /* Remove default padding on mobile */+ text-align: left; /* Left-align text on mobile for better readability */+ }++ /* Improve touch targets on mobile */+ button, select, input[type="button"], input[type="submit"] {+ min-height: 44px;+ min-width: 44px;+ }++ /* Optimize text selection on mobile */+ * {+ -webkit-tap-highlight-color: transparent;+ }+}diff --git a/.claude/skills/observability/apps/client/src/styles/compact.css b/.claude/skills/observability/apps/client/src/styles/compact.cssnew file mode 100644index 00000000..03f2f616--- /dev/null+++ b/.claude/skills/observability/apps/client/src/styles/compact.css@@ -0,0 +1,272 @@+/* Compact Layout Overrides - Tokyo Night Optimized */++/* Global compact spacing */+.compact-mode {+ /* Reduce all standard spacing by 30-40% */+ --compact-spacing-xs: 0.25rem; /* 4px - was 8px */+ --compact-spacing-sm: 0.5rem; /* 8px - was 12px */+ --compact-spacing-md: 0.75rem; /* 12px - was 16px */+ --compact-spacing-lg: 1rem; /* 16px - was 24px */+ --compact-spacing-xl: 1.25rem; /* 20px - was 32px */++ /* Reduce font sizes slightly */+ --compact-text-xs: 0.65rem; /* 10.4px - was 12px */+ --compact-text-sm: 0.8rem; /* 12.8px - was 14px */+ --compact-text-base: 0.875rem; /* 14px - was 16px */+ --compact-text-lg: 1rem; /* 16px - was 18px */+ --compact-text-xl: 1.125rem; /* 18px - was 20px */+ --compact-text-2xl: 1.25rem; /* 20px - was 24px */+}++/* Header compression */+.compact-mode header {+ padding-top: 0.5rem !important;+ padding-bottom: 0.5rem !important;+}++.compact-mode header h1 {+ font-size: var(--compact-text-xl) !important;+}++.compact-mode header .connection-status span {+ font-size: var(--compact-text-sm) !important;+}++.compact-mode header button {+ padding: 0.5rem !important;+}++/* Filter panel compression */+.compact-mode .filter-panel {+ padding-top: 0.75rem !important;+ padding-bottom: 0.75rem !important;+}++.compact-mode .filter-panel label {+ font-size: var(--compact-text-sm) !important;+ margin-bottom: 0.25rem !important;+}++.compact-mode .filter-panel select {+ padding: 0.375rem 0.75rem !important;+ font-size: var(--compact-text-sm) !important;+}++/* Live pulse chart compression */+.compact-mode .pulse-chart-header {+ margin-bottom: 0.5rem !important;+}++.compact-mode .pulse-chart-header h3 {+ font-size: var(--compact-text-base) !important;+}++.compact-mode .pulse-chart-stats {+ padding: 0.375rem 0.5rem !important;+ font-size: var(--compact-text-xs) !important;+ gap: 0.375rem !important;+}++.compact-mode .pulse-chart-stats .stat-icon {+ font-size: var(--compact-text-base) !important;+}++.compact-mode .pulse-chart-stats .stat-value {+ font-size: var(--compact-text-sm) !important;+}++.compact-mode .time-range-button {+ padding: 0.375rem 0.625rem !important;+ font-size: var(--compact-text-xs) !important;+ min-width: 24px !important;+ min-height: 24px !important;+}++/* Event row compression */+.compact-mode .event-row {+ padding: 0.625rem !important;+ margin-bottom: 0.375rem !important;+}++.compact-mode .event-row .app-indicator {+ width: 2px !important;+}++.compact-mode .event-row .session-indicator {+ width: 1px !important;+}++.compact-mode .event-row .event-tag {+ padding: 0.25rem 0.5rem !important;+ font-size: var(--compact-text-xs) !important;+}++.compact-mode .event-row .event-type-badge {+ padding: 0.25rem 0.625rem !important;+ font-size: var(--compact-text-xs) !important;+}++.compact-mode .event-row .event-emoji {+ font-size: var(--compact-text-sm) !important;+ margin-right: 0.25rem !important;+}++.compact-mode .event-row .tool-info {+ font-size: var(--compact-text-sm) !important;+ padding: 0.25rem 0.5rem !important;+}++.compact-mode .event-row .summary-badge {+ padding: 0.375rem 0.625rem !important;+ font-size: var(--compact-text-sm) !important;+}++/* Expanded event content compression */+.compact-mode .event-expanded {+ margin-top: 0.5rem !important;+ padding: 0.625rem !important;+}++.compact-mode .event-expanded h4 {+ font-size: var(--compact-text-sm) !important;+ margin-bottom: 0.375rem !important;+}++.compact-mode .event-expanded pre {+ font-size: var(--compact-text-xs) !important;+ padding: 0.5rem !important;+ max-height: 200px !important;+}++.compact-mode .event-expanded button {+ padding: 0.375rem 0.75rem !important;+ font-size: var(--compact-text-sm) !important;+}++/* Agent swim lane compression */+.compact-mode .swim-lane {+ padding: 0.5rem !important;+}++.compact-mode .swim-lane-header {+ padding: 0.375rem 0.625rem !important;+ font-size: var(--compact-text-sm) !important;+}++/* Toast notification compression */+.compact-mode .toast {+ padding: 0.5rem 0.75rem !important;+ font-size: var(--compact-text-sm) !important;+}++/* Modal compression */+.compact-mode .modal-header {+ padding: 0.75rem 1rem !important;+}++.compact-mode .modal-header h2 {+ font-size: var(--compact-text-lg) !important;+}++.compact-mode .modal-body {+ padding: 0.75rem 1rem !important;+}++.compact-mode .modal-footer {+ padding: 0.5rem 1rem !important;+}++/* Scrollbar styling for Tokyo Night */+.theme-tokyo-night ::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}++.theme-tokyo-night ::-webkit-scrollbar-track {+ background: var(--theme-bg-secondary);+ border-radius: 4px;+}++.theme-tokyo-night ::-webkit-scrollbar-thumb {+ background: var(--theme-border-primary);+ border-radius: 4px;+}++.theme-tokyo-night ::-webkit-scrollbar-thumb:hover {+ background: var(--theme-border-secondary);+}++/* Focus states for Tokyo Night */+.theme-tokyo-night *:focus {+ outline-color: var(--theme-primary);+ outline-offset: 1px;+}++/* Better contrast for small text in Tokyo Night */+.theme-tokyo-night .compact-mode .text-xs,+.theme-tokyo-night .compact-mode .text-sm {+ color: var(--theme-text-secondary);+}++/* Ensure badges have good contrast */+.theme-tokyo-night .compact-mode .event-type-badge,+.theme-tokyo-night .compact-mode .event-tag {+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);+}++/* Tighter line height for compact mode */+.compact-mode {+ line-height: 1.4;+}++.compact-mode h1,+.compact-mode h2,+.compact-mode h3,+.compact-mode h4 {+ line-height: 1.2;+}++/* Reduce shadow intensity in compact mode for cleaner look */+.compact-mode .shadow-lg {+ box-shadow: 0 4px 6px var(--theme-shadow) !important;+}++.compact-mode .shadow-md {+ box-shadow: 0 2px 4px var(--theme-shadow) !important;+}++/* Optimize space usage in flex layouts */+.compact-mode .flex {+ gap: 0.5rem;+}++.compact-mode .flex.space-x-4 {+ gap: 0.75rem !important;+}++.compact-mode .flex.space-x-3 {+ gap: 0.5rem !important;+}++.compact-mode .flex.space-x-2 {+ gap: 0.375rem !important;+}++/* Make buttons more compact */+.compact-mode button {+ font-weight: 600;+}++/* Reduce border widths slightly */+.compact-mode .border-2 {+ border-width: 1.5px !important;+}++/* Optimize rounded corners */+.compact-mode .rounded-lg {+ border-radius: 0.375rem !important;+}++.compact-mode .rounded-full {+ border-radius: 9999px !important;+}diff --git a/.claude/skills/observability/apps/client/src/styles/main.css b/.claude/skills/observability/apps/client/src/styles/main.cssnew file mode 100644index 00000000..d748fd25--- /dev/null+++ b/.claude/skills/observability/apps/client/src/styles/main.css@@ -0,0 +1,32 @@+/* Import theme system */+@import './themes.css';++/* Import compact layout system */+@import './compact.css';++@tailwind base;+@tailwind components;+@tailwind utilities;++@layer base {+ body {+ @apply font-sans;+ }++ h1, h2, h3, h4, h5, h6 {+ @apply font-concourse-t3;+ }++ code, pre {+ @apply font-mono;+ }++ /* Prose/long-form text styling - for prompts, chat messages, entries */+ .prose {+ @apply font-serif;+ }++ .prose p {+ @apply font-serif;+ }+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/styles/themes.css b/.claude/skills/observability/apps/client/src/styles/themes.cssnew file mode 100644index 00000000..a2852987--- /dev/null+++ b/.claude/skills/observability/apps/client/src/styles/themes.css@@ -0,0 +1,596 @@+/* Theme System - CSS Custom Properties */++/* Default theme variables (Light theme) */+:root {+ /* Primary colors */+ --theme-primary: #3b82f6;+ --theme-primary-hover: #2563eb;+ --theme-primary-light: #dbeafe;+ --theme-primary-dark: #1e40af;++ /* Background colors */+ --theme-bg-primary: #ffffff;+ --theme-bg-secondary: #f9fafb;+ --theme-bg-tertiary: #f3f4f6;+ --theme-bg-quaternary: #e5e7eb;++ /* Text colors */+ --theme-text-primary: #111827;+ --theme-text-secondary: #374151;+ --theme-text-tertiary: #6b7280;+ --theme-text-quaternary: #9ca3af;++ /* Border colors */+ --theme-border-primary: #e5e7eb;+ --theme-border-secondary: #d1d5db;+ --theme-border-tertiary: #9ca3af;++ /* Accent colors */+ --theme-accent-success: #10b981;+ --theme-accent-warning: #f59e0b;+ --theme-accent-error: #ef4444;+ --theme-accent-info: #3b82f6;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 0, 0.1);+ --theme-shadow-lg: rgba(0, 0, 0, 0.25);++ /* Interactive states */+ --theme-hover-bg: rgba(0, 0, 0, 0.05);+ --theme-active-bg: rgba(0, 0, 0, 0.1);+ --theme-focus-ring: #3b82f6;++ /* Theme transitions */+ --theme-transition: all 0.2s ease-in-out;+ --theme-transition-fast: all 0.1s ease-in-out;+}++/* Dark theme */+.theme-dark {+ /* Primary colors */+ --theme-primary: #60a5fa;+ --theme-primary-hover: #3b82f6;+ --theme-primary-light: #1e3a8a;+ --theme-primary-dark: #1d4ed8;++ /* Background colors */+ --theme-bg-primary: #111827;+ --theme-bg-secondary: #1f2937;+ --theme-bg-tertiary: #374151;+ --theme-bg-quaternary: #4b5563;++ /* Text colors */+ --theme-text-primary: #f9fafb;+ --theme-text-secondary: #e5e7eb;+ --theme-text-tertiary: #d1d5db;+ --theme-text-quaternary: #9ca3af;++ /* Border colors */+ --theme-border-primary: #374151;+ --theme-border-secondary: #4b5563;+ --theme-border-tertiary: #6b7280;++ /* Accent colors */+ --theme-accent-success: #34d399;+ --theme-accent-warning: #fbbf24;+ --theme-accent-error: #f87171;+ --theme-accent-info: #60a5fa;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 0, 0.5);+ --theme-shadow-lg: rgba(0, 0, 0, 0.75);++ /* Interactive states */+ --theme-hover-bg: rgba(255, 255, 255, 0.05);+ --theme-active-bg: rgba(255, 255, 255, 0.1);+ --theme-focus-ring: #60a5fa;+}++/* Modern theme - Sleek blues and grays */+.theme-modern {+ /* Primary colors */+ --theme-primary: #0ea5e9;+ --theme-primary-hover: #0284c7;+ --theme-primary-light: #e0f2fe;+ --theme-primary-dark: #0c4a6e;++ /* Background colors */+ --theme-bg-primary: #f8fafc;+ --theme-bg-secondary: #f1f5f9;+ --theme-bg-tertiary: #e2e8f0;+ --theme-bg-quaternary: #cbd5e1;++ /* Text colors */+ --theme-text-primary: #0f172a;+ --theme-text-secondary: #334155;+ --theme-text-tertiary: #64748b;+ --theme-text-quaternary: #94a3b8;++ /* Border colors */+ --theme-border-primary: #e2e8f0;+ --theme-border-secondary: #cbd5e1;+ --theme-border-tertiary: #94a3b8;++ /* Accent colors */+ --theme-accent-success: #059669;+ --theme-accent-warning: #d97706;+ --theme-accent-error: #dc2626;+ --theme-accent-info: #0ea5e9;++ /* Shadow colors */+ --theme-shadow: rgba(15, 23, 42, 0.1);+ --theme-shadow-lg: rgba(15, 23, 42, 0.25);++ /* Interactive states */+ --theme-hover-bg: rgba(15, 23, 42, 0.05);+ --theme-active-bg: rgba(15, 23, 42, 0.1);+ --theme-focus-ring: #0ea5e9;+}++/* Earth theme - Natural warm earth tones */+.theme-earth {+ /* Primary colors */+ --theme-primary: #8b4513;+ --theme-primary-hover: #a0522d;+ --theme-primary-light: #deb887;+ --theme-primary-dark: #654321;++ /* Background colors */+ --theme-bg-primary: #f5f5dc;+ --theme-bg-secondary: #f0e68c;+ --theme-bg-tertiary: #daa520;+ --theme-bg-quaternary: #cd853f;++ /* Text colors */+ --theme-text-primary: #2f1b14;+ --theme-text-secondary: #5d4e37;+ --theme-text-tertiary: #8b4513;+ --theme-text-quaternary: #a0522d;++ /* Border colors */+ --theme-border-primary: #deb887;+ --theme-border-secondary: #d2b48c;+ --theme-border-tertiary: #cd853f;++ /* Accent colors */+ --theme-accent-success: #228b22;+ --theme-accent-warning: #ff8c00;+ --theme-accent-error: #dc143c;+ --theme-accent-info: #4682b4;++ /* Shadow colors */+ --theme-shadow: rgba(139, 69, 19, 0.15);+ --theme-shadow-lg: rgba(139, 69, 19, 0.3);++ /* Interactive states */+ --theme-hover-bg: rgba(139, 69, 19, 0.08);+ --theme-active-bg: rgba(139, 69, 19, 0.15);+ --theme-focus-ring: #8b4513;+}++/* Glass theme - Translucent with subtle colors */+.theme-glass {+ /* Primary colors */+ --theme-primary: #8b5cf6;+ --theme-primary-hover: #7c3aed;+ --theme-primary-light: #f3e8ff;+ --theme-primary-dark: #581c87;++ /* Background colors */+ --theme-bg-primary: rgba(255, 255, 255, 0.95);+ --theme-bg-secondary: rgba(248, 250, 252, 0.9);+ --theme-bg-tertiary: rgba(241, 245, 249, 0.85);+ --theme-bg-quaternary: rgba(226, 232, 240, 0.8);++ /* Text colors */+ --theme-text-primary: #1e1b4b;+ --theme-text-secondary: #3730a3;+ --theme-text-tertiary: #6366f1;+ --theme-text-quaternary: #8b5cf6;++ /* Border colors */+ --theme-border-primary: rgba(226, 232, 240, 0.6);+ --theme-border-secondary: rgba(203, 213, 225, 0.7);+ --theme-border-tertiary: rgba(148, 163, 184, 0.8);++ /* Accent colors */+ --theme-accent-success: #10b981;+ --theme-accent-warning: #f59e0b;+ --theme-accent-error: #ef4444;+ --theme-accent-info: #8b5cf6;++ /* Shadow colors */+ --theme-shadow: rgba(139, 92, 246, 0.1);+ --theme-shadow-lg: rgba(139, 92, 246, 0.25);++ /* Interactive states */+ --theme-hover-bg: rgba(139, 92, 246, 0.05);+ --theme-active-bg: rgba(139, 92, 246, 0.1);+ --theme-focus-ring: #8b5cf6;+}++/* High Contrast theme - For accessibility */+.theme-high-contrast {+ /* Primary colors */+ --theme-primary: #000000;+ --theme-primary-hover: #333333;+ --theme-primary-light: #f0f0f0;+ --theme-primary-dark: #000000;++ /* Background colors */+ --theme-bg-primary: #ffffff;+ --theme-bg-secondary: #f0f0f0;+ --theme-bg-tertiary: #e0e0e0;+ --theme-bg-quaternary: #d0d0d0;++ /* Text colors */+ --theme-text-primary: #000000;+ --theme-text-secondary: #000000;+ --theme-text-tertiary: #333333;+ --theme-text-quaternary: #666666;++ /* Border colors */+ --theme-border-primary: #000000;+ --theme-border-secondary: #333333;+ --theme-border-tertiary: #666666;++ /* Accent colors */+ --theme-accent-success: #008000;+ --theme-accent-warning: #ff8c00;+ --theme-accent-error: #ff0000;+ --theme-accent-info: #0000ff;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 0, 0.3);+ --theme-shadow-lg: rgba(0, 0, 0, 0.6);++ /* Interactive states */+ --theme-hover-bg: rgba(0, 0, 0, 0.1);+ --theme-active-bg: rgba(0, 0, 0, 0.2);+ --theme-focus-ring: #000000;+}++/* Dark Blue theme - Deep blue with navy accents */+.theme-dark-blue {+ /* Primary colors */+ --theme-primary: #0099ff;+ --theme-primary-hover: #0077cc;+ --theme-primary-light: #33aaff;+ --theme-primary-dark: #0066cc;++ /* Background colors */+ --theme-bg-primary: #000033;+ --theme-bg-secondary: #000066;+ --theme-bg-tertiary: #000099;+ --theme-bg-quaternary: #0000cc;++ /* Text colors */+ --theme-text-primary: #e6f2ff;+ --theme-text-secondary: #ccddff;+ --theme-text-tertiary: #99bbff;+ --theme-text-quaternary: #6699ff;++ /* Border colors */+ --theme-border-primary: #003366;+ --theme-border-secondary: #004499;+ --theme-border-tertiary: #0066cc;++ /* Accent colors */+ --theme-accent-success: #00ff88;+ --theme-accent-warning: #ffaa00;+ --theme-accent-error: #ff3366;+ --theme-accent-info: #0099ff;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 51, 0.7);+ --theme-shadow-lg: rgba(0, 0, 51, 0.9);++ /* Interactive states */+ --theme-hover-bg: rgba(0, 153, 255, 0.15);+ --theme-active-bg: rgba(0, 153, 255, 0.25);+ --theme-focus-ring: #0099ff;+}++/* Colorblind Friendly theme - High contrast colors safe for color vision deficiency */+.theme-colorblind-friendly {+ /* Primary colors */+ --theme-primary: #993366;+ --theme-primary-hover: #663344;+ --theme-primary-light: #cc6699;+ --theme-primary-dark: #661144;++ /* Background colors */+ --theme-bg-primary: #ffffcc;+ --theme-bg-secondary: #ffcc99;+ --theme-bg-tertiary: #ffaa88;+ --theme-bg-quaternary: #ff9966;++ /* Text colors */+ --theme-text-primary: #331122;+ --theme-text-secondary: #442233;+ --theme-text-tertiary: #553344;+ --theme-text-quaternary: #664455;++ /* Border colors */+ --theme-border-primary: #cc9966;+ --theme-border-secondary: #996633;+ --theme-border-tertiary: #663300;++ /* Accent colors */+ --theme-accent-success: #117733;+ --theme-accent-warning: #cc6633;+ --theme-accent-error: #882233;+ --theme-accent-info: #993366;++ /* Shadow colors */+ --theme-shadow: rgba(51, 17, 34, 0.15);+ --theme-shadow-lg: rgba(51, 17, 34, 0.3);++ /* Interactive states */+ --theme-hover-bg: rgba(153, 51, 102, 0.08);+ --theme-active-bg: rgba(153, 51, 102, 0.15);+ --theme-focus-ring: #993366;+}++/* Ocean theme - Bright tropical ocean with turquoise and coral accents */+.theme-ocean {+ /* Primary colors */+ --theme-primary: #0088cc;+ --theme-primary-hover: #006699;+ --theme-primary-light: #33aadd;+ --theme-primary-dark: #005588;++ /* Background colors */+ --theme-bg-primary: #cceeff;+ --theme-bg-secondary: #99ddff;+ --theme-bg-tertiary: #66ccff;+ --theme-bg-quaternary: #33bbff;++ /* Text colors */+ --theme-text-primary: #003344;+ --theme-text-secondary: #004455;+ --theme-text-tertiary: #005566;+ --theme-text-quaternary: #006677;++ /* Border colors */+ --theme-border-primary: #66bbdd;+ --theme-border-secondary: #4499cc;+ --theme-border-tertiary: #2288bb;++ /* Accent colors */+ --theme-accent-success: #00cc66;+ --theme-accent-warning: #ff9933;+ --theme-accent-error: #ff3333;+ --theme-accent-info: #0088cc;++ /* Shadow colors */+ --theme-shadow: rgba(0, 136, 204, 0.15);+ --theme-shadow-lg: rgba(0, 136, 204, 0.3);++ /* Interactive states */+ --theme-hover-bg: rgba(0, 136, 204, 0.08);+ --theme-active-bg: rgba(0, 136, 204, 0.15);+ --theme-focus-ring: #0088cc;+}++/* Midnight Purple theme - Deep purples with neon accents */+.theme-midnight-purple {+ /* Primary colors */+ --theme-primary: #a78bfa;+ --theme-primary-hover: #c4b5fd;+ --theme-primary-light: #2e1065;+ --theme-primary-dark: #6d28d9;++ /* Background colors */+ --theme-bg-primary: #0f0a1a;+ --theme-bg-secondary: #1a1333;+ --theme-bg-tertiary: #2d1b4e;+ --theme-bg-quaternary: #3f2766;++ /* Text colors */+ --theme-text-primary: #f3e8ff;+ --theme-text-secondary: #e9d5ff;+ --theme-text-tertiary: #d8b4fe;+ --theme-text-quaternary: #c084fc;++ /* Border colors */+ --theme-border-primary: #6d28d9;+ --theme-border-secondary: #7e22ce;+ --theme-border-tertiary: #a855f7;++ /* Accent colors */+ --theme-accent-success: #34d399;+ --theme-accent-warning: #fbbf24;+ --theme-accent-error: #f472b6;+ --theme-accent-info: #a78bfa;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 0, 0.6);+ --theme-shadow-lg: rgba(0, 0, 0, 0.8);++ /* Interactive states */+ --theme-hover-bg: rgba(167, 139, 250, 0.1);+ --theme-active-bg: rgba(167, 139, 250, 0.2);+ --theme-focus-ring: #a78bfa;+}++/* Sunset Orange theme - Warm oranges and neutral tones */+.theme-sunset-orange {+ /* Primary colors */+ --theme-primary: #ea580c;+ --theme-primary-hover: #c2410c;+ --theme-primary-light: #fed7aa;+ --theme-primary-dark: #9a3412;++ /* Background colors */+ --theme-bg-primary: #f5ede4;+ --theme-bg-secondary: #fce4d6;+ --theme-bg-tertiary: #fbdcc3;+ --theme-bg-quaternary: #f8d4af;++ /* Text colors */+ --theme-text-primary: #1f1208;+ --theme-text-secondary: #3e2109;+ --theme-text-tertiary: #5d2d0e;+ --theme-text-quaternary: #7c3a14;++ /* Border colors */+ --theme-border-primary: #fbdcc3;+ --theme-border-secondary: #f8c9a8;+ --theme-border-tertiary: #f5a842;++ /* Accent colors */+ --theme-accent-success: #16a34a;+ --theme-accent-warning: #f59e0b;+ --theme-accent-error: #dc2626;+ --theme-accent-info: #ea580c;++ /* Shadow colors */+ --theme-shadow: rgba(218, 74, 13, 0.15);+ --theme-shadow-lg: rgba(218, 74, 13, 0.3);++ /* Interactive states */+ --theme-hover-bg: rgba(234, 88, 12, 0.08);+ --theme-active-bg: rgba(234, 88, 12, 0.15);+ --theme-focus-ring: #ea580c;+}++/* Mint Fresh theme - Cool mint greens with slate neutrals */+.theme-mint-fresh {+ /* Primary colors */+ --theme-primary: #0d9488;+ --theme-primary-hover: #0f766e;+ --theme-primary-light: #ccfbf1;+ --theme-primary-dark: #134e4a;++ /* Background colors */+ --theme-bg-primary: #f0fdfa;+ --theme-bg-secondary: #d1fae5;+ --theme-bg-tertiary: #a7f3d0;+ --theme-bg-quaternary: #7ee8c9;++ /* Text colors */+ --theme-text-primary: #0d3b36;+ --theme-text-secondary: #145352;+ --theme-text-tertiary: #1b6b67;+ --theme-text-quaternary: #2d827d;++ /* Border colors */+ --theme-border-primary: #a7f3d0;+ --theme-border-secondary: #7ee8c9;+ --theme-border-tertiary: #5eead4;++ /* Accent colors */+ --theme-accent-success: #059669;+ --theme-accent-warning: #d97706;+ --theme-accent-error: #dc2626;+ --theme-accent-info: #0d9488;++ /* Shadow colors */+ --theme-shadow: rgba(13, 148, 136, 0.12);+ --theme-shadow-lg: rgba(13, 148, 136, 0.25);++ /* Interactive states */+ --theme-hover-bg: rgba(13, 148, 136, 0.08);+ --theme-active-bg: rgba(13, 148, 136, 0.15);+ --theme-focus-ring: #0d9488;+}++/* Tokyo Night theme - Deep dark with vibrant accents */+.theme-tokyo-night {+ /* Primary colors */+ --theme-primary: #7aa2f7;+ --theme-primary-hover: #89b4fa;+ --theme-primary-light: #3d59a1;+ --theme-primary-dark: #565f89;++ /* Background colors */+ --theme-bg-primary: #1a1b26;+ --theme-bg-secondary: #16161e;+ --theme-bg-tertiary: #24283b;+ --theme-bg-quaternary: #292e42;++ /* Text colors - IMPROVED FOR READABILITY */+ --theme-text-primary: #c0caf5; /* 10.59:1 contrast ✅ - Perfect for primary text */+ --theme-text-secondary: #a9b1d6; /* 8.10:1 contrast ✅ - Good for secondary text */+ --theme-text-tertiary: #9aa5ce; /* IMPROVED from #787c99 - Now 5.2:1 contrast ✅ */+ --theme-text-quaternary: #7e89ac; /* IMPROVED from #565f89 - Now 3.8:1 contrast (AA for large text) */++ /* Border colors - IMPROVED FOR VISIBILITY */+ --theme-border-primary: #4a5578; /* IMPROVED from #414868 - Better visibility */+ --theme-border-secondary: #5d6690; /* IMPROVED from #545c7e - Better visibility */+ --theme-border-tertiary: #6b7599; /* IMPROVED from #565f89 - Better visibility */++ /* Accent colors */+ --theme-accent-success: #9ece6a;+ --theme-accent-warning: #e0af68;+ --theme-accent-error: #f7768e;+ --theme-accent-info: #7aa2f7;++ /* Shadow colors */+ --theme-shadow: rgba(0, 0, 0, 0.5);+ --theme-shadow-lg: rgba(0, 0, 0, 0.75);++ /* Interactive states */+ --theme-hover-bg: #292e42;+ --theme-active-bg: #3b4261;+ --theme-focus-ring: #7aa2f7;++ /* Special Tokyo Night colors */+ --tokyo-purple: #bb9af7;+ --tokyo-cyan: #7dcfff;+ --tokyo-teal: #1abc9c;+ --tokyo-red: #f7768e;+ --tokyo-orange: #ff9e64;+}++/* Utility classes for theme variables */+.theme-bg-primary { background-color: var(--theme-bg-primary); }+.theme-bg-secondary { background-color: var(--theme-bg-secondary); }+.theme-bg-tertiary { background-color: var(--theme-bg-tertiary); }+.theme-bg-quaternary { background-color: var(--theme-bg-quaternary); }++.theme-text-primary { color: var(--theme-text-primary); }+.theme-text-secondary { color: var(--theme-text-secondary); }+.theme-text-tertiary { color: var(--theme-text-tertiary); }+.theme-text-quaternary { color: var(--theme-text-quaternary); }++.theme-border-primary { border-color: var(--theme-border-primary); }+.theme-border-secondary { border-color: var(--theme-border-secondary); }+.theme-border-tertiary { border-color: var(--theme-border-tertiary); }++.theme-primary { color: var(--theme-primary); }+.theme-primary-bg { background-color: var(--theme-primary); }+.theme-primary-border { border-color: var(--theme-primary); }++.theme-accent-success { color: var(--theme-accent-success); }+.theme-accent-warning { color: var(--theme-accent-warning); }+.theme-accent-error { color: var(--theme-accent-error); }+.theme-accent-info { color: var(--theme-accent-info); }++.theme-shadow { box-shadow: 0 1px 3px var(--theme-shadow); }+.theme-shadow-lg { box-shadow: 0 10px 15px var(--theme-shadow-lg); }++.theme-transition { transition: var(--theme-transition); }+.theme-transition-fast { transition: var(--theme-transition-fast); }++/* Backdrop filter support for glass theme */+.theme-glass .backdrop-blur {+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+}++/* Focus ring styles */+.theme-focus:focus {+ outline: 2px solid var(--theme-focus-ring);+ outline-offset: 2px;+}++/* Interactive state styles */+.theme-hover:hover {+ background-color: var(--theme-hover-bg);+}++.theme-active:active {+ background-color: var(--theme-active-bg);+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/types.ts b/.claude/skills/observability/apps/client/src/types.tsnew file mode 100644index 00000000..3b41c96c--- /dev/null+++ b/.claude/skills/observability/apps/client/src/types.ts@@ -0,0 +1,92 @@+// Todo item interface+export interface TodoItem {+ content: string;+ status: 'pending' | 'in_progress' | 'completed';+ activeForm: string;+}++// New interface for human-in-the-loop requests+export interface HumanInTheLoop {+ question: string;+ responseWebSocketUrl: string;+ type: 'question' | 'permission' | 'choice';+ choices?: string[]; // For multiple choice questions+ timeout?: number; // Optional timeout in seconds+ requiresResponse?: boolean; // Whether response is required or optional+}++// Response interface+export interface HumanInTheLoopResponse {+ response?: string;+ permission?: boolean;+ choice?: string; // Selected choice from options+ hookEvent: HookEvent;+ respondedAt: number;+ respondedBy?: string; // Optional user identifier+}++// Status tracking interface+export interface HumanInTheLoopStatus {+ status: 'pending' | 'responded' | 'timeout' | 'error';+ respondedAt?: number;+ response?: HumanInTheLoopResponse;+}++export interface HookEvent {+ id?: number;+ source_app: string;+ session_id: string;+ hook_event_type: string;+ payload: Record<string, any>;+ chat?: any[];+ summary?: string;+ timestamp?: number;+ model_name?: string;+ agent_name?: string; // NEW: Agent name enriched by server (Phase 1)++ // NEW: Optional HITL data+ humanInTheLoop?: HumanInTheLoop;+ humanInTheLoopStatus?: HumanInTheLoopStatus;++ // NEW: Optional Todo data+ todos?: TodoItem[];+ completedTodos?: TodoItem[]; // Todos that were completed in this event+}++export interface FilterOptions {+ source_apps: string[];+ session_ids: string[];+ hook_event_types: string[];+}++export interface WebSocketMessage {+ type: 'initial' | 'event' | 'hitl_response';+ data: HookEvent | HookEvent[] | HumanInTheLoopResponse;+}++export type TimeRange = '1M' | '2M' | '4M' | '8M' | '16M';++export interface ChartDataPoint {+ timestamp: number;+ count: number;+ eventTypes: Record<string, number>; // event type -> count+ sessions: Record<string, number>; // session id -> count+ apps?: Record<string, number>; // app name -> count (optional for backward compatibility)+ summaryText?: string; // Optional AI-generated summary for clustered events+ isCluster?: boolean; // Whether this represents multiple aggregated events+ clusterId?: string; // Unique ID for the cluster+ rawEvents?: HookEvent[]; // Raw events for this data point (for drill-down)+}++export interface ChartConfig {+ maxDataPoints: number;+ animationDuration: number;+ barWidth: number;+ barGap: number;+ colors: {+ primary: string;+ glow: string;+ axis: string;+ text: string;+ };+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/types/theme.ts b/.claude/skills/observability/apps/client/src/types/theme.tsnew file mode 100644index 00000000..62fa5afb--- /dev/null+++ b/.claude/skills/observability/apps/client/src/types/theme.ts@@ -0,0 +1,249 @@+// Theme type definitions++export type ThemeName = 'light' | 'dark' | 'modern' | 'earth' | 'glass' | 'high-contrast' | 'dark-blue' | 'colorblind-friendly' | 'ocean' | 'midnight-purple' | 'sunset-orange' | 'mint-fresh' | 'tokyo-night';++export interface ThemeColors {+ // Primary colors+ primary: string;+ primaryHover: string;+ primaryLight: string;+ primaryDark: string;++ // Background colors+ bgPrimary: string;+ bgSecondary: string;+ bgTertiary: string;+ bgQuaternary: string;++ // Text colors+ textPrimary: string;+ textSecondary: string;+ textTertiary: string;+ textQuaternary: string;++ // Border colors+ borderPrimary: string;+ borderSecondary: string;+ borderTertiary: string;++ // Accent colors+ accentSuccess: string;+ accentWarning: string;+ accentError: string;+ accentInfo: string;++ // Shadow colors+ shadow: string;+ shadowLg: string;++ // Interactive states+ hoverBg: string;+ activeBg: string;+ focusRing: string;+}++export interface CustomTheme {+ id: string;+ name: string;+ displayName: string;+ description?: string;+ colors: ThemeColors;+ isCustom: boolean;+ isPublic?: boolean;+ authorId?: string;+ authorName?: string;+ createdAt?: string;+ updatedAt?: string;+ tags?: string[];+}++export interface PredefinedTheme {+ name: ThemeName;+ displayName: string;+ description: string;+ colors: ThemeColors;+ cssClass: string;+ preview: {+ primary: string;+ secondary: string;+ accent: string;+ };+}++export interface ThemeState {+ currentTheme: ThemeName | string;+ customThemes: CustomTheme[];+ isCustomTheme: boolean;+ isLoading: boolean;+ error: string | null;+}++export interface ThemeManagerState {+ isOpen: boolean;+ activeTab: 'predefined' | 'custom' | 'create';+ previewTheme: ThemeName | CustomTheme | null;+ editingTheme: CustomTheme | null;+}++export interface CreateThemeFormData {+ name: string;+ displayName: string;+ description: string;+ colors: Partial<ThemeColors>;+ isPublic: boolean;+ tags: string[];+}++export interface ThemeImportExport {+ version: string;+ theme: CustomTheme;+ exportedAt: string;+ exportedBy?: string;+}++export interface ThemeValidationResult {+ isValid: boolean;+ errors: string[];+ warnings: string[];+}++// Color picker types+export interface ColorPickerProps {+ modelValue: string;+ label: string;+ description?: string;+ required?: boolean;+ disabled?: boolean;+}++// Theme API types+export interface ThemeApiResponse<T = any> {+ success: boolean;+ data?: T;+ error?: string;+ message?: string;+}++export interface ThemeSearchFilters {+ query?: string;+ tags?: string[];+ authorId?: string;+ isPublic?: boolean;+ sortBy?: 'name' | 'created' | 'updated' | 'popularity';+ sortOrder?: 'asc' | 'desc';+ limit?: number;+ offset?: number;+}++export interface ThemeShareData {+ themeId: string;+ shareToken: string;+ expiresAt?: string;+ isPublic: boolean;+ allowedUsers?: string[];+}++// Utility types+export type ThemeColorKey = keyof ThemeColors;+export type PartialThemeColors = Partial<ThemeColors>;+export type RequiredThemeColors = Required<ThemeColors>;++// Constants for validation+export const THEME_COLOR_KEYS: ThemeColorKey[] = [+ 'primary',+ 'primaryHover',+ 'primaryLight',+ 'primaryDark',+ 'bgPrimary',+ 'bgSecondary',+ 'bgTertiary',+ 'bgQuaternary',+ 'textPrimary',+ 'textSecondary',+ 'textTertiary',+ 'textQuaternary',+ 'borderPrimary',+ 'borderSecondary',+ 'borderTertiary',+ 'accentSuccess',+ 'accentWarning',+ 'accentError',+ 'accentInfo',+ 'shadow',+ 'shadowLg',+ 'hoverBg',+ 'activeBg',+ 'focusRing',+];++export const PREDEFINED_THEME_NAMES: ThemeName[] = [+ 'light',+ 'dark',+ 'modern',+ 'earth',+ 'glass',+ 'high-contrast',+ 'dark-blue',+ 'colorblind-friendly',+ 'ocean',+ 'midnight-purple',+ 'sunset-orange',+ 'mint-fresh',+ 'tokyo-night',+];++// Color validation regex+export const COLOR_REGEX = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;+export const RGBA_REGEX = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d?(?:\.\d+)?))?\)$/;++// Theme metadata+export const THEME_METADATA = {+ light: {+ name: 'light' as ThemeName,+ displayName: 'Light',+ description: 'Clean and bright theme with high contrast',+ cssClass: 'theme-light',+ category: 'default',+ accessibility: 'high-contrast',+ },+ dark: {+ name: 'dark' as ThemeName,+ displayName: 'Dark',+ description: 'Dark theme with reduced eye strain',+ cssClass: 'theme-dark',+ category: 'default',+ accessibility: 'low-light',+ },+ modern: {+ name: 'modern' as ThemeName,+ displayName: 'Modern',+ description: 'Sleek modern theme with blue accents',+ cssClass: 'theme-modern',+ category: 'professional',+ accessibility: 'standard',+ },+ earth: {+ name: 'earth' as ThemeName,+ displayName: 'Earth',+ description: 'Natural theme with green and brown tones',+ cssClass: 'theme-earth',+ category: 'nature',+ accessibility: 'standard',+ },+ glass: {+ name: 'glass' as ThemeName,+ displayName: 'Glass',+ description: 'Translucent glass-like theme with purple accents',+ cssClass: 'theme-glass',+ category: 'modern',+ accessibility: 'low-contrast',+ },+ 'high-contrast': {+ name: 'high-contrast' as ThemeName,+ displayName: 'High Contrast',+ description: 'Maximum contrast theme for accessibility',+ cssClass: 'theme-high-contrast',+ category: 'accessibility',+ accessibility: 'maximum-contrast',+ },+} as const;\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/utils/chartRenderer.ts b/.claude/skills/observability/apps/client/src/utils/chartRenderer.tsnew file mode 100644index 00000000..eeb3dd8b--- /dev/null+++ b/.claude/skills/observability/apps/client/src/utils/chartRenderer.ts@@ -0,0 +1,1273 @@+import type { ChartDataPoint, ChartConfig } from '../types';++export interface ChartDimensions {+ width: number;+ height: number;+ padding: {+ top: number;+ right: number;+ bottom: number;+ left: number;+ };+}++export class ChartRenderer {+ private ctx: CanvasRenderingContext2D;+ private dimensions: ChartDimensions;+ private config: ChartConfig;+ private animationId: number | null = null;+ private currentFrameLabels: { x: number; y: number; width: number; height: number }[] = [];++ constructor(+ canvas: HTMLCanvasElement,+ dimensions: ChartDimensions,+ config: ChartConfig+ ) {+ const ctx = canvas.getContext('2d');+ if (!ctx) throw new Error('Failed to get canvas context');++ this.ctx = ctx;+ this.dimensions = dimensions;+ this.config = config;+ this.setupCanvas(canvas);+ }++ private setupCanvas(canvas: HTMLCanvasElement) {+ const dpr = window.devicePixelRatio || 1;+ canvas.width = this.dimensions.width * dpr;+ canvas.height = this.dimensions.height * dpr;+ canvas.style.width = `${this.dimensions.width}px`;+ canvas.style.height = `${this.dimensions.height}px`;+ this.ctx.scale(dpr, dpr);+ }++ private getChartArea() {+ const { width, height, padding } = this.dimensions;+ return {+ x: padding.left,+ y: padding.top,+ width: width - padding.left - padding.right,+ height: height - padding.top - padding.bottom+ };+ }++ private calculateNonOverlappingPosition(+ chartArea: { x: number; y: number; width: number; height: number },+ preferredX: number,+ labelWidth: number+ ): { x: number; y: number } | null {+ const LABEL_HEIGHT = 32;+ const MIN_SPACING = 6; // Minimum space between labels (both horizontal and vertical)+ const MAX_HORIZONTAL_OFFSET = 80; // Maximum pixels to shift horizontally+ const HORIZONTAL_OFFSET_STEP = 20; // How much to shift on each cascade level++ // Calculate vertical distribution based on label index+ // Distribute labels across full chart height instead of clustering at top+ const minY = chartArea.y + 20;+ const maxY = chartArea.y + chartArea.height - LABEL_HEIGHT - 10;+ const verticalRange = maxY - minY;++ // Use label index to determine preferred Y position (spreads them out)+ const labelIndex = this.currentFrameLabels.length;+ const preferredY = minY + (labelIndex * 47) % verticalRange; // 47px offset creates good distribution++ // If no existing labels, use distributed position+ if (this.currentFrameLabels.length === 0) {+ return { x: preferredX, y: minY };+ }++ // Helper function to check if a candidate position overlaps with any existing label+ const hasOverlap = (candidateX: number, candidateY: number): boolean => {+ for (const existing of this.currentFrameLabels) {+ // Check 2D bounding box collision+ const candidateRight = candidateX + labelWidth;+ const candidateBottom = candidateY + LABEL_HEIGHT;+ const existingRight = existing.x + existing.width;+ const existingBottom = existing.y + existing.height;++ // Add MIN_SPACING buffer to all sides+ const overlapsX = candidateX - MIN_SPACING < existingRight &&+ candidateRight + MIN_SPACING > existing.x;+ const overlapsY = candidateY - MIN_SPACING < existingBottom &&+ candidateBottom + MIN_SPACING > existing.y;++ if (overlapsX && overlapsY) {+ return true;+ }+ }+ return false;+ };++ // Try positions in a cascading pattern starting from preferred Y position+ // For each vertical level, try horizontal offsets (right, then left)+ const verticalStep = LABEL_HEIGHT + MIN_SPACING;++ // Start from preferred Y position and spiral outward (try nearby positions first)+ const tryPositions: number[] = [preferredY];+ for (let offset = verticalStep; offset <= verticalRange; offset += verticalStep) {+ if (preferredY + offset <= maxY) tryPositions.push(preferredY + offset);+ if (preferredY - offset >= minY) tryPositions.push(preferredY - offset);+ }++ let cascadeLevel = 0;+ for (const y of tryPositions) {+ // Try centered first+ if (!hasOverlap(preferredX, y)) {+ return { x: preferredX, y };+ }++ // Try cascading to the right (creates waterfall effect)+ for (let offset = HORIZONTAL_OFFSET_STEP; offset <= MAX_HORIZONTAL_OFFSET; offset += HORIZONTAL_OFFSET_STEP) {+ const rightX = preferredX + offset;+ // Make sure it doesn't go off the right edge+ if (rightX + labelWidth <= chartArea.x + chartArea.width - MIN_SPACING) {+ if (!hasOverlap(rightX, y)) {+ return { x: rightX, y };+ }+ }+ }++ // Try cascading to the left+ for (let offset = HORIZONTAL_OFFSET_STEP; offset <= MAX_HORIZONTAL_OFFSET; offset += HORIZONTAL_OFFSET_STEP) {+ const leftX = preferredX - offset;+ // Make sure it doesn't go off the left edge+ if (leftX >= chartArea.x + MIN_SPACING) {+ if (!hasOverlap(leftX, y)) {+ return { x: leftX, y };+ }+ }+ }++ cascadeLevel++;+ }++ // NO FALLBACK - return null to indicate "no space available"+ // This prevents bunching at bottom - caller will handle by hiding label+ return null;+ }++ clear() {+ this.ctx.clearRect(0, 0, this.dimensions.width, this.dimensions.height);+ this.currentFrameLabels = []; // Reset label positions for next frame+ }++ drawBackground() {+ const chartArea = this.getChartArea();++ // Create subtle gradient background+ const gradient = this.ctx.createLinearGradient(+ chartArea.x,+ chartArea.y,+ chartArea.x,+ chartArea.y + chartArea.height+ );+ gradient.addColorStop(0, 'rgba(0, 0, 0, 0.02)');+ gradient.addColorStop(1, 'rgba(0, 0, 0, 0.05)');++ this.ctx.fillStyle = gradient;+ this.ctx.fillRect(+ chartArea.x,+ chartArea.y,+ chartArea.width,+ chartArea.height+ );+ }++ drawAxes() {+ const chartArea = this.getChartArea();++ // Super thin grey horizontal line only+ this.ctx.strokeStyle = '#444444'; // Dark grey+ this.ctx.lineWidth = 0.5; // Super thin+ this.ctx.globalAlpha = 0.5; // Slightly more visible++ // X-axis (horizontal timeline) - ONLY THIS, NO Y-AXIS+ this.ctx.beginPath();+ this.ctx.moveTo(chartArea.x, chartArea.y + chartArea.height);+ this.ctx.lineTo(chartArea.x + chartArea.width, chartArea.y + chartArea.height);+ this.ctx.stroke();++ // Restore alpha+ this.ctx.globalAlpha = 1.0;+ }++ drawTimeLabels(timeRange: string) {+ const chartArea = this.getChartArea();++ const labels = this.getTimeLabels(timeRange);+ const spacing = chartArea.width / (labels.length - 1);++ // Draw vertical grid lines at time markers+ this.ctx.save();+ this.ctx.strokeStyle = '#444444'; // Dark grey+ this.ctx.lineWidth = 0.5; // Super thin+ this.ctx.globalAlpha = 0.5; // Slightly more visible++ labels.forEach((label, index) => {+ const x = chartArea.x + (index * spacing);++ // Draw vertical grid line+ this.ctx.beginPath();+ this.ctx.moveTo(x, chartArea.y);+ this.ctx.lineTo(x, chartArea.y + chartArea.height);+ this.ctx.stroke();+ });++ this.ctx.restore();++ // Draw text labels - neutral gray, thin weight+ this.ctx.fillStyle = '#565f89'; // Tokyo Night comment gray (neutral)+ this.ctx.font = '400 11px system-ui, -apple-system, sans-serif';+ this.ctx.textBaseline = 'top';++ labels.forEach((label, index) => {+ const x = chartArea.x + (index * spacing);+ const y = chartArea.y + chartArea.height + 10;++ // Adjust alignment for edge labels so they don't get clipped+ if (index === 0) {+ this.ctx.textAlign = 'left';+ } else if (index === labels.length - 1) {+ this.ctx.textAlign = 'right';+ } else {+ this.ctx.textAlign = 'center';+ }++ this.ctx.fillText(label, x, y);+ });+ }++ private getTimeLabels(timeRange: string): string[] {+ switch (timeRange) {+ case '1M':+ return ['60s', '45s', '30s', '15s', 'Now'];+ case '2M':+ return ['2m', '90s', '1m', '30s', 'Now'];+ case '4M':+ return ['4m', '3m', '2m', '1m', 'Now'];+ case '8M':+ return ['8m', '6m', '4m', '2m', 'Now'];+ case '16M':+ return ['16m', '12m', '8m', '4m', 'Now'];+ default:+ return ['60s', '45s', '30s', '15s', 'Now'];+ }+ }++ drawBars(+ dataPoints: ChartDataPoint[],+ maxValue: number,+ progress: number = 1,+ formatLabel?: (eventTypes: Record<string, number>) => string,+ getSessionColor?: (sessionId: string) => string,+ getAppColor?: (appName: string) => string+ ) {+ const chartArea = this.getChartArea();+ const barCount = this.config.maxDataPoints;+ const totalBarWidth = chartArea.width / barCount;+ const barWidth = this.config.barWidth;++ dataPoints.forEach((point, index) => {+ if (point.count === 0) return;++ const x = chartArea.x + (index * totalBarWidth) + (totalBarWidth - barWidth) / 2;+ const barHeight = (point.count / maxValue) * chartArea.height * progress;+ const y = chartArea.y + chartArea.height - barHeight;++ // Get the dominant session color for this bar+ let barColor = this.config.colors.primary;+ if (getSessionColor && point.sessions && Object.keys(point.sessions).length > 0) {+ // Get the session with the most events in this time bucket+ const dominantSession = Object.entries(point.sessions)+ .sort((a, b) => b[1] - a[1])[0][0];+ barColor = getSessionColor(dominantSession);+ }++ // Draw full-height grey vertical lines for all events+ this.ctx.save();+ this.ctx.strokeStyle = '#444444'; // Dark grey (matching grid lines)+ this.ctx.lineWidth = 0.5; // Super thin (matching grid lines)+ this.ctx.globalAlpha = 0.5; // Slightly more visible (matching grid lines)++ this.ctx.beginPath();+ this.ctx.moveTo(x + barWidth/2, chartArea.y);+ this.ctx.lineTo(x + barWidth/2, chartArea.y + chartArea.height);+ this.ctx.stroke();++ this.ctx.restore();++ // Draw timeline labels (agent name + tool pill only, matching event rows)+ if (point.eventTypes && Object.keys(point.eventTypes).length > 0 && barHeight > 10) {+ const entries = Object.entries(point.eventTypes)+ .sort((a, b) => b[1] - a[1])+ .slice(0, 3); // Top 3 event types (used for filtering display)++ if (entries.length > 0) {+ this.ctx.save();++ // Get dominant app name first to include in layout calculation+ let appName = '';+ let agentColor = '#7aa2f7'; // Default blue+ if (point.apps && Object.keys(point.apps).length > 0) {+ const dominantAppEntry = Object.entries(point.apps)+ .sort((a, b) => b[1] - a[1])[0];+ appName = dominantAppEntry[0]; // Full agent ID like "designer:abc123"++ // Extract just the agent name part (before the colon) for color lookup+ const agentNameOnly = appName.split(':')[0].toLowerCase();++ // HARDCODED colors directly - bypass function call+ const colorMap: Record<string, string> = {+ 'user': '#C084FC',+ 'pentester': '#EF4444',+ 'engineer': '#22C55E',+ 'principal-engineer': '#3B82F6',+ 'designer': '#A855F7',+ 'architect': '#A855F7',+ 'intern': '#06B6D4',+ 'artist': '#06B6D4',+ 'perplexity-researcher': '#EAB308',+ 'claude-researcher': '#EAB308',+ 'gemini-researcher': '#EAB308',+ 'grok-researcher': '#EAB308',+ 'qatester': '#EAB308',+ 'kai': '#3B82F6',+ 'claude-code': '#3B82F6',+ };++ agentColor = colorMap[agentNameOnly] || '#7aa2f7';+ }++ // Calculate total width needed (agent name + tool pill only)+ // NO event type icons - only show tool pills matching event rows++ // Measure agent name (strip session ID for display and capitalize)+ this.ctx.font = '700 13px "SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace';+ const rawDisplayName = appName ? appName.split(':')[0] : '';+ const displayName = rawDisplayName ? rawDisplayName.charAt(0).toUpperCase() + rawDisplayName.slice(1) : '';+ const agentNameWidth = displayName ? this.ctx.measureText(displayName).width : 0;++ // Calculate tool pill width (show actual tool names from events)+ let toolPillWidth = 0;+ let toolName = '';+ const toolPillGap = 6;+ const toolIconSize = 10;+ const toolIconGap = 3;+ if (point.rawEvents && point.rawEvents.length > 0) {+ // Get the most common tool name from rawEvents+ const toolCounts: Record<string, number> = {};+ for (const event of point.rawEvents) {+ const tool = event.payload?.tool_name;+ if (tool) {+ toolCounts[tool] = (toolCounts[tool] || 0) + 1;+ }+ }+ if (Object.keys(toolCounts).length > 0) {+ toolName = Object.entries(toolCounts).sort((a, b) => b[1] - a[1])[0][0];+ console.log('[Timeline] Found tool:', toolName, 'from', point.rawEvents.length, 'events');+ this.ctx.font = '600 9px "SF Mono", Monaco, monospace';+ const toolTextWidth = this.ctx.measureText(toolName).width;+ const pillPadding = 4;+ toolPillWidth = toolPillGap + toolIconSize + toolIconGap + toolTextWidth + (pillPadding * 2);+ }+ } else {+ console.log('[Timeline] No rawEvents for this point, count:', point.count);+ }++ // Calculate total width for all three pills (agent + event type + tool)+ const pillGapCalc = 6; // Gap between pills+ const pillPaddingCalc = 6; // Horizontal padding per pill++ // Agent pill width+ this.ctx.font = '700 10px "SF Mono", Monaco, monospace';+ const agentPillWidth = appName ? this.ctx.measureText(appName.split(':')[0]).width + (pillPaddingCalc * 2) : 0;++ // Event type pill width (icon + gap + text + padding)+ this.ctx.font = '600 10px system-ui, -apple-system, sans-serif';+ const eventTypeLabel = entries.length > 0 ? this.formatEventTypeLabel(entries[0][0]) : '';+ const eventPillWidth = eventTypeLabel ? 10 + 4 + this.ctx.measureText(eventTypeLabel).width + (pillPaddingCalc * 2) : 0;++ // Tool pill width (already calculated above)+ // toolPillWidth is already set++ const totalWidth = agentPillWidth ++ (agentPillWidth && eventPillWidth ? pillGapCalc : 0) ++ eventPillWidth ++ (eventPillWidth && toolPillWidth ? pillGapCalc : 0) ++ toolPillWidth;+ const padding = 8;+ const bgWidth = totalWidth + padding * 2;+ const bgHeight = 32;++ // Calculate preferred position (centered on the bar)+ const preferredCenterX = x + barWidth / 2;+ const preferredBgX = preferredCenterX - bgWidth / 2;++ // Use 2D waterfall collision detection to find non-overlapping position+ const position = this.calculateNonOverlappingPosition(chartArea, preferredBgX, bgWidth);++ // If no space available, draw minimal indicator (colored dot) instead of full label+ if (position === null) {+ this.ctx.save();++ // Draw colored dot at event position+ const dotRadius = 4;+ const dotX = preferredCenterX;+ const dotY = chartArea.y + chartArea.height - barHeight / 2;++ // Outer glow+ const glowGradient = this.ctx.createRadialGradient(dotX, dotY, 0, dotX, dotY, dotRadius * 3);+ glowGradient.addColorStop(0, agentColor + '40');+ glowGradient.addColorStop(1, 'transparent');+ this.ctx.fillStyle = glowGradient;+ this.ctx.beginPath();+ this.ctx.arc(dotX, dotY, dotRadius * 3, 0, Math.PI * 2);+ this.ctx.fill();++ // Solid colored dot+ this.ctx.fillStyle = agentColor;+ this.ctx.beginPath();+ this.ctx.arc(dotX, dotY, dotRadius, 0, Math.PI * 2);+ this.ctx.fill();++ // Inner highlight+ this.ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';+ this.ctx.beginPath();+ this.ctx.arc(dotX - dotRadius/3, dotY - dotRadius/3, dotRadius/2, 0, Math.PI * 2);+ this.ctx.fill();++ this.ctx.restore();++ // Skip drawing the full label - chart is saturated+ // Continue to next bar+ this.ctx.restore();+ return;+ }++ const bgX = position.x;+ const bgY = position.y;+ const labelY = bgY + bgHeight / 2; // Center Y from top edge++ // CRITICAL: Store label position BEFORE drawing to prevent same-frame collisions+ // This ensures subsequent labels in the same render pass see this label's position+ this.currentFrameLabels.push({+ x: bgX,+ y: bgY,+ width: bgWidth,+ height: bgHeight+ });++ // Draw leader line if label was offset from its preferred position+ const wasOffset = Math.abs(bgX - preferredBgX) > 5;+ if (wasOffset) {+ this.ctx.save();+ this.ctx.strokeStyle = agentColor + '60'; // Semi-transparent agent color+ this.ctx.lineWidth = 1.5;+ this.ctx.setLineDash([3, 3]); // Dotted line++ // Line from event bar center to label left edge+ const eventX = preferredCenterX;+ const eventY = chartArea.y + chartArea.height - barHeight / 2;+ const labelConnectionX = bgX + bgWidth / 2;+ const labelConnectionY = labelY;++ this.ctx.beginPath();+ this.ctx.moveTo(eventX, eventY);+ this.ctx.lineTo(labelConnectionX, labelConnectionY);+ this.ctx.stroke();++ this.ctx.setLineDash([]); // Reset line dash+ this.ctx.restore();+ }++ // Draw THREE pills matching event rows: Agent Name + Event Type + Tool+ let currentX = bgX + padding;+ const pillGap = 7; // gap between pills+ const pillHeight = 21; // pill height (15% larger)+ const pillPadding = 7; // horizontal padding++ // PILL 1: Agent Name Pill (muted style - no border, colored text)+ if (appName) {+ this.ctx.font = '600 11px "SF Mono", Monaco, monospace';+ const agentTextWidth = this.ctx.measureText(displayName).width;+ const agentPillWidth = agentTextWidth + (pillPadding * 2);++ const agentPillX = currentX;+ const agentPillY = labelY - (pillHeight / 2);+ const pillRadius = 4;++ // Background (15% opacity - muted)+ this.ctx.fillStyle = this.hexToRgba(agentColor, 0.15);++ this.ctx.beginPath();+ this.ctx.moveTo(agentPillX + pillRadius, agentPillY);+ this.ctx.lineTo(agentPillX + agentPillWidth - pillRadius, agentPillY);+ this.ctx.quadraticCurveTo(agentPillX + agentPillWidth, agentPillY, agentPillX + agentPillWidth, agentPillY + pillRadius);+ this.ctx.lineTo(agentPillX + agentPillWidth, agentPillY + pillHeight - pillRadius);+ this.ctx.quadraticCurveTo(agentPillX + agentPillWidth, agentPillY + pillHeight, agentPillX + agentPillWidth - pillRadius, agentPillY + pillHeight);+ this.ctx.lineTo(agentPillX + pillRadius, agentPillY + pillHeight);+ this.ctx.quadraticCurveTo(agentPillX, agentPillY + pillHeight, agentPillX, agentPillY + pillHeight - pillRadius);+ this.ctx.lineTo(agentPillX, agentPillY + pillRadius);+ this.ctx.quadraticCurveTo(agentPillX, agentPillY, agentPillX + pillRadius, agentPillY);+ this.ctx.closePath();+ this.ctx.fill();++ // Agent name text (colored)+ this.ctx.fillStyle = agentColor;+ this.ctx.textAlign = 'left';+ this.ctx.textBaseline = 'middle';+ this.ctx.fillText(displayName, agentPillX + pillPadding, labelY);++ currentX += agentPillWidth + pillGap;+ }++ // PILL 2: Event Type Pill (muted style - no border, colored text)+ if (entries.length > 0) {+ const dominantEventType = entries[0][0];+ const eventTypeColor = this.getEventTypeColor(dominantEventType);+ const eventTypeLabel = this.formatEventTypeLabel(dominantEventType);+ const eventTypeIcon = this.getEventTypeIconName(dominantEventType);++ this.ctx.font = '600 11px system-ui, -apple-system, sans-serif';+ const eventTextWidth = this.ctx.measureText(eventTypeLabel).width;+ const eventIconSize = 10;+ const eventIconGap = 4;+ const eventPillWidth = eventIconSize + eventIconGap + eventTextWidth + (pillPadding * 2);++ const eventPillX = currentX;+ const eventPillY = labelY - (pillHeight / 2);+ const eventPillRadius = 4;++ // Background (15% opacity - muted)+ this.ctx.fillStyle = this.hexToRgba(eventTypeColor, 0.15);++ this.ctx.beginPath();+ this.ctx.moveTo(eventPillX + eventPillRadius, eventPillY);+ this.ctx.lineTo(eventPillX + eventPillWidth - eventPillRadius, eventPillY);+ this.ctx.quadraticCurveTo(eventPillX + eventPillWidth, eventPillY, eventPillX + eventPillWidth, eventPillY + eventPillRadius);+ this.ctx.lineTo(eventPillX + eventPillWidth, eventPillY + pillHeight - eventPillRadius);+ this.ctx.quadraticCurveTo(eventPillX + eventPillWidth, eventPillY + pillHeight, eventPillX + eventPillWidth - eventPillRadius, eventPillY + pillHeight);+ this.ctx.lineTo(eventPillX + eventPillRadius, eventPillY + pillHeight);+ this.ctx.quadraticCurveTo(eventPillX, eventPillY + pillHeight, eventPillX, eventPillY + pillHeight - eventPillRadius);+ this.ctx.lineTo(eventPillX, eventPillY + eventPillRadius);+ this.ctx.quadraticCurveTo(eventPillX, eventPillY, eventPillX + eventPillRadius, eventPillY);+ this.ctx.closePath();+ this.ctx.fill();++ // Event type icon (colored)+ const eventIconX = eventPillX + pillPadding + eventIconSize / 2;+ const eventIconY = labelY;+ this.drawLucideIcon(eventTypeIcon, eventIconX, eventIconY, eventIconSize, eventTypeColor);++ // Event type text (colored)+ this.ctx.fillStyle = eventTypeColor;+ this.ctx.textAlign = 'left';+ this.ctx.textBaseline = 'middle';+ this.ctx.fillText(eventTypeLabel, eventPillX + pillPadding + eventIconSize + eventIconGap, labelY);++ currentX += eventPillWidth + pillGap;+ }++ // PILL 3: Tool Pill (muted style - no border, colored text)+ if (toolName) {+ const toolColor = this.getActualToolTypeColor(toolName);++ this.ctx.font = '500 11px "SF Mono", Monaco, monospace';+ const toolTextWidth = this.ctx.measureText(toolName).width;+ const toolIconSize = 10;+ const toolIconGap = 4;+ const toolPillWidth = toolIconSize + toolIconGap + toolTextWidth + (pillPadding * 2);+ const toolRadius = 4;++ const toolPillX = currentX;+ const toolPillY = labelY - (pillHeight / 2);++ // Background (15% opacity - muted)+ this.ctx.fillStyle = this.hexToRgba(toolColor, 0.15);++ this.ctx.beginPath();+ this.ctx.moveTo(toolPillX + toolRadius, toolPillY);+ this.ctx.lineTo(toolPillX + toolPillWidth - toolRadius, toolPillY);+ this.ctx.quadraticCurveTo(toolPillX + toolPillWidth, toolPillY, toolPillX + toolPillWidth, toolPillY + toolRadius);+ this.ctx.lineTo(toolPillX + toolPillWidth, toolPillY + pillHeight - toolRadius);+ this.ctx.quadraticCurveTo(toolPillX + toolPillWidth, toolPillY + pillHeight, toolPillX + toolPillWidth - toolRadius, toolPillY + pillHeight);+ this.ctx.lineTo(toolPillX + toolRadius, toolPillY + pillHeight);+ this.ctx.quadraticCurveTo(toolPillX, toolPillY + pillHeight, toolPillX, toolPillY + pillHeight - toolRadius);+ this.ctx.lineTo(toolPillX, toolPillY + toolRadius);+ this.ctx.quadraticCurveTo(toolPillX, toolPillY, toolPillX + toolRadius, toolPillY);+ this.ctx.closePath();+ this.ctx.fill();++ // Tool icon (colored)+ const toolIconX = toolPillX + pillPadding + toolIconSize / 2;+ const toolIconY = labelY;+ this.drawToolIcon(toolName, toolIconX, toolIconY, toolIconSize, toolColor);++ // Tool text (colored)+ this.ctx.fillStyle = toolColor;+ this.ctx.textAlign = 'left';+ this.ctx.textBaseline = 'middle';+ this.ctx.fillText(toolName, toolPillX + pillPadding + toolIconSize + toolIconGap, labelY);++ currentX += toolPillWidth;+ }++ // Label position already stored BEFORE drawing (see above)+ // This ensures same-frame collision detection works correctly++ this.ctx.restore();+ }+ }+ });+ }++ private getToolName(eventType: string): string {+ const toolMap: Record<string, string> = {+ 'PreToolUse': 'Tool',+ 'PostToolUse': 'Tool',+ 'Notification': 'Alert',+ 'Stop': 'Stop',+ 'SubagentStop': 'Agent',+ 'PreCompact': 'Compact',+ 'UserPromptSubmit': 'Prompt',+ 'SessionStart': 'Start',+ 'SessionEnd': 'End'+ };+ return toolMap[eventType] || '';+ }++ private getToolTypeColor(eventType: string): string {+ const colorMap: Record<string, string> = {+ 'PreToolUse': '#e0af68', // Yellow (Tokyo Night)+ 'PostToolUse': '#ff9e64', // Orange (Tokyo Night) - updated to match EventRow+ 'Completed': '#9ece6a', // Green (Tokyo Night) - for completed events+ 'Notification': '#ff9e64',+ 'Stop': '#f7768e',+ 'SubagentStop': '#bb9af7',+ 'PreCompact': '#1abc9c',+ 'UserPromptSubmit': '#7dcfff',+ 'SessionStart': '#7aa2f7',+ 'SessionEnd': '#7aa2f7'+ };+ return colorMap[eventType] || '#7aa2f7';+ }++ private getActualToolTypeColor(toolName: string): string {+ // Tool-specific colors matching EventRow useEventColors composable+ const colorMap: Record<string, string> = {+ 'Read': '#7aa2f7', // Tokyo Night blue+ 'Write': '#9ece6a', // Tokyo Night green+ 'Edit': '#e0af68', // Tokyo Night yellow+ 'Bash': '#bb9af7', // Tokyo Night purple+ 'Grep': '#f7768e', // Tokyo Night red+ 'Glob': '#ff9e64', // Tokyo Night orange+ 'Task': '#73daca', // Tokyo Night cyan+ 'WebFetch': '#7dcfff', // Tokyo Night bright cyan+ 'WebSearch': '#7dcfff', // Tokyo Night bright cyan+ 'Skill': '#c0caf5', // Tokyo Night foreground+ 'SlashCommand': '#c0caf5',+ 'TodoWrite': '#e0af68', // Tokyo Night yellow+ 'AskUserQuestion': '#bb9af7',+ 'NotebookEdit': '#9ece6a',+ 'NotebookRead': '#7aa2f7',+ 'BashOutput': '#bb9af7',+ 'KillShell': '#f7768e',+ 'ExitPlanMode': '#9ece6a'+ };+ return colorMap[toolName] || '#7aa2f7'; // Default blue+ }++ private getEventTypeColor(eventType: string): string {+ const colorMap: Record<string, string> = {+ 'PreToolUse': '#e0af68', // Tokyo Night yellow+ 'PostToolUse': '#ff9e64', // Tokyo Night orange+ 'Completed': '#9ece6a', // Tokyo Night green+ 'Notification': '#ff9e64', // Tokyo Night orange+ 'Stop': '#f7768e', // Tokyo Night red+ 'SubagentStop': '#bb9af7', // Tokyo Night magenta+ 'PreCompact': '#1abc9c', // Tokyo Night teal+ 'UserPromptSubmit': '#7dcfff', // Tokyo Night cyan+ 'SessionStart': '#7aa2f7', // Tokyo Night blue+ 'SessionEnd': '#7aa2f7' // Tokyo Night blue+ };+ return colorMap[eventType] || '#7aa2f7';+ }++ private formatEventTypeLabel(eventType: string): string {+ const labelMap: Record<string, string> = {+ 'PreToolUse': 'Pre-Tool',+ 'PostToolUse': 'Post-Tool',+ 'UserPromptSubmit': 'Prompt',+ 'SessionStart': 'Session Start',+ 'SessionEnd': 'Session End',+ 'Stop': 'Stop',+ 'SubagentStop': 'Subagent',+ 'PreCompact': 'Compact',+ 'Notification': 'Notification',+ 'Completed': 'Completed'+ };+ return labelMap[eventType] || eventType;+ }++ private getEventTypeIconName(eventType: string): string {+ const iconMap: Record<string, string> = {+ 'PreToolUse': 'wrench',+ 'PostToolUse': 'check-circle',+ 'Notification': 'bell',+ 'Stop': 'stop-circle',+ 'SubagentStop': 'user-check',+ 'PreCompact': 'package',+ 'UserPromptSubmit': 'message-square',+ 'SessionStart': 'rocket',+ 'SessionEnd': 'flag',+ 'Completed': 'check-circle'+ };+ return iconMap[eventType] || 'check-circle';+ }++ private drawBarGlow(x: number, y: number, width: number, height: number, intensity: number, color?: string) {+ const glowRadius = 10 + (intensity * 20);+ const centerX = x + width / 2;+ const centerY = y + height / 2;++ const glowColor = color || this.config.colors.glow;+ const gradient = this.ctx.createRadialGradient(+ centerX, centerY, 0,+ centerX, centerY, glowRadius+ );+ gradient.addColorStop(0, this.adjustColorOpacity(glowColor, 0.3 * intensity));+ gradient.addColorStop(1, 'transparent');++ this.ctx.fillStyle = gradient;+ this.ctx.fillRect(+ centerX - glowRadius,+ centerY - glowRadius,+ glowRadius * 2,+ glowRadius * 2+ );+ }++ private adjustColorOpacity(color: string, opacity: number): string {+ // Simple opacity adjustment - assumes hex color+ if (color.startsWith('#')) {+ const r = parseInt(color.slice(1, 3), 16);+ const g = parseInt(color.slice(3, 5), 16);+ const b = parseInt(color.slice(5, 7), 16);+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;+ }+ return color;+ }++ private hexToRgba(hex: string, opacity: number): string {+ const r = parseInt(hex.slice(1, 3), 16);+ const g = parseInt(hex.slice(3, 5), 16);+ const b = parseInt(hex.slice(5, 7), 16);+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;+ }++ drawPulseEffect(x: number, y: number, radius: number, opacity: number) {+ const gradient = this.ctx.createRadialGradient(x, y, 0, x, y, radius);+ gradient.addColorStop(0, this.adjustColorOpacity(this.config.colors.primary, opacity));+ gradient.addColorStop(0.5, this.adjustColorOpacity(this.config.colors.primary, opacity * 0.5));+ gradient.addColorStop(1, 'transparent');++ this.ctx.fillStyle = gradient;+ this.ctx.beginPath();+ this.ctx.arc(x, y, radius, 0, Math.PI * 2);+ this.ctx.fill();+ }++ animate(renderCallback: (progress: number) => void) {+ const startTime = performance.now();++ const frame = (currentTime: number) => {+ const elapsed = currentTime - startTime;+ const progress = Math.min(elapsed / this.config.animationDuration, 1);++ renderCallback(this.easeOut(progress));++ if (progress < 1) {+ this.animationId = requestAnimationFrame(frame);+ } else {+ this.animationId = null;+ }+ };++ this.animationId = requestAnimationFrame(frame);+ }++ private easeOut(t: number): number {+ return 1 - Math.pow(1 - t, 3);+ }++ stopAnimation() {+ if (this.animationId) {+ cancelAnimationFrame(this.animationId);+ this.animationId = null;+ }+ }++ resize(dimensions: ChartDimensions) {+ this.dimensions = dimensions;+ this.setupCanvas(this.ctx.canvas as HTMLCanvasElement);+ }++ // Draw Lucide icons using Path2D with exact SVG paths+ // These match the EXACT icons shown in EventRow.vue++ private drawLucideIcon(iconName: string, x: number, y: number, size: number, color: string) {+ this.ctx.save();++ // Scale and translate to position icon correctly+ // Lucide icons have 24x24 viewBox, scale to our size+ const scale = size / 24;+ this.ctx.translate(x - size/2, y - size/2);+ this.ctx.scale(scale, scale);++ this.ctx.strokeStyle = color;+ this.ctx.lineWidth = 2;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';+ this.ctx.fillStyle = 'none';++ // Exact Lucide SVG path data (from lucide-vue-next package)+ switch (iconName) {+ case 'wrench': {+ const p = new Path2D('M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z');+ this.ctx.stroke(p);+ break;+ }+ case 'check-circle': {+ const p1 = new Path2D('M22 11.08V12a10 10 0 1 1-5.93-9.14');+ const p2 = new Path2D('M9 11l3 3L22 4');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'bell': {+ const p1 = new Path2D('M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9');+ const p2 = new Path2D('M10.3 21a1.94 1.94 0 0 0 3.4 0');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'stop-circle': {+ // Circle+ this.ctx.beginPath();+ this.ctx.arc(12, 12, 10, 0, Math.PI * 2);+ this.ctx.stroke();+ // Rectangle+ this.ctx.strokeRect(9, 9, 6, 6);+ break;+ }+ case 'user-check': {+ // User path+ const p1 = new Path2D('M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2');+ // Head circle+ this.ctx.beginPath();+ this.ctx.arc(9, 7, 4, 0, Math.PI * 2);+ this.ctx.stroke();+ this.ctx.stroke(p1);+ // Checkmark+ const p2 = new Path2D('M16 11l2 2l4-4');+ this.ctx.stroke(p2);+ break;+ }+ case 'package': {+ const p1 = new Path2D('M7.5 4.27l9 5.15');+ const p2 = new Path2D('M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z');+ const p3 = new Path2D('M3.3 7l8.7 5l8.7-5');+ const p4 = new Path2D('M12 22V12');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ this.ctx.stroke(p4);+ break;+ }+ case 'message-square': {+ const p = new Path2D('M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z');+ this.ctx.stroke(p);+ break;+ }+ case 'rocket': {+ const p1 = new Path2D('M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z');+ const p2 = new Path2D('M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z');+ const p3 = new Path2D('M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0');+ const p4 = new Path2D('M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ this.ctx.stroke(p4);+ break;+ }+ case 'flag': {+ const p1 = new Path2D('M4 15s1-1 4-1s5 2 8 2s4-1 4-1V3s-1 1-4 1s-5-2-8-2s-4 1-4 1z');+ this.ctx.stroke(p1);+ // Line+ this.ctx.beginPath();+ this.ctx.moveTo(4, 15);+ this.ctx.lineTo(4, 22);+ this.ctx.stroke();+ break;+ }+ case 'eye': {+ const p1 = new Path2D('M2 12s3-7 10-7s10 7 10 7s-3 7-10 7s-10-7-10-7');+ const p2 = new Path2D('M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'file-plus': {+ const p1 = new Path2D('M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z');+ const p2 = new Path2D('M14 2v6h6');+ const p3 = new Path2D('M12 18v-6');+ const p4 = new Path2D('M9 15h6');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ this.ctx.stroke(p4);+ break;+ }+ case 'edit-3': {+ const p1 = new Path2D('M12 20h9');+ const p2 = new Path2D('M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1l1-4L16.5 3.5z');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'terminal': {+ const p1 = new Path2D('M4 17l6-6l-6-6');+ const p2 = new Path2D('M12 19h8');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'search': {+ const p1 = new Path2D('M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0 -16 0');+ const p2 = new Path2D('M21 21l-4.35-4.35');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'folder-search': {+ const p1 = new Path2D('M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z');+ const p2 = new Path2D('M11.5 12.5m-2.5 0a2.5 2.5 0 1 0 5 0a2.5 2.5 0 1 0 -5 0');+ const p3 = new Path2D('M13.3 14.3l1.7 1.7');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ break;+ }+ case 'users': {+ const p1 = new Path2D('M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2');+ const p2 = new Path2D('M23 21v-2a4 4 0 0 0-3-3.87');+ const p3 = new Path2D('M16 3.13a4 4 0 0 1 0 7.75');+ this.ctx.beginPath();+ this.ctx.arc(9, 7, 4, 0, Math.PI * 2);+ this.ctx.stroke();+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ break;+ }+ case 'globe': {+ const p1 = new Path2D('M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0 -20 0');+ const p2 = new Path2D('M2 12h20');+ const p3 = new Path2D('M12 2a15.3 15.3 0 0 1 4 10a15.3 15.3 0 0 1-4 10a15.3 15.3 0 0 1-4-10a15.3 15.3 0 0 1 4-10z');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ break;+ }+ case 'compass': {+ const p1 = new Path2D('M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0 -20 0');+ const p2 = new Path2D('M16.24 7.76l-2.12 6.36l-6.36 2.12l2.12-6.36l6.36-2.12z');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'zap': {+ const p1 = new Path2D('M13 2L3 14h9l-1 8l10-12h-9l1-8z');+ this.ctx.stroke(p1);+ break;+ }+ case 'command': {+ const p1 = new Path2D('M18 3a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3a3 3 0 0 0 3-3a3 3 0 0 0-3-3H6a3 3 0 0 0-3 3a3 3 0 0 0 3 3a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3a3 3 0 0 0-3 3a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3a3 3 0 0 0-3-3z');+ this.ctx.stroke(p1);+ break;+ }+ case 'check-square': {+ const p1 = new Path2D('M9 11l3 3L22 4');+ const p2 = new Path2D('M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'message-circle-question': {+ const p1 = new Path2D('M7.9 20A9 9 0 1 0 4 16.1L2 22Z');+ const p2 = new Path2D('M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.beginPath();+ this.ctx.arc(12, 17, 0.1, 0, Math.PI * 2);+ this.ctx.fill();+ break;+ }+ case 'book-open': {+ const p1 = new Path2D('M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z');+ const p2 = new Path2D('M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ break;+ }+ case 'file-text': {+ const p1 = new Path2D('M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z');+ const p2 = new Path2D('M14 2v6h6');+ const p3 = new Path2D('M16 13H8');+ const p4 = new Path2D('M16 17H8');+ const p5 = new Path2D('M10 9H8');+ this.ctx.stroke(p1);+ this.ctx.stroke(p2);+ this.ctx.stroke(p3);+ this.ctx.stroke(p4);+ this.ctx.stroke(p5);+ break;+ }+ }++ this.ctx.restore();+ }++ // Draw tool-specific icons (matching EventRow tool icons)+ private drawToolIcon(toolName: string, x: number, y: number, size: number, color: string) {+ const iconMap: Record<string, string> = {+ 'Read': 'eye',+ 'Write': 'file-plus',+ 'Edit': 'edit-3',+ 'Bash': 'terminal',+ 'Grep': 'search',+ 'Glob': 'folder-search',+ 'Task': 'users',+ 'WebFetch': 'globe',+ 'WebSearch': 'compass',+ 'Skill': 'zap',+ 'SlashCommand': 'command',+ 'TodoWrite': 'check-square',+ 'AskUserQuestion': 'message-circle-question',+ 'NotebookEdit': 'book-open',+ 'NotebookRead': 'file-text',+ 'BashOutput': 'terminal',+ 'KillShell': 'terminal',+ 'ExitPlanMode': 'check-circle'+ };++ const lucideIconName = iconMap[toolName];+ if (lucideIconName) {+ this.drawLucideIcon(lucideIconName, x, y, size, color);+ } else {+ // Fallback: draw small circle for unknown tools+ this.ctx.save();+ this.ctx.fillStyle = color;+ this.ctx.beginPath();+ this.ctx.arc(x, y, size / 3, 0, Math.PI * 2);+ this.ctx.fill();+ this.ctx.restore();+ }+ }++ private drawWrench(x: number, y: number, size: number) {+ // This will be replaced with SVG rendering in the main draw loop+ }++ private drawCheckmark(x: number, y: number, size: number) {+ // CheckCircle icon - matches Lucide CheckCircle (PostToolUse)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Outer circle+ this.ctx.beginPath();+ this.ctx.arc(x, y, size/2.2, 0, Math.PI * 2);+ this.ctx.stroke();++ // Checkmark inside+ this.ctx.beginPath();+ this.ctx.moveTo(x - size/4, y);+ this.ctx.lineTo(x - size/10, y + size/4);+ this.ctx.lineTo(x + size/3, y - size/3);+ this.ctx.stroke();+ }++ private drawBell(x: number, y: number, size: number) {+ // Bell icon - matches Lucide Bell (Notification)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Bell body (curved trapezoid)+ this.ctx.beginPath();+ this.ctx.moveTo(x, y - size/2.2);+ this.ctx.bezierCurveTo(x - size/2.5, y - size/3, x - size/2.5, y, x - size/2.5, y + size/5);+ this.ctx.lineTo(x + size/2.5, y + size/5);+ this.ctx.bezierCurveTo(x + size/2.5, y, x + size/2.5, y - size/3, x, y - size/2.2);+ this.ctx.stroke();++ // Bell bottom line+ this.ctx.beginPath();+ this.ctx.moveTo(x - size/2.8, y + size/5);+ this.ctx.lineTo(x + size/2.8, y + size/5);+ this.ctx.stroke();++ // Bell clapper (small arc)+ this.ctx.beginPath();+ this.ctx.arc(x, y + size/2.5, size/10, 0, Math.PI * 2);+ this.ctx.stroke();+ }++ private drawStopCircle(x: number, y: number, size: number) {+ // StopCircle icon - matches Lucide StopCircle (Stop)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Outer circle+ this.ctx.beginPath();+ this.ctx.arc(x, y, size/2.2, 0, Math.PI * 2);+ this.ctx.stroke();++ // Inner square (stroke only, not filled)+ const squareSize = size/3.5;+ this.ctx.beginPath();+ this.ctx.rect(x - squareSize/2, y - squareSize/2, squareSize, squareSize);+ this.ctx.stroke();+ }++ private drawUsers(x: number, y: number, size: number) {+ // Users icon - matches Lucide Users (SubagentStop)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Left person+ this.ctx.beginPath();+ this.ctx.arc(x - size/4, y - size/5, size/7, 0, Math.PI * 2);+ this.ctx.stroke();+ this.ctx.beginPath();+ this.ctx.arc(x - size/4, y + size/3, size/3.5, Math.PI * 1.1, Math.PI * 1.9);+ this.ctx.stroke();++ // Right person+ this.ctx.beginPath();+ this.ctx.arc(x + size/4, y - size/5, size/7, 0, Math.PI * 2);+ this.ctx.stroke();+ this.ctx.beginPath();+ this.ctx.arc(x + size/4, y + size/3, size/3.5, Math.PI * 1.1, Math.PI * 1.9);+ this.ctx.stroke();+ }++ private drawPackage(x: number, y: number, size: number) {+ // Package icon - matches Lucide Package (PreCompact)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Box outline+ const boxSize = size * 0.85;+ this.ctx.beginPath();+ this.ctx.rect(x - boxSize/2, y - boxSize/2, boxSize, boxSize);+ this.ctx.stroke();++ // Cross lines+ this.ctx.beginPath();+ this.ctx.moveTo(x - boxSize/2, y);+ this.ctx.lineTo(x + boxSize/2, y);+ this.ctx.moveTo(x, y - boxSize/2);+ this.ctx.lineTo(x, y + boxSize/2);+ this.ctx.stroke();+ }++ private drawMessage(x: number, y: number, size: number) {+ // MessageSquare icon - matches Lucide MessageSquare (UserPromptSubmit)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Rounded rectangle+ const rectSize = size * 0.8;+ const radius = size/5;+ this.ctx.beginPath();+ this.ctx.moveTo(x - rectSize/2 + radius, y - rectSize/2);+ this.ctx.arcTo(x + rectSize/2, y - rectSize/2, x + rectSize/2, y + rectSize/2, radius);+ this.ctx.arcTo(x + rectSize/2, y + rectSize/2, x - rectSize/2, y + rectSize/2, radius);+ this.ctx.arcTo(x - rectSize/2, y + rectSize/2, x - rectSize/2, y - rectSize/2, radius);+ this.ctx.arcTo(x - rectSize/2, y - rectSize/2, x + rectSize/2, y - rectSize/2, radius);+ this.ctx.stroke();+ }++ private drawRocket(x: number, y: number, size: number) {+ // Rocket icon - matches Lucide Rocket (SessionStart)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Rocket body+ this.ctx.beginPath();+ this.ctx.moveTo(x, y - size/2);+ this.ctx.lineTo(x - size/3, y);+ this.ctx.lineTo(x - size/3, y + size/3);+ this.ctx.lineTo(x + size/3, y + size/3);+ this.ctx.lineTo(x + size/3, y);+ this.ctx.closePath();+ this.ctx.stroke();++ // Fins+ this.ctx.beginPath();+ this.ctx.moveTo(x - size/3, y + size/6);+ this.ctx.lineTo(x - size/1.8, y + size/2.5);+ this.ctx.moveTo(x + size/3, y + size/6);+ this.ctx.lineTo(x + size/1.8, y + size/2.5);+ this.ctx.stroke();++ // Window+ this.ctx.beginPath();+ this.ctx.arc(x, y - size/8, size/8, 0, Math.PI * 2);+ this.ctx.stroke();+ }++ private drawFlag(x: number, y: number, size: number) {+ // Flag icon - matches Lucide Flag (SessionEnd)+ // Stroke-only, no fill+ this.ctx.lineWidth = 3;+ this.ctx.lineCap = 'round';+ this.ctx.lineJoin = 'round';++ // Flag pole+ this.ctx.beginPath();+ this.ctx.moveTo(x - size/2.5, y - size/2);+ this.ctx.lineTo(x - size/2.5, y + size/2);+ this.ctx.stroke();++ // Flag fabric+ this.ctx.beginPath();+ this.ctx.moveTo(x - size/2.5, y - size/2);+ this.ctx.lineTo(x + size/3, y - size/3);+ this.ctx.lineTo(x + size/3, y + size/8);+ this.ctx.lineTo(x - size/2.5, y + size/6);+ this.ctx.stroke();+ }+}++export function createChartRenderer(+ canvas: HTMLCanvasElement,+ dimensions: ChartDimensions,+ config: ChartConfig+): ChartRenderer {+ return new ChartRenderer(canvas, dimensions, config);+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/src/utils/haiku.ts b/.claude/skills/observability/apps/client/src/utils/haiku.tsnew file mode 100644index 00000000..b031fc30--- /dev/null+++ b/.claude/skills/observability/apps/client/src/utils/haiku.ts@@ -0,0 +1,146 @@+/**+ * Haiku API Integration for Timeline Intelligence+ * Provides fast, cheap summarization for event clustering+ * Uses backend proxy to read API key from ~/.claude/.env+ */++import type { HookEvent } from '../types';++const BACKEND_PROXY = 'http://localhost:4000/api/haiku/summarize';++// Track API call statistics+let apiCallCount = 0;++export interface EventSummary {+ text: string;+ agentType: string;+ eventCount: number;+ timestamp: number;+}++/**+ * Get the total number of Haiku API calls made+ */+export function getHaikuCallCount(): number {+ return apiCallCount;+}++/**+ * Reset the Haiku API call counter+ */+export function resetHaikuCallCount(): void {+ apiCallCount = 0;+}++/**+ * Summarize a batch of events using Haiku+ * @param events Array of events to summarize+ * @returns Concise summary suitable for timeline display+ */+export async function summarizeEvents(events: HookEvent[]): Promise<EventSummary> {+ if (events.length === 0) {+ return {+ text: 'No activity',+ agentType: 'unknown',+ eventCount: 0,+ timestamp: Date.now()+ };+ }++ // Single event - no summarization needed+ if (events.length === 1) {+ const event = events[0];+ return {+ text: formatSingleEvent(event),+ agentType: event.source_app,+ eventCount: 1,+ timestamp: event.timestamp || Date.now()+ };+ }++ // Multiple events - use Haiku to summarize+ try {+ const eventDescriptions = events.map((e, i) =>+ `${i + 1}. ${e.source_app} (${e.hook_event_type})`+ ).join('\n');++ const prompt = `Summarize these ${events.length} agent events in 3-5 words using format "Verbing noun" or "N agent actions" (e.g., "Processing API requests", "27 intern actions", "Updating config files"). Output ONLY the summary text:++${eventDescriptions}`;++ const response = await fetch(BACKEND_PROXY, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ prompt })+ });++ if (!response.ok) {+ throw new Error(`Haiku proxy error: ${response.status}`);+ }++ const data = await response.json();+ if (!data.success) {+ throw new Error(data.error || 'Summarization failed');+ }++ // Increment API call counter on successful call+ apiCallCount++;++ const summaryText = data.text?.trim() || `${events.length} events`;++ // Determine primary agent type (most frequent)+ const agentCounts = events.reduce((acc, e) => {+ acc[e.source_app] = (acc[e.source_app] || 0) + 1;+ return acc;+ }, {} as Record<string, number>);+ const primaryAgent = Object.entries(agentCounts).sort((a, b) => b[1] - a[1])[0][0];++ return {+ text: summaryText,+ agentType: primaryAgent,+ eventCount: events.length,+ timestamp: events[events.length - 1].timestamp || Date.now()+ };+ } catch (error) {+ console.error('Haiku summarization failed:', error);+ // Fallback to simple count+ return {+ text: `${events.length} ${events[0].source_app} actions`,+ agentType: events[0].source_app,+ eventCount: events.length,+ timestamp: events[events.length - 1].timestamp || Date.now()+ };+ }+}++/**+ * Format a single event for display+ */+function formatSingleEvent(event: HookEvent): string {+ const type = event.hook_event_type;+ const app = event.source_app;++ // Map event types to readable labels+ const typeMap: Record<string, string> = {+ 'PreToolUse': 'tool call',+ 'PostToolUse': 'tool result',+ 'Stop': 'completed',+ 'AgentStart': 'started',+ 'AgentStop': 'finished',+ 'PreCompact': 'compacting'+ };++ const label = typeMap[type] || type.toLowerCase();+ return `${app} ${label}`;+}++/**+ * Check if backend proxy is available (API key configured in ~/.claude/.env)+ */+export function isHaikuConfigured(): boolean {+ // Always return true - backend will handle API key check+ // If key is missing, backend returns error and we fall back gracefully+ return true;+}diff --git a/.claude/skills/observability/apps/client/src/utils/obfuscate.ts b/.claude/skills/observability/apps/client/src/utils/obfuscate.tsnew file mode 100644index 00000000..8ef0743c--- /dev/null+++ b/.claude/skills/observability/apps/client/src/utils/obfuscate.ts@@ -0,0 +1,198 @@+/**+ * Security utility for obfuscating sensitive data in displayed output+ * Prevents API keys, tokens, and other secrets from being visible in recordings+ */++/**+ * Patterns for detecting sensitive data+ */+const SENSITIVE_PATTERNS = [+ // API Keys+ { name: 'OpenAI API Key', pattern: /sk-proj-[a-zA-Z0-9_-]{20,}/g },+ { name: 'OpenAI API Key (legacy)', pattern: /sk-[a-zA-Z0-9]{48}/g },+ { name: 'Anthropic API Key', pattern: /sk-ant-api03-[a-zA-Z0-9_-]{95}/g },+ { name: 'Google API Key', pattern: /AIza[0-9A-Za-z_-]{35}/g },+ { name: 'AWS Access Key', pattern: /AKIA[0-9A-Z]{16}/g },+ { name: 'GitHub Token', pattern: /gh[pousr]_[A-Za-z0-9_]{36,}/g },+ { name: 'Stripe Key', pattern: /sk_live_[0-9a-zA-Z]{24,}/g },+ { name: 'Generic API Key', pattern: /[a-zA-Z0-9]{32,}/g }, // Catch-all for long alphanumeric strings++ // Tokens+ { name: 'JWT Token', pattern: /eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g },+ { name: 'Bearer Token', pattern: /Bearer\s+[a-zA-Z0-9_-]{20,}/gi },++ // Passwords and secrets+ { name: 'Password Field', pattern: /(password|passwd|pwd)["']?\s*[:=]\s*["']?([^"'\s,}]+)/gi },+ { name: 'Secret Field', pattern: /(secret|token|key)["']?\s*[:=]\s*["']?([^"'\s,}]+)/gi },++ // AWS Secrets+ { name: 'AWS Secret Key', pattern: /[A-Za-z0-9/+=]{40}/g },++ // Email addresses (optionally obfuscate)+ { name: 'Email', pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g },++ // IP addresses (internal networks)+ { name: 'Private IP', pattern: /\b(?:10|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b/g },++ // Credit card numbers+ { name: 'Credit Card', pattern: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g },++ // Social Security Numbers+ { name: 'SSN', pattern: /\b\d{3}-\d{2}-\d{4}\b/g },+];++/**+ * Key names that indicate sensitive data+ */+const SENSITIVE_KEY_NAMES = [+ 'password',+ 'passwd',+ 'pwd',+ 'secret',+ 'token',+ 'api_key',+ 'apikey',+ 'api-key',+ 'access_token',+ 'refresh_token',+ 'private_key',+ 'privatekey',+ 'auth',+ 'authorization',+ 'credential',+ 'credentials',+ 'aws_access_key_id',+ 'aws_secret_access_key',+ 'stripe_key',+ 'anthropic_api_key',+ 'openai_api_key',+];++/**+ * Obfuscate a single value+ */+function obfuscateValue(value: string, showChars: number = 4): string {+ if (value.length <= showChars * 2) {+ return '*'.repeat(value.length);+ }++ const start = value.slice(0, showChars);+ const end = value.slice(-showChars);+ const middle = '*'.repeat(Math.min(20, value.length - showChars * 2)); // Cap at 20 stars++ return `${start}${middle}${end}`;+}++/**+ * Check if a key name suggests sensitive data+ */+function isSensitiveKeyName(key: string): boolean {+ const lowerKey = key.toLowerCase();+ return SENSITIVE_KEY_NAMES.some(sensitive => lowerKey.includes(sensitive));+}++/**+ * Check if string is a file path in .claude directory+ */+function isClaudeDirectoryPath(text: string): boolean {+ // Match any user's .claude directory path+ return text.includes('/.claude/') || /^\/Users\/[^/]+\/\.claude/.test(text);+}++/**+ * Obfuscate sensitive data in a string+ */+export function obfuscateString(text: string): string {+ // Don't obfuscate file paths in .claude directory+ if (isClaudeDirectoryPath(text)) {+ return text;+ }++ let result = text;++ // Apply each pattern+ for (const { pattern } of SENSITIVE_PATTERNS) {+ result = result.replace(pattern, (match) => {+ // Don't obfuscate very short matches (likely false positives)+ if (match.length < 10) return match;++ return obfuscateValue(match);+ });+ }++ return result;+}++/**+ * Obfuscate sensitive data in a JSON object (recursively)+ */+export function obfuscateObject(obj: any, depth: number = 0): any {+ // Prevent infinite recursion+ if (depth > 10) return obj;++ if (obj === null || obj === undefined) return obj;++ // Handle arrays+ if (Array.isArray(obj)) {+ return obj.map(item => obfuscateObject(item, depth + 1));+ }++ // Handle objects+ if (typeof obj === 'object') {+ const result: any = {};++ for (const [key, value] of Object.entries(obj)) {+ // Check if key name suggests sensitive data+ if (isSensitiveKeyName(key)) {+ if (typeof value === 'string') {+ result[key] = obfuscateValue(value);+ } else {+ result[key] = '***REDACTED***';+ }+ } else if (typeof value === 'string') {+ // Check string value for sensitive patterns+ result[key] = obfuscateString(value);+ } else if (typeof value === 'object') {+ // Recursively process nested objects+ result[key] = obfuscateObject(value, depth + 1);+ } else {+ // Pass through other types (numbers, booleans, etc.)+ result[key] = value;+ }+ }++ return result;+ }++ // Handle primitive strings+ if (typeof obj === 'string') {+ return obfuscateString(obj);+ }++ // Pass through other primitives+ return obj;+}++/**+ * Obfuscate sensitive data in JSON string+ */+export function obfuscateJSON(jsonString: string): string {+ try {+ const obj = JSON.parse(jsonString);+ const obfuscated = obfuscateObject(obj);+ return JSON.stringify(obfuscated, null, 2);+ } catch (error) {+ // If not valid JSON, treat as plain text+ return obfuscateString(jsonString);+ }+}++/**+ * Quick check if text contains potentially sensitive data+ */+export function containsSensitiveData(text: string): boolean {+ return SENSITIVE_PATTERNS.some(({ pattern }) => {+ const regex = new RegExp(pattern.source, pattern.flags);+ return regex.test(text);+ });+}diff --git a/.claude/skills/observability/apps/client/src/vite-env.d.ts b/.claude/skills/observability/apps/client/src/vite-env.d.tsnew file mode 100644index 00000000..11f02fe2--- /dev/null+++ b/.claude/skills/observability/apps/client/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/.claude/skills/observability/apps/client/tailwind.config.js b/.claude/skills/observability/apps/client/tailwind.config.jsnew file mode 100644index 00000000..53cbf2af--- /dev/null+++ b/.claude/skills/observability/apps/client/tailwind.config.js@@ -0,0 +1,146 @@+/** @type {import('tailwindcss').Config} */+export default {+ content: [+ "./index.html",+ "./src/**/*.{vue,js,ts,jsx,tsx}",+ ],+ darkMode: 'class',+ theme: {+ extend: {+ fontFamily: {+ "equity-text-b": ["equity-text-b", "Georgia", "serif"],+ "concourse-t3": ["concourse-t3", "sans-serif"],+ "concourse-c3": ["concourse-c3", "sans-serif"],+ "advocate": ["advocate", "sans-serif"],+ "valkyrie-text": ["valkyrie-text", "Georgia", "serif"],+ "sans": ["concourse-t3", "system-ui", "-apple-system", "sans-serif"],+ "serif": ["valkyrie-text", "Georgia", "serif"],+ "mono": ["ui-monospace", "SFMono-Regular", "monospace"],+ },+ screens: {+ 'mobile': {'max': '699px'}, // Custom mobile breakpoint for < 700px+ 'short': {'raw': '(max-height: 400px)'}, // Custom breakpoint for height <= 400px+ },+ colors: {+ // Theme-aware colors using CSS custom properties+ 'theme': {+ 'primary': 'var(--theme-primary)',+ 'primary-hover': 'var(--theme-primary-hover)',+ 'primary-light': 'var(--theme-primary-light)',+ 'primary-dark': 'var(--theme-primary-dark)',+ 'bg': {+ 'primary': 'var(--theme-bg-primary)',+ 'secondary': 'var(--theme-bg-secondary)',+ 'tertiary': 'var(--theme-bg-tertiary)',+ 'quaternary': 'var(--theme-bg-quaternary)',+ },+ 'text': {+ 'primary': 'var(--theme-text-primary)',+ 'secondary': 'var(--theme-text-secondary)',+ 'tertiary': 'var(--theme-text-tertiary)',+ 'quaternary': 'var(--theme-text-quaternary)',+ },+ 'border': {+ 'primary': 'var(--theme-border-primary)',+ 'secondary': 'var(--theme-border-secondary)',+ 'tertiary': 'var(--theme-border-tertiary)',+ },+ 'accent': {+ 'success': 'var(--theme-accent-success)',+ 'warning': 'var(--theme-accent-warning)',+ 'error': 'var(--theme-accent-error)',+ 'info': 'var(--theme-accent-info)',+ }+ }+ },+ boxShadow: {+ 'theme': 'var(--theme-shadow)',+ 'theme-lg': 'var(--theme-shadow-lg)',+ },+ transitionProperty: {+ 'theme': 'var(--theme-transition)',+ 'theme-fast': 'var(--theme-transition-fast)',+ }+ },+ },+ plugins: [],+ safelist: [+ // Background colors+ 'bg-blue-500',+ 'bg-green-500',+ 'bg-yellow-500',+ 'bg-purple-500',+ 'bg-pink-500',+ 'bg-indigo-500',+ 'bg-red-500',+ 'bg-orange-500',+ 'bg-teal-500',+ 'bg-cyan-500',+ // Border colors+ 'border-blue-500',+ 'border-green-500',+ 'border-yellow-500',+ 'border-purple-500',+ 'border-pink-500',+ 'border-indigo-500',+ 'border-red-500',+ 'border-orange-500',+ 'border-teal-500',+ 'border-cyan-500',+ // Gradient colors+ 'from-blue-500',+ 'to-blue-600',+ 'from-green-500',+ 'to-green-600',+ 'from-yellow-500',+ 'to-yellow-600',+ 'from-purple-500',+ 'to-purple-600',+ 'from-pink-500',+ 'to-pink-600',+ 'from-indigo-500',+ 'to-indigo-600',+ 'from-red-500',+ 'to-red-600',+ 'from-orange-500',+ 'to-orange-600',+ 'from-teal-500',+ 'to-teal-600',+ 'from-cyan-500',+ 'to-cyan-600',+ // Theme classes+ 'theme-bg-primary',+ 'theme-bg-secondary',+ 'theme-bg-tertiary',+ 'theme-bg-quaternary',+ 'theme-text-primary',+ 'theme-text-secondary',+ 'theme-text-tertiary',+ 'theme-text-quaternary',+ 'theme-border-primary',+ 'theme-border-secondary',+ 'theme-border-tertiary',+ 'theme-primary',+ 'theme-primary-bg',+ 'theme-primary-border',+ 'theme-accent-success',+ 'theme-accent-warning',+ 'theme-accent-error',+ 'theme-accent-info',+ 'theme-shadow',+ 'theme-shadow-lg',+ 'theme-transition',+ 'theme-transition-fast',+ 'theme-hover',+ 'theme-active',+ 'theme-focus',+ 'backdrop-blur',+ // Theme class names+ 'theme-light',+ 'theme-dark',+ 'theme-modern',+ 'theme-earth',+ 'theme-glass',+ 'theme-high-contrast',+ ]+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/client/tsconfig.app.json b/.claude/skills/observability/apps/client/tsconfig.app.jsonnew file mode 100644index 00000000..3dbbc453--- /dev/null+++ b/.claude/skills/observability/apps/client/tsconfig.app.json@@ -0,0 +1,15 @@+{+ "extends": "@vue/tsconfig/tsconfig.dom.json",+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]+}diff --git a/.claude/skills/observability/apps/client/tsconfig.json b/.claude/skills/observability/apps/client/tsconfig.jsonnew file mode 100644index 00000000..1ffef600--- /dev/null+++ b/.claude/skills/observability/apps/client/tsconfig.json@@ -0,0 +1,7 @@+{+ "files": [],+ "references": [+ { "path": "./tsconfig.app.json" },+ { "path": "./tsconfig.node.json" }+ ]+}diff --git a/.claude/skills/observability/apps/client/tsconfig.node.json b/.claude/skills/observability/apps/client/tsconfig.node.jsonnew file mode 100644index 00000000..f85a3990--- /dev/null+++ b/.claude/skills/observability/apps/client/tsconfig.node.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",+ "target": "ES2023",+ "lib": ["ES2023"],+ "module": "ESNext",+ "skipLibCheck": true,++ /* Bundler mode */+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["vite.config.ts"]+}diff --git a/.claude/skills/observability/apps/client/vite.config.ts b/.claude/skills/observability/apps/client/vite.config.tsnew file mode 100644index 00000000..08eed689--- /dev/null+++ b/.claude/skills/observability/apps/client/vite.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from 'vite'+import vue from '@vitejs/plugin-vue'++// https://vite.dev/config/+export default defineConfig({+ plugins: [vue()],+ server: {+ port: 5172,+ strictPort: true,+ },+})diff --git a/.claude/skills/observability/apps/server/.gitignore b/.claude/skills/observability/apps/server/.gitignorenew file mode 100644index 00000000..f83520fc--- /dev/null+++ b/.claude/skills/observability/apps/server/.gitignore@@ -0,0 +1,11 @@+# Database files (too large for git)+events.db+events.db-shm+events.db-wal++# Logs+*.log+logs/++# Dependencies+node_modules/diff --git a/.claude/skills/observability/apps/server/package.json b/.claude/skills/observability/apps/server/package.jsonnew file mode 100644index 00000000..cadaeb2b--- /dev/null+++ b/.claude/skills/observability/apps/server/package.json@@ -0,0 +1,18 @@+{+ "name": "multi-agent-observability-server",+ "version": "1.2.0",+ "module": "src/index.ts",+ "type": "module",+ "private": true,+ "scripts": {+ "dev": "bun --watch src/index.ts",+ "start": "bun src/index.ts",+ "typecheck": "tsc --noEmit"+ },+ "devDependencies": {+ "@types/bun": "latest",+ "@types/ws": "^8.5.13",+ "typescript": "^5.8.3"+ },+ "dependencies": {}+}diff --git a/.claude/skills/observability/apps/server/src/db.ts b/.claude/skills/observability/apps/server/src/db.tsnew file mode 100644index 00000000..57cdfab1--- /dev/null+++ b/.claude/skills/observability/apps/server/src/db.ts@@ -0,0 +1,225 @@+import { Database } from 'bun:sqlite';+import type { Theme, ThemeSearchQuery } from './types';++let db: Database;++export function initDatabase(): void {+ db = new Database('themes.db');++ // Enable WAL mode for better concurrent performance+ db.exec('PRAGMA journal_mode = WAL');+ db.exec('PRAGMA synchronous = NORMAL');++ // Create themes table+ db.exec(`+ CREATE TABLE IF NOT EXISTS themes (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ displayName TEXT NOT NULL,+ description TEXT,+ colors TEXT NOT NULL,+ isPublic INTEGER NOT NULL DEFAULT 0,+ authorId TEXT,+ authorName TEXT,+ createdAt INTEGER NOT NULL,+ updatedAt INTEGER NOT NULL,+ tags TEXT,+ downloadCount INTEGER DEFAULT 0,+ rating REAL DEFAULT 0,+ ratingCount INTEGER DEFAULT 0+ )+ `);++ // Create theme shares table+ db.exec(`+ CREATE TABLE IF NOT EXISTS theme_shares (+ id TEXT PRIMARY KEY,+ themeId TEXT NOT NULL,+ shareToken TEXT NOT NULL UNIQUE,+ expiresAt INTEGER,+ isPublic INTEGER NOT NULL DEFAULT 0,+ allowedUsers TEXT,+ createdAt INTEGER NOT NULL,+ accessCount INTEGER DEFAULT 0,+ FOREIGN KEY (themeId) REFERENCES themes (id) ON DELETE CASCADE+ )+ `);++ // Create theme ratings table+ db.exec(`+ CREATE TABLE IF NOT EXISTS theme_ratings (+ id TEXT PRIMARY KEY,+ themeId TEXT NOT NULL,+ userId TEXT NOT NULL,+ rating INTEGER NOT NULL,+ comment TEXT,+ createdAt INTEGER NOT NULL,+ UNIQUE(themeId, userId),+ FOREIGN KEY (themeId) REFERENCES themes (id) ON DELETE CASCADE+ )+ `);++ // Create indexes for theme tables+ db.exec('CREATE INDEX IF NOT EXISTS idx_themes_name ON themes(name)');+ db.exec('CREATE INDEX IF NOT EXISTS idx_themes_isPublic ON themes(isPublic)');+ db.exec('CREATE INDEX IF NOT EXISTS idx_themes_createdAt ON themes(createdAt)');+ db.exec('CREATE INDEX IF NOT EXISTS idx_theme_shares_token ON theme_shares(shareToken)');+ db.exec('CREATE INDEX IF NOT EXISTS idx_theme_ratings_theme ON theme_ratings(themeId)');+}++// Theme database functions+export function insertTheme(theme: Theme): Theme {+ const stmt = db.prepare(`+ INSERT INTO themes (id, name, displayName, description, colors, isPublic, authorId, authorName, createdAt, updatedAt, tags, downloadCount, rating, ratingCount)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `);++ stmt.run(+ theme.id,+ theme.name,+ theme.displayName,+ theme.description || null,+ JSON.stringify(theme.colors),+ theme.isPublic ? 1 : 0,+ theme.authorId || null,+ theme.authorName || null,+ theme.createdAt,+ theme.updatedAt,+ JSON.stringify(theme.tags),+ theme.downloadCount || 0,+ theme.rating || 0,+ theme.ratingCount || 0+ );++ return theme;+}++export function updateTheme(id: string, updates: Partial<Theme>): boolean {+ const allowedFields = ['displayName', 'description', 'colors', 'isPublic', 'updatedAt', 'tags'];+ const setClause = Object.keys(updates)+ .filter(key => allowedFields.includes(key))+ .map(key => `${key} = ?`)+ .join(', ');++ if (!setClause) return false;++ const values = Object.keys(updates)+ .filter(key => allowedFields.includes(key))+ .map(key => {+ if (key === 'colors' || key === 'tags') {+ return JSON.stringify(updates[key as keyof Theme]);+ }+ if (key === 'isPublic') {+ return updates[key as keyof Theme] ? 1 : 0;+ }+ return updates[key as keyof Theme];+ });++ const stmt = db.prepare(`UPDATE themes SET ${setClause} WHERE id = ?`);+ const result = stmt.run(...values, id);++ return result.changes > 0;+}++export function getTheme(id: string): Theme | null {+ const stmt = db.prepare('SELECT * FROM themes WHERE id = ?');+ const row = stmt.get(id) as any;++ if (!row) return null;++ return {+ id: row.id,+ name: row.name,+ displayName: row.displayName,+ description: row.description,+ colors: JSON.parse(row.colors),+ isPublic: Boolean(row.isPublic),+ authorId: row.authorId,+ authorName: row.authorName,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ tags: JSON.parse(row.tags || '[]'),+ downloadCount: row.downloadCount,+ rating: row.rating,+ ratingCount: row.ratingCount+ };+}++export function getThemes(query: ThemeSearchQuery = {}): Theme[] {+ let sql = 'SELECT * FROM themes WHERE 1=1';+ const params: any[] = [];++ if (query.isPublic !== undefined) {+ sql += ' AND isPublic = ?';+ params.push(query.isPublic ? 1 : 0);+ }++ if (query.authorId) {+ sql += ' AND authorId = ?';+ params.push(query.authorId);+ }++ if (query.query) {+ sql += ' AND (name LIKE ? OR displayName LIKE ? OR description LIKE ?)';+ const searchTerm = `%${query.query}%`;+ params.push(searchTerm, searchTerm, searchTerm);+ }++ // Add sorting+ const sortBy = query.sortBy || 'created';+ const sortOrder = query.sortOrder || 'desc';+ const sortColumn = {+ name: 'name',+ created: 'createdAt',+ updated: 'updatedAt',+ downloads: 'downloadCount',+ rating: 'rating'+ }[sortBy] || 'createdAt';++ sql += ` ORDER BY ${sortColumn} ${sortOrder.toUpperCase()}`;++ // Add pagination+ if (query.limit) {+ sql += ' LIMIT ?';+ params.push(query.limit);++ if (query.offset) {+ sql += ' OFFSET ?';+ params.push(query.offset);+ }+ }++ const stmt = db.prepare(sql);+ const rows = stmt.all(...params) as any[];++ return rows.map(row => ({+ id: row.id,+ name: row.name,+ displayName: row.displayName,+ description: row.description,+ colors: JSON.parse(row.colors),+ isPublic: Boolean(row.isPublic),+ authorId: row.authorId,+ authorName: row.authorName,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ tags: JSON.parse(row.tags || '[]'),+ downloadCount: row.downloadCount,+ rating: row.rating,+ ratingCount: row.ratingCount+ }));+}++export function deleteTheme(id: string): boolean {+ const stmt = db.prepare('DELETE FROM themes WHERE id = ?');+ const result = stmt.run(id);+ return result.changes > 0;+}++export function incrementThemeDownloadCount(id: string): boolean {+ const stmt = db.prepare('UPDATE themes SET downloadCount = downloadCount + 1 WHERE id = ?');+ const result = stmt.run(id);+ return result.changes > 0;+}++export { db };\ No newline at end of filediff --git a/.claude/skills/observability/apps/server/src/file-ingest.ts b/.claude/skills/observability/apps/server/src/file-ingest.tsnew file mode 100644index 00000000..f58dd941--- /dev/null+++ b/.claude/skills/observability/apps/server/src/file-ingest.ts@@ -0,0 +1,353 @@+#!/usr/bin/env bun+/**+ * File-based Event Streaming (In-Memory Only)+ * Watches JSONL files from capture-all-events.ts hook+ * NO DATABASE - streams directly to WebSocket clients+ * Fresh start each time - no persistence+ */++import { watch, existsSync } from 'fs';+import { readFileSync } from 'fs';+import { join } from 'path';+import { homedir } from 'os';+import type { HookEvent } from './types';++// In-memory event store (last N events only)+const MAX_EVENTS = 1000;+const events: HookEvent[] = [];++// Track the last read position for each file+const filePositions = new Map<string, number>();++// Track which files we're currently watching+const watchedFiles = new Set<string>();++// Callback for when new events arrive (for WebSocket broadcasting)+let onEventsReceived: ((events: HookEvent[]) => void) | null = null;++// NEW: Agent session mapping (session_id -> agent_name)+const agentSessions = new Map<string, string>();++// NEW: Todo tracking per session (session_id -> current todos)+const sessionTodos = new Map<string, any[]>();++/**+ * Get the path to today's all-events file+ */+function getTodayEventsFile(): string {+ const paiDir = join(homedir(), '.claude');+ const now = new Date();+ // Convert to PST+ const pstDate = new Date(now.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' }));+ const year = pstDate.getFullYear();+ const month = String(pstDate.getMonth() + 1).padStart(2, '0');+ const day = String(pstDate.getDate()).padStart(2, '0');++ const monthDir = join(paiDir, 'history', 'raw-outputs', `${year}-${month}`);+ return join(monthDir, `${year}-${month}-${day}_all-events.jsonl`);+}++/**+ * Read new events from a JSONL file starting from a given position+ */+function readNewEvents(filePath: string): HookEvent[] {+ if (!existsSync(filePath)) {+ return [];+ }++ const lastPosition = filePositions.get(filePath) || 0;++ try {+ const content = readFileSync(filePath, 'utf-8');+ const newContent = content.slice(lastPosition);++ // Update position to end of file+ filePositions.set(filePath, content.length);++ if (!newContent.trim()) {+ return [];+ }++ // Parse JSONL - one JSON object per line+ const lines = newContent.trim().split('\n');+ const newEvents: HookEvent[] = [];++ for (const line of lines) {+ if (!line.trim()) continue;++ try {+ let event = JSON.parse(line);+ // Add auto-incrementing ID for UI+ event.id = events.length + newEvents.length + 1;+ // Enrich with agent name+ event = enrichEventWithAgentName(event);+ // Process todo events (returns array of events)+ const processedEvents = processTodoEvent(event);+ // Reassign IDs for any synthetic events+ for (let i = 0; i < processedEvents.length; i++) {+ processedEvents[i].id = events.length + newEvents.length + i + 1;+ }+ newEvents.push(...processedEvents);+ } catch (error) {+ console.error(`Failed to parse line: ${line.slice(0, 100)}...`, error);+ }+ }++ return newEvents;+ } catch (error) {+ console.error(`Error reading file ${filePath}:`, error);+ return [];+ }+}++/**+ * Add events to in-memory store (keeping last MAX_EVENTS only)+ */+function storeEvents(newEvents: HookEvent[]): void {+ if (newEvents.length === 0) return;++ // Add to in-memory array+ events.push(...newEvents);++ // Keep only last MAX_EVENTS+ if (events.length > MAX_EVENTS) {+ events.splice(0, events.length - MAX_EVENTS);+ }++ console.log(`✅ Received ${newEvents.length} event(s) (${events.length} in memory)`);++ // Notify subscribers (WebSocket clients)+ if (onEventsReceived) {+ onEventsReceived(newEvents);+ }+}++/**+ * Load agent sessions from agent-sessions.json+ */+function loadAgentSessions(): void {+ const sessionsFile = join(homedir(), '.claude', 'agent-sessions.json');++ if (!existsSync(sessionsFile)) {+ console.log('⚠️ agent-sessions.json not found, agent names will be "unknown"');+ return;+ }++ try {+ const content = readFileSync(sessionsFile, 'utf-8');+ const data = JSON.parse(content);++ agentSessions.clear();+ Object.entries(data).forEach(([sessionId, agentName]) => {+ agentSessions.set(sessionId, agentName as string);+ });++ console.log(`✅ Loaded ${agentSessions.size} agent sessions`);+ } catch (error) {+ console.error('❌ Error loading agent-sessions.json:', error);+ }+}++/**+ * Watch agent-sessions.json for changes+ */+function watchAgentSessions(): void {+ const sessionsFile = join(homedir(), '.claude', 'agent-sessions.json');++ if (!existsSync(sessionsFile)) {+ console.log('⚠️ agent-sessions.json not found, skipping watch');+ return;+ }++ console.log('👀 Watching agent-sessions.json for changes');++ const watcher = watch(sessionsFile, (eventType) => {+ if (eventType === 'change') {+ console.log('🔄 agent-sessions.json changed, reloading...');+ loadAgentSessions();+ }+ });++ watcher.on('error', (error) => {+ console.error('❌ Error watching agent-sessions.json:', error);+ });+}++/**+ * Enrich event with agent name from session mapping+ */+function enrichEventWithAgentName(event: HookEvent): HookEvent {+ // Special case: UserPromptSubmit events are from the user, not the agent+ if (event.hook_event_type === 'UserPromptSubmit') {+ return {+ ...event,+ agent_name: 'User'+ };+ }++ // Default to 'kai' for main agent sessions (not 'unknown')+ const agentName = agentSessions.get(event.session_id) || 'kai';+ return {+ ...event,+ agent_name: agentName+ };+}++/**+ * Process todo events and detect completions+ * Returns array of events: original event + synthetic completion events+ */+function processTodoEvent(event: HookEvent): HookEvent[] {+ // Only process TodoWrite tool events+ if (event.payload.tool_name !== 'TodoWrite') {+ return [event];+ }++ // Extract todos from the event+ const currentTodos = event.payload.tool_input?.todos || [];++ // Get previous todos for this session+ const previousTodos = sessionTodos.get(event.session_id) || [];++ // Find newly completed todos+ const completedTodos = [];++ for (const currentTodo of currentTodos) {+ if (currentTodo.status === 'completed') {+ // Check if this todo was NOT completed in the previous state+ const prevTodo = previousTodos.find((t: any) => t.content === currentTodo.content);+ if (!prevTodo || prevTodo.status !== 'completed') {+ completedTodos.push(currentTodo);+ }+ }+ }++ // Update session todos+ sessionTodos.set(event.session_id, currentTodos);++ // Create synthetic completion events+ const events: HookEvent[] = [event];++ for (const completedTodo of completedTodos) {+ const completionEvent: HookEvent = {+ ...event,+ id: event.id, // Will be reassigned by caller+ hook_event_type: 'Completed',+ payload: {+ task: completedTodo.content+ },+ summary: undefined, // Don't duplicate - toolInfo.detail shows the task+ timestamp: event.timestamp+ };+ events.push(completionEvent);+ }++ return events;+}++/**+ * Watch a file for changes and stream new events+ */+function watchFile(filePath: string): void {+ if (watchedFiles.has(filePath)) {+ return; // Already watching+ }++ console.log(`👀 Watching: ${filePath}`);+ watchedFiles.add(filePath);++ // Set file position to END of file - only read NEW events from now on+ // Do NOT load historical events from before server start+ if (existsSync(filePath)) {+ const content = readFileSync(filePath, 'utf-8');+ filePositions.set(filePath, content.length);+ console.log(`📍 Positioned at end of file - only new events will be captured`);+ }++ // Watch for changes+ const watcher = watch(filePath, (eventType) => {+ if (eventType === 'change') {+ const newEvents = readNewEvents(filePath);+ storeEvents(newEvents);+ }+ });++ watcher.on('error', (error) => {+ console.error(`Error watching ${filePath}:`, error);+ watchedFiles.delete(filePath);+ });+}++/**+ * Start watching for events+ * @param callback Optional callback to be notified when new events arrive+ */+export function startFileIngestion(callback?: (events: HookEvent[]) => void): void {+ console.log('🚀 Starting file-based event streaming (in-memory only)');+ console.log('📂 Reading from ~/.claude/history/raw-outputs/');++ // Set the callback for event notifications+ if (callback) {+ onEventsReceived = callback;+ }++ // Load and watch agent sessions for name enrichment+ loadAgentSessions();+ watchAgentSessions();++ // Watch today's file+ const todayFile = getTodayEventsFile();+ watchFile(todayFile);++ // Check for new day's file every hour+ setInterval(() => {+ const newTodayFile = getTodayEventsFile();+ if (newTodayFile !== todayFile) {+ console.log('📅 New day detected, watching new file');+ watchFile(newTodayFile);+ }+ }, 60 * 60 * 1000); // Check every hour++ console.log('✅ File streaming started');+}++/**+ * Get all events currently in memory+ */+export function getRecentEvents(limit: number = 100): HookEvent[] {+ return events.slice(-limit).reverse();+}++/**+ * Get filter options from in-memory events+ */+export function getFilterOptions() {+ const sourceApps = new Set<string>();+ const sessionIds = new Set<string>();+ const hookEventTypes = new Set<string>();++ for (const event of events) {+ if (event.source_app) sourceApps.add(event.source_app);+ if (event.session_id) sessionIds.add(event.session_id);+ if (event.hook_event_type) hookEventTypes.add(event.hook_event_type);+ }++ return {+ source_apps: Array.from(sourceApps).sort(),+ session_ids: Array.from(sessionIds).slice(0, 100),+ hook_event_types: Array.from(hookEventTypes).sort()+ };+}++// For testing - can be run directly+if (import.meta.main) {+ startFileIngestion();++ console.log('Press Ctrl+C to stop');++ // Keep process alive+ process.on('SIGINT', () => {+ console.log('\n👋 Shutting down...');+ process.exit(0);+ });+}diff --git a/.claude/skills/observability/apps/server/src/index.ts b/.claude/skills/observability/apps/server/src/index.tsnew file mode 100644index 00000000..3491b489--- /dev/null+++ b/.claude/skills/observability/apps/server/src/index.ts@@ -0,0 +1,452 @@+import type { HookEvent } from './types';+import {+ createTheme,+ updateThemeById,+ getThemeById,+ searchThemes,+ deleteThemeById,+ exportThemeById,+ importTheme,+ getThemeStats+} from './theme';+import { startFileIngestion, getRecentEvents, getFilterOptions } from './file-ingest';++// Store WebSocket clients+const wsClients = new Set<any>();++// Start file-based ingestion (reads from ~/.claude/history/raw-outputs/)+// Pass a callback to broadcast new events to connected WebSocket clients+startFileIngestion((events) => {+ // Broadcast each event to all connected WebSocket clients+ events.forEach(event => {+ const message = JSON.stringify({ type: 'event', data: event });+ wsClients.forEach(client => {+ try {+ client.send(message);+ } catch (err) {+ // Client disconnected, remove from set+ wsClients.delete(client);+ }+ });+ });+});++// Create Bun server with HTTP and WebSocket support+const server = Bun.serve({+ port: 4000,++ async fetch(req: Request) {+ const url = new URL(req.url);++ // Handle CORS+ const headers = {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type',+ };++ // Handle preflight+ if (req.method === 'OPTIONS') {+ return new Response(null, { headers });+ }++ // GET /events/filter-options - Get available filter options+ if (url.pathname === '/events/filter-options' && req.method === 'GET') {+ const options = getFilterOptions();+ return new Response(JSON.stringify(options), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // GET /events/recent - Get recent events+ if (url.pathname === '/events/recent' && req.method === 'GET') {+ const limit = parseInt(url.searchParams.get('limit') || '100');+ const events = getRecentEvents(limit);+ return new Response(JSON.stringify(events), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // GET /events/by-agent/:agentName - Get events for specific agent+ if (url.pathname.startsWith('/events/by-agent/') && req.method === 'GET') {+ const agentName = decodeURIComponent(url.pathname.split('/')[3]);+ const limit = parseInt(url.searchParams.get('limit') || '100');++ if (!agentName) {+ return new Response(JSON.stringify({+ error: 'Agent name is required'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const allEvents = getRecentEvents(limit);+ const agentEvents = allEvents.filter(e => e.agent_name === agentName);++ return new Response(JSON.stringify(agentEvents), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // Theme API endpoints++ // POST /api/themes - Create a new theme+ if (url.pathname === '/api/themes' && req.method === 'POST') {+ try {+ const themeData = await req.json();+ const result = await createTheme(themeData);++ const status = result.success ? 201 : 400;+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ } catch (error) {+ console.error('Error creating theme:', error);+ return new Response(JSON.stringify({+ success: false,+ error: 'Invalid request body'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }+ }++ // GET /api/themes - Search themes+ if (url.pathname === '/api/themes' && req.method === 'GET') {+ const query = {+ query: url.searchParams.get('query') || undefined,+ isPublic: url.searchParams.get('isPublic') ? url.searchParams.get('isPublic') === 'true' : undefined,+ authorId: url.searchParams.get('authorId') || undefined,+ sortBy: url.searchParams.get('sortBy') as any || undefined,+ sortOrder: url.searchParams.get('sortOrder') as any || undefined,+ limit: url.searchParams.get('limit') ? parseInt(url.searchParams.get('limit')!) : undefined,+ offset: url.searchParams.get('offset') ? parseInt(url.searchParams.get('offset')!) : undefined,+ };++ const result = await searchThemes(query);+ return new Response(JSON.stringify(result), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // GET /api/themes/:id - Get a specific theme+ if (url.pathname.startsWith('/api/themes/') && req.method === 'GET') {+ const id = url.pathname.split('/')[3];+ if (!id) {+ return new Response(JSON.stringify({+ success: false,+ error: 'Theme ID is required'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const result = await getThemeById(id);+ const status = result.success ? 200 : 404;+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // PUT /api/themes/:id - Update a theme+ if (url.pathname.startsWith('/api/themes/') && req.method === 'PUT') {+ const id = url.pathname.split('/')[3];+ if (!id) {+ return new Response(JSON.stringify({+ success: false,+ error: 'Theme ID is required'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ try {+ const updates = await req.json();+ const result = await updateThemeById(id, updates);++ const status = result.success ? 200 : 400;+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ } catch (error) {+ console.error('Error updating theme:', error);+ return new Response(JSON.stringify({+ success: false,+ error: 'Invalid request body'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }+ }++ // DELETE /api/themes/:id - Delete a theme+ if (url.pathname.startsWith('/api/themes/') && req.method === 'DELETE') {+ const id = url.pathname.split('/')[3];+ if (!id) {+ return new Response(JSON.stringify({+ success: false,+ error: 'Theme ID is required'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const authorId = url.searchParams.get('authorId');+ const result = await deleteThemeById(id, authorId || undefined);++ const status = result.success ? 200 : (result.error?.includes('not found') ? 404 : 403);+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // GET /api/themes/:id/export - Export a theme+ if (url.pathname.match(/^\/api\/themes\/[^\/]+\/export$/) && req.method === 'GET') {+ const id = url.pathname.split('/')[3];++ const result = await exportThemeById(id);+ if (!result.success) {+ const status = result.error?.includes('not found') ? 404 : 400;+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ return new Response(JSON.stringify(result.data), {+ headers: {+ ...headers,+ 'Content-Type': 'application/json',+ 'Content-Disposition': `attachment; filename="${result.data.theme.name}.json"`+ }+ });+ }++ // POST /api/themes/import - Import a theme+ if (url.pathname === '/api/themes/import' && req.method === 'POST') {+ try {+ const importData = await req.json();+ const authorId = url.searchParams.get('authorId');++ const result = await importTheme(importData, authorId || undefined);++ const status = result.success ? 201 : 400;+ return new Response(JSON.stringify(result), {+ status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ } catch (error) {+ console.error('Error importing theme:', error);+ return new Response(JSON.stringify({+ success: false,+ error: 'Invalid import data'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }+ }++ // GET /api/themes/stats - Get theme statistics+ if (url.pathname === '/api/themes/stats' && req.method === 'GET') {+ const result = await getThemeStats();+ return new Response(JSON.stringify(result), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // GET /api/activities - Get current activities from Kitty tab titles+ if (url.pathname === '/api/activities' && req.method === 'GET') {+ try {+ // Run kitty @ ls to get tab/window info+ const proc = Bun.spawn(['kitty', '@', 'ls'], {+ stdout: 'pipe',+ stderr: 'pipe'+ });++ const stdout = await new Response(proc.stdout).text();+ const exitCode = await proc.exited;++ if (exitCode !== 0) {+ return new Response(JSON.stringify([]), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const kittyData = JSON.parse(stdout);+ const activities: { agent: string; activity: string; timestamp: string }[] = [];++ // Parse ALL Kitty tabs - just return their titles as-is+ for (const osWindow of kittyData) {+ for (const tab of osWindow.tabs || []) {+ // Strip trailing ellipsis and leading "N: " tab number prefix+ const title = (tab.title || '')+ .replace(/\.{3}$/, '')+ .replace(/^\d+:\s*/, '')+ .trim();++ if (!title) continue;++ activities.push({+ agent: 'kai',+ activity: title,+ timestamp: new Date().toISOString()+ });+ }+ }++ return new Response(JSON.stringify(activities), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ } catch (error) {+ console.error('Error fetching Kitty activities:', error);+ return new Response(JSON.stringify([]), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }+ }++ // POST /api/haiku/summarize - Proxy for Haiku summarization (reads API key from ~/.claude/.env)+ if (url.pathname === '/api/haiku/summarize' && req.method === 'POST') {+ try {+ // Load .env from ~/.claude/.env+ const homeDir = process.env.HOME || '';+ const envPath = `${homeDir}/.claude/.env`;++ let apiKey = '';+ try {+ const envFile = await Bun.file(envPath).text();+ const match = envFile.match(/ANTHROPIC_API_KEY=(.+)/);+ if (match) {+ apiKey = match[1].trim();+ }+ } catch (err) {+ console.error('Failed to read .env:', err);+ }++ if (!apiKey) {+ return new Response(JSON.stringify({+ success: false,+ error: 'ANTHROPIC_API_KEY not configured in ~/.claude/.env'+ }), {+ status: 500,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const body = await req.json();+ const { prompt } = body;++ if (!prompt) {+ return new Response(JSON.stringify({+ success: false,+ error: 'Missing prompt'+ }), {+ status: 400,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ // Call Anthropic API+ const response = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-api-key': apiKey,+ 'anthropic-version': '2023-06-01'+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5',+ max_tokens: 50,+ messages: [{+ role: 'user',+ content: prompt+ }]+ })+ });++ if (!response.ok) {+ const error = await response.text();+ return new Response(JSON.stringify({+ success: false,+ error: `Haiku API error: ${response.status}`,+ details: error+ }), {+ status: response.status,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }++ const data = await response.json();+ return new Response(JSON.stringify({+ success: true,+ text: data.content?.[0]?.text || ''+ }), {+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ } catch (error) {+ console.error('Error in Haiku proxy:', error);+ return new Response(JSON.stringify({+ success: false,+ error: 'Internal server error'+ }), {+ status: 500,+ headers: { ...headers, 'Content-Type': 'application/json' }+ });+ }+ }++ // WebSocket upgrade+ if (url.pathname === '/stream') {+ const success = server.upgrade(req);+ if (success) {+ return undefined;+ }+ }++ // Default response+ return new Response('Multi-Agent Observability Server', {+ headers: { ...headers, 'Content-Type': 'text/plain' }+ });+ },++ websocket: {+ open(ws) {+ console.log('WebSocket client connected');+ wsClients.add(ws);++ // Send recent events on connection+ const events = getRecentEvents(50);+ ws.send(JSON.stringify({ type: 'initial', data: events }));+ },++ message(ws, message) {+ // Handle any client messages if needed+ console.log('Received message:', message);+ },++ close(ws) {+ console.log('WebSocket client disconnected');+ wsClients.delete(ws);+ },++ error(ws, error) {+ console.error('WebSocket error:', error);+ wsClients.delete(ws);+ }+ }+});++console.log(`🚀 Server running on http://localhost:${server.port}`);+console.log(`📊 WebSocket endpoint: ws://localhost:${server.port}/stream`);+console.log(`📮 POST events to: http://localhost:${server.port}/events`);\ No newline at end of filediff --git a/.claude/skills/observability/apps/server/src/theme.ts b/.claude/skills/observability/apps/server/src/theme.tsnew file mode 100644index 00000000..bcfb983a--- /dev/null+++ b/.claude/skills/observability/apps/server/src/theme.ts@@ -0,0 +1,430 @@+import {+ insertTheme,+ updateTheme,+ getTheme,+ getThemes,+ deleteTheme,+ incrementThemeDownloadCount+} from './db';+import type { Theme, ThemeSearchQuery, ThemeValidationError, ApiResponse } from './types';++// Utility functions+function generateId(): string {+ return Math.random().toString(36).substr(2, 16);+}++function validateTheme(theme: Partial<Theme>): ThemeValidationError[] {+ const errors: ThemeValidationError[] = [];++ // Required fields validation+ if (!theme.name) {+ errors.push({+ field: 'name',+ message: 'Theme name is required',+ code: 'REQUIRED'+ });+ } else if (!/^[a-z0-9-_]+$/.test(theme.name)) {+ errors.push({+ field: 'name',+ message: 'Theme name must contain only lowercase letters, numbers, hyphens, and underscores',+ code: 'INVALID_FORMAT'+ });+ }++ if (!theme.displayName) {+ errors.push({+ field: 'displayName',+ message: 'Display name is required',+ code: 'REQUIRED'+ });+ }++ if (!theme.colors) {+ errors.push({+ field: 'colors',+ message: 'Theme colors are required',+ code: 'REQUIRED'+ });+ } else {+ // Validate color format+ const requiredColors = [+ 'primary', 'primaryHover', 'primaryLight', 'primaryDark',+ 'bgPrimary', 'bgSecondary', 'bgTertiary', 'bgQuaternary',+ 'textPrimary', 'textSecondary', 'textTertiary', 'textQuaternary',+ 'borderPrimary', 'borderSecondary', 'borderTertiary',+ 'accentSuccess', 'accentWarning', 'accentError', 'accentInfo',+ 'shadow', 'shadowLg', 'hoverBg', 'activeBg', 'focusRing'+ ];++ for (const colorKey of requiredColors) {+ const color = theme.colors[colorKey as keyof typeof theme.colors];+ if (!color) {+ errors.push({+ field: `colors.${colorKey}`,+ message: `Color ${colorKey} is required`,+ code: 'REQUIRED'+ });+ } else if (!isValidColor(color)) {+ errors.push({+ field: `colors.${colorKey}`,+ message: `Invalid color format for ${colorKey}`,+ code: 'INVALID_COLOR'+ });+ }+ }+ }++ // Tags validation+ if (theme.tags && Array.isArray(theme.tags)) {+ for (const tag of theme.tags) {+ if (typeof tag !== 'string' || tag.length === 0) {+ errors.push({+ field: 'tags',+ message: 'All tags must be non-empty strings',+ code: 'INVALID_FORMAT'+ });+ break;+ }+ }+ }++ return errors;+}++function isValidColor(color: string): boolean {+ // Check hex colors+ if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color)) {+ return true;+ }++ // Check rgba/rgb colors+ if (/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d?(?:\.\d+)?))?\)$/.test(color)) {+ return true;+ }++ // Check named colors (basic validation)+ const namedColors = [+ 'transparent', 'black', 'white', 'red', 'green', 'blue',+ 'yellow', 'cyan', 'magenta', 'gray', 'grey'+ ];++ return namedColors.includes(color.toLowerCase());+}++function sanitizeTheme(theme: any): Partial<Theme> {+ return {+ name: theme.name?.toString().toLowerCase().replace(/[^a-z0-9-_]/g, '') || '',+ displayName: theme.displayName?.toString().trim() || '',+ description: theme.description?.toString().trim() || '',+ colors: theme.colors || {},+ isPublic: Boolean(theme.isPublic),+ tags: Array.isArray(theme.tags) ? theme.tags.filter(tag => typeof tag === 'string' && tag.trim()) : [],+ authorId: theme.authorId?.toString() || null,+ authorName: theme.authorName?.toString() || null+ };+}++// Theme management functions+export async function createTheme(themeData: any): Promise<ApiResponse<Theme>> {+ try {+ const sanitized = sanitizeTheme(themeData);+ const errors = validateTheme(sanitized);++ if (errors.length > 0) {+ return {+ success: false,+ error: 'Validation failed',+ validationErrors: errors+ };+ }++ // Check if theme name already exists+ const existingThemes = getThemes({ query: sanitized.name });+ if (existingThemes.some(t => t.name === sanitized.name)) {+ return {+ success: false,+ error: 'Theme name already exists',+ validationErrors: [{+ field: 'name',+ message: 'A theme with this name already exists',+ code: 'DUPLICATE'+ }]+ };+ }++ const theme: Theme = {+ id: generateId(),+ name: sanitized.name!,+ displayName: sanitized.displayName!,+ description: sanitized.description,+ colors: sanitized.colors!,+ isPublic: sanitized.isPublic!,+ authorId: sanitized.authorId,+ authorName: sanitized.authorName,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ tags: sanitized.tags || [],+ downloadCount: 0,+ rating: 0,+ ratingCount: 0+ };++ const savedTheme = insertTheme(theme);++ return {+ success: true,+ data: savedTheme,+ message: 'Theme created successfully'+ };+ } catch (error) {+ console.error('Error creating theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function updateThemeById(id: string, updates: any): Promise<ApiResponse<Theme>> {+ try {+ const existingTheme = getTheme(id);+ if (!existingTheme) {+ return {+ success: false,+ error: 'Theme not found'+ };+ }++ const sanitized = sanitizeTheme(updates);++ // Don't allow changing the name after creation+ delete sanitized.name;++ const errors = validateTheme({ ...existingTheme, ...sanitized });++ if (errors.length > 0) {+ return {+ success: false,+ error: 'Validation failed',+ validationErrors: errors+ };+ }++ const updateData = {+ ...sanitized,+ updatedAt: Date.now()+ };++ const success = updateTheme(id, updateData);++ if (!success) {+ return {+ success: false,+ error: 'Failed to update theme'+ };+ }++ const updatedTheme = getTheme(id);++ return {+ success: true,+ data: updatedTheme!,+ message: 'Theme updated successfully'+ };+ } catch (error) {+ console.error('Error updating theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function getThemeById(id: string): Promise<ApiResponse<Theme>> {+ try {+ const theme = getTheme(id);++ if (!theme) {+ return {+ success: false,+ error: 'Theme not found'+ };+ }++ // Increment download count for public themes+ if (theme.isPublic) {+ incrementThemeDownloadCount(id);+ }++ return {+ success: true,+ data: theme+ };+ } catch (error) {+ console.error('Error getting theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function searchThemes(query: ThemeSearchQuery): Promise<ApiResponse<Theme[]>> {+ try {+ // Default to only public themes unless specific author requested+ const searchQuery = {+ ...query,+ isPublic: query.authorId ? undefined : true+ };++ const themes = getThemes(searchQuery);++ return {+ success: true,+ data: themes+ };+ } catch (error) {+ console.error('Error searching themes:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function deleteThemeById(id: string, authorId?: string): Promise<ApiResponse<void>> {+ try {+ const theme = getTheme(id);++ if (!theme) {+ return {+ success: false,+ error: 'Theme not found'+ };+ }++ // Only allow deletion by theme author (in a real app, you'd have proper auth)+ if (authorId && theme.authorId !== authorId) {+ return {+ success: false,+ error: 'Unauthorized - you can only delete your own themes'+ };+ }++ const success = deleteTheme(id);++ if (!success) {+ return {+ success: false,+ error: 'Failed to delete theme'+ };+ }++ return {+ success: true,+ message: 'Theme deleted successfully'+ };+ } catch (error) {+ console.error('Error deleting theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function exportThemeById(id: string): Promise<ApiResponse<any>> {+ try {+ const theme = getTheme(id);++ if (!theme) {+ return {+ success: false,+ error: 'Theme not found'+ };+ }++ const exportData = {+ version: '1.0.0',+ theme: {+ ...theme,+ // Remove server-specific data for export+ id: undefined,+ authorId: undefined,+ downloadCount: undefined,+ rating: undefined,+ ratingCount: undefined,+ createdAt: undefined,+ updatedAt: undefined+ },+ exportedAt: new Date().toISOString(),+ exportedBy: 'observability-system'+ };++ return {+ success: true,+ data: exportData+ };+ } catch (error) {+ console.error('Error exporting theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++export async function importTheme(importData: any, authorId?: string): Promise<ApiResponse<Theme>> {+ try {+ if (!importData.theme) {+ return {+ success: false,+ error: 'Invalid import data - missing theme'+ };+ }++ const themeData = {+ ...importData.theme,+ authorId,+ authorName: importData.theme.authorName || 'Imported',+ isPublic: false // Imported themes are private by default+ };++ return await createTheme(themeData);+ } catch (error) {+ console.error('Error importing theme:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}++// Utility function to get theme statistics+export async function getThemeStats(): Promise<ApiResponse<any>> {+ try {+ const allThemes = getThemes();+ const publicThemes = getThemes({ isPublic: true });++ const stats = {+ totalThemes: allThemes.length,+ publicThemes: publicThemes.length,+ privateThemes: allThemes.length - publicThemes.length,+ totalDownloads: allThemes.reduce((sum, theme) => sum + (theme.downloadCount || 0), 0),+ averageRating: allThemes.length > 0+ ? allThemes.reduce((sum, theme) => sum + (theme.rating || 0), 0) / allThemes.length+ : 0+ };++ return {+ success: true,+ data: stats+ };+ } catch (error) {+ console.error('Error getting theme stats:', error);+ return {+ success: false,+ error: 'Internal server error'+ };+ }+}\ No newline at end of filediff --git a/.claude/skills/observability/apps/server/src/types.ts b/.claude/skills/observability/apps/server/src/types.tsnew file mode 100644index 00000000..a6dfa1af--- /dev/null+++ b/.claude/skills/observability/apps/server/src/types.ts@@ -0,0 +1,150 @@+// Todo item interface+export interface TodoItem {+ content: string;+ status: 'pending' | 'in_progress' | 'completed';+ activeForm: string;+}++// New interface for human-in-the-loop requests+export interface HumanInTheLoop {+ question: string;+ responseWebSocketUrl: string;+ type: 'question' | 'permission' | 'choice';+ choices?: string[]; // For multiple choice questions+ timeout?: number; // Optional timeout in seconds+ requiresResponse?: boolean; // Whether response is required or optional+}++// Response interface+export interface HumanInTheLoopResponse {+ response?: string;+ permission?: boolean;+ choice?: string; // Selected choice from options+ hookEvent: HookEvent;+ respondedAt: number;+ respondedBy?: string; // Optional user identifier+}++// Status tracking interface+export interface HumanInTheLoopStatus {+ status: 'pending' | 'responded' | 'timeout' | 'error';+ respondedAt?: number;+ response?: HumanInTheLoopResponse;+}++export interface HookEvent {+ id?: number;+ source_app: string;+ session_id: string;+ agent_name?: string; // NEW: Agent name enriched from agent-sessions.json+ hook_event_type: string;+ payload: Record<string, any>;+ chat?: any[];+ summary?: string;+ timestamp?: number;+ model_name?: string;++ // NEW: Optional HITL data+ humanInTheLoop?: HumanInTheLoop;+ humanInTheLoopStatus?: HumanInTheLoopStatus;++ // NEW: Optional Todo data+ todos?: TodoItem[];+ completedTodos?: TodoItem[]; // Todos that were completed in this event+}++export interface FilterOptions {+ source_apps: string[];+ session_ids: string[];+ hook_event_types: string[];+}++// Theme-related interfaces for server-side storage and API+export interface ThemeColors {+ primary: string;+ primaryHover: string;+ primaryLight: string;+ primaryDark: string;+ bgPrimary: string;+ bgSecondary: string;+ bgTertiary: string;+ bgQuaternary: string;+ textPrimary: string;+ textSecondary: string;+ textTertiary: string;+ textQuaternary: string;+ borderPrimary: string;+ borderSecondary: string;+ borderTertiary: string;+ accentSuccess: string;+ accentWarning: string;+ accentError: string;+ accentInfo: string;+ shadow: string;+ shadowLg: string;+ hoverBg: string;+ activeBg: string;+ focusRing: string;+}++export interface Theme {+ id: string;+ name: string;+ displayName: string;+ description?: string;+ colors: ThemeColors;+ isPublic: boolean;+ authorId?: string;+ authorName?: string;+ createdAt: number;+ updatedAt: number;+ tags: string[];+ downloadCount?: number;+ rating?: number;+ ratingCount?: number;+}++export interface ThemeSearchQuery {+ query?: string;+ tags?: string[];+ authorId?: string;+ isPublic?: boolean;+ sortBy?: 'name' | 'created' | 'updated' | 'downloads' | 'rating';+ sortOrder?: 'asc' | 'desc';+ limit?: number;+ offset?: number;+}++export interface ThemeShare {+ id: string;+ themeId: string;+ shareToken: string;+ expiresAt?: number;+ isPublic: boolean;+ allowedUsers: string[];+ createdAt: number;+ accessCount: number;+}++export interface ThemeRating {+ id: string;+ themeId: string;+ userId: string;+ rating: number; // 1-5+ comment?: string;+ createdAt: number;+}++export interface ThemeValidationError {+ field: string;+ message: string;+ code: string;+}++export interface ApiResponse<T = any> {+ success: boolean;+ data?: T;+ error?: string;+ message?: string;+ validationErrors?: ThemeValidationError[];+}\ No newline at end of filediff --git a/.claude/skills/observability/manage.sh b/.claude/skills/observability/manage.shnew file mode 100755index 00000000..e8058712--- /dev/null+++ b/.claude/skills/observability/manage.sh@@ -0,0 +1,89 @@+#!/bin/bash+# Observability Dashboard Manager - PAI Agent Activity Monitor+# Location: ~/.claude/skills/observability/++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++case "${1:-}" in+ start)+ # Check if already running+ if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then+ echo "❌ Already running. Use: manage.sh restart"+ exit 1+ fi++ # Start server (silent)+ cd "$SCRIPT_DIR/apps/server"+ bun run dev >/dev/null 2>&1 &+ SERVER_PID=$!++ # Wait for server+ for i in {1..10}; do+ curl -s http://localhost:4000/events/filter-options >/dev/null 2>&1 && break+ sleep 1+ done++ # Start client (silent)+ cd "$SCRIPT_DIR/apps/client"+ bun run dev >/dev/null 2>&1 &+ CLIENT_PID=$!++ # Wait for client+ for i in {1..10}; do+ curl -s http://localhost:5172 >/dev/null 2>&1 && break+ sleep 1+ done++ echo "✅ Observability running at http://localhost:5172"++ # Cleanup on exit+ cleanup() {+ kill $SERVER_PID $CLIENT_PID 2>/dev/null+ exit 0+ }+ trap cleanup INT+ wait $SERVER_PID $CLIENT_PID+ ;;++ stop)+ # Kill processes (silent)+ for port in 4000 5172; do+ if [[ "$OSTYPE" == "darwin"* ]]; then+ PIDS=$(lsof -ti :$port 2>/dev/null)+ else+ PIDS=$(lsof -ti :$port 2>/dev/null || fuser -n tcp $port 2>/dev/null | awk '{print $2}')+ fi+ [ -n "$PIDS" ] && kill -9 $PIDS 2>/dev/null+ done++ # Kill remaining bun processes+ ps aux | grep -E "bun.*(apps/(server|client))" | grep -v grep | awk '{print $2}' | while read PID; do+ [ -n "$PID" ] && kill -9 $PID 2>/dev/null+ done++ # Clean SQLite WAL files+ rm -f "$SCRIPT_DIR/apps/server/events.db-wal" "$SCRIPT_DIR/apps/server/events.db-shm" 2>/dev/null++ echo "✅ Observability stopped"+ ;;++ restart)+ echo "🔄 Restarting..."+ "$0" stop 2>/dev/null+ sleep 1+ exec "$0" start+ ;;++ status)+ if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then+ echo "✅ Running at http://localhost:5172"+ else+ echo "❌ Not running"+ fi+ ;;++ *)+ echo "Usage: manage.sh {start|stop|restart|status}"+ exit 1+ ;;+esacdiff --git a/.claude/skills/observability/scripts/reset-system.sh b/.claude/skills/observability/scripts/reset-system.shnew file mode 100755index 00000000..aeaa10df--- /dev/null+++ b/.claude/skills/observability/scripts/reset-system.sh@@ -0,0 +1,32 @@+#!/bin/bash+# Stop observability dashboard - silent operation++SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"+PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"++# Kill processes on ports (silent)+kill_port() {+ local port=$1+ if [[ "$OSTYPE" == "darwin"* ]]; then+ PIDS=$(lsof -ti :$port 2>/dev/null)+ else+ PIDS=$(lsof -ti :$port 2>/dev/null || fuser -n tcp $port 2>/dev/null | awk '{print $2}')+ fi++ if [ -n "$PIDS" ]; then+ for PID in $PIDS; do+ kill -9 $PID 2>/dev/null+ done+ fi+}++kill_port 4000+kill_port 5172++# Kill remaining bun processes (silent)+ps aux | grep -E "bun.*(apps/(server|client))" | grep -v grep | awk '{print $2}' | while read PID; do+ [ -n "$PID" ] && kill -9 $PID 2>/dev/null+done++# Clean SQLite WAL files (silent)+rm -f "$PROJECT_ROOT/apps/server/events.db-wal" "$PROJECT_ROOT/apps/server/events.db-shm" 2>/dev/null\ No newline at end of filediff --git a/.claude/skills/observability/scripts/start-agent-observability-dashboard.sh b/.claude/skills/observability/scripts/start-agent-observability-dashboard.shnew file mode 100755index 00000000..0b64d547--- /dev/null+++ b/.claude/skills/observability/scripts/start-agent-observability-dashboard.sh@@ -0,0 +1,52 @@+#!/bin/bash+# Start observability dashboard - minimal output++SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"+PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"++# Check if ports are in use+if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then+ echo "❌ Port 4000 in use. Run: ~/.claude/scripts/stop-observability.sh"+ exit 1+fi++if lsof -Pi :5172 -sTCP:LISTEN -t >/dev/null 2>&1; then+ echo "❌ Port 5172 in use. Run: ~/.claude/scripts/stop-observability.sh"+ exit 1+fi++# Start server (suppress verbose output)+cd "$PROJECT_ROOT/apps/server"+bun run dev >/dev/null 2>&1 &+SERVER_PID=$!++# Wait for server (silent)+for i in {1..10}; do+ curl -s http://localhost:4000/events/filter-options >/dev/null 2>&1 && break+ sleep 1+done++# Start client (suppress verbose output)+cd "$PROJECT_ROOT/apps/client"+bun run dev >/dev/null 2>&1 &+CLIENT_PID=$!++# Wait for client (silent)+for i in {1..10}; do+ curl -s http://localhost:5172 >/dev/null 2>&1 && break+ sleep 1+done++# Confirm startup+echo "✅ Observability Dashboard Running"+echo " Dashboard: http://localhost:5172"+echo " API: http://localhost:4000"++# Cleanup on exit+cleanup() {+ kill $SERVER_PID $CLIENT_PID 2>/dev/null+ exit 0+}++trap cleanup INT+wait $SERVER_PID $CLIENT_PID\ No newline at end of filediff --git a/.claude/skills/observability/scripts/test-system.sh b/.claude/skills/observability/scripts/test-system.shnew file mode 100755index 00000000..7ea5900c--- /dev/null+++ b/.claude/skills/observability/scripts/test-system.sh@@ -0,0 +1,85 @@+#!/bin/bash++echo "🚀 Multi-Agent Observability System Test"+echo "========================================"++# Colors for output+GREEN='\033[0;32m'+RED='\033[0;31m'+NC='\033[0m' # No Color++# Get the directory of this script+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"+# Get the project root directory (parent of scripts)+PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"++# Step 1: Start the server in background+echo -e "\n${GREEN}Step 1: Starting server...${NC}"+cd "$PROJECT_ROOT/apps/server"+bun run start &+SERVER_PID=$!+sleep 3++# Check if server is running+if ps -p $SERVER_PID > /dev/null; then+ echo "✅ Server started successfully (PID: $SERVER_PID)"+else+ echo -e "${RED}❌ Server failed to start${NC}"+ exit 1+fi++# Step 2: Test sending an event+echo -e "\n${GREEN}Step 2: Testing event endpoint...${NC}"+RESPONSE=$(curl -s -X POST http://localhost:4000/events \+ -H "Content-Type: application/json" \+ -d '{"source_app":"test","session_id":"test-123","hook_event_type":"PreToolUse","payload":{"tool":"Bash","command":"ls -la"}}')++if [ $? -eq 0 ]; then+ echo "✅ Event sent successfully"+ echo "Response: $RESPONSE"+else+ echo -e "${RED}❌ Failed to send event${NC}"+fi++# Step 3: Test filter options endpoint+echo -e "\n${GREEN}Step 3: Testing filter options endpoint...${NC}"+FILTERS=$(curl -s http://localhost:4000/events/filter-options)+if [ $? -eq 0 ]; then+ echo "✅ Filter options retrieved"+ echo "Filters: $FILTERS"+else+ echo -e "${RED}❌ Failed to get filter options${NC}"+fi++# Step 4: Test demo agent hook+echo -e "\n${GREEN}Step 4: Testing demo agent hook script...${NC}"+cd "$PROJECT_ROOT/apps/demo-cc-agent"+echo '{"session_id":"demo-test","tool_name":"Bash","tool_input":{"command":"echo test"}}' | \+ uv run .claude/hooks/send_event.py --source-app demo --event-type PreToolUse++if [ $? -eq 0 ]; then+ echo "✅ Demo agent hook executed successfully"+else+ echo -e "${RED}❌ Demo agent hook failed${NC}"+fi++# Step 5: Check recent events+echo -e "\n${GREEN}Step 5: Checking recent events...${NC}"+RECENT=$(curl -s http://localhost:4000/events/recent?limit=5)+if [ $? -eq 0 ]; then+ echo "✅ Recent events retrieved"+ echo "Events: $RECENT" | python3 -m json.tool 2>/dev/null || echo "$RECENT"+else+ echo -e "${RED}❌ Failed to get recent events${NC}"+fi++# Cleanup+echo -e "\n${GREEN}Cleaning up...${NC}"+kill $SERVER_PID 2>/dev/null+echo "✅ Server stopped"++echo -e "\n${GREEN}Test complete!${NC}"+echo "To run the full system:"+echo "1. In terminal 1: cd apps/server && bun run dev"+echo "2. In terminal 2: cd apps/client && bun run dev"+echo "3. Open http://localhost:5173 in your browser"\ No newline at end of file