> 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-session04-source-setup-target-configuration/spec.md).

# Session Specification

**Session ID**: `phase24-session04-source-setup-target-configuration` **Phase**: 24 - Trend Finder Outlier Signal Upgrade **Status**: Not Started **Created**: 2026-06-08

***

## 1. Session Overview

This session makes reviewed Trend Finder source setup operable from the local Sources surface without weakening the existing source compliance boundary. The current product path already has reviewed Apify source declarations, private `data/trend-finder.apify-actors.json` configuration, source health summaries, runtime readiness labels, and hardened local bridge precedents. The missing piece is a browser-safe setup panel that can show declaration/configuration state and write only approved target fields through a token-gated loopback bridge.

The work builds directly on Sessions 01 through 03. Source-local scoring, delta-aware enrichment/spend accounting, and browser-safe asset/file hardening are complete, so the next natural step is local operator setup for reviewed sources and target lists. This must land before scheduler first-run controls and Signal Workbench because those later sessions need a clear source readiness and target configuration state.

The session is intentionally conservative. The UI may show credential presence, review status, safe target fields, caps, warnings, last-run health, and configuration state, but it must never echo full credentials, raw Actor inputs, Dataset rows, private config paths, account IDs, raw logs, or unreviewed source IDs. Unknown, placeholder, private, restricted, and unsafe target requests must fail closed with actionable browser-safe diagnostics.

***

## 2. Objectives

1. Add reviewed source setup declarations that identify editable source target fields, credential requirements, caps, and compliance documents.
2. Add private source setup read/write helpers for `data/trend-finder.apify-actors.json` that preserve existing parser compatibility while validating source IDs and target fields.
3. Add a token-gated loopback source setup bridge for browser-safe GET and mutation requests with bounded JSON bodies and redacted diagnostics.
4. Add a local Source Setup panel in the Sources view with reviewed source readiness, target list management, warnings, and last-run health states.
5. Update source setup docs and examples so they describe implemented local UI behavior, private config boundaries, and unsupported source constraints.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase24-session01-source-local-scoring-signals` - Provides reviewed source identity, placement exclusions, and source-local documentation that setup must preserve.
* [x] `phase24-session02-delta-aware-enrichment-spend-accounting` - Provides source spend/cache state and source row projection patterns.
* [x] `phase24-session03-browser-safe-evidence-assets-file-hardening` - Provides hardened file/bridge boundary patterns and opaque local bridge behavior.

### Required Tools/Knowledge

* Current `loadTrendFinderApifySourceConfig` parser behavior and `data/trend-finder.apify-actors.example.json` shape.
* Existing local bridge patterns in `trend-finder-lens-bridge`, `trend-finder-visibility-config-bridge`, and `trend-finder-asset-bridge`.
* Current Sources view, runtime readiness panel, source view-model, and Trend Finder schema defaults.
* Source compliance docs for GitHub, Reddit, arXiv, Product Hunt, YouTube, RSS/news, Hugging Face, Google News, and Apify onboarding.

### Environment Requirements

* Bun 1.3.14 project toolchain from `.bun-version`.
* Dev bridge behavior runs on loopback Vite middleware only.
* Private source config remains gitignored at `data/trend-finder.apify-actors.json`.
* Browser payloads and bridge responses must not expose credentials, full private config paths, raw Actor inputs, raw Dataset rows, raw logs, source account auth, or token-shaped strings.

***

## 4. Scope

### In Scope (MVP)

* Trend Finder can describe reviewed source setup metadata for each static Apify declaration, including editable target fields, credential requirement, caps, compliance document, actor candidate labels, and unsupported reasons.
* Trend Finder can read private source setup state from the existing Apify source config file and expose only source IDs, active/configured booleans, safe target summaries, credential presence, warnings, and last-run health.
* Trend Finder can add, update, remove, and enable/disable reviewed source target fields through a loopback-only, token-gated bridge with schema-validated input, duplicate-trigger protection, and atomic writes.
* Trend Finder can reject unknown source IDs, placeholder Actor IDs, unreviewed source IDs, unsafe target fields, private/unavailable targets, oversized bodies, invalid tokens, non-loopback requests, and malformed JSON.
* Trend Finder Sources view can render a local Source Setup panel with loading, empty, error, offline, setup-required, credential-missing, configured, active, and degraded states.
* Trend Finder docs can explain the implemented local source setup UI, editable target field boundaries, credential redaction, private config file, and unsupported direct-copy behaviors.

### Out of Scope (Deferred)

* Configuring Instagram/Reels sources, arbitrary Actor inputs, private accounts, private feeds, or unrestricted raw JSON - *Reason: those require separate source compliance review and declaration work.*
* Storing credentials in browser state or writing `.env.local` from the UI - *Reason: credentials remain script-only and operator-managed.*
* Replacing existing env/file-driven configuration - *Reason: the local UI is an additive helper over the existing private config file.*
* Scheduler cadence, first-run checklist execution, and live stage progress - *Reason: Session 05 owns scheduler controls and first-run flow.*
* Static Brief export or hosted source setup - *Reason: Session 07 owns export, and this source setup bridge is local-only.*

***

## 5. Technical Approach

### Architecture

Add a script-side source setup helper beside the existing Apify source config module. It should derive setup metadata from static reviewed declarations, define a whitelist of editable target fields per source, parse the private source config file into browser-safe setup state, validate mutation requests, and write the file atomically in the same shape the existing Apify parser can already consume. The helper should preserve config entries and supported fields that the current parser accepts while rejecting unknown source IDs, placeholder Actors, unsupported target fields, unsafe values, and private target patterns.

Add a focused `scripts/lib/trend-finder-source-setup-bridge.ts` module and register it in Vite middleware. The bridge should follow the existing loopback/token model and fail closed for unsupported methods, invalid tokens, non-loopback requests, oversized bodies, malformed JSON, schema failures, and write failures. Response payloads should contain safe source setup state and diagnostics only.

On the browser side, add additive schemas, a source setup client/hook, a compact Source Setup panel, and view-model helpers. The panel should live on the Sources view and stay operationally dense: source rows, readiness badges, target chips/inputs, warnings, and mutation controls with pending states. It should keep layout stable across mobile and desktop and revalidate state after mutations.

### Design Patterns

* Additive schema defaults: Preserve legacy Trend Finder payloads and fixture data.
* Static declarations over UI self-approval: Only reviewed source IDs and declared target fields can be configured.
* Script-only runtime boundary: Keep config file paths, credentials, and raw Actor inputs out of browser code.
* Fail-closed local bridge: Require loopback, token validation, method limits, bounded bodies, schema validation, atomic writes, and safe error mapping.
* Typed degradation over throws: Represent missing config, missing credential, restricted source, placeholder actor, and invalid target states explicitly.
* Existing parser compatibility: Writes should produce a source config shape accepted by `loadTrendFinderApifySourceConfig`.

### Technology Stack

* TypeScript with Bun script runtime.
* Vitest for helper, bridge, schema, hook/view-model, and UI tests.
* Zod for browser-safe source setup parsing and mutation validation.
* React 19 with existing Tailwind/Radix conventions for the Sources view panel.
* Vite local middleware for dev-only loopback bridge registration.

***

## 6. Deliverables

### Files to Create

| File                                                                           | Purpose                                                                                                            | Est. Lines |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ---------- |
| `scripts/extensions/trend-finder/sources/source-setup.ts`                      | Source setup declarations, safe target schemas, private config read/write, and mutation validation.                | \~320      |
| `scripts/extensions/trend-finder/sources/__tests__/source-setup.test.ts`       | Source setup helper tests for reviewed IDs, target validation, parser compatibility, redaction, and atomic writes. | \~260      |
| `scripts/lib/trend-finder-source-setup-bridge.ts`                              | Loopback/token-gated source setup bridge for GET and safe target mutations.                                        | \~260      |
| `scripts/lib/__tests__/trend-finder-source-setup-bridge.test.ts`               | Bridge tests for auth, methods, malformed input, validation, write failures, redaction, and response headers.      | \~240      |
| `src/extensions/trend-finder/source-setup.ts`                                  | Browser-safe source setup schemas, endpoint constants, and request helpers.                                        | \~220      |
| `src/extensions/trend-finder/use-source-setup.ts`                              | Hook for loading, mutating, and revalidating local source setup state.                                             | \~180      |
| `src/extensions/trend-finder/components/source-setup-panel.tsx`                | Dense Sources view panel for reviewed source readiness and target management.                                      | \~260      |
| `src/extensions/trend-finder/components/__tests__/source-setup-panel.test.tsx` | UI coverage for loading, error, configured, credential, warning, and mutation states.                              | \~220      |

### Files to Modify

| File                                                             | Changes                                                                                               | Est. Lines |
| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/extensions/trend-finder/sources/types.ts`               | Add setup metadata and safe target field type contracts.                                              | \~80       |
| `scripts/extensions/trend-finder/sources/apify-source-config.ts` | Attach reviewed setup metadata and safe target field declarations to static sources.                  | \~160      |
| `scripts/extensions/trend-finder/collector.ts`                   | Include safe source setup summaries in generated Trend Finder payloads.                               | \~120      |
| `src/extensions/trend-finder/schema.ts`                          | Add additive source setup summary and source setup state defaults.                                    | \~160      |
| `src/extensions/trend-finder/view-model.ts`                      | Project setup state, credential labels, target summaries, and warnings.                               | \~120      |
| `src/extensions/trend-finder/views/sources-view.tsx`             | Render the Source Setup panel and visibility menu entry in the Sources view.                          | \~120      |
| `src/extensions/trend-finder/fixtures.ts`                        | Add source setup fixture states for configured, missing credential, restricted, and degraded sources. | \~100      |
| `src/data/live-data.example.json`                                | Add additive fallback source setup shape.                                                             | \~60       |
| `data/trend-finder.apify-actors.example.json`                    | Document safe editable source targets in the sanitized starter example.                               | \~80       |
| `vite.config.ts`                                                 | Register the source setup bridge with token, loopback check, and private config path.                 | \~50       |
| `docs/extensions/trend-finder-sources.md`                        | Document local Source Setup UI, target field constraints, and safe diagnostics.                       | \~120      |
| `docs/sources/apify-source-onboarding.md`                        | Document reviewed source setup declarations and private config mutation rules.                        | \~90       |
| `docs/apify.md`                                                  | Document UI-backed private source config path and unsupported raw Actor edits.                        | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Source Setup can configure only reviewed source IDs and whitelisted target fields.
* [ ] Invalid source IDs, placeholder Actor IDs, unreviewed source IDs, private/unavailable targets, unsupported fields, and missing credentials produce actionable browser-safe warnings.
* [ ] Existing env/file-driven source configuration remains backward compatible with `loadTrendFinderApifySourceConfig`.
* [ ] Browser-visible output exposes credential presence and target summaries only, never full secret values, raw Actor input, Dataset rows, private paths, auth headers, or token-shaped strings.
* [ ] Source Setup mutations are disabled while in-flight and revalidate state after success or failure.
* [ ] The Sources view remains dense, stable, accessible, and responsive with explicit loading, empty, error, offline, and setup-required states.

### Testing Requirements

* [ ] Unit tests cover source setup declarations, safe target field validation, private config read/write, atomic writes, redaction, and parser compatibility.
* [ ] Bridge tests cover method rejection, loopback enforcement, token checks, oversized bodies, malformed JSON, schema failures, write failures, safe headers, and redacted diagnostics.
* [ ] Schema/view-model/UI tests cover source setup defaults, warning states, credential labels, target summaries, mutation pending states, and fallback behavior.
* [ ] Focused Trend Finder tests, bridge tests, app typecheck, script typecheck, docs formatting, ASCII validation, and git diff check pass.

### Non-Functional Requirements

* [ ] Source setup bridge responses stay `no-store` and same-origin local-only.
* [ ] Source setup payloads remain bounded and additive inside the shared extension payload budget.
* [ ] Private source config writes are atomic and do not clobber unrelated parser-supported fields.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No generated private data or credential files committed.

***

## 8. Implementation Notes

### Key Considerations

* Treat static source declarations as the authority for editable target fields. The browser cannot self-approve source IDs, Actor IDs, or target keys.
* Keep `FINDTREND_APIFY_ACTORS_PATH` and `FINDTREND_APIFY_ACTORS` behavior compatible; the local UI should write the default private file unless future implementation explicitly validates another path.
* The bridge can expose a redacted config file status such as missing, loaded, invalid, or shadowed, but not full absolute paths or raw file contents.
* Source setup UI copy should describe what exists today and avoid implying scheduler or static export behavior.

### Potential Challenges

* Preserving unknown-but-parser-supported config fields: keep merge logic scoped to declared safe target fields and known status fields.
* Avoiding raw Actor input exposure: target summaries should show approved values only and redact or omit unsupported nested fields.
* UI density: source setup should fit the existing Sources view without displacing source health, evidence contribution, and runtime readiness.
* Credential state: show presence and setup-required states, not credential values or validation secrets.

### Relevant Considerations

* \[P02] **New source adapters need per-source compliance review**: Source setup can only configure reviewed declarations and declared target fields.
* \[P06] **Apify actor outputs remain operator-dependent**: Diagnostics must expose safe source IDs and status labels, not Actor internals.
* \[P02] **Extension payloads and demo labels stay bounded**: Additive setup state must remain capped and explicit.
* \[P15] **Aggregate collection must stay budgeted**: Setup should preserve source caps and not silently widen collection scope.
* \[P05] **Script-only runtime boundary**: Auth, raw config, and source helpers stay script-side; browser code consumes sanitized state only.
* \[P00] **Do not document planned features as implemented**: Docs must label scheduler, first-run controls, and static export as later-session behavior.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Source setup mutations could write unsafe source IDs, target fields, or raw Actor input unless every request is schema-validated against static declarations.
* Local bridge writes could leak credentials, private paths, or raw config in success/error responses unless diagnostics are redacted at the boundary.
* Reopenable Source Setup UI could show stale target or credential state after mutations unless it revalidates and resets pending/error state on re-entry.
* Source list controls could duplicate writes or clobber unrelated file fields unless submit actions are disabled while in-flight and writes are atomic.

***

## 9. Testing Strategy

### Unit Tests

* Validate setup declarations and safe target field metadata for all reviewed static source IDs.
* Validate private config parsing, sanitized summaries, target mutations, atomic writes, redaction, and compatibility with `loadTrendFinderApifySourceConfig`.
* Validate schema defaults and view-model labels for legacy payloads and configured/missing/degraded states.

### Integration Tests

* Test the source setup bridge through registered middleware handlers for GET, POST/PUT/DELETE style mutations, loopback/token checks, body bounds, invalid payloads, write failures, and `no-store` headers.
* Test Sources view rendering with mocked setup states and mutation responses.

### Manual Testing

* Start the dev server, open `/extensions/trend-finder/sources`, verify Source Setup renders reviewed declarations, add/remove a safe target in the private config file, and verify source status revalidates without exposing secrets.

### Edge Cases

* Missing private config file.
* Malformed private config file.
* Inline env config shadowing the file.
* Missing `APIFY_TOKEN`.
* Unknown source ID.
* Placeholder Actor ID.
* Unsupported target field.
* Private/unavailable target value.
* Duplicate target values.
* Non-loopback bridge request.
* Invalid or missing refresh token.
* Reopening Sources view after failed mutation.

***

## 10. Dependencies

### External Libraries

* No new external libraries expected.

### Other Sessions

* **Depends on**: `phase24-session01-source-local-scoring-signals`, `phase24-session02-delta-aware-enrichment-spend-accounting`, `phase24-session03-browser-safe-evidence-assets-file-hardening`
* **Depended by**: `phase24-session05-scheduler-first-run-live-progress-controls`, `phase24-session06-signal-workbench-local-triage`, `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-session04-source-setup-target-configuration/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.
