> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase27-session07-convergence-detection-and-trajectory-visuals/spec.md).

# Session Specification

**Session ID**: `phase27-session07-convergence-detection-and-trajectory-visuals` **Phase**: 27 - Trend Finder Alpha Radar Adoption **Status**: Not Started **Created**: 2026-06-13

***

## 1. Session Overview

This session adds the first timing-aware cross-source signal to Trend Finder. The current source diversity and consensus fields tell whether multiple sources mention a topic, but they do not explain when each source picked the topic up. Session 07 derives a bounded convergence object from real evidence timestamps, records which sources appeared inside a reviewed time window, and renders the lead-lag order in the selected-trend inspection surface.

The session also turns existing historical score context into a compact score trajectory visual. The visual must show actual historical and current score points and label any slope extrapolation as an extrapolation. It must not ship Alpha Radar style time-to-breakout, peak-day, or `tbts` point estimates.

The work stays deterministic, additive, and browser-safe. No new sources, AI calls, score weights, credentials, or raw private archives are introduced. Missing or invalid timestamps produce explicit unavailable states instead of guessed ordering.

***

## 2. Objectives

1. Derive per-topic convergence from real evidence timestamps, source IDs, source roles, and a bounded default window.
2. Publish additive convergence and score trajectory schema branches with explicit unavailable states and bounded arrays.
3. Render a selected-topic lead-lag timeline that identifies the lead source role and lag to follower sources.
4. Render a selected-topic score trajectory visual with actual points and a clearly labeled slope extrapolation.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase27-session04-daily-time-series-persistence-and-sparklines` - provides daily series and historical context patterns for bounded browser projections.
* [x] `phase27-session05-velocity-dynamics-upgrade` - provides score-panel dynamics and unavailable-state patterns for time-series math.
* [x] `phase27-session06-lifecycle-stage-taxonomy` - provides lifecycle chips, radar stage color context, and current selected-topic inspector patterns.

### Required Tools/Knowledge

* Bun 1.3.14 for scripts and tests.
* TypeScript, Zod, React 19, Tailwind CSS 4, and existing Trend Finder UI conventions.
* Existing Trend Finder collector flow in `scripts/extensions/trend-finder/collector.ts`.
* Existing score, source, historical, and view-model contracts in `scripts/lib/ai-runtime/scoring.ts`, `scripts/lib/ai-runtime/historical-context.ts`, `scripts/lib/ai-runtime/source-breakdown.ts`, `src/extensions/trend-finder/schema.ts`, and `src/extensions/trend-finder/view-model.ts`.

### Environment Requirements

* Repository rooted at `/home/aiwithapex/projects/aios`.
* Phase 27 stubs present under `.spec_system/PRD/phase_27/`.
* No open security findings per `.spec_system/SECURITY-COMPLIANCE.md`.
* Existing fixture and unit-test suites runnable with Bun/Vitest.

***

## 4. Scope

### In Scope (MVP)

* A deterministic convergence helper that extracts first-seen timestamps per source from a topic's linked evidence.
* Reviewed default convergence window semantics, bounded source-hit rows, and stable ordering by first-seen time, source role, source name, and source ID.
* Explicit states for detected, not detected, single-source, and unavailable timestamp scenarios.
* Additive topic schema fields for convergence and score trajectory with strict bounds and legacy defaults.
* Collector integration after topic scoring and source-breakdown enrichment so convergence uses final evidence IDs and source metadata.
* A selected-topic lead-lag timeline in `SignalRadarPanel` that labels the lead source role and follower lag in hours.
* A selected-topic score trajectory visual that uses bounded historical score points plus current score and labels slope extrapolation as extrapolated.
* Fixture, schema, view-model, component, and runtime tests for window edges, missing timestamps, single-source topics, stable ordering, and legacy payloads.

### Out of Scope (Deferred)

* Time-to-breakout, peak-day, or `tbts` estimates - Reason: explicitly rejected by Phase 27 as invented precision.
* Any change to weighted score factors or scoring weights - Reason: convergence is context, not a score factor in this session.
* New public source adapters, source calls, or compliance reviews - Reason: this session derives from already-collected evidence only.
* Lifecycle-targeted predictions or dated prediction grading - Reason: Session 08 owns prediction wiring.
* Static Brief or public export rendering for convergence - Reason: this session targets the selected-trend inspection surface; export docs close in Session 12.

***

## 5. Technical Approach

### Architecture

Keep convergence and trajectory derivation in script/runtime helpers, then project small view models for React components:

* `scripts/lib/ai-runtime/convergence.ts` owns timestamp normalization, source first-seen extraction, convergence window detection, source ordering, lag calculation, and unavailable-state reasons.
* `scripts/lib/ai-runtime/scoring.ts` or a small trajectory helper builds the bounded score trajectory from existing `HistoricalTopicContext.scoreHistory` plus the current scored topic. This publishes actual points only; the UI computes and labels an extrapolated guide from `scoreSlope` when available.
* `scripts/extensions/trend-finder/collector.ts` calls convergence after `deriveTopicSourceBreakdowns()` and before final payload assembly. The collector emits only aggregate convergence counters in sanitized trace context.
* `src/extensions/trend-finder/schema.ts` adds convergence and trajectory schemas with `.default()` or `.catch()` fallbacks so old payloads parse.
* `src/extensions/trend-finder/view-model.ts` converts convergence and trajectory fields into labels, SVG coordinates, tones, ARIA labels, and explicit empty states.
* `src/extensions/trend-finder/components/convergence-timeline.tsx` renders fixed-height lead-lag rows with source role chips, first-seen labels, and lag labels.
* `src/extensions/trend-finder/components/score-trajectory.tsx` renders a compact SVG trajectory with actual points, current score, and a dashed or otherwise labeled extrapolation guide.
* `src/extensions/trend-finder/components/signal-radar.tsx` inserts both components into the selected-topic inspector without disrupting score factors, source context, evidence links, or radar selection behavior.

Suggested convergence semantics:

* Default window: 48 hours, capped to a safe range in the helper.
* Timestamp source: `publishedAt` on linked evidence only.
* First appearance: earliest valid evidence timestamp per source.
* Detected: at least two distinct timestamped sources have first appearances within the window.
* Not detected: at least two timestamped sources exist, but the first and last source appearances exceed the window.
* Single source: fewer than two distinct sources have linked evidence.
* Unavailable: multiple sources exist but fewer than two have valid timestamps.

### Design Patterns

* Script-only runtime boundary: derivation stays under `scripts/lib/` and the collector, not inside React components.
* Additive schema defaults: legacy payloads render explicit unavailable states.
* Project before rendering: UI components consume view-model labels and point coordinates.
* Deterministic ordering: all timelines and trajectory points sort stably with clear tie-breakers.
* Behavioral quality by design: components have stable dimensions, accessible labels, empty states, exhaustive enum handling, and reduced-motion-safe visuals.

### Technology Stack

* TypeScript 6.0.3
* React 19.2.0
* Zod 4.4.3
* Vitest 4.1.6
* Bun 1.3.14

***

## 6. Deliverables

### Files to Create

| File                                                                             | Purpose                                                       | Est. Lines |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------- | ---------- |
| `scripts/lib/ai-runtime/convergence.ts`                                          | Pure convergence helper, timestamp normalization, and states. | \~280      |
| `scripts/lib/ai-runtime/__tests__/convergence.test.ts`                           | Window, ordering, missing timestamp, and single-source tests. | \~220      |
| `src/extensions/trend-finder/components/convergence-timeline.tsx`                | Lead-lag timeline component for the selected topic inspector. | \~180      |
| `src/extensions/trend-finder/components/score-trajectory.tsx`                    | Compact historical score trajectory and extrapolation visual. | \~190      |
| `src/extensions/trend-finder/components/__tests__/convergence-timeline.test.tsx` | Component empty, detected, and unavailable state tests.       | \~120      |
| `src/extensions/trend-finder/components/__tests__/score-trajectory.test.tsx`     | Component trajectory and extrapolation label tests.           | \~120      |

### Files to Modify

| File                                                          | Changes                                                                | Est. Lines |
| ------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------- |
| `scripts/lib/ai-runtime/scoring.ts`                           | Attach bounded score trajectory fields to scored topics.               | \~90       |
| `scripts/extensions/trend-finder/collector.ts`                | Attach convergence to final topics and sanitized trace counters.       | \~90       |
| `src/extensions/trend-finder/schema.ts`                       | Add convergence and trajectory schemas, defaults, and topic fields.    | \~220      |
| `src/extensions/trend-finder/view-model.ts`                   | Add convergence and trajectory view models, labels, and SVG points.    | \~240      |
| `src/extensions/trend-finder/components/signal-radar.tsx`     | Render timeline and trajectory in the selected-topic inspector.        | \~90       |
| `src/extensions/trend-finder/fixtures.ts`                     | Add detected, unavailable, and not-detected convergence fixtures.      | \~140      |
| `src/data/live-data.example.json`                             | Add compact additive examples for convergence and trajectory.          | \~90       |
| `scripts/extensions/trend-finder/__tests__/collector.test.ts` | Cover collector convergence attachment and trace counters.             | \~120      |
| `scripts/lib/ai-runtime/__tests__/scoring.test.ts`            | Cover score trajectory projection from historical context.             | \~100      |
| `src/lib/__tests__/trend-finder-schema.test.ts`               | Cover schema defaults, bounds, malformed branches, and legacy parsing. | \~140      |
| `src/extensions/trend-finder/__tests__/view-model.test.ts`    | Cover labels, lags, trajectory points, and extrapolation copy.         | \~140      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Convergence derives only from linked evidence timestamps and source metadata already present in the run.
* [ ] Missing or invalid evidence timestamps produce explicit unavailable states, never guessed source order.
* [ ] Single-source topics render a non-converged state consistent with the `single-source-signal` risk flag.
* [ ] Detected convergence labels the lead source role and lag to follower sources inside the reviewed window.
* [ ] Score trajectory displays actual historical/current points and labels any slope extrapolation as an extrapolation.
* [ ] No `tbts`, peak-day, time-to-breakout, or unlabeled forecast estimate appears in payload or UI.

### Testing Requirements

* [ ] Unit tests cover convergence window edges, invalid timestamps, duplicate evidence IDs, single-source topics, and deterministic ordering.
* [ ] Scoring or trajectory tests cover historical score point bounds, current-score inclusion, and missing-history states.
* [ ] Schema tests cover additive defaults, array bounds, malformed branches, and legacy payload compatibility.
* [ ] View-model and component tests cover detected, not-detected, unavailable, and extrapolated trajectory labels.
* [ ] Focused Trend Finder runtime and UI test suites pass.

### Non-Functional Requirements

* [ ] Browser payload remains bounded and under the shared 1 MB extension payload limit.
* [ ] No new source adapter, credential, AI call, public collection path, or third-party transfer is introduced.
* [ ] Private snapshot archive paths and raw histories stay out of browser payloads, UI, static outputs, logs, and traces.
* [ ] Dense timeline and trajectory UI keeps stable dimensions and does not overlap text at mobile or desktop widths.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Relevant TypeScript and Vitest checks pass.

***

## 8. Implementation Notes

### Key Considerations

* Convergence should run after topic evidence IDs are finalized and after source breakdowns are attached, otherwise source names and roles can drift between the timeline and source context.
* Treat invalid dates as unavailable inputs, not as epoch dates or current run dates.
* Use source first-seen timestamps, not every evidence timestamp, for the window decision.
* Keep score trajectory bounded. Use actual historical score points from `HistoricalTopicContext.scoreHistory` and the current topic score; do not publish raw snapshot paths or private archive metadata.
* If a topic has no historical score points, show an explicit missing-history trajectory state instead of drawing a flat line.

### Potential Challenges

* Historical score series is currently richer in script context than in the browser schema: publish only bounded score points needed for the visual.
* Evidence timestamps can be sparse across sources: the helper must separate single-source evidence from multi-source evidence with missing timestamps.
* The selected-topic inspector is already dense: timeline and trajectory components need compact, fixed-size layouts and truncation-safe labels.
* Existing telemetry text in `SignalRadarPanel` is decorative: new timeline copy must clearly be data-driven and not mixed with simulated HUD strings.

### Relevant Considerations

* \[P02] **Extension payloads and demo labels stay bounded**: Convergence and trajectory arrays must be capped and additive with explicit states.
* \[P02] **New source adapters need per-source compliance review**: This session avoids new sources entirely.
* \[P05] **Script-only runtime boundary**: Runtime math stays in `scripts/lib/ai-runtime/` and collector wiring.
* \[P24] **Browser-safe export and triage boundaries**: Raw snapshots, private archive paths, and local-only state must not leak into browser-visible output.
* \[P24] **Additive defaults keep legacy payloads alive**: New schema fields default to unavailable states for old fixtures and generated payloads.
* \[P24] **Deterministic ordering helps dense triage**: Timeline and trajectory rows need stable tie-breakers for repeatable UI and tests.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Timeline and trajectory components consume external payload contracts and need exhaustive enum handling plus legacy fallback defaults.
* Selected-topic inspector controls are revisitable as the user selects different radar points, so view models must revalidate on selection changes.
* SVG visuals and dense labels can overflow on mobile unless dimensions, truncation, and accessible fallback text are explicit.

***

## 9. Testing Strategy

### Unit Tests

* `scripts/lib/ai-runtime/__tests__/convergence.test.ts`: detected window, exact edge equality, outside-window, invalid dates, duplicate evidence, missing sources, single-source topics, and stable ordering.
* `scripts/lib/ai-runtime/__tests__/scoring.test.ts`: bounded score trajectory points, current score inclusion, legacy missing-history fallback, and no extrapolated point in payload.

### Integration Tests

* `scripts/extensions/trend-finder/__tests__/collector.test.ts`: convergence attachment after source breakdowns and sanitized trace counters.
* `src/lib/__tests__/trend-finder-schema.test.ts`: strict schema parsing, malformed fallback, max-array rejection or fallback, and legacy payload defaults.

### Component Tests

* `src/extensions/trend-finder/components/__tests__/convergence-timeline.test.tsx`: detected, not-detected, single-source, unavailable, and accessible labels.
* `src/extensions/trend-finder/components/__tests__/score-trajectory.test.tsx`: actual points, missing-history state, and visibly labeled extrapolation.
* `src/extensions/trend-finder/__tests__/view-model.test.ts`: lag labels, source role labels, SVG points, trajectory summary labels, and sanitized text.

### Manual Testing

* Open `/extensions/trend-finder/trends`, select ranked topics in the radar, and verify the selected-topic inspector updates timeline and trajectory content without layout shift.
* Check a single-source fixture topic and a missing-history fixture topic to confirm explicit empty states.
* Resize to mobile width and confirm timeline rows, source names, and score labels do not overlap.

### Edge Cases

* Multiple evidence items from the same source with different timestamps.
* Two sources whose first appearances are exactly at the window boundary.
* Invalid, blank, future, or malformed `publishedAt` values.
* Topic evidence IDs that do not resolve to evidence rows.
* Historical score history with one point, zero points, duplicate run times, or more points than the browser cap.

***

## 10. Dependencies

### External Libraries

* None. This session should use existing TypeScript, React, Zod, and Vitest dependencies only.

### Internal Dependencies

* `scripts/lib/ai-runtime/scoring.ts`
* `scripts/lib/ai-runtime/historical-context.ts`
* `scripts/lib/ai-runtime/source-breakdown.ts`
* `scripts/extensions/trend-finder/collector.ts`
* `src/extensions/trend-finder/schema.ts`
* `src/extensions/trend-finder/view-model.ts`
* `src/extensions/trend-finder/components/signal-radar.tsx`
* `src/extensions/trend-finder/fixtures.ts`

### Other Sessions

* **Depends on**: `phase27-session04-daily-time-series-persistence-and-sparklines`, `phase27-session05-velocity-dynamics-upgrade`, `phase27-session06-lifecycle-stage-taxonomy`
* **Depended by**: `phase27-session08-dated-predictions-and-story-log`, `phase27-session12-documentation-validation-and-release`

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase27-session07-convergence-detection-and-trajectory-visuals/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
