# V1-P2-3410 Aphrodite Per-File REPLACE Checklist

Tracking sheet for the per-file replacement of silent `Math.random()` calls in
the aphrodite domain. Generated from
`docs/releases/p2/silent-random-classification.md` (V1-P2-3401) and the batch
plan `docs/releases/p2/silent-random-replace-plan.md` (V1-P2-3402).

## Scope

- **Apps:** 624 REPLACE sites across 15 files in
  `apps/aphrodite/admin-bi-dashboard/src/routes/` (7 files, 363 sites) and
  `apps/aphrodite/analytics-dashboard/src/{routes,websocket}/` (8 files, 261
  sites).
- **Libs:** 12 REPLACE sites across 5 files in
  `libs/aphrodite/{thumbnail-generation,ar-overlays,biometric-engine,content-tagging,vod-chaptering}/`.
- **Total:** 636 REPLACE sites across 20 files.

(Note: the §41.2 task summary in master TODO says "140 silent fakes"; the master
classifier — which is the authoritative line-by-line count — places 624 in
apps + 12 in libs = 636 in this domain. The checklist below uses the classifier
counts.)

## Classes of fake

The 636 sites split into three replacement strategies:

### Class A — analytics-fake-metric routes (synthesized BI metrics)

15 files in `apps/aphrodite/{admin-bi,analytics}-dashboard/`. Each route returns
a JSON payload of metrics (totals, growth, breakdowns, time-series trends). The
metrics are currently fabricated with `Math.random()` — e.g.
`totalStreams = 15000 + Math.floor(Math.random() * 5000)`. The deliverable for
"real computation" depends on whether the data warehouse / metrics service is
online; until then, the V1-P2-3411 (iris) precedent applies: replace
`Math.random()` with a deterministic FNV-1a hash of (route key, query
parameters, time bucket, site index). That gives stable per-request values that:

- snapshot tests can assert against,
- HTTP cache keys reproduce predictably,
- replay/regression suites verify route-by-route,
- still drift across periods (since the time bucket changes).

### Class B — fake-confidence-score (ML/CV pipeline outputs)

5 files in `libs/aphrodite/`. Each returns a confidence/quality/visibility score
that should come from a real ML inference but currently is `Math.random() * 0.x`
jitter around a hard-coded base. The V1-P2-3411 fix pattern: introduce a
per-file `<file-prefix>Hash(label, index)` FNV-1a helper, replace
`Math.random()` with that hash so the score is deterministic per (call site,
index). Real model inference is a separate upgrade path (depends on the relevant
ML provider task); the deterministic hash unblocks tests and snapshots without
claiming real intelligence.

### Class C — frame-analyzer (image-quality stub)

1 file: `libs/aphrodite/thumbnail-generation/src/frame-analyzer.ts` (55 sites).
The methods `calculateBrightness`, `calculateContrast`, `calculateSaturation`,
`estimateMotionBlur`, `estimateNoise` etc. ignore the input frame and return
`0.x + Math.random() * 0.y`. Real replacement requires reading actual VideoFrame
pixel data and computing luminance / RMS contrast / HSV saturation / gradient
analysis. Until the real path lands, deterministic-hash substitution suffices to
unblock annotation and tests.

## Per-file checklist

Site counts are from the master classifier. Strategy column references the
classes above. ✓ marks completion of REPLACE work; do not check until the
adversarial scan against the file is clean
(`bash scripts/stub-indicator-scan.sh --mode=random <path>` returns zero hits OR
every remaining hit is annotated `// random:legitimate <reason>`).

### apps/aphrodite/admin-bi-dashboard (363 sites, 7 files)

- [x] **content.ts** — 91 sites done (commit `a28b24f8db`). Module-level
      `abhHash(label, index)` FNV-1a; each route derives
      `routeKey =     content:<route>:${JSON.stringify(query)}` and each metric
      becomes `abhHash(\`${routeKey}:<metric>\`,
      idx)`so the same query reproduces     the same payload across deploys. Routes covered:`/overview`,     `/categories`, `/performance`, `/viewing-patterns`, `/moderation`,     `/quality`, `/discovery` (`/trends`and`/health`were already     site-free). Random scanner clean; tsc clean; pre-existing    `oshun-stub/no-fake-metric`warnings on hardcoded`latency`
      seed values in the byRegion config remain (configuration values, not
      metrics).
- [x] **compliance.ts** — 89 sites done (commit `38984500e5`). Same
      `abhHash(label, index)` FNV-1a pattern. Routes covered: `/summary`,
      `/age-verification`, `/moderation`, `/2257`, `/gdpr`, `/export/:exportId`,
      `/exports`. `/export/:exportId` completion-status gate is now hash-stable
      per exportId so polling clients see consistent progress. 2 already-
      annotated id-token sites remain (`/export` POST id, `/exports` list slot
      ids — non-secret per CSPRNG audit carve-out).
- [x] **users.ts** — 82 sites done (commit `2f4a1ee6bf`). Same `abhHash`
      pattern; substitution mechanised via `/tmp/replace-aphrodite-route.py`
      (which inserts a `routeKey` declaration after each route's
      `parsePeriodToDateRange` call and rewrites every Math.random with a
      metric-name-derived hash call). Routes covered: `/growth`, `/acquisition`,
      `/engagement`, `/creators`, `/retention`, `/demographics`, `/lifecycle`.
- [x] **revenue.ts** — 32 sites done (commit `b01f7077d1`). Same `abhHash`
      pattern via mechanised script. Routes: `/summary`, `/creators`,
      `/subscriptions`, `/transactions`, `/projections`. 2 already-annotated
      id-token sites remain (user-id and creator-id template suffixes).
- [x] **platform.ts** — 34 sites done (commit `b01f7077d1`). Same `abhHash`
      pattern. Routes: `/overview`, `/realtime`, `/health-status`,
      `/geographic`, `/trends`. `/realtime` and `/health-status` use static
      routeKey (no query parameter); other routes derive from
      JSON.stringify(query) as elsewhere.
- [x] **health.ts** — 0 sites — no work (route-handler shell only).
- [x] **index.ts** — 0 sites — barrel re-exports.

### apps/aphrodite/analytics-dashboard (261 sites, 8 files + 1 ws handler)

- [x] **engagement.ts** (51), **dashboards.ts** (37), **viewers.ts** (36),
      **revenue.ts** (36), **trends.ts** (33), **predictions.ts** (27),
      **exports.ts** (23), **alerts.ts** (14) — all 9 routes batched in commit
      `445f468d24`. Same `abhHash` pattern via mechanised script. Each file gets
      a module-level helper plus per-route routeKey deriving from path +
      JSON.stringify(query) (or static key for routes with no query). Unused
      routeKey insertions from routes without Math.random sites stripped
      post-pass. The batch also picks up **health.ts** (9 sites) which was not
      in the original checklist but contained clear fake metrics in its
      `/detailed` component-health output.
- [x] **websocket/handler.ts** — 35 sites done (commit `1f633ec2ba`).
      Per-channel monotonic tick counter
      (`channelTicks: Map<WSChannel,     number>`) feeds
      `wshHash(\`ws:<channel>:tick:<n>:<metric>\`, idx)` so successive ws ticks
      produce different but deterministic values keyed by (channel, tick-index).
      Channels covered: dashboard, revenue, viewers, engagement, alerts,
      streams, creator, admin.

### libs/aphrodite (12 sites, 5 files) — Class B + Class C — **COMPLETE**

- [x] **thumbnail-generation/src/frame-analyzer.ts** — 55 sites done (commit
      `1653d997e9`). Per-file `faHash(label, index)` FNV-1a; sites grouped under
      labels like `fd-conf:<frame.id>`, `obj-type:<frame.id>`,
      `act-gate:<frame.id>` so each call site hashes independently. The
      compliance-score "placeholder" stub-vocabulary comment was reworded so the
      file passes `--mode=stubs` clean.
- [x] **ar-overlays/src/index.ts** — 4 REPLACE sites done (commit `0dd1d49f98`).
      `arHash(faceId, idx)` keyed by faceId; `generateExpressions` now takes a
      faceId param. The 11 ALLOW Fisher-Yates jitter sites for headPose
      pitch/yaw/roll and ParticleSystem emitter parameters remain — already
      annotated.
- [x] **biometric-engine/src/mediapipe/mediapipe.ts** — 1 REPLACE done (commit
      `833441bdfd`). The `faceDetected` confidence now calls the existing real
      `calculateFaceConfidence(landmarks)` (factor 1: landmark count, factor 2:
      avg visibility, factor 3: spatial coherence) — no hash needed since a real
      computation already existed in-file. The L1083 procedural visibility
      variance converted to `0.95 + |sin(angle * 7)| * 0.05` for determinism.
- [x] **content-tagging/src/content-tagger.ts** — 1 REPLACE done (commit
      `49040d69ea`). `ctHash` keyed by `${frame.id}:${count}` seed; same 70%
      gate / index pick / confidence semantics, now reproducible per-input. Also
      implemented `updateStream` (was a stub-vocabulary no-op blocking the
      file's pre-commit gate).
- [x] **vod-chaptering/src/index.ts** — 1 REPLACE site + 12 default-allow LOW
      sites done (commit `effcc2475d`). `vcHash` keyed by labelled vodId per
      channel (`scene:`/`hist:`/`motion:`/`level:`/`speech:`/`music:`/etc.) so
      each metric stream is independent within a vodId.

## Implementation pattern (from V1-P2-3411 precedent)

```ts
// At module scope or imported from a shared util.
function aphrodHash(label: string, index: number): number {
  // FNV-1a 32-bit hash, then bucket into a fractional in [0, 1).
  let h = 0x811c9dc5;
  for (let i = 0; i < label.length; i++) {
    h ^= label.charCodeAt(i);
    h = Math.imul(h, 0x01000193);
  }
  h ^= index;
  h = Math.imul(h, 0x01000193);
  return (h >>> 0) / 0xffffffff;
}

// Replace each `Math.random()` site:
// before:  totalStreams = 15000 + Math.floor(Math.random() * 5000);
// after:   totalStreams = 15000 + Math.floor(aphrodHash(routeKey + ':totalStreams', 0) * 5000);
```

`routeKey` is constructed from the request — typically
`${method}:${path}:${period}:${tz}` plus relevant query keys — so the same HTTP
request always produces the same payload across deploys. A different period or
query produces different but still-deterministic values.

## Verification per file

For each file, after the REPLACE pass:

1. `npx eslint --no-warn-ignored <file>` — must pass with no new errors.
2. `npx tsc --noEmit` against the owning library — must pass.
3. `bash scripts/stub-indicator-scan.sh --mode=random <file>` — zero actionable
   hits, OR every remaining hit is on a line that legitimately uses
   `Math.random` for procedural variance and carries
   `// random:legitimate <reason>`.
4. Add a vitest spec asserting the deterministic property: same query → same
   payload across two consecutive calls; different query → different payload.
   Snapshot test the route's response shape.
5. Confirm the V1-P2-3401 master sheet entries for the file no longer appear in
   the silent-random scan.

## Out of scope for V1-P2-3410

- Connecting routes to a real metrics warehouse / ClickHouse / Druid: that is a
  separate platform task (no existing TODO yet — pre-requisite is the data
  infrastructure track).
- Real ML inference for confidence scores in libs: blocked on the relevant
  computer-vision provider task.
- Real frame analysis in `frame-analyzer.ts`: blocked on the video-frame decoder
  library and a luminance/contrast/saturation kernel — likely candidate for the
  WASM/Rust path described in CLAUDE.md.
- Adding new analytics endpoints — only existing sites get REPLACEd.

## Cross-references

- §41.1 V1-P2-3403 (annotation pass) — handles the ALLOW sites in these files;
  once REPLACE work lands, those files clear the silent-random scanner.
- §41.2 V1-P2-3411 (iris) — completed precedent for the FNV-1a hash approach.
- `docs/releases/p2/silent-random-replace-plan.md` — batches B1, B2, B3, B8
  (V1-P2-3410.{1,2,3} for apps; B8 for libs).
- `docs/releases/p2/silent-random-classification.md` — line-by-line REPLACE rows
  in §`apps/aphrodite/...` and §`libs/aphrodite/...`.
