> ## Documentation Index
> Fetch the complete documentation index at: https://docs.glider.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# tRPC v2 Portfolio API

> Canonical portfolio-first tRPC surface for CLI and agent integrations

The `v2` tRPC namespace is the canonical API surface for agent and CLI consumers.

* Base endpoint: `POST /v1/trpc`
* Namespace: `v2.*`
* Auth:
  * Wallet session for `v2.portfolio.create.*` and `v2.portfolio.permission.refresh.*`
  * Wallet session for `v2.portfolio.builder.getProfile`, `saveProfile`, `getDraft`, `saveDraft`, `recommend`, and `seedCopilot`
  * Wallet session or API key for `v2.portfolio.builder.generateDraft`
  * Wallet session for `v2.portfolio.scheduledFunctions.*`
  * Wallet session or API key for other `v2.portfolio.*`, `v2.executions.*`, and `v2.automationRuns.*`
  * For API key calls, owner is resolved from canonical API key metadata/KMS linkage. `x-glider-owner-address` is optional and must match canonical owner when provided.
  * Public rate-limited access for `v2.public.*` non-owner read surfaces

## Procedure Groups

* `v2.portfolio.*`
  * `list`, `listByOwnerDbV2`, `get`, `status`
  * `vaults.list`
  * `performance.get`, `performance.series`, `performance.assetMetrics`
  * `activity.list`, `activity.allocationHistory.list`, `activity.allocationHistory.chart`
  * `recipients.list`
  * `deposit.instructions`
  * `builder.getProfile`, `builder.saveProfile`, `builder.getDraft`, `builder.saveDraft`, `builder.recommend`, `builder.generateDraft`, `builder.seedCopilot`
  * `create.prepare`, `create.confirm`
  * `permission.status`, `permission.refresh.prepare`, `permission.refresh.confirm`
  * `archive`, `unarchive`
  * `updates.list`, `updates.get`, `updates.preview`, `updates.create`, `updates.submit`, `updates.supersede`
  * `approvals.list`, `approvals.get`, `approvals.decide`
  * `runs.list`, `runs.get`
  * `events.list`, `events.stream`
  * `context.list`, `context.get`
  * `agents.list`, `agents.get`
  * `actions.previewOndoDirectQuote`, `actions.submit`
  * `policy.evaluate`, `policy.scheduleAdvisory`
  * `policy.config.get`, `policy.config.update`
  * `schedule.get`, `schedule.create`, `schedule.update`, `schedule.setFromText`, `schedule.pause`, `schedule.archive`, `schedule.resume`, `schedule.runNow`
  * `scheduledFunctions.list`, `scheduledFunctions.create`, `scheduledFunctions.delete` (beta/private rollout; exposed in the webapp only behind the recurring-swaps and recurring-transfers feature flags)
* `v2.executions.*`
  * `get`, `detail`, `result`, `list`, `stream`
* `v2.receipts.*`
  * `get` — receipt view of one operation (`receiptId` = operation id): operation header, summary, full timeline, and a normalized result summary (on-chain transaction ids sourced from `engine.operation_transactions` correlation plus event fallback, bridge legs, amounts). Optional `enrichmentSource` input (`engine` | `gold`) overrides the deployment default (`RECEIPTS_ENRICHMENT_SOURCE`); `gold` adds an `enrichment` block with per-action USD valuations from the indexer's gold layer. Private receipts whose authenticated user is enabled for the server-side `receipt_enrichment_v4` flag use the v4 action/accounting source instead; `v4` is deliberately not a request override and public share-slug reads remain on gold. `resultSummary.enrichmentStatus` is `available`, `pending_correlation`, `pending_pricing`, or `{ state: "unavailable", reason: "actions_disabled" | "source_unavailable" | "too_large" }`; an unavailable or not-yet-correlated source returns `enrichment: null`.
  * Receipt share cards render at `GET /v1/og/receipt/:slug.png` (public; interim home until the OpenGraph-images worker)
  * `list` — user-scoped receipt list across portfolios (keyed off the authenticated user id; pass `portfolioId` to scope to one owned portfolio), filterable by `kinds`/`states`
  * `share.create`, `share.revoke` — mint or revoke a public share slug for a receipt (auth: wallet session or API key; receipt owner only)
  * `shared.get` — public rate-limited read of a shared receipt by slug; payload is sanitized (no user, portfolio, or workflow identifiers)
* `v2.automationRuns.*`
  * `get`, `events`, `stream`
* `v2.workflows.*` (feature-gated beta/private rollout)
  * `list`, `get`
  * `drafts.list`, `drafts.start`, `drafts.startFromWorkflow`, `drafts.get`, `drafts.answer`, `drafts.cancel`
  * `authoring.validate`, `authoring.preview`
* `v2.indexerV4.*` (feature-gated beta/private rollout)
  * `exposureSummary`
  * `engineSignals`
  * `disposalSimulation`
* `v2.agentAuth.*`
  * `createApiKey`
* `v2.public.*`
  * `portfolio.list`, `portfolio.listByIds`, `portfolio.get`
  * `portfolio.vaults.list`
  * `portfolio.schedule.get`
  * `portfolio.activity.list`, `portfolio.activity.allocationHistory`, `portfolio.activity.allocationHistoryChart`
  * `account.profile.get`
  * `account.assets.list`
  * `account.performance.chart`
  * `account.performance.series`
  * `account.performance.overview`

## `actions.submit` Withdrawal Modes

For `v2.portfolio.actions.submit` with `kind: "withdraw"`:

* `mode: "withdraw"` transfers the selected assets out directly.
* `mode: "transfer"` requires `recipient` and is limited to the owner address or
  an owned vault.
* `mode: "external"` requires `recipient` for custom-recipient withdrawals.
  It is available for Investing Account portfolios on EVM and Solana. Legacy
  normal-portfolio support remains for embedded-Privy EVM withdraws and the
  Privy Solana external fallback; other normal-portfolio custom-recipient
  requests are rejected.
* `mode: "withdraw_as_usdc"` requires `recipient` and lets the backend either:
  * transfer already-USDC assets directly, or
  * smart-route one-or-many non-USDC assets through backend swap execution and
    send the resulting USDC to that recipient.
  * A server-approved yield source may support a full-balance exit with
    `assets[].useMaxBalance: true`. `assets[].amount` remains required and is
    the caller's expected full raw share-balance commitment. The engine checks
    that commitment against the live onchain balance and the vault's redemption
    limit; a drifted commitment must be refreshed and retried.
  * Partial exits remain exact-amount requests: omit `useMaxBalance` (or set it
    to `false`) and provide the exact raw amount in `assets[].amount`.
    For Investing Account portfolios, `recipient` may be a custom EVM wallet
    address. Normal portfolio recipients remain limited to the owner or one of the
    owner's managed vault addresses.

## `actions.submit` Swap Constraints

For `v2.portfolio.actions.submit` with `kind: "swap"`:

* `params.chainId` remains the execution chain for the submitted LiFi route.
* `params.executionConstraints` is optional and additive. When present, the
  backend enforces stricter settlement rules without changing existing generic
  swap callers.
* `params.executionConstraints.sameChainOnly: true` rejects multi-chain routes.
* `params.executionConstraints.expectedVaultChainId` requires the route to stay
  on that chain and settle into the authenticated portfolio's exact vault on
  that chain.

This is used by Investing Account buy/sell flows to keep Base, Mainnet, and
Arbitrum cash balances chain-local and to fail closed when the requested-chain
vault is missing.

Ondo Direct EVM market orders are feature-gated by
`execution_ondo_direct_market_orders`. When enabled, callers can first query
`v2.portfolio.actions.previewOndoDirectQuote`:

```json theme={null}
{
  "portfolioId": "<portfolio-id>",
  "chainId": "1",
  "sellTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
  "buyTokenAddress": "0x1111111111111111111111111111111111111111",
  "sellAmount": "1000000"
}
```

The quote response includes `provider: "ondo_direct"`, `side`, raw
`spendAmount`, raw `estimatedReceiveAmount`, asset/cash token metadata, and the
Ondo manager address used by the execution engine.

To execute the confirmed quote, submit `kind: "swap"` with
`params.provider: "ondo_direct"`:

```json theme={null}
{
  "portfolioId": "<portfolio-id>",
  "kind": "swap",
  "params": {
    "provider": "ondo_direct",
    "chainId": "1",
    "sellTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "buyTokenAddress": "0x1111111111111111111111111111111111111111",
    "sellAmount": "1000000",
    "recipientAddress": "0x2222222222222222222222222222222222222222",
    "expectedReceiveAmount": "5000000000000000000"
  }
}
```

`recipientAddress` must be one of the authenticated owner's vaults on the
requested chain. `expectedReceiveAmount` is required: send the previewed
`estimatedReceiveAmount`; the engine rejects firm attestations that fall outside
the server-side quote-deviation guard and fails closed if it is absent.

## `actions.submit` Yield Actions

For `v2.portfolio.actions.submit` with `kind: "yield"`:

```json theme={null}
{
  "portfolioId": "<portfolio-id>",
  "kind": "yield",
  "params": {
    "mode": "deposit",
    "chainId": 42161,
    "protocolId": "aave:v3:ausdc:42161",
    "amount": "1000000",
    "assetId": "0xaf88d065e77c8cc2239327c5edb3a432268e5831:42161"
  }
}
```

* `mode: "deposit"` requires `assetId` and submits a manual engine
  `yield-deposit` operation.
* `mode: "withdraw"` requires `assetId` and submits a manual engine
  `yield-withdraw` operation for a USDC-denominated exit amount.
* `mode: "redeem"` requires `shareAssetId` and submits a manual engine
  `yield-redeem` operation for an exact share-token amount.
* Sources advertising full-balance redeem support may additionally set
  `useMaxBalance: true`. In that case, `amount` is the client's expected full
  raw share balance. The engine verifies the live balance and, for ERC-4626,
  `maxRedeem` before binding the transaction. Other sources remain exact-amount
  only.
* Protocol/source/chain combinations are validated against the server's
  approved yield-source registry. Unregistered combinations are rejected.
* Submitted yield actions return an execution handle with `kind: "execution"`;
  clients should poll `v2.executions.get` or stream `v2.executions.stream`.

## Performance Series Response Shape

`v2.portfolio.performance.series` and `v2.public.account.performance.series` return a unified response containing historical portfolio value and cash-flow points, response metadata identifying the selected return methodology, pre-computed stats per timeframe, and a live value snapshot. Portfolio and account clients should request `returnMethod: "MWR"`; strategy-only performance surfaces remain TWR.

```json theme={null}
{
  "meta": {
    "currency": "USD",
    "returnMethod": "MWR"
  },
  "series": [
    {
      "ts": "2026-03-24T00:00:00.000Z",
      "eventType": null,
      "tvlUsd": "1234.56",
      "amount": "0.00",
      "isLive": false
    }
  ],
  "stats": {
    "DAY": {
      "absoluteChangeUsd": "12.34",
      "returnPct": "1.05"
    },
    "WEEK": {
      "absoluteChangeUsd": "45.67",
      "returnPct": "3.21"
    },
    "MONTH": {
      "absoluteChangeUsd": "123.45",
      "returnPct": "8.90"
    },
    "YEAR": {
      "absoluteChangeUsd": "456.78",
      "returnPct": "25.00"
    },
    "ALL": {
      "absoluteChangeUsd": "789.01",
      "returnPct": "42.00"
    }
  },
  "live": {
    "value": "1234.56",
    "assets": [
      {
        "assetId": "asset-db-id",
        "symbol": "USDC",
        "valueUsd": "500.00"
      }
    ]
  }
}
```

* `meta.returnMethod` is either `MWR` or `TWR`; portfolio performance defaults to `MWR` when no method is provided. `MWR` is a money-weighted return, which reflects the user's actual money outcome after deposits and withdrawals. Portfolio and public account callers should pass `MWR`; strategy performance surfaces remain TWR.
* `series[]` may include a trailing `isLive: true` point representing the current live valuation.
* `stats` is keyed by `PerformanceChartResolution` (`DAY`, `WEEK`, `MONTH`, `YEAR`, `ALL`).
* `live` contains the real-time portfolio value and per-asset breakdown. `live.assets` is present on `v2.portfolio.performance.series` but omitted from the account-level endpoint.
* Responses are cached in Redis with a 30s TTL.

## Public Account Performance Chart

`v2.public.account.performance.chart` is the lightweight user-profile chart contract. It is fixed to a 90 day window and returns daily account TVL points for hoverable public user pages without sending the full account performance series payload:

```json theme={null}
{
  "live": { "value": "1234.56" },
  "meta": {
    "currency": "USD",
    "returnMethod": "MWR"
  },
  "stats": {
    "absoluteChangeUsd": "123.45",
    "returnPct": "8.90"
  },
  "chart": {
    "windowDays": 90,
    "resolution": "day",
    "points": [{ "ts": "2026-03-24T00:00:00.000Z", "tvlUsd": "1234.56" }]
  }
}
```

* The endpoint is derived from the existing account performance service; it does not require a dedicated database table.
* `stats` powers the user-profile hero headline and matches the 90D chart window.
* The public user page should prefer this endpoint over `v2.public.account.performance.series` unless it needs the complete event series.

## Indexer V4 Beta Reads

`v2.indexerV4.exposureSummary`, `v2.indexerV4.engineSignals`, and
`v2.indexerV4.disposalSimulation` are additive beta reads for the v4 accounting
workstream. They require wallet-session or API-key auth, verify the caller can
read the portfolio, and are hidden behind the `indexer_v4_shadow` feature flag.

`exposureSummary` input:

```json theme={null}
{
  "portfolioId": "00000000-0000-4000-8000-000000000001",
  "accountingStreamVersion": "stream-v1",
  "strictness": "engine_action",
  "exposureIds": ["USDC"]
}
```

`engineSignals` input:

```json theme={null}
{
  "portfolioId": "00000000-0000-4000-8000-000000000001",
  "accountingStreamVersion": "stream-v1",
  "allowProvisional": false,
  "triggerMetric": "aggregate_multiple"
}
```

`disposalSimulation` input:

```json theme={null}
{
  "portfolioId": "00000000-0000-4000-8000-000000000001",
  "accountingStreamVersion": "stream-v1",
  "exposureId": "USDC",
  "quantityBaseUnits": "400000",
  "proceedsUsdMicros": "1000000"
}
```

The exposure summary and engine signal responses include explicit readiness,
reasons, snapshot IDs, source finality, accounting stream version, and
FIFO/price completeness fields. Engine signals default to finalized-only
actionability; provisional signals require an explicit caller opt-in.

`disposalSimulation` is read-only. It reconstructs the current FIFO lot stack
from immutable v4 accounting events, then returns the lots that would be
consumed, projected cost basis, optional proceeds allocation, projected realized
PnL, basis completeness, reasons, and source-event watermark. It blocks generic
sell simulation for liability exposures and returns `partial` or `unavailable`
instead of defaulting unknown basis or proceeds.

## Execution Handle

Long-running actions return a canonical execution envelope:

```json theme={null}
{
  "operationId": "rebalance:<portfolioId>:<runId>",
  "portfolioId": "<portfolio-id>",
  "kind": "rebalance",
  "state": "accepted",
  "createdAt": "2026-02-27T00:00:00.000Z",
  "updatedAt": "2026-02-27T00:00:00.000Z",
  "refs": {
    "workflowId": "<workflow-id>",
    "runId": "<run-id>",
    "requestId": "<request-id>",
    "executionSource": "manual",
    "scheduleId": "<rebalance-schedule-id>",
    "scheduledFunctionId": "42",
    "scheduledRunAt": "2026-02-27T00:00:00.000Z"
  }
}
```

`v2.portfolio.actions.submit` also includes additive execution guidance:

* `nextSteps.poll` -> `v2.executions.get`
* `nextSteps.stream` -> `v2.executions.stream`
* `nextRecommendedCommands` with ready-to-copy polling/stream commands
* `refs.executionSource` distinguishes manual and automated starts (`manual`, `scheduled`, `event`, `scheduled_function`)
* `refs.requestId`, `refs.scheduleId`, `refs.scheduledFunctionId`, and `refs.scheduledRunAt` are additive correlation fields when the upstream flow can provide them

Handles returned by `v2.executions.get` / `v2.executions.detail` /
`v2.executions.list` additionally carry optional **display refs** — additive,
display-safe projections of the operation's stored refs (all fields nullable;
present only when the underlying flow recorded them):

* `refs.withdraw` — `{ sourcePortfolioId, chainId, assetId, amount, displayAmount, assetSymbol, sourcePortfolioName, recipientLabel }` (the raw recipient address is never exposed; `recipientLabel` carries the display need)
* `refs.transfer` — `{ sourcePortfolioId, destinationPortfolioId, assetId, amount, displayAmount, assetSymbol, sourcePortfolioName, destinationPortfolioName }`
* `refs.marketOrder` — `{ provider, intentSide, chainId, sellAssetId, buyAssetId, sellAmount, cashAssetId, quoteAssetId }`
* `refs.bridge` — `{ sourceChainId, destinationChainId, assetId, amount, sourceTxHash, destinationTxHash, displayAmount, assetSymbol }`

## Execution Detail

Use `v2.executions.get` for a lightweight summary handle,
`v2.executions.detail` for the persisted execution narrative, and
`v2.executions.result` for raw terminal machine output.

`v2.executions.detail` returns:

* `operation`: the canonical execution handle
* `summary`: the current headline, phase, and terminal reason when available
* `timeline`: curated execution events suitable for user-facing progress UIs or agents
* `graph`: optional rebalance observer graph metadata for richer visualizations

## Execution Stream

`v2.executions.stream` is the canonical typed realtime surface for first-party
web clients. It replays ordered canonical execution events and then switches to
live tail delivery.

Each event uses this envelope:

```json theme={null}
{
  "streamId": "execution:op_123",
  "eventId": "1743163201000-0",
  "sequence": 17,
  "ts": "2026-03-28T15:10:00.000Z",
  "kind": "execution.timeline_appended",
  "operationId": "op_123",
  "cursor": "1743163201000-0",
  "payload": {}
}
```

* Resume is supported with `cursor`. SSE reconnects also use the same opaque
  cursor via `Last-Event-ID`.
* `v2.executions.get` and `v2.executions.detail` remain the snapshot and
  hydration APIs.
* `GET /v1/executions/:operationId/stream` exposes the same canonical event log
  over SSE for CLIs, API integrators, and future chat surfaces.
* `GET /v1/ai/executions/:operationId/ag-ui-stream` exposes an AG-UI projection
  of that same execution log for TanStack AI-compatible clients.

## Automation Run Detail

Use `v2.automationRuns.get` for the current canonical authored-run snapshot and
`v2.automationRuns.events` for ordered timeline pagination.

`v2.automationRuns.get` returns:

* `run`: the current automation run handle
* `latestSequence`: the latest persisted timeline sequence

`v2.automationRuns.events` returns:

* `runId`
* `items`: canonical automation timeline items
* `nextSequence`: the last delivered sequence for resume/polling

## Automation Run Stream

`v2.automationRuns.stream` is the typed realtime surface for authored
automation-engine runs. It follows the same resume model as
`v2.executions.stream`.

Each event uses this envelope:

```json theme={null}
{
  "streamId": "automation:auto_run_123",
  "eventId": "timeline:auto_run_123:4",
  "sequence": 4,
  "ts": "2026-04-19T16:00:00.000Z",
  "kind": "automation.timeline_appended",
  "runId": "auto_run_123",
  "cursor": "sequence:4",
  "payload": {}
}
```

* Resume is supported with `cursor`.
* Direct HTTP SSE for automation runs has been retired. HTTP consumers can read
  snapshots and event pages through `GET /v1/automation-runs/:runId` and
  `GET /v1/automation-runs/:runId/events`.

## Retired/Legacy Mapping

* `sessionKeys.getPortfolioSignableMessage` -> `v2.portfolio.create.prepare`
* `sessionKeys.createPortfolioWithSignature` -> `v2.portfolio.create.confirm`
* `sessionKeys.refreshSessionKeyMessage*` -> `v2.portfolio.permission.refresh.prepare`
* `sessionKeys.refreshSessionKeyWithSignature` -> `v2.portfolio.permission.refresh.confirm`
* `strategyInstances.getStrategyInstancesOwnedByAddress` -> `v2.portfolio.list`
* authenticated dashboard owner-list hydration -> `v2.portfolio.listByOwnerDbV2`
* `strategyInstances.getStrategyInstance` -> `v2.portfolio.get`
* `strategyInstances.archiveStrategyInstance` -> `v2.portfolio.archive`
* `strategyInstances.unarchiveStrategyInstance` -> `v2.portfolio.unarchive`
* `strategyInstances.getUnifiedPortfolioHistory` -> `v2.portfolio.activity.list` (`kind="history"`)
* derived allocation history feed -> `v2.portfolio.activity.allocationHistory.list`
  * `items` remains the cursor-paginated newest-first activity feed for the History table.
  * The response still includes `checkpoints` for backward compatibility when `includeCheckpoints=true`; chart consumers should pass `includeCheckpoints=false` and use the fixed chart route instead.
* fixed allocation history chart -> `v2.portfolio.activity.allocationHistory.chart`
  * `checkpoints` is the 90-day chart-ready sampled allocation series. It includes daily balance-history snapshots, including days without events, so charts should not treat event rows as the only drawable points.
  * Event feed pagination remains on `allocationHistory.list`; chart checkpoints do not use the event cursor.
* `strategyInstances.getStrategyPerformanceMultipleTimeframes` -> `v2.portfolio.performance.get` (`timeframes`)
* `strategyInstances.getNetDepositsAndWithdrawals` -> `v2.portfolio.performance.get` (`netFlows`)
* `strategyInstances.getStrategyPerformanceSeries` -> `v2.portfolio.performance.series`
* dashboard asset analytics -> `v2.portfolio.performance.assetMetrics`
* `strategyInstances.getStrategyInstanceVaultsOwnedByAddress` -> `v2.portfolio.recipients.list`
* `strategyInstances.getStrategyInstancesOwnedByAddress` (public profile view) -> `v2.public.portfolio.list`
* curated public portfolio-card hydration -> `v2.public.portfolio.listByIds`
* `strategyInstances.getStrategyInstance` (unowned read) -> `v2.public.portfolio.get`
* `vaults.getVaultsPortfolioDataForStrategyInstance` (unowned read) -> `v2.public.portfolio.vaults.list`
* `schedules.getStrategyInstanceSchedule` (unowned read) -> `v2.public.portfolio.schedule.get`
* public allocation history feed -> `v2.public.portfolio.activity.allocationHistory`
* public fixed allocation history chart -> `v2.public.portfolio.activity.allocationHistoryChart`
* Explore strategy discovery boards -> `v2.public.explore.strategyDiscoveryBoards`
* user profile hydration aggregate -> `v2.public.account.profile.get`
* `strategyInstances.getAllAssetsAcrossWalletStrategies` (public profile aggregate) -> `v2.public.account.assets.list`
* `strategyInstances.getAccountPerformanceOverview` (public profile aggregate) -> `v2.public.account.performance.overview`
* compact 90D public account chart -> `v2.public.account.performance.chart`
* `strategyInstances.getAccountPerformanceSeries` (public profile aggregate) -> `v2.public.account.performance.series`
* `rebalance.execute` -> `v2.portfolio.actions.submit` (`kind="rebalance"`)
* `withdrawAndDeposits.process*` -> `v2.portfolio.actions.submit` (`kind="withdraw"`)
* `bridge.processBridgeRequest` -> `v2.portfolio.actions.submit` (`kind="bridge"`)
* `executeLifiQuote.execute` -> `v2.portfolio.actions.submit` (`kind="swap"`)
* backend-quoted LiFi swap execution -> `v2.portfolio.actions.submit` (`kind="swap_backend_quote"`)
* manual Aave/Morpho/Fluid yield execution -> `v2.portfolio.actions.submit`
  (`kind="yield"`, returned as `kind="execution"`)
* `schedules.*` -> `v2.portfolio.schedule.*`
* user-approved scheduled functions -> `v2.portfolio.scheduledFunctions.*`
* `rebalance.getStatus` / `workflows.*` / `temporal.*` / `bridge.getBridgeStatus` / `executeLifiQuote.getStatus` -> `v2.executions.get` / `v2.executions.detail` / `v2.executions.result` / `v2.executions.stream`

## Portfolio Create Confirm

`v2.portfolio.create.confirm` accepts the signed permission payload returned by
`v2.portfolio.create.prepare` plus one strategy attachment:

* `portfolioBlueprint`: create a new blueprint from submitted strategy data.
* `blueprintTemplateId`: create from an existing template/forked blueprint. The
  id must reference an existing blueprint.
* `blueprintTemplateMode: "mirror"` with `sourcePortfolioId`: create a
  backend-gated mirrored portfolio from a public, mirrorable upstream source
  portfolio.

Mirror creation is not a general replacement for fork creation. The backend
requires the source portfolio's blueprint to be public and marked mirrorable in
db-v2 `strategy_blueprints.can_mirror`, derives the blueprint from that source,
and creates the downstream portfolio owned by the authenticated caller.
`blueprintTemplateId` is optional in mirror mode; when provided it must match
the source portfolio's blueprint. `portfolioBlueprint` is invalid in mirror
mode.

Mirrored creates inherit the source portfolio's configured rebalance schedule
state from db-v2. If the source portfolio has an active interval, windowed,
cron, or rrule schedule, the mirrored portfolio gets the same spec with a fresh
next-due time. If the source schedule is paused or disabled, the mirrored
schedule is created in the same paused or disabled state. Schedule execution
history, cooldown, failure counters, and last-error fields are not copied. If
the source portfolio has no configured rebalance schedule, the mirrored
portfolio is created without one. The `createSchedule` flag is ignored as a
mirror schedule override; for mirror creates the source portfolio's schedule
state is authoritative.

Mirrored creates also inherit source portfolio-local configuration snapshots.
Stored smart-portfolio policy config is copied with the downstream
owner/portfolio id when the source has a stored config. Source effective swap
preferences (`thresholdUsd`, `slippageBps`, `priceImpactBps`) are resolved from
source portfolio override, source owner global override, and chain defaults,
then copied into the downstream user's portfolio override. These are
creation-time snapshots, like schedule inheritance; later edits to the source
portfolio's local config do not rewrite already-created mirrors. Strategy-level
allocation and drift-threshold changes remain live because mirrored portfolios
continue pointing at the source blueprint.

Mirrored child portfolios cannot edit inherited schedule, smart-portfolio policy
config, or portfolio swap preference overrides. The owning user can still use
global swap defaults for other portfolios, but the mirrored portfolio uses its
creation-time copied portfolio override.

## Compatibility Notes

* `v2.portfolio.create.confirm` validates construction-style blueprints
  server-side regardless of stored builder-draft state: weight blocks using
  `equal`/`specified-percentage` allocation modes must have a valid asset per
  slot, a matching positive weight per slot, no duplicate holdings, and
  custom percentages summing to 100%. Violations return `BAD_REQUEST` with a
  `Portfolio draft is not ready to create: …` message. Blueprints using other
  allocation modes are unaffected.
* Selected legacy namespaces remain mounted for backwards compatibility.
* Retired procedure paths are intentionally removed from legacy routers (for example `rebalance.execute` and migrated `schedules.*` write mutations), and should be treated as `v2.portfolio.*`-only.
* New agent/CLI integrations should target only `v2.*`.
* v2 keeps external language portfolio-first (`portfolioId`), even when internal implementations still use strategy-instance identifiers.
* `v2.executions.list` reads from the persisted execution narrative store for `rebalance`, `swap`, `withdraw`, and `bridge`.
* `v2.executions.get` can also hydrate manual engine `execution` handles, including yield actions, from the runtime engine operation API while those operations are in flight.
* `v2.executions.detail` reads the persisted execution narrative store and adds timeline plus optional graph metadata.
* `v2.executions.stream` replays and tails the canonical execution event log rather than synthesizing updates from repeated detail polling in the normal path.
* `v2.portfolio.status` is resilient: permission/session data still returns if rebalance status source is unavailable; `rebalance` is `null` and `degraded.rebalanceUnavailable=true`.
* `v2.portfolio.status` includes additive semantic `convergence` metadata for owner UIs:
  * `state`: `awaiting_review | queued | moving | blocked | aligned | failed`
  * `summary`: portfolio-level explanation of the highest-priority outstanding condition
  * `approvalId?`, `proposalId?`, `runId?`, `targetId?`, `targetType?`, `executionStatus?`, `updatedAt`: optional references for detail surfaces
* `v2.portfolio.updates.*` is the desired-state composer surface for `webapp-v2`:
  * `preview` derives semantic before/after state without mutating live strategy definitions
  * `create` writes a `draft` revision
  * `submit(mode="review")` promotes that revision to `pending_review`
  * `submit(mode="apply_now")` accepts the revision and syncs it through blueprint versioning for runtime parity
  * `get` returns `PORTFOLIO_UPDATE_NOT_FOUND` when the revision is missing; it does not return a nullable success payload
  * update rows expose additive `revision` metadata so owner surfaces can reason about desired-state history
  * update status includes `dismissed` for review declines
* `v2.portfolio.approvals.*` is the canonical owner-facing approval surface:
  * approval targets are semantic (`portfolio_update` or `portfolio_update`)
  * `decide` is the canonical owner decision entrypoint
* `v2.portfolio.runs.*` exposes semantic convergence/execution rows projected from desired-state apply, copilot execution, and rebalance runtime sources.
* `v2.portfolio.events.*` exposes stored semantic control-plane history:
  * `list` returns canonical timeline events and paginates with an opaque cursor derived from `(createdAt,id)`
  * `stream` provides polling-backed internal event streaming for owner surfaces and can resume from the last opaque cursor
* semantic control-plane reads are now pure `db-v2` reads by default; operational read repair remains available only behind `PORTFOLIO_CONTROL_PLANE_ENABLE_READ_REPAIR`
* `v2.portfolio.context.*` exposes immutable context snapshots referenced by approvals, runs, and events.
* `v2.portfolio.agents.*` exposes portfolio-scoped automated principals and their allowed scopes.
* Permission UIs should prefer `v2.portfolio.permission.status` (session keys + evm agent only) for lighter polling.
* Portfolio identity payloads expose blueprint lineage:
  * `v2.portfolio.list` returns `canonical_strategy_blueprint_id` and `forked_from_blueprint_id` on each portfolio row.
  * `v2.portfolio.get` and `v2.public.portfolio.get` return `canonical_strategy_blueprint_id` and `forked_from_blueprint_id` on the nested `blueprint` object.
  * Consumers should prefer `forked_from_blueprint_id` for copied/forked portfolio strategy links, then fall back to `canonical_strategy_blueprint_id` for unchanged forks.
  * Dashboard owner-list rows also expose `forked_from_blueprint_id` so campaign surfaces can fall back to direct fork lineage when canonical lineage is unavailable.
* Dashboard migration contracts:
  * `v2.portfolio.listByOwnerDbV2` is the db-v2-backed authenticated owner-list route used by the webapp dashboard shell.
  * Each row includes `id`, `archived`, `created_at`, `owner_address`, `owner_account_index`, `blueprint_name`, `blueprint_description`, `canonical_strategy_blueprint_id`, `forked_from_blueprint_id`, `is_public`, `primary_chain_id`, `updated_at`, and `vault_addresses`.
  * `v2.portfolio.performance.series` is now a typed envelope, not a raw array:
    * `meta`: selected return methodology and currency
    * `series`: historical/accounting performance points
    * `stats`: backend-computed `DAY | WEEK | MONTH | YEAR | ALL` metrics with `absoluteChangeUsd` and `returnPct`; the return method lives in `meta.returnMethod`
    * `live`: current value plus normalized `live.assets`
  * `live.assets` uses frontend-facing asset IDs directly and includes:
    * `assetId`, optional `dbAssetId`, `symbol`, `decimals`, `priceUsd`, `valueUsd`, `liveBalanceFormatted`, `liveBalanceRaw`, `vaultAddress`
  * `v2.portfolio.performance.assetMetrics` augments live assets with db-v2 analytics:
    * `assetId`, optional `dbAssetId`, `marketValueUsd`, `netInvestedUsd`, `pnlUsd`, `priceUsd`, `priceMissing`, `asOf`
* Schedule APIs are manual-first and optional:
  * new/forked portfolios do not auto-create a rebalance schedule. Backend-gated mirrored creates inherit the source portfolio's configured rebalance schedule state, including no schedule; `createSchedule` does not override mirror schedule inheritance. Mirrored creates also snapshot source portfolio-local policy config when present and source effective swap preferences.
  * `v2.portfolio.schedule.get` adds `scheduleStatus` (`active | paused | disabled | archived | null`).
  * archived schedules are returned as non-active compatibility payloads (`scheduleExists=false`, `scheduleId=null`, `scheduleData=null`) while still reporting `scheduleStatus="archived"`.
  * archived schedules are terminal: `v2.portfolio.schedule.create`, `v2.portfolio.schedule.update`, and `v2.portfolio.schedule.setFromText` return `SCHEDULE_ARCHIVED` and do not reactivate automation.
  * `v2.portfolio.schedule.runNow` includes additive operation identifiers: `accepted`, `runId`, and `operationId`.
* Scheduled function APIs are UTC-anchored:
  * `v2.portfolio.scheduledFunctions.*` is currently in beta/private rollout and is hidden in the webapp unless the relevant UI feature flag is enabled for the user.
  * `v2.portfolio.scheduledFunctions.list` accepts additive
    `includeTargeting=true` to include schedules owned by the user's investing
    account or other owned portfolios when their config targets the requested
    portfolio.
  * `v2.portfolio.scheduledFunctions.create` supports additive
    `schedule` input for `functionKey="recurring_swap"` and `functionKey="recurring_transfer"`:
    `hourly`, or `{ frequency: "daily" | "weekly", hourUtc, day? }`.
  * The server translates that input into persisted `intervalMs/startAt/endAt`.
  * `v2.portfolio.scheduledFunctions.delete` is a soft delete. Rows are retained for audit/history, marked deleted in storage, and excluded from normal list/run queries.
  * `hourUtc` and weekly `day` are interpreted in UTC; local DST shifts are not preserved.
  * Current product-supported handlers:
    * `recurring_swap`: buy a token with USDC or sell a token to USDC.
    * `recurring_transfer`: move Base USDC from the Investing Account into an owned Base portfolio.
* Portfolio builder APIs:
  * `v2.portfolio.builder.*` persists pre-portfolio onboarding state in `db-v2`.
  * `builder.generateDraft` accepts `portfolioConstructionPlanV2` from the agent control plane. Platform-api treats typed slots, bps allocation, and hard constraints as the runtime contract; source-span text is trace evidence only.
  * Typed portfolio-construction plans preserve canonical exposure separately from the selected executable product. For example, `BTC` exposure can resolve to Base `cbBTC` or Ethereum `WBTC` while the response still carries the canonical underlying metadata (`canonicalExposureId`, `canonicalExposureSymbol`) alongside the resolved product/asset id.
  * Platform-api does not parse English, call model providers, or fall back to prompt-string strategy generation for v2 portfolio construction.
  * Portfolio-construction draft responses include resolver review metadata on `construction`: `reviewStatus`, per-asset `requiresConfirmation`, `reviewMode`, `reviewReason`, candidate alternatives, and `questions[]` for asset/chain/contract clarification before a generated draft is applied.
* Policy APIs are authoritative backend preflight surfaces:
  * `v2.portfolio.policy.evaluate` is the canonical machine-facing evaluator for `rebalance`, `schedule`, `swap`, and `withdraw`.
  * `v2.portfolio.policy.scheduleAdvisory` is a convenience wrapper over the same schedule evaluation path.
  * `v2.portfolio.policy.config.get|update` is the additive Smart Portfolio configuration surface for declarative allocation, rebalance, and yield settings.
  * Observed portfolio facts for public policy evaluation come from backend resolvers, not caller-supplied exposure snapshots.
  * Public `swap` and `withdraw` policy evaluation uses `chainIds` to derive request exposure. Raw `requestExposure` remains accepted temporarily for wire compatibility, but is ignored.
  * Public `rebalance`, `schedule`, and `scheduleAdvisory` still accept legacy `currentExposure` / `plannedExposure` fields for compatibility, but those fields are ignored immediately.
  * Public `withdraw` policy evaluation also ignores legacy raw `portfolioTotalUsd` and `isFullWithdraw` inputs; the backend derives those facts authoritatively when available.
  * Decision payloads preserve `status`, `allowed`, `primaryBlockingReason`, `reasons`, `remainingConditions`, and `nextEligibleAt`, and now also include:
    * `authoritative`
    * `facts`
    * `ruleResults`
  * `primaryBlockingReason` and each entry in `reasons[]` now also include:
    * `policyId`
    * `category`
    * `policySetId` when the reason came from a chain-scoped policy set
  * `ruleResults[]` now includes:
    * `reasonCodes`
    * `policyIds`
    * `reasonCode` remains as the first/primary code for backward compatibility.
  * `facts[].status` distinguishes `present`, `missing`, `stale`, and `synthetic`.
  * `facts[].origin` distinguishes backend-loaded facts (`server`), backend-derived request facts (`derived`), and caller-supplied fallback/hypothetical facts (`client`).
  * `authoritative=true` only means the triggered policy rules had sufficient trusted backend facts; missing, stale, synthetic-only, or client-sourced required facts downgrade the decision to non-authoritative.
  * Backend primary-chain resolution is authoritative: service loaders win over caller fallback hints, and `fallbackPrimaryChainId` is treated as a compatibility hint rather than the source of truth.
  * `remainingConditions[]` may include `market_available` for covered `rebalance` and `swap` decisions, carrying the blocked asset IDs, symbols, provider (`trading_availability` for the unified issuance-agnostic contract; `ondo` may still appear from the legacy shadow during migration), availability type (`closed`, `halted`, `paused`, or `unknown`), and `nextOpenAt` when available. `paused` means the availability source reports a temporary trading pause, and `unknown` means availability could not be established and is treated fail-closed.
  * Omitting `schedule` input on the schedule policy endpoints returns the backend default cadence instead of a denial.
  * Schedule defaults are resolved through a backend chain-policy-set catalog. The generic non-ETH baseline is the current Base-mainnet policy shape, while Ethereum remains stricter because of gas-cost-driven limits.
  * Multi-chain policy-set selection now prefers the authoritative primary chain over catalog order. If multiple supported policy sets match and the primary chain cannot disambiguate them, evaluation defers instead of picking one arbitrarily.
  * Configured-but-unsupported chain policy sets fail closed with a blocking denial rather than silently inheriting the generic non-ETH baseline.

## ETH Mainnet Product Limits (Effective March 2, 2026)

For portfolios where `primary_chain_id = "1"`:

* Rebalance cooldown: max once every 24 hours.
  * error: `REBALANCE_ETH_MAINNET_COOLDOWN_ACTIVE`
* Schedule constraints:
  * interval cadence only,
  * interval must be `>= 24h`,
  * default interval on schedule creation is `24h`.
  * errors: `SCHEDULE_ETH_MAINNET_INTERVAL_TOO_SHORT`, `SCHEDULE_ETH_MAINNET_INTERVAL_ONLY`
* Withdraw constraints:
  * minimum selected withdraw amount `$10`,
  * if portfolio total is below `$10`, only full-balance withdraw is allowed.
  * errors: `WITHDRAW_ETH_MAINNET_BELOW_MINIMUM`, `WITHDRAW_ETH_MAINNET_FULL_REQUIRED_UNDER_MINIMUM`
* Swap-like actions (`kind="swap"` and `kind="swap_backend_quote"`):
  * minimum notional `$10`,
  * error: `LIFI_ETH_MAINNET_BELOW_MINIMUM_TRADE`
* `v2.portfolio.scheduledFunctions.*` currently allows:
  * `functionKey="recurring_swap"`
  * `functionKey="recurring_transfer"`
  * `functionKey="recurring_account_deposit"` for account-origin recurring
    deposits into an existing portfolio
* As of March 30, 2026:
  * `recurring_swap` is intentionally narrow: buy a token with USDC or sell a token to USDC.
  * `recurring_transfer` is intentionally narrow: transfer Base USDC from the Investing Account into an owned portfolio with an active Base vault.

## Public Read Surface Notes

* `v2.public.portfolio.list`, `v2.public.portfolio.listByIds`, `v2.public.portfolio.get`, `v2.public.portfolio.vaults.list`, `v2.public.portfolio.schedule.get`, `v2.public.portfolio.performance.*`, `v2.public.portfolio.activity.list`, `v2.public.portfolio.activity.allocationHistory`, and `v2.public.portfolio.activity.allocationHistoryChart` enforce `is_public=true`.
  * Private portfolios are treated as unreadable: detail-style routes return `PORTFOLIO_NOT_FOUND`, list-by-id entries return `null`, and owner lists omit private rows.
* The web portfolio detail route now intentionally relies on this public-read surface for shared/read-only sections even when the viewer later authenticates as the owner.
  * Shared page regions do not swap data sources after auth resolves.
* `v2.public.portfolio.listByIds` is the lightweight multi-card hydration route for curated public portfolio pages.
  * Input: `portfolioIds[]` with up to 50 ids.
  * Output: `results` keyed by portfolio id.
  * Missing or unreadable ids return `null` for that entry instead of failing the whole batch.
* `v2.public.explore.strategyDiscoveryBoards` is the backend-only V1 proof route for public Explore strategy rails.
  * It returns `highestTvl`, `mostUsed`, `newWithTraction`, `recentInflows`, and `featured` boards keyed by canonical root strategy blueprint.
  * The public route reads the latest successful DB-backed discovery snapshot. The engine refresh job recomputes the snapshot from cursor-backed hourly portfolio snapshots and hourly ledger aggregates every three hours in staging/production.
  * Request-time reads do not scan raw ledgers, current positions, or asset prices.
  * Forked/copied strategy instances roll up to their original root blueprint so board metrics match strategy-family semantics.
  * Rollup equivalence currently uses full stored-spec equality between the instance version and root head version as a temporary guard. A follow-up should add and backfill an indexed `target_allocation_hash` on `strategy_blueprint_versions`, generated from validated target allocation extraction on version writes, then switch discovery equivalence to that allocation hash.
  * Ranked and featured boards apply discoverability filters so placeholder/internal roots such as Investing Account, Glider Reserve, blank, untitled, and test/refactor/staging strategies do not appear. Featured ids are de-duped and must resolve to roots with active usage.
  * `activeInstanceCount` and `activeUserCount` count active non-archived strategy instances/users under the public root, including private instances, while preserving the root-public and spec-equivalence filters.
  * `usageCount` is the display adoption metric used by the `mostUsed` board. It matches the strategy page count semantics: direct mirrors plus direct forks plus configured display seed users.
  * TVL uses fresh active instances, including private instances under public roots; `recentInflows` remains based on public active instances with positive 7-day net inflow.
  * `newWithTraction` requires the configured active-user floor plus TVL and either enough active users or positive 7-day net inflow.
  * Production input is fixed to the warmed snapshot profile for now: `limitPerBoard=3`, `freshnessWindowHours=24`, `newWindowDays=30`, `minTvlUsd=50`, `newWithTractionMinUserCount=2`, `featuredLegacyBlueprintIds=[]`.
  * Staging/non-production callers can use the relaxed profile: `minTvlUsd=0`, `newWithTractionMinUserCount=1`, and the configured staging featured ids. The staging profile fails closed unless the server config explicitly marks the environment as non-production.
  * Unsupported request params are rejected so public reads cannot trigger ad hoc discovery recomputation outside the scheduled snapshot job.
  * Output includes body-level cache metadata (`source`, `stale`, `ttlSeconds`) so clients can surface stale snapshots while the last good refresh remains available.
  * Output data includes additive `schemaVersion=1` and `explore` fields while preserving `data.boards` for existing consumers. The v1 Explore payload contains versioned `tagAggregates` and `trendingTokens` generated with 7-day and 30-day flow windows from the cached discovery snapshot.
* `v2.public.account.profile.get` is the canonical user-profile hydration endpoint used by `/user/:userId`.
  * It returns the user-page aggregate header value, Investing Account snapshot, and profile portfolio cards/table payload in one response.
  * Profile portfolio rows include only active public non-Investing Account portfolios for the account.
  * Private profile portfolios are omitted from the public response so the API does not reveal private portfolio count or ordering.
  * Public profile portfolio `currentValueUsd` and `tokenPreviews` come from the dashboard-normalized account profile snapshot so the table can render without per-portfolio vault/performance fan-out; token previews include best-effort icon popover metadata such as name, chain/address, current price, and token value when already available, but the endpoint does not hydrate per-portfolio performance series.
  * Profile portfolio return fields may be `null` when no cheap aggregate is available. Use the dedicated public performance endpoints for return charts or detailed performance metrics.
  * User-profile schedule rendering is db-v2-only and public-row-only: public portfolios without a v2 schedule row surface as manual/unscheduled.
* `v2.public.account.assets.list`, `v2.public.account.performance.chart`, `v2.public.account.performance.series`, and `v2.public.account.performance.overview` aggregate only the public portfolio subset for the requested owner. Mixed public/private accounts no longer fail closed solely because private portfolios exist.

## Agent Auth Notes

* `v2.agentAuth.createApiKey` keeps `ownerAddress` optional for compatibility.
* If `ownerAddress` is provided, it must match the authenticated wallet address.
* API key metadata persists the canonical wallet owner; mismatches are rejected.

## Webapp Migration Status

As of February 28, 2026, the webapp is migrating in phases:

* Migrated to `v2.*` in owner-authenticated flows:
  * portfolio create/confirm and permission refresh
  * owner portfolio list/get/archive
  * desired-state composer preview/draft/review/apply via `v2.portfolio.updates.*`
  * owner schedule get/create/update/setFromText/pause/resume/runNow
  * bridge submit via `v2.portfolio.actions.submit`
  * withdraw/transfer submit via `v2.portfolio.actions.submit`
  * swap submit via `v2.portfolio.actions.submit` (`kind="swap"`)
  * backend-quoted swap submit via `v2.portfolio.actions.submit` (`kind="swap_backend_quote"`)
  * unified history via `v2.portfolio.activity.list`
  * rebalance runtime status reads via `v2.portfolio.status`
  * execution polling via `v2.executions.get` in migrated withdraw/transfer/swap paths
* Soft deprecation logging is enabled for selected migrated v1 procedures.
* Migrated to `v2.public.*` in non-owner/public flows:
  * user profile hydration via `v2.public.account.profile.get`
  * competition row vault data + schedule reads

## Deferred v1 Allowlist

The following remain on v1 in this phase by design:

* Operation/status exceptions with no clean parity signal yet:
  * withdraw-as-target-asset (`ETH/USDC`) is unsupported and rejected client-side (legacy backend path is also unsupported)
* Public/unowned reads that conflict with v2 owner-auth requirements:
  * public profile and competition views
  * OG routes and legacy routes reading arbitrary user portfolio data
* Analytics endpoints without v2 parity:
  * chart/account/competitor/backtest-style `strategyInstances.*`
* `schedules.getSchedulesForMultipleStrategies` (no v2 equivalent yet)
