Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
trading-desk: add Company Profile analyst as 5th Phase 1 grounding ag…
…ent (FIX-606)

A renderer-style analyst that fetches structured business identity (name,
sector, industry, description, scale) from Finnhub /stock/profile2 +
Yahoo quoteSummary and renders it as a memo, so downstream phases reason
from data instead of training priors. The prompt constrains the LLM to
trace every claim to a `<data>` field and to quote one figure verbatim;
when no provider can resolve the ticker the memo explicitly says so
rather than inventing the company.

Runs in parallel with the existing four Phase 1 analysts; downstream
phases pick it up via the existing `formatAnalystMemos` flow (no
capability or formatter changes). `setupPhase1Memos` is refactored to
derive its memoStatus seed from `PHASE_1_MEMO_KEYS` so future analyst
additions don't have to touch this file.
  • Loading branch information
claude committed May 17, 2026
commit bda09df211aeb3747aa82ad83d553d6628ecae7a
14 changes: 7 additions & 7 deletions apps/docs/guides/trading-desk-walkthrough.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ title: A walkthrough of the Trading Desk example

# A walkthrough of the Trading Desk example

The Trading Desk example is a five-phase multi-agent pipeline that turns a ticker and a date into a structured trade decision. Four analyst sub-agents read different data sources, two researchers argue bull versus bear, a synthesizer writes an investment thesis, a trader proposes a trade, three risk officers critique it, and a portfolio manager makes the final call.
The Trading Desk example is a five-phase multi-agent pipeline that turns a ticker and a date into a structured trade decision. Five analyst sub-agents read different data sources, two researchers argue bull versus bear, a synthesizer writes an investment thesis, a trader proposes a trade, three risk officers critique it, and a portfolio manager makes the final call.

It is a teaching demo. The agents reason in plain English about stocks because that domain has public, structured prior art to model against. Don't trade real money on it.

This walkthrough names the framework pieces the example uses, in roughly the order they show up during a run. Read [Anatomy of a Flow](/guides/anatomy-of-a-flow) first if the words "block," "generator," and "sequencer" don't already mean something concrete to you.

## The pipeline at a glance

Phase 1 fans out four analyst sub-agents in parallel. Each reads its own data sources and writes a typed `Thesis` memo with claims, evidence, risks, and a recommendation. The technical analyst reads a wide indicator set (RSI, MACD, ATR, SMA50/200, Bollinger Bands, VWMA, Stochastic, KDJ, OBV). The news analyst reads headlines, macro indicators, and 90 days of insider Form 4 transactions.
Phase 1 fans out five analyst sub-agents in parallel. Each reads its own data sources and writes a typed `Thesis` memo with claims, evidence, risks, and a recommendation. The technical analyst reads a wide indicator set (RSI, MACD, ATR, SMA50/200, Bollinger Bands, VWMA, Stochastic, KDJ, OBV). The news analyst reads headlines, macro indicators, and 90 days of insider Form 4 transactions. The company-profile analyst renders structured business identity, sector, industry, description, and scale, from a deterministic provider fetch, so the rest of the pipeline reasons from data instead of training priors.

Phase 2 runs a bounded bull-versus-bear loop. A research manager synthesizes the debate into an `InvestmentThesis` with explicit `unresolvedDisagreements`.

Expand All @@ -24,7 +24,7 @@ Phase 4 runs three risk officers in round-robin order, then a consolidator emits
Phase 5 reads everything upstream and emits a `PortfolioDecision` with a five-tier final rating, accepted-or-rejected risk adjustments, key dependencies, and a rationale that cites each stage.

```
analysts (x4 in parallel)
analysts (x5 in parallel)
→ bull/bear debate → research manager
→ trader
→ risk officers (x3 round-robin) → risk consolidator
Expand All @@ -37,7 +37,7 @@ Each arrow above is a `.then()` in a sequencer. The whole flow is one chain.

A sequencer is the composition primitive. It takes blocks and chains them. The `.parallel()` step on a sequencer runs a set of branches concurrently and produces a single combined output.

Phase 1 uses one `.parallel()` step with four branches. Each branch is itself a sub-sequencer that mirrors the same shape:
Phase 1 uses one `.parallel()` step with five branches. Each branch is itself a sub-sequencer that mirrors the same shape:

```ts
sequencer({ name: "analyst-fundamentals" })
Expand All @@ -53,11 +53,11 @@ A few teaching moments live in that one declaration.

The analyst is not a special "agent" type. It's a sequencer composed of a handler (the silent state-mutating block kind), a generator (the LLM-calling block kind), and another handler. Any block composes with any other. There is no agent-versus-workflow split.

The four memo slots get pre-created in `pending` by a setup tap that runs before the parallel block. The right-pane navigator sees four placeholder cards from the start of the phase, not just as each analyst completes. That kind of "show the work as it happens" UI falls out of pre-creating the resource entries.
The five memo slots get pre-created in `pending` by a setup tap that runs before the parallel block. The right-pane navigator sees five placeholder cards from the start of the phase, not just as each analyst completes. That kind of "show the work as it happens" UI falls out of pre-creating the resource entries.

Resources are the live data layer. Each analyst writes its typed memo to a session-scoped resource collection. React reads it through `useResourceCollectionItem`. The framework handles the SSE plumbing; your component is a renderer.

The per-branch `.rescue()` matters too. If the news fetch fails, only the news memo flips to `error`. The other three analysts still complete.
The per-branch `.rescue()` matters too. If the news fetch fails, only the news memo flips to `error`. The other four analysts still complete.

## Phase 2: Round Robin with a synthesizer

Expand Down Expand Up @@ -116,7 +116,7 @@ pnpm --filter @flow-state-dev/example-trading-desk dev

The top bar exposes a ticker input, a date, a cost preset (`fast` or `full`), and a data source toggle (`fixture` or `live`). A disclaimer band sits above the transcript: this is a demo, not investment advice.

On a fresh run, you'll see the four analyst cards appear in `pending` right away. They flip to `writing` as each analyst starts its generator call, then to `done` as the memos commit. The bull and bear cards follow. Then the trade proposal, then the three risk persona cards, then the consolidated risk assessment, then the PM Hero on the right.
On a fresh run, you'll see the five analyst cards appear in `pending` right away. They flip to `writing` as each analyst starts its generator call, then to `done` as the memos commit. The bull and bear cards follow. Then the trade proposal, then the three risk persona cards, then the consolidated risk assessment, then the PM Hero on the right.

The `fast` preset completes well under a minute on one provider key. `full` takes longer because the debate runs two rounds against larger models.

Expand Down
11 changes: 11 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@
All notable implementation-repo changes are recorded here as concise, wave-level summaries.


## 2026-05-17

### Trading-desk: Company Profile analyst grounds the desk in what the business actually is (FIX-606)

- New fifth Phase 1 analyst (`companyProfileAnalyst`) runs in parallel with the existing four and publishes a memo describing the underlying business: name, sector, industry, country/exchange/currency, business description, and rough scale (market cap, employees, IPO date). Downstream phases pick it up automatically via the `tradingDesk` capability's `phase1Memos` formatter.
- Renderer, not synthesizer. The analyst is given structured fields from a deterministic provider fetch and constrained at the prompt level to render them — every body claim must trace to a field in `<data>`, with a "quote one figure verbatim" requirement as a structural defense against fabrication. The shared `<grounding>` clause from FIX-605 reinforces the boundary.
- Provider chain reuses what's already wired: Finnhub `/stock/profile2` preferred (no new key, already called by `get_fundamentals`), Yahoo `quoteSummary` (assetProfile + summaryDetail) fallback for sector and business description. When both providers fail, the analyst emits a memo whose body explicitly states identity could not be resolved rather than inventing the company.
- Fixture coverage for the three pinned tickers (NVDA, AAPL, JPM) at the `2026-05-06` snapshot.
- README, walkthrough, and internal design doc updated to reflect the five-analyst fan-out and the grounding analyst's role.


## 2026-05-16

### Sequencer DSL: `.throwIf(condition, error)` guard primitive
Expand Down
8 changes: 4 additions & 4 deletions docs/internal/design/trading-desk.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Design: Trading Desk Example (FIX-564)

The trading desk is a five-phase, twelve-agent stock-research pipeline assembled out of flow-state-dev primitives. It takes a `(ticker, date)` input, fans out to four analyst memos, runs a bull/bear debate consolidated by a research manager, asks a trader for a structured trade proposal, runs a three-way risk critique consolidated into a typed risk assessment, and ends with a portfolio manager committing a typed `PortfolioDecision`. The example exists to exercise the framework: capabilities, resource collections, round-robin and per-step rescue patterns, BP-016 strict schemas, cost-preset routing, and identity-aware transcript rendering. It is not a trading product and is not advice. The pipeline shape and persona structure are a reimplementation in spirit of Tauric Research's [`TradingAgents`](https://github.com/TauricResearch/TradingAgents) (Apache-2.0); the framework wiring, schemas, and rendering are original.
The trading desk is a five-phase, thirteen-agent stock-research pipeline assembled out of flow-state-dev primitives. It takes a `(ticker, date)` input, fans out to five analyst memos (including a Company Profile renderer that grounds the desk in the underlying business identity before signal-oriented synthesis runs), runs a bull/bear debate consolidated by a research manager, asks a trader for a structured trade proposal, runs a three-way risk critique consolidated into a typed risk assessment, and ends with a portfolio manager committing a typed `PortfolioDecision`. The example exists to exercise the framework: capabilities, resource collections, round-robin and per-step rescue patterns, BP-016 strict schemas, cost-preset routing, and identity-aware transcript rendering. It is not a trading product and is not advice. The pipeline shape and persona structure are a reimplementation in spirit of Tauric Research's [`TradingAgents`](https://github.com/TauricResearch/TradingAgents) (Apache-2.0); the framework wiring, schemas, and rendering are original.

## 1. Pipeline shape

Expand All @@ -20,7 +20,7 @@ See [`flow.ts`](../../../examples/trading-desk/src/flows/trading-desk/flow.ts) f

## 2. Identity registry

Twelve agents across five phases live in a single `AGENTS` table in [`agents.ts`](../../../examples/trading-desk/src/flows/trading-desk/agents.ts). Each entry carries `role`, `glyph` (two-character badge mark), `hue` (OKLCH degrees for the per-agent accent), and `team`. Every agent ships from day one — Phase 2–5 entries render in `pending` styling before their phases run. `PHASE_GROUPS` buckets them for the sidebar.
Thirteen agents across five phases live in a single `AGENTS` table in [`agents.ts`](../../../examples/trading-desk/src/flows/trading-desk/agents.ts). Each entry carries `role`, `glyph` (two-character badge mark), `hue` (OKLCH degrees for the per-agent accent), and `team`. Every agent ships from day one — Phase 2–5 entries render in `pending` styling before their phases run. `PHASE_GROUPS` buckets them for the sidebar.

Per-phase registries (`PHASE_1_MEMO_KEYS` through `PHASE_5_MEMO_KEYS`) map a short name (`fundamentals`, `bull`, `trader`, `aggressive`, `portfolioManager`) to `{ agentName, memoKey, collectionKey }`. `memoKey` is the full storage key (`memos/p1/fundamentals`). `collectionKey` is the bare suffix the framework auto-prefixes when you call `collection.create("p1/fundamentals")`. `ALL_MEMO_KEYS` merges every per-phase registry — the navigator iterates this single object.

Expand All @@ -44,7 +44,7 @@ Session state lives in [`state.ts`](../../../examples/trading-desk/src/flows/tra

Every memo state transition is a dual write. `markWriting`, `commitMemo`, and `markError` (see [`memo-writer.ts`](../../../examples/trading-desk/src/flows/trading-desk/memo-writer.ts) for the Phase 1 originals; later phases copy the shape) both patch the resource state and write `session.memoStatus[shortName]`. The reason for both: resource snapshots batch to terminal status, but session state-change items propagate immediately through the stream. The sidebar wants to flicker live, so it reads `memoStatus`. The memo body wants the consolidated terminal snapshot, so it reads the resource.

The parallel Phase 1 fan-out uses `setStateRecord` instead of `patchState` for `memoStatus` writes — atomic per-key updates avoid the read-modify-write race a `{...prev, [name]: ...}` pattern would hit with four concurrent analysts.
The parallel Phase 1 fan-out uses `setStateRecord` instead of `patchState` for `memoStatus` writes — atomic per-key updates avoid the read-modify-write race a `{...prev, [name]: ...}` pattern would hit with five concurrent analysts.

## 5. The `tradingDesk` capability

Expand Down Expand Up @@ -106,7 +106,7 @@ The `formatMemoBlock` helper renders an "unavailable" sentinel when a memo's `he

Three classes of work the framework absorbs that would otherwise be a couple thousand lines of plumbing.

*Typed resource pre-creation plus live status mirror.* The pipeline pre-creates 13 memo slots so the navigator scaffolds correctly, then transitions each through `pending → writing → published` with a dual write — resource patch plus session-state mirror — so the sidebar can flicker live mid-stream. Without the framework you'd hand-roll a resource registry, a per-key status map, a state-mutation API that handles concurrent writers without races, and the SSE plumbing to ship state changes mid-stream. The framework gives you `defineResourceCollection`, `setStateRecord`, `client.expose`, and `useClientData`. The example uses all four.
*Typed resource pre-creation plus live status mirror.* The pipeline pre-creates 14 memo slots so the navigator scaffolds correctly, then transitions each through `pending → writing → published` with a dual write — resource patch plus session-state mirror — so the sidebar can flicker live mid-stream. Without the framework you'd hand-roll a resource registry, a per-key status map, a state-mutation API that handles concurrent writers without races, and the SSE plumbing to ship state changes mid-stream. The framework gives you `defineResourceCollection`, `setStateRecord`, `client.expose`, and `useClientData`. The example uses all four.

*Structured outputs that show up as identity-aware transcript cards.* Setting `agentType: "primary"` with an `agentName` drawn from the canonical `AGENTS` table is the entire mechanism for getting a `TxStruct` card emitted in the transcript with the right glyph and hue. The renderer picks the per-agent accent from the same table. Without the framework you'd reinvent agent identity, manage card emission yourself, and write per-agent rendering rules. With the framework, the only registration step is the `PRIMARY_STRUCT_AGENTS` set on the transcript pane that gates which agents get cards.

Expand Down
24 changes: 16 additions & 8 deletions examples/trading-desk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,22 @@ A multi-phase agent-pipeline showcase. A first-time developer types a ticker,
watches analyst memo slots appear in the navigator, then watches a bull/bear
debate unfold, a research manager synthesize an investment thesis, a trader
propose a sized trade, three risk officers critique it, and a portfolio
manager hand down a five-tier final decision. Five phases, twelve agents,
manager hand down a five-tier final decision. Five phases, thirteen agents,
one structured artifact at every convergence point.

## What's included

Phase 1 — analyst fan-out:

- **Parallel analyst fan-out** — four sub-agents (Fundamentals, Sentiment,
News, Technical) running in parallel, each with a distinct identity.
- **Parallel analyst fan-out** — five sub-agents (Fundamentals, Sentiment,
News, Technical, Company Profile) running in parallel, each with a
distinct identity.
- **Company Profile grounding** — a renderer-style analyst that fetches
structured business identity (sector, industry, business description,
scale) from public providers and writes it as a memo, so downstream
phases reason from a data-derived baseline rather than the model's
training priors. Returns an explicit `unavailable` memo when the
ticker cannot be resolved.
- **Typed memo resources** — every analyst writes a structured `Thesis`-shape
memo readable via the standard resource hook.
- **Two-pane streaming UI** — transcript on the left, theses on the right.
Expand Down Expand Up @@ -57,7 +64,7 @@ Phase 3 — trader synthesis:
and let Phase 4 (risk) and Phase 5 (PM) read structured values without
parsing strings.
- **Cost-preset gates prompt depth** — the cheap preset reads the thesis
and its extension fields only; the full preset adds the four analyst
and its extension fields only; the full preset adds the five analyst
memos and the full bull/bear debate transcript.

Phase 4 — risk debate:
Expand All @@ -82,15 +89,15 @@ Phase 4 — risk debate:
remaining personas still run.
- **Cost-preset gates prompt depth** — the cheap preset reads the trade
proposal, the investment thesis, and prior persona memos; the full
preset adds the four analyst memos and the full bull/bear debate
preset adds the five analyst memos and the full bull/bear debate
transcript.

Phase 5 — portfolio manager:

- **Final converging step** — a single `portfolioManager` generator reads
the always-on upstream artifacts (Phase 2 investment thesis, Phase 3
trade proposal, Phase 4 risk assessment) and writes a typed
`PortfolioDecision`. On the `full` preset it also reads the four
`PortfolioDecision`. On the `full` preset it also reads the five
analyst memos, the full bull/bear debate transcript, and the three
persona risk critiques.
- **Five-tier rating** — `finalRating` is one of `Sell`, `Underweight`,
Expand Down Expand Up @@ -196,12 +203,13 @@ the news analyst treats insider data as missing signal.
analyze
└─ seedSession (patch session state from input)
└─ phase-1-analysts (sub-sequencer, container item)
├─ setupPhase1Memos (.tap — pre-create 4 memos in `pending`)
├─ setupPhase1Memos (.tap — pre-create 5 memos in `pending`)
└─ parallel
├─ fundamentalsAnalyst
├─ sentimentAnalyst
├─ newsAnalyst
└─ technicalAnalyst
├─ technicalAnalyst
└─ companyProfileAnalyst
└─ phase-2-research-debate (sub-sequencer, container item)
├─ setupPhase2Memos (.tap — pre-create 3 memos in `pending`)
├─ deriveDebateGoal (.then — { goal } from session state)
Expand Down
1 change: 1 addition & 0 deletions examples/trading-desk/components/theses/theses-pane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const PUBLISH_ORDER: ReadonlyArray<AnyMemoShortName> = [
"sentiment",
"news",
"technical",
"companyProfile",
"bull",
"bear",
"researchManager",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const PHASE_1_ANALYST_AGENTS = new Set<string>([
"sentimentAnalyst",
"newsAnalyst",
"technicalAnalyst",
"companyProfileAnalyst",
]);

export function TranscriptPane({ session }: Props): ReactElement {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"source": "fixture",
"ticker": "AAPL",
"asOf": "2026-05-06",
"name": "Apple Inc.",
"sector": "Technology",
"industry": "Consumer Electronics",
"country": "United States",
"exchange": "NASDAQ NMS - GLOBAL MARKET",
"currency": "USD",
"businessDescription": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, Mac, iPad, and Wearables, Home and Accessories including AirPods, Apple TV, Apple Watch, and Beats products. It also provides AppleCare support, cloud services, and an array of services including the App Store, Apple Music, Apple TV+, Apple Arcade, Apple Card, Apple Pay, and iCloud.",
"marketCapUsd": 3400000000000,
"employees": 164000,
"ipoDate": "1980-12-12",
"website": "https://www.apple.com"
}
Loading
Loading