# Error Dashboard — Design Spec

## Overview

A workspace-level Error Dashboard under the **Monitor** sidebar section, providing a unified view of all runtime errors across container types (API, Function, Task, Middleware, Trigger). Two full-page views connected by route navigation: an **Error Listing** for triage and an **Error Detail** for investigation.

**Approach:** Phased delivery in 3 increments, each shipping standalone value.

## Phase Summary

| Phase | Theme | Backend Work | Key Deliverables |
|-------|-------|-------------|-----------------|
| **P1 — Core** | Listing + basic detail | Extend existing endpoints (container type filter, stats by type) | Error Listing page, Error Detail page (header, histogram, statement link, performance, stack issues) |
| **P2 — Regression** | Version tracking + smart sort | Regression coefficient field on signatures | Version track timeline, edge diff link, callers panel, trend-based sort |
| **P3 — Intelligence** | Notes + similarity + payload | Notes CRUD endpoints, similar issues query | Notes system, similar issues, common payload analysis |

---

## Error Listing View

### Route & Component

- **Route:** `/workspace/:id/error-dashboard`
- **Sidebar:** New entry under Monitor section (alongside Performance Insights, Audit Logs, Compliance Center)
- **Component:** Standalone `WorkspaceErrorDashboardPageComponent`
- **State:** New NgRx feature slice `errorDashboard` (separate from existing `errorLog` to avoid conflicts)

### Filter Bar

Four filter controls in a horizontal bar:

| Control | Type | Values | Behavior |
|---------|------|--------|----------|
| Text search | Input | Free text | Searches across `error_code`, `error_msg`, `statement_name` |
| Container | Dropdown | API, Function, Task, Middleware, Trigger | Filters by `type` field. Also toggled by clicking summary cards |
| Statement | Dropdown | Dynamic list from loaded signatures | Filters by `statement_name` |
| Status | Dropdown | New, Ignored, Fixed | Filters by signature status |

All filters are combinable. Changing any filter resets to page 1.

### Container Summary Cards

A row of 4 cards (Task, API, Function, Middleware), each showing:

- **+N** (red) — 24h gain (new error occurrences in last 24 hours)
- **Total count** — total error occurrences (sum of `total_count` across signatures) for this container type
- **Container label** — type name

Cards are **clickable** and act as container type filter toggles. Active card gets a highlighted border. Click again to deselect.

**Data source:** Extended `GET /workspace/:id/error_signatures/stats` endpoint — needs to return counts grouped by container type, plus 24h gain per type.

### Error Table

| Column | Source | Notes |
|--------|--------|-------|
| Past 24h | `hourly_counts` on signature | Inline sparkline bar chart (24 bars, one per hour) |
| Error | `error_code` + `error_msg` | Code in bold, message below in muted text |
| Stack | `statement_name` or URI | Shows the triggering statement or API endpoint |
| Last seen | `last_seen_at` | Relative time ("2m ago") |
| First seen | `first_seen_at` | Relative time ("3d ago") |
| Trend | Computed from `hourly_counts` | Badge: new / ongoing / escalating / shrinking |

**Trend classification (P1 — frontend-computed):**

Computed via linear regression on the 24 hourly data points (`f(y) = ax + b`):

| Trend | Condition | Color |
|-------|-----------|-------|
| new | `first_seen_at` < 4 hours ago | Red |
| escalating | regression slope `a > 1.2` | Orange |
| shrinking | regression slope `a < 0.8` | Green |
| ongoing | everything else | Gray |

**Sorting:**
- P1: Default sort by `last_seen` descending
- P2: Default sort by trend severity (escalating → new → ongoing → shrinking), backed by backend-stored regression coefficient

**Pagination:** 50 items per page, matching existing patterns.

**Row click:** Navigates to Error Detail page (`/workspace/:id/error-dashboard/:signatureId`).

### Sparkline Component

A reusable inline bar chart component rendering `hourly_counts` data:

- 24 bars, each representing one hour
- Height proportional to max count in the dataset
- Recent hours with high counts rendered in red, others in gray
- Fixed height (~20px), variable width based on column

### Data Flow (P1)

**API calls on page load:**

1. `GET /workspace/:id/error_signatures` — paginated list with filters (existing endpoint, extended with `type` filter for container)
2. `GET /workspace/:id/error_signatures/stats` — counts per container type + 24h gain (extended endpoint)

**Frontend computation:**
- Trend classification from `hourly_counts` via linear regression
- Sparkline rendering from `hourly_counts`

---

## Error Detail View

### Route & Component

- **Route:** `/workspace/:id/error-dashboard/:signatureId`
- **Component:** Standalone `WorkspaceErrorDetailPageComponent`
- **Layout:** Two-column — main content (~65%) + sidebar (~35%)
- **Navigation:** Breadcrumb "Error Dashboard → [error_code]" with back link

### Main Content (Left Column)

#### Error Header (P1)

- Error code + status badge (new/ignored/fixed) + container type badge
- Error message
- Function/statement name (linked)
- Action buttons: "Mark Ignored" / "Mark Fixed" (uses existing `PATCH /error_signatures/:id/status` endpoint)

#### 24h Occurrence Histogram (P1)

- Bar chart of hourly error counts over past 24 hours
- Max occurrence count displayed in corner
- Trend indicator below chart ("▲ escalating — rate increasing by 1.4x")
- Uses `hourly_counts` from the signature + existing `getErrorHistoryBySignature` for deeper data

#### Version Track (P2)

- Horizontal timeline showing published versions of the stack
- Error occurrences plotted as red dots on the timeline
- Helps identify "errors started at version N"
- **"View edge diff"** link: opens the existing xanoscript monaco diff viewer comparing version N-1 → N where errors first appeared
- **Data source:** Backend version/publish history API (already exists) correlated with error `first_seen_at`

#### Statement Link (P1)

- Shows the statement that triggered the error (e.g., "Get Record from user")
- "as user" context label showing the auth context
- **Click action:** Opens the statement in its stack context (navigates to the function/API editor at the relevant statement)

#### Common Payload (P3)

**Phase 3a — Frequency analysis:**
- Analyze input payloads across error instances for this signature
- Show: missing keys (with % of errors), common values (with %), constant fields
- Format: list with severity indicators (✗ missing, ⚠ suspicious value, ○ constant)

**Phase 3b — Success vs failure diff (future):**
- Compare error request payloads against successful requests from request history
- Highlight fields that differ between success and failure paths

#### Notes (P3)

- "Add note" button at top
- Chronological list of notes with author name, date, and content
- **Backend:** New CRUD endpoints on error signatures:
  - `POST /workspace/:id/error_signatures/:signatureId/notes` — create note
  - `GET /workspace/:id/error_signatures/:signatureId/notes` — list notes
  - `DELETE /workspace/:id/error_signatures/:signatureId/notes/:noteId` — delete note

### Sidebar (Right Column)

#### Performance Panel (P1)

Comparison table:

| | calls | response |
|---|---|---|
| error | N | Xms |
| standard | N | Xms |

- Shows call count and average response time for error path vs success path
- Highlights when error response time is abnormally high (red) — indicates congestion or timeouts
- **Data source:** Derived from error history records (duration, count) + request history for the same stack

#### Stack Issues (P1)

- Lists other error signatures that occur in the same call stack as the current error
- Each entry shows: error code, statement name, "same stack" label
- Clickable — navigates to that error's detail page
- **Data source:** Query error signatures sharing the same `obj` (function/API/task) and overlapping `statement_xsid` values

#### Similar Issues (P3)

- Backend-matched errors sharing characteristics across different stacks
- Match dimensions (exploratory — start with explicit, evolve to dynamic):
  - Same `error_code` across different stacks
  - Same table name in database statements
  - Same URL in fetch statements
  - Same middleware chain
- Each entry shows: error code, statement name, match reason
- **Backend:** New query endpoint `GET /workspace/:id/error_signatures/:signatureId/similar`

#### Callers (P2)

- API endpoints that invoke the function/middleware where the error occurs
- Shows HTTP verb badge (GET/POST/etc.) + endpoint path
- Clickable — navigates to the API endpoint's editor
- **Data source:** Traverse the workspace "kitchen sink" JSON to build the caller graph — find all API stacks that reference this function/middleware by ID

---

## NgRx State Design

### New Feature Slice: `errorDashboard`

```typescript
interface IErrorDashboardState {
  // Listing
  signatures: IErrorSignature[];
  stats: IErrorDashboardStats;     // counts per container type + 24h gains
  loading: boolean;
  page: number;
  totalPages: number;

  // Filters
  textFilter: string;
  containerFilter: TErrorContainerType | null;  // 'query' | 'function' | 'task' | 'middleware' | 'trigger'
  statementFilter: string | null;
  statusFilter: TErrorSignatureStatus | null;

  // Detail
  activeSignature: IErrorSignature | null;
  activeErrorDetail: IErrorHistory | null;
  errorHistoryList: IErrorHistory[];
  loadingDetail: boolean;

  // Phase 2
  versionHistory: IVersionEntry[];
  callers: ICaller[];

  // Phase 3
  notes: IErrorNote[];
  similarIssues: IErrorSignature[];
  commonPayload: IPayloadAnalysis | null;
}
```

### New Interface: `IErrorDashboardStats`

```typescript
interface IErrorDashboardStats {
  byType: {
    type: TErrorContainerType;
    total: number;
    gain24h: number;
  }[];
}
```

### Actions

Listing: `LoadSignatures`, `SetSignatures`, `SetStats`, `SetFilters`, `SetPage`, `SetLoading`
Detail: `LoadDetail`, `SetActiveSignature`, `SetActiveDetail`, `SetHistoryList`, `SetLoadingDetail`
Phase 2: `LoadVersionHistory`, `SetVersionHistory`, `LoadCallers`, `SetCallers`
Phase 3: `LoadNotes`, `AddNote`, `DeleteNote`, `SetNotes`, `LoadSimilar`, `SetSimilar`, `LoadPayloadAnalysis`, `SetPayloadAnalysis`

---

## Backend Changes

### P1 — Extend Existing Endpoints

1. **`GET /workspace/:id/error_signatures`** — add `type` query parameter for container type filtering
2. **`GET /workspace/:id/error_signatures/stats`** — return counts grouped by container type with 24h gain per type

### P2 — Regression + Versions

3. **Add `regression_coeff` field to error signature** — float, computed on error ingestion or periodic job. Stores the `a` in `f(y) = ax + b` from hourly data
4. **Support `sort=trend` on signatures endpoint** — order by regression coefficient descending
5. **Version correlation** — endpoint or query to map error occurrences to published stack versions

### P3 — Notes + Similarity

6. **Notes CRUD** — `POST/GET/DELETE /workspace/:id/error_signatures/:signatureId/notes`
7. **Similar issues query** — `GET /workspace/:id/error_signatures/:signatureId/similar` with matching on error_code, table name, URL, middleware chain

---

## Component Structure

```
workspace/
├── pages/
│   ├── workspace-error-dashboard-page/     # Listing view (standalone)
│   │   ├── workspace-error-dashboard-page.component.ts
│   │   ├── workspace-error-dashboard-page.component.html
│   │   └── workspace-error-dashboard-page.component.scss
│   └── workspace-error-detail-page/        # Detail view (standalone)
│       ├── workspace-error-detail-page.component.ts
│       ├── workspace-error-detail-page.component.html
│       └── workspace-error-detail-page.component.scss
├── components/
│   ├── error-sparkline/                    # Reusable inline bar chart
│   ├── error-summary-cards/                # Container type card row
│   ├── error-histogram/                    # 24h occurrence chart (detail)
│   ├── error-version-track/                # Version timeline (P2)
│   ├── error-performance-panel/            # Error vs standard comparison
│   ├── error-callers-panel/                # API caller list (P2)
│   ├── error-notes-panel/                  # Notes CRUD (P3)
│   ├── error-similar-panel/                # Similar issues (P3)
│   └── error-common-payload/               # Payload analysis (P3)
├── services/
│   └── error-log-data.service.ts           # Extend with new methods
├── actions/
│   └── error-dashboard.action.ts           # New action set
├── effects/
│   └── error-dashboard.effect.ts           # New effects
├── reducers/
│   └── error-dashboard.reducer.ts          # New reducer
├── selectors/
│   └── error-dashboard.selector.ts         # New selectors
└── interfaces/
    ├── error-dashboard-state.interface.ts
    ├── error-dashboard-stats.interface.ts
    └── error-note.interface.ts             # P3
```

---

## Relationship to Existing Error Infrastructure

The Error Dashboard **coexists** with the existing error log system:

- **Existing `errorLog` slice** — remains for per-object error inspection (opened from request history, process editor, etc.)
- **New `errorDashboard` slice** — workspace-wide view for monitoring and triage
- **Shared service** — `ErrorLogDataService` is extended with new methods; existing methods remain unchanged
- **Shared interfaces** — `IErrorSignature`, `IErrorHistory`, `IErrorStackEntry` are reused directly
- **No migration** — existing error log widget and panel continue to work as-is
