> 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/phase24-session03-browser-safe-evidence-assets-file-hardening/spec.md).

# Session Specification

**Session ID**: `phase24-session03-browser-safe-evidence-assets-file-hardening` **Phase**: 24 - Trend Finder Outlier Signal Upgrade **Status**: Not Started **Created**: 2026-06-07

***

## 1. Session Overview

This session adds the browser-safe evidence asset contract and hardened local file-serving boundary that later media preview and static export work depends on. Sessions 01 and 02 already established stable source-local evidence identity, enrichment cache summaries, retention counts, and spend visibility; this session builds on those additive contracts instead of changing the core six-factor Trend Finder score.

The work is intentionally conservative. Current source compliance documents do not approve arbitrary media exposure, raw transcripts, hotlinked images, or cached YouTube audiovisual content. The session therefore creates a reviewed, typed asset metadata path with explicit unavailable, blocked, failed, missing, and pruned states, plus a local bridge that can only serve approved files from explicit generated asset roots.

This is the next session because Session 03 is the first incomplete Phase 24 candidate after Sessions 01 and 02. It must land before Source Setup, scheduler controls, Signal Workbench, and static Brief export can safely rely on media or file-serving behavior.

***

## 2. Objectives

1. Add additive `evidenceAssets` and asset summary schemas for browser-safe evidence asset metadata.
2. Add a private evidence asset manifest and pruning helper keyed by stable evidence IDs and explicit generated asset roots.
3. Add a hardened local file bridge that is loopback-only, token-gated, path-contained, and content-type allowlisted.
4. Surface asset availability, blocked, failed, missing, unsupported, and pruned states in evidence UI and Engine Replay without exposing private file paths.
5. Update Trend Finder docs to explain asset compliance, retention, pruning, and local file-serving boundaries without claiming unapproved media support.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase24-session01-source-local-scoring-signals` - Provides stable evidence IDs and source-local metadata that asset manifests can key against.
* [x] `phase24-session02-delta-aware-enrichment-spend-accounting` - Provides private cache, pruning summary, spend summary, and Engine Replay extension patterns used by this session.

### Required Tools/Knowledge

* Current Trend Finder schema, view-model, evidence UI, collector, Engine Trace, and source adapter contracts.
* Existing local bridge patterns in Creator Lens, visibility config, Hermes, and Vite middleware registration.
* Current source compliance boundaries, especially media and transcript exclusions for YouTube, RSS/news, Google News, Reddit, and Product Hunt.
* Phase 24 findings 5, 10, and 13 and the Outlier Lab references for asset previews, pruning, and path containment as implementation references only.

### Environment Requirements

* Bun 1.3.14 project toolchain from `.bun-version`.
* No live Apify, YouTube, or media credentials are required for this session; fixture and local temporary files must cover asset behavior.
* Generated private asset data remains under ignored `.cache/extensions/` conventions and must never be committed.
* Browser payloads and local bridge responses must not expose credentials, raw source payloads, raw transcripts, private cache paths, raw logs, Actor internals, Dataset rows, or account auth.

***

## 4. Scope

### In Scope (MVP)

* Trend Finder can represent optional browser-safe evidence asset metadata on evidence items, including kind, status, source ID, evidence ID, content type, byte size, created time, provenance label, compliance document reference, local bridge URL, and fallback label.
* Trend Finder can write and read a private evidence asset manifest under an explicit generated asset root, keyed by stable evidence IDs and validated asset IDs.
* Trend Finder can prune manifest entries and files that are no longer in the active evidence keep set and report retained, pruned, failed, and blocked counts.
* Trend Finder can serve approved local asset files through a bridge that requires loopback, the dev refresh token, path containment, explicit roots, allowed content types, bounded file sizes, and safe response headers.
* Trend Finder source normalization can identify asset candidates only as reviewed metadata or blocked/unsupported states; current unapproved media fields remain excluded from browser-safe evidence.
* Trend Finder Evidence UI and Engine Replay can display asset availability and fallback states without layout shifts, broken previews, or private paths.
* Trend Finder docs can describe asset contracts, pruning, bridge hardening, and source compliance gates as implemented behavior.

### Out of Scope (Deferred)

* Downloading or exposing media from sources whose compliance docs do not allow it - *Reason: source-specific compliance permission is required first.*
* Hotlinking arbitrary remote thumbnails, media URLs, images, or videos - *Reason: this session only supports approved local/proxied asset references.*
* Exposing raw transcripts or long text extracts - *Reason: transcript handling remains private unless a compliance doc explicitly allows bounded excerpts.*
* Static Brief export and cache-header guidance for hosted exports - *Reason: Session 07 owns export behavior and delivery docs.*
* Adding unreviewed source adapters, unrestricted Actor inputs, or public deployment defaults - *Reason: those require separate source and security reviews.*

***

## 5. Technical Approach

### Architecture

Add script-side evidence asset helpers that validate manifest entries, derive safe asset IDs, resolve paths below explicit generated asset roots, write manifest updates atomically, and prune stale assets from the active evidence keep set. The helper should treat unsupported or blocked asset candidates as first-class states rather than errors, so current sources can remain compliant while the browser contract is ready for future reviewed assets.

Add a focused Trend Finder asset bridge under `scripts/lib/` and register it from Vite dev middleware. The bridge should fail closed for non-loopback requests, missing or invalid tokens, unsupported methods, escaped paths, unsupported content types, missing files, and oversized files. Browser-visible URLs should be opaque same-origin bridge URLs, never local filesystem paths.

Browser schemas, Engine Trace schemas, fixtures, view-models, and UI components should be additive. Legacy payloads must parse with empty/unavailable asset defaults. Engine Replay should show summary counts and failure labels, while evidence cards render compact preview/fallback affordances that remain dense and accessible on desktop and mobile.

### Design Patterns

* Additive schema defaults: Preserve legacy Trend Finder payloads and fixtures.
* Script-only runtime boundary: Keep manifest reads, file paths, pruning, and source candidate handling out of browser-only code.
* Fail-closed local bridge: Require loopback, token validation, root containment, content-type allowlists, and bounded file sizes.
* Typed degradation over throws: Represent unsupported, blocked, failed, missing, and pruned asset states explicitly.
* Trace summaries over raw details: Emit counts, source IDs, asset kinds, and safe status labels only.

### Technology Stack

* TypeScript with Bun script runtime.
* Vitest for schema, helper, bridge, collector, and view-model tests.
* Zod for browser-safe Trend Finder and Engine Trace payload parsing.
* React 19 and existing Tailwind/Radix component conventions for evidence UI and Engine Replay presentation.

***

## 6. Deliverables

### Files to Create

| File                                                                | Purpose                                                                                    | Est. Lines |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------- |
| `scripts/extensions/trend-finder/evidence-assets.ts`                | Private asset manifest schema, safe IDs, path containment, retention, and pruning helpers. | \~260      |
| `scripts/extensions/trend-finder/__tests__/evidence-assets.test.ts` | Manifest schema, path containment, blocked state, and pruning coverage.                    | \~220      |
| `scripts/lib/trend-finder-asset-bridge.ts`                          | Loopback/token-gated local bridge for approved generated asset files.                      | \~240      |
| `scripts/lib/__tests__/trend-finder-asset-bridge.test.ts`           | Bridge tests for method, token, loopback, traversal, content type, file size, and headers. | \~240      |
| `src/extensions/trend-finder/components/evidence-asset-preview.tsx` | Compact asset preview and fallback component for evidence cards.                           | \~160      |

### Files to Modify

| File                                                           | Changes                                                                                  | Est. Lines |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/trend-finder/schema.ts`                        | Add `evidenceAssets` item and run summary schemas/defaults.                              | \~160      |
| `src/extensions/trend-finder/engine-trace.ts`                  | Add browser-safe asset summary fields to Engine Trace.                                   | \~120      |
| `scripts/extensions/trend-finder/sources/types.ts`             | Add reviewed asset candidate and source support contracts.                               | \~90       |
| `scripts/extensions/trend-finder/sources/apify-normalizers.ts` | Keep unapproved media blocked while emitting reviewed asset candidate states.            | \~120      |
| `scripts/extensions/trend-finder/collector.ts`                 | Merge asset manifest state, prune stale assets, and include asset summaries in payloads. | \~180      |
| `scripts/extensions/trend-finder/engine-trace.ts`              | Sanitize asset trace events and block unsafe keys/values.                                | \~140      |
| `src/extensions/trend-finder/view-model.ts`                    | Project asset metadata into evidence view models and fallback labels.                    | \~140      |
| `src/extensions/trend-finder/components/evidence-links.tsx`    | Render asset preview/fallback UI in evidence cards.                                      | \~100      |
| `src/extensions/trend-finder/engine-replay-model.ts`           | Project asset summary counts, tones, and notes.                                          | \~140      |
| `src/extensions/trend-finder/views/engine-replay-view.tsx`     | Surface asset summary and failure/pruning labels.                                        | \~80       |
| `src/extensions/trend-finder/fixtures.ts`                      | Add fixture asset available, blocked, missing, failed, and pruned states.                | \~100      |
| `src/data/live-data.example.json`                              | Add committed fallback shape for additive asset fields.                                  | \~60       |
| `vite.config.ts`                                               | Register the Trend Finder asset bridge with explicit roots and token.                    | \~40       |
| `docs/extensions/trend-finder-ui-surfaces.md`                  | Document evidence asset preview and fallback states.                                     | \~90       |
| `docs/extensions/trend-finder-pipeline.md`                     | Document asset manifest, retention, pruning, and bridge lifecycle.                       | \~90       |
| `docs/extensions/trend-finder-runtime-and-provenance.md`       | Document Engine Replay asset labels and privacy boundaries.                              | \~90       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Legacy Trend Finder payloads parse with empty/unavailable asset defaults.
* [ ] Evidence items can carry only validated browser-safe asset metadata and opaque local bridge URLs, never private filesystem paths.
* [ ] Asset manifest reads, writes, and pruning stay contained under explicit generated asset roots.
* [ ] Requests outside allowed roots, unsupported content types, unsupported methods, invalid tokens, non-loopback addresses, and missing files fail closed.
* [ ] Engine Replay and evidence cards show useful fallback labels for unsupported, blocked, missing, failed, unavailable, and pruned assets.
* [ ] Current unapproved media fields remain blocked or unsupported rather than becoming browser-visible media.

### Testing Requirements

* [ ] Unit tests cover asset schema validation, manifest write/read, safe ID derivation, path containment, stale pruning, and blocked states.
* [ ] Bridge tests cover loopback, token, method, path traversal, content-type allowlist, missing file, oversized file, and headers.
* [ ] Schema and collector tests prove asset defaults, summaries, pruning counts, warnings, and legacy payload compatibility.
* [ ] View-model and UI tests cover available, unsupported, blocked, failed, missing, pruned, empty, degraded, and offline states.

### Non-Functional Requirements

* [ ] Browser-visible asset fields stay bounded, typed, additive, and deterministic.
* [ ] Private asset files and manifests stay under ignored `.cache/` conventions.
* [ ] Payload growth stays within the shared Trend Finder extension payload cap.
* [ ] Documentation distinguishes implemented asset contracts from future source-specific media permissions and static export behavior.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No new dependencies unless required and documented.

***

## 8. Implementation Notes

### Key Considerations

* Treat source compliance as the asset permission gate. If a compliance doc does not approve an asset type, represent it as blocked or unsupported.
* Keep asset URLs opaque. Browser payloads can include bridge URLs or asset IDs, but never local filesystem paths or private cache roots.
* Default to `no-store` for dynamic bridge responses. Session 07 can add content-addressed immutable cache guidance for export delivery later.
* Avoid SVG and scriptable formats in the default allowlist. Start with tightly reviewed image/video content types and enforce source-specific permission before exposing any file.

### Potential Challenges

* Accidental media overexposure: Add source support flags and require a compliance document reference before an asset can be marked available.
* Path traversal through encoded URL components: Resolve decoded paths below explicit roots and reject escaped or absolute paths.
* Stale asset growth: Prune from the active evidence keep set on each run and record retained/pruned/error counts.
* UI layout shifts from optional previews: Give preview slots stable compact dimensions and fallback labels.

### Relevant Considerations

* \[P02] **New source adapters need per-source compliance review**: Asset types require source-specific permission before browser exposure.
* \[P06] **Apify actor outputs remain operator-dependent**: Actor media fields stay blocked unless reviewed and normalized into safe asset metadata.
* \[P02] **Extension payloads and demo labels stay bounded**: Asset summaries must remain capped and explicit.
* \[P05] **Script-only runtime boundary**: Manifest paths, private cache files, and source candidate handling stay outside browser-only code.
* \[P11] **Scheduler state/log privacy boundary**: No raw logs or private run files are served through the asset bridge.
* \[P00] **Do not document planned features as implemented**: Docs must present shipped asset contracts separately from future media permissions and static export.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Local bridge traversal or content-type bypass exposes private files.
* Browser payload accidentally exposes raw transcripts, media URLs, source dumps, cache paths, or Actor internals.
* Optional preview states cause broken cards, inaccessible controls, or layout shifts when assets are missing, blocked, or pruned.

***

## 9. Testing Strategy

### Unit Tests

* Test asset ID validation, manifest schema parsing, root containment, atomic writes, safe fallback states, keep-set pruning, and blocked source states.
* Test bridge authorization, method rejection, encoded traversal attempts, unsupported content types, missing files, oversized files, and safe headers.

### Integration Tests

* Test collector aggregation of asset summaries and pruning warnings.
* Test Engine Trace sanitization for asset events and unsafe key/value rejection.
* Test Trend Finder schema parsing for legacy payloads and new asset fixtures.

### Manual Testing

* Run focused Trend Finder tests and inspect evidence cards and Engine Replay using fixture data with available, blocked, missing, failed, and pruned asset states.

### Edge Cases

* Asset manifest references an existing file with an unsupported content type.
* Asset bridge receives encoded `..` traversal or absolute path attempts.
* Evidence has a stable ID but no allowed asset permission.
* Asset was pruned after the evidence row was removed from the active keep set.
* Offline or fixture payloads include asset summaries but no live bridge.

***

## 10. Dependencies

### External Libraries

* No new dependencies planned.

### Other Sessions

* **Depends on**: `phase24-session01-source-local-scoring-signals`, `phase24-session02-delta-aware-enrichment-spend-accounting`
* **Depended by**: `phase24-session04-source-setup-target-configuration`, `phase24-session07-static-brief-export`, `phase24-session08-cross-surface-documentation-reference-mode`, `phase24-session09-end-to-end-validation-release-hardening`

***

## 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/phase24-session03-browser-safe-evidence-assets-file-hardening/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.
