# AI Trend Analysis

## Objective

Explain what a chart is actually showing, in sentences backed by computed numbers.

A written summary attached to a time series or metric set, describing direction, magnitude, and comparison period.

## 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. Compute every number in ordinary code before the model is involved: the change, the rate, the comparison period, the baseline, the seasonal adjustment. The model writes prose about figures it is given and must never produce a figure of its own.
2. State the comparison window and the time zone in the summary text, resolved from the workspace's configured zone rather than the server's. A change described as week over week is meaningless without saying which weeks.
3. Instruct the model to describe what the data shows and to stop there. Do not let it assert causes, attribute movement to campaigns or releases, or predict what happens next.
4. Detect the conditions under which a summary should not be written — too few data points, a gap in collection, a tracking change mid-window — and skip generation with a plain explanation rather than narrating noise.
5. This entry owns the routine explanation of a normal series. Explaining a specific outlier belongs to AI Anomaly Explanation, and describing projected future values belongs to AI Forecast Narrative. Share the same computed-metrics layer across all three and do not let this feature drift into either.

## 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

- Every figure that appears in the prose must have come from the deterministic calculation. Cross-check the numbers in the generated text against the computed values and reject the summary if they disagree, because a wrong number in a confident sentence is the worst possible output.
- A seasonal pattern, a recurring weekly cycle, and a genuine trend all look like movement. Feed the model the seasonally adjusted view alongside the raw one and require it to say which it is describing.
- A single large spike can dominate an average and make a flat series look like growth. Identify outliers in code and tell the model they are outliers so it does not describe a one-off as a trend.
- Sparse periods, missing days, and a metric whose definition or tracking changed mid-window must suppress the summary or carry an explicit caveat, not be silently averaged over.
- Causal language must be blocked. A summary claiming the drop was caused by anything is stating something the data cannot support and must be treated as a defect.
- The summary must be cached against the exact data window and filter set that produced it, or a user changing the date range will read last week's prose above this week's chart.
- If the model times out or returns truncated text, show the chart alone. A half-finished sentence under a graph is worse than silence.
- Regenerating a summary on every filter change on a dashboard is a runaway cost. Generate on demand or on a schedule, with a per-workspace ceiling.

## 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

- [ ] All numbers in the summary come from deterministic calculation and are verified to match the underlying computation.
- [ ] The comparison period and time zone are stated explicitly in the text.
- [ ] Trend, seasonality, and one-off spikes are distinguished rather than conflated.
- [ ] Sparse, incomplete, or definition-changed data suppresses the summary or produces an explicit caveat.
- [ ] No summary asserts a cause for the movement it describes.
- [ ] Summaries are cached against the data window and filters that produced them, and generation is rate-limited.
- [ ] A model timeout or truncated response leaves the chart rendered with no summary.
- [ ] 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.
