> 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-session05-velocity-dynamics-upgrade/spec.md).

# Session Specification

**Session ID**: `phase27-session05-velocity-dynamics-upgrade` **Phase**: 27 - Trend Finder Alpha Radar Adoption **Status**: Not Started **Created**: 2026-06-12

***

## 1. Session Overview

This session upgrades Trend Finder's velocity model from a single current-run delta into a small, deterministic dynamics layer. Session 04 now persists private daily evidence counts and publishes bounded sparklines, so Trend Finder can derive acceleration, significance, and burst context without new sources, new AI calls, or private archive exposure.

The work keeps the existing six-factor score contract stable. Acceleration and significance are additive context fields, while burst is a capped support signal that can help momentum but cannot dominate the weighted score. All three values must show explicit unavailable states when history is missing or sample sizes are too low.

This session is the direct prerequisite for Session 06 lifecycle stages and Session 07 trajectory/convergence visuals. Those later sessions need reliable velocity dynamics, bounded browser fields, and UI copy that explains whether a topic is accelerating, statistically meaningful, or only a short-lived burst.

***

## 2. Objectives

1. Derive per-topic acceleration from consecutive evidence-count deltas across archived snapshots and the current run.
2. Derive a significance estimate by comparing the current delta against the topic's historical delta variance, with `unavailable` below 3 snapshots.
3. Derive a bounded burst signal from the 14-day daily series, using the last-48-hour share of volume and an explicit unavailable state when series data is missing.
4. Publish bounded browser schema fields and score-breakdown display rows for acceleration, significance, and burst while preserving legacy payload compatibility.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase27-session01-brief-movement-groups-and-calibration-metrics` - establishes Phase 27 additive payload and calibration patterns.
* [x] `phase27-session02-deterministic-derived-signals-and-risk-flags` - establishes deterministic derived signal defaults and risk-state rendering.
* [x] `phase27-session03-data-driven-radar-aliases-and-watching-state` - establishes current trend card, radar, and Workbench projection patterns.
* [x] `phase27-session04-daily-time-series-persistence-and-sparklines` - provides private daily evidence counts and bounded 14-day sparkline output consumed by burst detection.

### Required Tools/Knowledge

* Bun 1.3.14 for scripts and test execution.
* TypeScript, Zod, React, Tailwind CSS 4, and existing Trend Finder component conventions.
* Current scoring flow in `scripts/lib/ai-runtime/scoring.ts`.
* Current historical context and snapshot flow in `scripts/lib/ai-runtime/historical-context.ts`, `scripts/lib/ai-runtime/snapshots.ts`, and `scripts/lib/ai-runtime/trend-series.ts`.
* Current score-breakdown and view-model projection patterns in `src/extensions/trend-finder/`.

### Environment Requirements

* Repository rooted at `/home/aiwithapex/projects/aios`.
* Phase 27 session stubs present under `.spec_system/PRD/phase_27/`.
* Existing fixture and unit-test suites runnable with Bun/Vitest.

***

## 4. Scope

### In Scope (MVP)

* Trend Finder runtime derives acceleration from the current evidence-count delta minus the prior evidence-count delta for the same canonical topic.
* Trend Finder runtime derives velocity significance from historical delta variance only when at least 3 snapshots are available.
* Trend Finder runtime derives a burst score from the bounded 14-day daily series, using the last 2 day buckets as the last-48-hour window.
* Trend Finder runtime applies burst as a capped support contribution to the momentum factor without changing six-factor weights.
* Browser payload exposes bounded dynamics fields with explicit `available`/`unavailable` states, sample counts, and short reasons.
* Score breakdown UI renders rows for acceleration, significance, and burst with explicit unavailable states and stable dense-dashboard sizing.
* Engine Replay scoring proof labels and sanitized trace counters remain accurate after the new math is wired.
* Tests cover hand-computed acceleration, significance, burst, low-sample, missing-history, new-topic, and legacy-payload cases.

### Out of Scope (Deferred)

* Changing the six-factor weights - Reason: the phase stub explicitly keeps the existing weighted score contract and adds only capped burst support.
* Lifecycle stage classification - Reason: Session 06 consumes the dynamics fields after this session lands.
* Forecast and trajectory visuals - Reason: Session 07 consumes the dynamics fields after lifecycle classification.
* Dated predictions or Story Log behavior - Reason: Session 08 owns target-date prediction changes.
* New source adapters, new public collection, or new AI calls - Reason: this session derives from existing snapshots, evidence, and daily series.

***

## 5. Technical Approach

### Architecture

Keep the math pure and script-owned, then project bounded browser fields:

* `scripts/lib/ai-runtime/velocity-dynamics.ts` owns pure helpers for evidence-count history normalization, delta series construction, acceleration, statistical significance, and burst scoring.
* `scripts/lib/ai-runtime/historical-context.ts` extends each historical topic context with bounded evidence-count history and delta history assembled from dated snapshots in deterministic order.
* `scripts/lib/ai-runtime/scoring.ts` receives the historical delta context and topic sparkline context, derives velocity dynamics for each canonical topic, applies a capped burst support value to momentum, and attaches the bounded dynamics object to the topic.
* `scripts/extensions/trend-finder/collector.ts` passes historical sparkline context into scoring, logs only aggregate dynamics counters, and keeps private snapshot paths out of trace output.
* `src/extensions/trend-finder/schema.ts` adds additive dynamics schemas with strict caps and defaults so old generated payloads still parse.
* `src/extensions/trend-finder/view-model.ts` turns raw dynamics states into compact labels, tones, descriptions, and accessibility copy.
* `src/extensions/trend-finder/components/score-breakdown.tsx` renders the three dynamics rows near existing score-factor context, with explicit unavailable states and stable dimensions.
* `src/extensions/trend-finder/engine-replay-model.ts` and sanitized trace mapping continue to explain the scoring stage accurately.

Acceleration should use evidence-count deltas, not score deltas, because the Phase 27 stub anchors item 1.1 to the current momentum velocity signal based on evidence-count change. Significance should compare the current delta with historical deltas for the same canonical topic and return unavailable below 3 snapshots or when variance is zero. Burst should use 14-day daily counts and the final two day buckets, capping support so a short spike cannot overwhelm score factors.

### Design Patterns

* Script-only runtime boundary: private history and math stay under `scripts/lib/` and collector code.
* Additive schema defaults: new browser fields default to unavailable states so legacy payloads and fixtures continue parsing.
* Explicit unavailable states: low sample, missing history, zero variance, and no daily volume are represented as intentional states.
* Project before rendering: components consume view models and labels, not raw math internals.
* Deterministic ordering: snapshot histories, delta points, and UI rows use stable canonical-topic and timestamp ordering.
* Behavioral quality by design: score-breakdown rows include accessible labels, stable compact sizing, and exhaustive state handling.

### 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/velocity-dynamics.ts`                               | Pure acceleration, significance, burst, and capped-support helpers. | \~260      |
| `scripts/lib/ai-runtime/__tests__/velocity-dynamics.test.ts`                | Hand-computed math tests for dynamics states and caps.              | \~220      |
| `src/extensions/trend-finder/components/__tests__/score-breakdown.test.tsx` | Component tests for dynamics rows, unavailable copy, and labels.    | \~140      |

### Files to Modify

| File                                                          | Changes                                                                       | Est. Lines |
| ------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------- |
| `scripts/lib/ai-runtime/historical-context.ts`                | Add bounded evidence-count and delta history per canonical topic.             | \~180      |
| `scripts/lib/ai-runtime/scoring.ts`                           | Derive dynamics, apply capped burst support, and attach topic fields.         | \~220      |
| `scripts/extensions/trend-finder/collector.ts`                | Pass historical sparkline context into scoring and log aggregate counters.    | \~80       |
| `scripts/extensions/trend-finder/engine-trace.ts`             | Preserve sanitized scoring-stage labels and counters for new dynamics.        | \~60       |
| `src/extensions/trend-finder/schema.ts`                       | Add bounded velocity dynamics schemas and defaults.                           | \~180      |
| `src/extensions/trend-finder/view-model.ts`                   | Add dynamics labels, tones, descriptions, and accessibility text.             | \~180      |
| `src/extensions/trend-finder/components/score-breakdown.tsx`  | Render acceleration, significance, and burst rows.                            | \~130      |
| `src/extensions/trend-finder/components/trend-card.tsx`       | Pass topic dynamics into score breakdown.                                     | \~40       |
| `src/extensions/trend-finder/engine-replay-model.ts`          | Keep scoring proof descriptions aligned with burst support.                   | \~60       |
| `src/extensions/trend-finder/fixtures.ts`                     | Add available and unavailable dynamics fixture states.                        | \~120      |
| `scripts/lib/ai-runtime/__tests__/historical-context.test.ts` | Cover historical count and delta-history assembly.                            | \~120      |
| `scripts/lib/ai-runtime/__tests__/scoring.test.ts`            | Cover scoring integration, low-sample states, and capped burst support.       | \~160      |
| `src/lib/__tests__/trend-finder-schema.test.ts`               | Cover additive dynamics defaults, caps, malformed values, and legacy parsing. | \~120      |
| `src/extensions/trend-finder/__tests__/view-model.test.ts`    | Cover dynamics view-model labels, ordering, and unavailable states.           | \~100      |
| `src/lib/__tests__/trend-finder-engine-replay.test.tsx`       | Cover updated scoring proof copy/counters.                                    | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Acceleration is derived from consecutive evidence-count deltas for the same canonical topic.
* [ ] Significance returns `unavailable` below 3 snapshots or when variance is not meaningful.
* [ ] Burst derives from the 14-day series and uses the last 2 day buckets as the last-48-hour window.
* [ ] Burst support is capped and cannot dominate the six-factor score.
* [ ] Legacy payloads without dynamics fields still parse and render unavailable states.
* [ ] New-topic and missing-history topics never show invented acceleration, significance, or burst values.
* [ ] Engine Replay scoring stage labels remain accurate for the new math.

### Testing Requirements

* [ ] Unit tests cover acceleration, significance, burst, caps, low sample, zero variance, new topic, missing history, and missing series.
* [ ] Historical-context tests cover bounded evidence-count and delta-history assembly from dated snapshots.
* [ ] Schema tests cover additive defaults, bounds, malformed values, and legacy payload compatibility.
* [ ] Component/view-model tests cover available and unavailable dynamics rows with accessible labels.
* [ ] Focused Trend Finder runtime and UI test suites pass.

### Non-Functional Requirements

* [ ] Browser payload stays within the shared 1 MB extension payload limit.
* [ ] No new public source collection path, credential, AI call, or third-party transfer path is introduced.
* [ ] Private snapshot archives and paths remain out of browser payloads, traces, UI, static exports, and logs.
* [ ] Deterministic reruns produce the same dynamics values for the same inputs.

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

* Acceleration and significance should use evidence-count deltas, not score deltas, to stay aligned with the existing velocity signal described in the Phase 27 stub.
* The significance output should be a conservative estimate, not a claim of causal certainty. A normalized z-style score and state label are enough for MVP.
* Burst is a support signal. Keep the cap explicit, tested, and visible in code so future score work does not accidentally turn burst into a dominant factor.
* Keep unavailable reasons short enough for browser payload and UI labels.

### Potential Challenges

* Historical snapshots can be sparse: mitigate with explicit low-sample and missing-history states.
* Zero variance can make significance misleading: mitigate by returning unavailable rather than dividing by zero or inventing confidence.
* Collector ordering currently attaches sparklines after scoring: mitigate by passing historical sparkline context and deriving current daily counts where scoring has access to evidence timestamps.
* Dense UI rows can overflow: mitigate with compact labels, fixed row sizing, and component tests.

### Relevant Considerations

* \[P02] **Extension payloads and demo labels stay bounded**: Dynamics fields must be bounded, additive, and explicit about unavailable states.
* \[P05] **Script-only runtime boundary**: Dynamics math and private history stay under `scripts/lib/` and collector code; browser code receives bounded projections only.
* \[P24] **Browser-safe export and triage boundaries**: Private snapshot paths, raw archives, and local cache internals must not leak into browser-visible output.
* \[P24] **Additive defaults keep legacy payloads alive**: Schema defaults must preserve existing fixtures and generated payloads.
* \[P24] **Deterministic ordering helps dense triage**: Sort histories and UI rows deterministically.
* \[P00] **Do not document planned features as implemented**: This session does not update manuals beyond code-facing labels; full docs closeout remains Session 12.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Low-history topics could show numeric values that look authoritative.
* Burst support could silently overpower existing momentum behavior.
* Score-breakdown UI could crowd dense trend cards or hide unavailable states.
* Engine Replay could describe the scoring stage incompletely after new math lands.

***

## 9. Testing Strategy

### Unit Tests

* Test acceleration with hand-computed current, previous, and prior deltas.
* Test significance with 3+ snapshots, below-threshold snapshots, zero variance, and negative deltas.
* Test burst scoring with last-2-day volume, zero volume, missing series, and capped support contribution.
* Test historical-context assembly from dated snapshots with canonical-topic matching and deterministic ordering.

### Integration Tests

* Test `scoreTrendTopics` attaches dynamics fields and keeps legacy weighted score behavior stable aside from capped burst support.
* Test collector scoring trace output reports aggregate dynamics counters without private paths.
* Test schema parsing for old payloads, malformed dynamics fields, and capped arrays/numbers.

### Manual Testing

* Open Trend Finder fixture data and inspect a selected trend with available dynamics rows.
* Inspect a low-sample/new-topic fixture and confirm all dynamics rows show explicit unavailable states.
* Open Engine Replay and confirm the scoring proof still explains accepted score factors and burst support without exposing private history.

### Edge Cases

* New topic with no previous snapshot.
* Topic with one prior snapshot only.
* Topic with 3 snapshots but identical deltas.
* Topic with evidence volume only in older day buckets.
* Topic with malformed or missing evidence timestamps.
* Legacy generated payload without any dynamics fields.

***

## 10. Dependencies

### External Libraries

* None. Use existing TypeScript, Zod, React, and Vitest dependencies.

### Other Sessions

* **Depends on**: `phase27-session04-daily-time-series-persistence-and-sparklines`
* **Depended by**: `phase27-session06-lifecycle-stage-taxonomy`, `phase27-session07-convergence-detection-and-trajectory-visuals`

***

## 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-session05-velocity-dynamics-upgrade/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.
