> 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-session02-deterministic-derived-signals-and-risk-flags/spec.md).

# Session Specification

**Session ID**: `phase27-session02-deterministic-derived-signals-and-risk-flags` **Phase**: 27 - Trend Finder Alpha Radar Adoption **Status**: Not Started **Created**: 2026-06-12

***

## 1. Session Overview

This session adds the next Tier 1 Alpha Radar improvements to Trend Finder: deterministic, zero-AI-cost derived signals that make each topic easier to judge without changing the weighted six-factor opportunity score. The new fields cover crowding, gem ranking strength, source consensus, builder/research role share, and topic-specific risk flags.

The work builds directly on Session 01's additive schema and view-model pattern. It keeps all math under the script/runtime boundary, publishes only bounded browser-safe fields through `src/extensions/trend-finder/schema.ts`, and renders explicit unavailable states rather than using zeros when a signal cannot be derived.

The result is a better Trend Finder triage loop: cards explain whether a trend is already crowded, Hidden Gems sort by a continuous signal instead of a boolean gate, Workbench users can filter by saturation and risk, and degraded runs report consensus against the healthy source denominator only.

***

## 2. Objectives

1. Add additive schema fields and defaults for saturation, hidden-gem score, consensus ratio, role-share/builder signal, and deterministic risk flags.
2. Derive every new signal from existing topic, source, evidence, source-local, and historical context without changing the six-factor opportunity score.
3. Render compact chips, unavailable states, Hidden Gems ordering, and Workbench filters/sorts for the new signals.
4. Add focused tests for derivation math, degraded/empty cases, legacy payload parsing, UI view models, and deterministic ordering.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase27-session01-brief-movement-groups-and-calibration-metrics` - establishes Phase 27 additive schema, view-model, fixture, and test patterns.

### Required Tools/Knowledge

* Bun 1.3.14 for package scripts and Vitest.
* React 19, TanStack Start, Tailwind CSS 4, and existing dense Trend Finder UI patterns.
* Zod additive defaults for browser payload compatibility.
* Existing Trend Finder scoring, source breakdown, source-local signal, Signal Workbench, Hidden Gems, and card view-model helpers.

### Environment Requirements

* Repository rooted at `/home/aiwithapex/projects/aios`.
* Phase 27 PRD stubs present under `.spec_system/PRD/phase_27/`.
* No live source run is required; fixtures and unit tests must cover healthy, degraded, empty, stale, and legacy payload cases.

***

## 4. Scope

### In Scope (MVP)

* Trend Finder operator can see a bounded saturation estimate per topic with explicit unavailable state when there is no evidence or no healthy source denominator.
* Trend Finder operator can rank Hidden Gems by a continuous hidden-gem score derived from novelty margin, evidence-strength margin, inverse saturation, and existing hidden-gem criteria.
* Trend Finder operator can see consensus ratio normalized by active/degraded sources from the current run, not total configured or offline sources.
* Trend Finder operator can see per-topic role shares and a builder signal share for developer/research evidence.
* Trend Finder operator can see deterministic risk flags for `single-source-signal`, `low-quality-source-dominated`, `stale-evidence`, and `placement-adjacent`.
* Signal Workbench can filter by saturation band and risk flag while keeping stable deterministic sorting and tie-breakers.
* Legacy payloads, fallback fixtures, and generated example data keep parsing through additive defaults.

### Out of Scope (Deferred)

* Radar axis wiring - Reason: planned for Session 03 after saturation exists.
* Data-driven aliases and watching/pin state - Reason: planned for Session 03.
* Daily time-series persistence, velocity dynamics, lifecycle taxonomy, and convergence visuals - Reason: planned for Sessions 04-07.
* Dated prediction breakout likelihood or AI-written risk rationale - Reason: planned prediction/story machinery begins in Session 08; this session keeps flags deterministic.
* Any change to the weighted six-factor opportunity score or score weights - Reason: the session adds display/filter signals only.
* New public source adapters, AI calls, or source calls - Reason: no new collection or third-party transfer belongs in this session.

***

## 5. Technical Approach

### Architecture

Keep the score path additive. Extend `TrendTopicSchema` with bounded defaults for the derived fields, then populate those fields from existing runtime helpers:

* `scripts/lib/ai-runtime/scoring.ts` computes saturation and continuous hidden-gem score from topic evidence context, historical recurrence, and current-run source health while leaving `calculateOpportunityScore` and `OPPORTUNITY_SCORE_WEIGHTS` unchanged.
* `scripts/lib/ai-runtime/source-breakdown.ts` attaches consensus ratio, source role shares, and builder signal share while it already has topic evidence, source summaries, source roles, quality tiers, and source health.
* `scripts/lib/ai-runtime/risk-flags.ts` derives bounded per-topic flag codes from topic/source/evidence context and keeps flag logic testable outside UI.
* `src/extensions/trend-finder/view-model.ts` turns raw fields into labels, tones, unavailable copy, and risk-chip models so cards, Hidden Gems, source breakdown, and Workbench do not duplicate formatting rules.

Consensus denominator is the number of current-run sources whose status is not `offline`. If that denominator is zero, `consensusRatio` is unavailable. Risk flags are deterministic and bounded; they must not contain free-form AI-written rationale text.

### Design Patterns

* Additive schema defaults: Preserve old generated payloads and fixtures.
* Script-only runtime boundary: Derived math stays under `scripts/lib/` and browser code consumes validated fields only.
* Explicit unavailable states: Null/empty derived fields render as unavailable, never as misleading zero-confidence signals.
* Stable deterministic ordering: Hidden Gems and Workbench tie-break by rank, score, name, and ID.
* Project before rendering: UI surfaces consume view models and sanitized labels rather than raw enum/display decisions.
* Behavioral quality by design: Fetching/display views include empty/error states, interactive filters have labels and reset behavior, and component contract fields use exhaustive enum 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/risk-flags.ts`                | Deterministic per-topic risk flag helper.      | \~160      |
| `scripts/lib/ai-runtime/__tests__/risk-flags.test.ts` | Unit tests for flag derivation and edge cases. | \~120      |

### Files to Modify

| File                                                                   | Changes                                                                                                          | Est. Lines |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/trend-finder/schema.ts`                                | Add derived signal fields, role-share shape, risk flag enum/defaults, and exported types.                        | \~160      |
| `scripts/lib/ai-runtime/scoring.ts`                                    | Derive saturation and continuous hidden-gem score without changing opportunity score weights.                    | \~180      |
| `scripts/lib/ai-runtime/source-breakdown.ts`                           | Attach consensus ratio, source role shares, and builder signal share from topic evidence/source context.         | \~180      |
| `src/extensions/trend-finder/view-model.ts`                            | Add labels, bands, unavailable copy, risk-chip view models, and Hidden Gems sort helper usage.                   | \~180      |
| `src/extensions/trend-finder/components/trend-card.tsx`                | Render saturation, hidden-gem score, builder/consensus, and risk chips with accessible labels and fallback copy. | \~120      |
| `src/extensions/trend-finder/components/source-breakdown.tsx`          | Render source consensus and role-share summary with explicit unavailable state.                                  | \~90       |
| `src/extensions/trend-finder/views/hidden-gems-view.tsx`               | Update copy and ordering to use continuous hidden-gem score with deterministic tie-breakers.                     | \~60       |
| `src/extensions/trend-finder/signal-workbench-model.ts`                | Add saturation/risk fields, filters, facets, search text, and deterministic sort behavior.                       | \~180      |
| `src/extensions/trend-finder/components/signal-workbench-controls.tsx` | Add labeled saturation and risk filter controls with reset integration.                                          | \~80       |
| `src/extensions/trend-finder/components/signal-workbench-table.tsx`    | Surface saturation/risk/builder values in compact rows without layout overflow.                                  | \~90       |
| `src/extensions/trend-finder/fixtures.ts`                              | Add filled, unavailable, risk-flagged, and legacy/default fixture coverage.                                      | \~120      |
| `scripts/lib/ai-runtime/__tests__/scoring.test.ts`                     | Cover saturation, hidden-gem score, historical recurrence, and unchanged opportunity score.                      | \~140      |
| `scripts/lib/ai-runtime/__tests__/source-breakdown.test.ts`            | Cover consensus denominator, role shares, low-quality dominance, and degraded source cases.                      | \~120      |
| `src/extensions/trend-finder/__tests__/view-model.test.ts`             | Cover labels, bands, unavailable states, and risk-chip view models.                                              | \~110      |
| `src/extensions/trend-finder/__tests__/signal-workbench-model.test.ts` | Cover filter/facet/sort behavior for saturation and risk flags.                                                  | \~120      |
| `src/lib/__tests__/trend-finder-schema.test.ts`                        | Cover legacy payload parsing when derived fields are omitted.                                                    | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Saturation, hidden-gem score, consensus ratio, role shares, builder signal, and risk flags derive deterministically from existing run data.
* [ ] The weighted six-factor opportunity score and score weights are unchanged.
* [ ] Degraded runs calculate consensus ratio against healthy current-run sources only.
* [ ] Topics without evidence or denominator support render explicit unavailable labels rather than fake zero signals.
* [ ] Hidden Gems ordering uses continuous hidden-gem score first, then stable tie-breakers.
* [ ] Cards and Workbench show risk flags as bounded chips, with no free-form AI-generated rationale.
* [ ] Legacy payloads that omit the new fields parse with safe defaults.

### Testing Requirements

* [ ] Script tests cover saturation, hidden-gem score, consensus ratio, role shares, and risk flags.
* [ ] Schema tests cover omitted-field defaults and unknown/invalid risk flag rejection or fallback behavior.
* [ ] View-model tests cover labels, tones, empty/unavailable states, and deterministic Hidden Gems ordering.
* [ ] Signal Workbench tests cover saturation/risk filters, facets, search, and stable sort tie-breakers.
* [ ] Focused tests pass before full validation is attempted.

### Non-Functional Requirements

* [ ] No new source calls, AI calls, third-party transfers, browser-visible raw source payloads, private paths, prompts, provider responses, or local triage notes are introduced.
* [ ] New arrays and role-share lists remain bounded under the existing Trend Finder payload limit.
* [ ] UI controls remain keyboard accessible, labeled, resettable, and usable in empty/error/offline states.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `bun run test` passes or failures are documented before validation.
* [ ] `bun run typecheck` and `bun run typecheck:scripts` pass or failures are documented before validation.

***

## 8. Implementation Notes

### Key Considerations

* Treat saturation as a display/filter estimate, not a replacement for novelty or the opportunity score.
* Keep hidden-gem boolean selection for compatibility, but add a continuous score for ordering and explanation.
* Normalize consensus by active/degraded sources only. Offline or blocked sources should not punish an otherwise healthy partial run.
* Keep role shares evidence-count based and bounded. A missing source role should map to `unknown`, not developer/research.
* `placement-adjacent` should use existing source-local placement treatment and excluded-placement counts; it must not inspect raw private source payloads.

### Potential Challenges

* Saturation thresholds may look authoritative: use labels such as "derived" and "unavailable" so users understand this is a deterministic estimate.
* Source health denominator can be zero: render unavailable and test the empty denominator explicitly.
* Risk flags can become noisy: cap to the four scoped flags and keep stable ordering.
* Workbench controls can overflow: keep labels compact, use existing select control patterns, and test rows with long topic names.

### Relevant Considerations

* \[P02] **Extension payloads and demo labels stay bounded**: new fields are bounded and additive with explicit provenance/unavailable states.
* \[P02] **New source adapters need per-source compliance review**: this session does not add sources or source calls.
* \[P15] **Aggregate collection must stay budgeted**: all signals are computed from already-collected data and do not increase collection cost.
* \[P24] **Browser-safe export and triage boundaries**: derived browser fields must not expose raw evidence, private paths, or local triage notes.
* \[P24] **Additive defaults keep legacy payloads alive**: repeat the additive Zod default pattern used by prior Trend Finder sessions.
* \[P24] **Deterministic ordering helps dense triage**: new Hidden Gems and Workbench ordering must have stable tie-breakers.
* \[P05] **Script-only runtime boundary**: derived math belongs in script/runtime helpers, with browser UI reading validated fields only.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Derived numeric fields could render as zeros when they are actually unavailable.
* Workbench filters could hide all rows without explaining the active filter combination.
* Repeated filter/sort interactions could shift table layout or lose focus.

***

## 9. Testing Strategy

### Unit Tests

* Scoring tests for saturation pressure, hidden-gem score, historical recurrence, no-evidence unavailable state, and unchanged weighted score.
* Source breakdown tests for active/degraded denominator handling, offline exclusion, role-share totals, builder signal share, and quality dominance.
* Risk flag tests for each scoped flag plus no-flag, stale-date, missing-date, and bounded-order cases.
* Schema tests for legacy payload defaults and invalid risk flag handling.

### Integration Tests

* Collector-adjacent tests proving scored topics keep the derived fields after source breakdown and source-local signal derivation.
* Signal Workbench model tests proving filters/facets/sorts combine without mutating generated payloads.

### Manual Testing

* Open Trend Finder cards, Hidden Gems, and Signal Workbench with fixture data and verify chips, unavailable labels, filters, and long-row layout.
* Verify a degraded-source fixture shows consensus based on active/degraded sources only.

### Edge Cases

* No topics, no evidence, or no healthy sources.
* Single-source topic with otherwise high score.
* Topic dominated by low-quality evidence.
* Evidence dates missing or older than the stale threshold.
* All source-local placement signals excluded or unavailable.
* Legacy payloads without any Session 02 fields.

***

## 10. Dependencies

### External Libraries

* None new.

### Other Sessions

* **Depends on**: `phase27-session01-brief-movement-groups-and-calibration-metrics`
* **Depended by**: `phase27-session03-data-driven-radar-aliases-and-watching-state`, `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-session02-deterministic-derived-signals-and-risk-flags/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.
