# AI Anomaly Explanation

## Objective

When a metric moves strangely, show which segments and events moved with it.

An explanation attached to a detected outlier, naming the contributing segments, the baseline, and the magnitude.

## Before You Begin

This feature is being added to an application that already exists and already
works. Do not scaffold a new project, and do not assume a blank slate.

Inspect the codebase first and establish:

- The existing application structure and where code of this kind already lives.
- The framework and version in use.
- The existing design system — colours, spacing, typography, and component conventions.
- Existing UI components you can reuse instead of writing new ones.
- The existing database structure, if this feature needs to persist anything.
- The existing authentication and authorization system, if this feature is user-scoped.
- Dependencies already installed, so you don't add a library that duplicates one.
- The existing test setup and conventions.

Only start writing code once you understand the above. If the application
already implements part of this feature, extend it rather than replacing it.

## Implementation Instructions

1. Detect the anomaly in code, not with the model. Define the baseline, the threshold, and the window with deterministic rules, and only invoke the model once something has already been flagged as unusual.
2. Do the segment comparison in code as well: break the flagged period down by the dimensions the app already supports, compute each segment's contribution, and hand the model the ranked contributions to describe.
3. Require the explanation to state the exact period, the baseline it was compared against, and the size of the deviation in the metric's own units. An explanation without those three is not checkable.
4. Word every finding as a correlation. The output may say which segments moved together with the anomaly; it must not say one caused the other, and the instruction to the model should say so directly.
5. Anomaly detection thresholds and the segment contribution calculation are shared with AI Trend Analysis, which owns the routine summary of a normal series. Build the metric computation once and let this feature consume it rather than defining a second baseline that disagrees with the first.

## UI and UX Requirements

Match the application's existing design system exactly. Reuse its components,
spacing, and typography. This feature should look like it was always there.

## Responsive Requirements

Works on mobile, tablet, and desktop. Touch targets are large enough to hit on a
phone, and nothing overflows horizontally at 320px.

## Accessibility Requirements

- Fully keyboard navigable.
- Correct semantic elements and ARIA roles.
- Visible focus states.
- Meets WCAG AA contrast.
- Dynamic changes are announced to screen readers.
- Respects prefers-reduced-motion.

## Edge Cases

- Segment comparisons must respect the viewer's data access. Building a contribution table across segments the user is not permitted to see leaks restricted data through the explanation even though the underlying screens are locked.
- Correlation presented as cause will be acted on. If two segments moved together, say so in those terms and do not let the model promote a coincidence into an explanation of why.
- When no segment explains a meaningful share of the deviation, the correct output is inconclusive. Return that plainly rather than naming the largest segment by default, which is usually just the biggest segment.
- The exact window, the baseline, and the magnitude must appear in the output. An explanation that says traffic dropped sharply without saying from what, to what, and when cannot be verified or dismissed.
- A metric that is simply low-volume will trip a naive threshold constantly. Require a minimum absolute volume before an anomaly is eligible for explanation, or the feature becomes a noise generator.
- A deployment, a pricing change, or a tracking change can produce a step that is real but not interesting. Let operators mark known events so the explanation can reference them instead of hunting for a segment.
- The model may be unavailable exactly when an incident is unfolding. The detected anomaly, its baseline, and its magnitude must still be shown from the deterministic layer with the prose absent.
- Explanations must be generated once per detected anomaly and stored, not recomputed each time someone opens the dashboard.

## Testing

Exercise the feature end to end in the running application. Cover every edge case
above, then run the existing test suite and confirm nothing regressed.

## Acceptance Criteria

- [ ] Anomalies are detected by deterministic rules before any model call is made.
- [ ] Segment contributions are computed in code and restricted to segments the viewer is permitted to see.
- [ ] Every explanation states the period, the baseline, and the magnitude of the deviation.
- [ ] Findings are worded as correlations and contain no causal claims.
- [ ] Weak or diffuse evidence produces an explicit inconclusive result.
- [ ] The anomaly, baseline, and magnitude remain visible when the model is unavailable.
- [ ] Each anomaly is explained once and the result is stored rather than regenerated per view.
- [ ] The feature matches the existing design system.
- [ ] No existing functionality is broken.

## Adaptation Rules

- Match the existing design system. Do not introduce a new colour palette,
  spacing scale, or component library.
- Reuse existing components and utilities wherever they fit.
- Follow the naming, file layout, and code style already present.
- Do not upgrade, replace, or remove existing dependencies to make this
  feature fit. Adapt the feature to the app, not the app to the feature.
- Do not break existing functionality. If a change is genuinely required in
  existing code, make the smallest one that works and say so.
- If something in these instructions conflicts with how the application is
  built, follow the application and explain the deviation.

## Final Verification

Before you report the work as done:

1. Re-read the acceptance criteria above and check each one against what you
   actually built.
2. Run the application and exercise the feature end to end.
3. Run the existing test suite and confirm you have broken nothing.
4. Check the feature on mobile, tablet, and desktop widths.
5. Check keyboard navigation and focus handling.
6. Summarize what changed: files added, files modified, and anything you
   deliberately did differently because of how this application is built.

If any acceptance criterion is unmet, fix it before reporting completion.
