diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 0e87913a..eeaee018 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -142,6 +142,9 @@ jobs: node --experimental-default-type=module tests/research_promotion_application_worker_validation.mjs node tests/human_decisions_worker_validation.mjs node --experimental-strip-types tests/decision_review_material_pure_validation.mjs + node tests/console_api_contract_validation.mjs + node tests/console_api_worker_validation.mjs + node tests/console_performance_stats_validation.mjs node tests/account_settings_worker_validation.mjs node --experimental-default-type=module tests/console_evidence_metadata_validation.mjs node --experimental-strip-types tests/account_settings_state_validation.mjs diff --git a/docs/adr/0001-console-read-contracts.md b/docs/adr/0001-console-read-contracts.md new file mode 100644 index 00000000..8333050f --- /dev/null +++ b/docs/adr/0001-console-read-contracts.md @@ -0,0 +1,25 @@ +# Console read contracts and draft saves + +Status: accepted + +## Context + +A console interface needs stable display data without interpreting technical +records or assuming missing financial data are zero. Existing save callers need +their identity and revision conflict behavior preserved. + +## Decision + +Expose additive read projections and a combined draft-save alias. Keep legacy +routes and exact evidence receipts compatible. Read history from existing stored +records. Reuse the existing save transaction and shared performance calculations. +Publish TypeScript contracts and JSON Schemas. Return availability and coverage +alongside values, and keep evidence prose outside the display projection. + +## Consequences + +New clients can use a single inbox, structured setting differences and explicit +unavailable states. Existing clients continue using their current routes. +Incomplete cash flows prevent qualified P/L, TWR and drawdown. Unconnected fill +and effect-verification sources remain explicitly unavailable. Draft saves grant +no execution authority and do not apply runtime changes. diff --git a/docs/console-api.md b/docs/console-api.md new file mode 100644 index 00000000..e43b46b7 --- /dev/null +++ b/docs/console-api.md @@ -0,0 +1,219 @@ +# Console API + +The console exposes stored data and draft preferences for authenticated readers. +TypeScript contracts are in +[`contracts.ts`](../web/strategy-switch-console/frontend/src/api/contracts.ts). +JSON Schemas are in +[`console-api.schema.json`](../web/strategy-switch-console/contracts/console-api.schema.json) +under `$defs`. Types and schemas describe successful reads, unavailable reads, +draft saves and conflicts. All responses use `Cache-Control: no-store`. + +## Endpoints + +| Method and path | Parameters or body | Response contract | +|---|---|---| +| GET `/api/decisions-inbox` | none | `InboxResponse` / `inbox` | +| GET `/api/owner-decisions/history` | `limit`, `cursor` | `DecisionHistoryResponse` / `decision_history` | +| GET `/api/accounts` | none | `AccountsResponse` / `accounts` | +| GET `/api/account-settings/diff` | `account`, optional `platform` | `SettingsDiffResponse` / `settings_diff` | +| GET `/api/account-settings/history` | `account`, optional `platform`, `limit`, `cursor` | `SettingsHistoryResponse` / `settings_history` | +| POST `/api/account-settings/draft` | `CombinedDraftRequest` | `CombinedDraftResponse` / `draft` | +| GET `/api/performance/calendar` | `scope`, `range`, `year`, optional `month`, `platform` | `CalendarResponse` / `calendar` | +| GET `/api/performance/summary` | `scope`, `range`, optional `platform` | `SummaryResponse` / `summary` | +| GET `/api/performance/returns` | `scope`, `range`, optional `platform` | `ReturnsResponse` / `returns` | +| GET `/api/performance/assets` | `scope`, `range`, optional `platform` | `AssetsResponse` / `assets` | +| GET `/api/performance/holdings` | `scope`, `range`, optional `platform` | `HoldingsResponse` / `holdings` | +| GET `/api/performance/trades` | `scope`, `range`, optional `platform` | `TradeStatsResponse` / `trades` | + +`account` and `scope` are configured account aliases, never broker account numbers. +`scope=all` selects accounts explicitly configured as live and excludes conflicting +or duplicate facts. Single-account reads also allow configured paper accounts. +An ambiguous alias requires `platform`. Settings reads also accept the existing +`platform` and `key` parameter pair. + +`range` is `1M|3M|YTD|1Y|ALL`, default `ALL`. The server's Asia/Shanghai date +ends the range. The calendar uses its explicit `year` and `month`, independently +of the range. `year` defaults to the current year. Omitting `month` returns twelve +monthly cells; setting `month=1..12` returns every date in that month. Holdings are +current unrealized holdings, independent of the selected range. + +`limit` defaults to 25 and accepts 1–100. `next_cursor` is an opaque string or +`null`. Pass it unchanged as `cursor`. Histories sort newest first. Decision +history uses timestamp and a stored key as a tie-breaker. These are offset pages; +new records can shift pages, so refresh from the beginning for a current view. +Settings history is bounded by existing record retention. + +## Decisions + +The unified inbox returns display-safe fields only. The old owner, promotion, +recovery and credential reads remain available. Their pending entries also carry +additive `DecisionFields`. Exact evidence-receipt reads keep their existing shape. + +| Category | Priority | `affects_live` | +|---|---|---| +| `reconciliation_recovery` | `high` | true: a later controller action can affect execution | +| `credential_maintenance` | `medium` at 30/7/1 days or expired; otherwise `normal` | false | +| `strategy_promotion` | `normal` | true only for a stored live confirmation mode; intent remains non-executable | +| `owner_decision` | `normal` | true for a stored live-decision recommendation; intent remains non-executable | + +A stored decision produces `decided`. Expired evidence or an elapsed recorded +expiry produces `expired`; otherwise the item is `pending`. Unknown dates are +`null`. `evidence_freshness` reports only existing freshness metadata. A ticket's +record update time does not certify research freshness. Credential items have +one stable `credential:` identity in the unified inbox, and the old credential +endpoint is retained. + +`diff` contains scalar before/after values for available strategy, version, +parameter and shadow metrics. A missing old value is `null`, not an inferred +baseline. Unsupported or unrecorded facts are omitted. `affects_live` on a diff +row describes the effect of eventually applying that field, not permission to +apply it. Parameters use `decisions.parameters`; shadow metrics use +`decisions.shadow`. The field identifier distinguishes individual metrics. + +History comes from durable `human_decision_record` rows across owner, promotion +and recovery categories. `action` records `adopt_intent` or `decline_intent`. +`evidence_sha256` is the exact stored material fingerprint. Actor aliases are +stable pseudonyms derived from the stored actor; raw logins are not returned. +There are no batch actions. + +A source failure remains visible in `sources` and produces inbox +`status=read_failed`, even if other sources returned items. An unreadable history +returns HTTP 503 with `ReadFailed`, never an empty success. + +## Draft settings + +The diff returns seven supported fields across strategy, DCA, cash reserve, +income and options. `current_status=unknown` distinguishes a missing effective +value from a known null. `overridden` and `changed` distinguish inherited fields, +explicit overrides and actual differences. `identity_status=identity_conflict` +means the draft is bound to an older identity and must be reconciled through the +existing flow before saving. + +The combined draft request uses the same identity and revision returned by +`GET /api/account-settings`: + +```json +{ + "platform": "longbridge", + "key": "synthetic-alpha", + "identity": { "use": "the complete identity from the settings response" }, + "expected_draft_revision": 2, + "overrides": { + "reserved_cash_floor": "10", + "reserved_cash_ratio": "0.15", + "income_layer_enabled": false + } +} +``` + +Submit the whole edited override set in one request. Omitted fields retain their +saved overrides; `null` removes an override and inherits the effective setting. +Amounts and ratios remain decimal strings. DCA mode and amount must be supplied +together and explicitly bound to a supported strategy, as on the legacy route. +The identity object above is illustrative; clients must use the actual complete +identity, not reconstruct it from this example. + +All fields are validated before a single durable transaction commits. Origin, +admin, identity, strategy compatibility, revision and conflict checks are shared +with the legacy save. A stale revision returns HTTP 409 with the same error code +as the legacy route, including `account_settings_draft_revision_conflict` and +`account_settings_identity_conflict`. Reload and review the fresh diff before +retrying. A timeout or unknown result requires the existing readback procedure; +clients must not blindly resend. + +The combined endpoint rejects risk preferences, activation flags and controller +fields. Saving creates a draft only: `adopted=false`, `no_order=true`, +`execution_authority_granted=false`. Strategy applications, options activation, +enable/resume and recovery retain their existing controllers and confirmation +requirements. The existing four UI saves and legacy POST remain supported. + +History returns existing draft-save audit entries and profile-application +approvals. The save log is bounded and can be incomplete. Risk-only audit entries +are excluded. No stored effect-verification event source exists, so +`availability.effect_verification` is unavailable with +`effect_verification_not_recorded`. An approval or claim is not proof of effect. + +Account-list draft counts count sections with stored overrides, not verified +runtime changes. Decision counts cover explicit account bindings; global items +are counted separately in `unassigned_decision_count`. A failed source makes the +per-account decision count `null`. `last_change_at` is the latest stored draft, +profile approval or runtime-instance update, or `null` when none is available. + +## Performance data and statuses + +See [performance methods](console-performance-charts.md) for formulas, calendar +dates, return alignment, cash flows and data coverage. The API uses the same +shared range, rebasing, fixed-cohort aggregation and TWR helpers as the charts. +The shared implementation is +[`performance_math.js`](../web/strategy-switch-console/performance_math.js). +The frontend's former helper import path remains a typed re-export. + +| Status | Meaning | +|---|---| +| `ok` | Data support the stated calculation | +| `partial` | Missing flows, observations or coverage limit interpretation | +| `stale` | Last series date is more than three calendar days old | +| `no_data` | No usable observations in the requested block | +| `not_connected` | The record source is not connected | +| `unavailable` | The calculation cannot be supported | + +Every performance block includes `as_of`, `coverage`, `value_kind` and +`unavailable_reason`. `pnl` requires known external cash flows; otherwise amounts +are `asset_change`. Return curves with unknown flows are explicitly +`unadjusted_asset_ratio`, and qualified TWR and drawdown remain null. One point +provides a zero baseline only, not an earned return. Missing cells remain null. + +Native currencies are not added together. Mixed scopes return no aggregate +amount or aggregate asset curve and report `mixed_currency`. Returns include +`per_currency` percentage curves, each aggregated and aligned independently. +These do not represent an average or a combined portfolio return. This API does +not fetch FX quotes or claim historical FX returns. + +Stable reasons include: + +| Reason | Meaning | +|---|---| +| `external_cashflow_required` | Flows do not qualify P/L or TWR | +| `mixed_currency` | No aggregate native-currency amount | +| `snapshot_history_missing`, `snapshot_missing`, `previous_snapshot_missing` | History or a required endpoint is absent | +| `non_trading_weekend`, `incomplete_month` | Non-trading cell or incomplete calendar coverage | +| `insufficient_observations`, `invalid_return_period` | Return calculation lacks valid endpoints | +| `benchmark_history_missing`, `no_common_date` | Comparison cannot align | +| `benchmark_history_unreadable` | Stored benchmark read failed | +| `positions_not_connected`, `positions_partial_coverage` | Holdings are absent or scoped | +| `positions_stale` | Existing position source is stale | +| `avg_cost_missing`, `position_value_missing` | Unrealized P/L lacks required fields | +| `fills_not_connected` | No console fill source; no trade statistics are emitted | +| `stored_records_unreadable` | A required store read failed | + +`coverage.excluded_accounts` and `omitted_dates` disclose incomplete cohorts. +A missing currency excludes that account's full history rather than understating +its assets. Benchmark availability is independent of account data availability. + +## Authentication and errors + +Reads use the existing allowed session. Combined saves also require the existing +admin role and same-origin header. No login, trading or infrastructure permission +is added. HTTP 401 means login is required; 403 means access or origin is denied; +400 means invalid input; 405 means unsupported method; 409 means a conflict; 503 +means a stored source could not be read. No production verification should POST +to these endpoints. + +Use `label_key` and `title_key` through the frontend locale system. Identifiers, +evidence bindings and fingerprints are opaque references, not display prose. +Legacy payloads retain evidence notes, research explanations and technical +metadata for compatibility; treat those legacy fields as internal and do not +render them in the rewritten UI. The unified inbox never includes that prose. + +## Synthetic development + +Run `npm run dev:synthetic --prefix web/strategy-switch-console/frontend` and open +`http://127.0.0.1:4173/v2/?qa=api-ready`. Fixtures are defined in +[`console-api-synthetic.mjs`](../web/strategy-switch-console/frontend/scripts/console-api-synthetic.mjs). +Every new endpoint is served locally. The combined-save endpoint is a local mock; +it does not persist or dispatch anything. The existing demo remains available. + +Use `qa=api-empty`, `api-partial`, `api-stale`, `api-not-connected`, +`api-read-failed` or `api-conflict`. The last scenario returns 409 for the mock +combined POST. Trade stats are not connected in every scenario. No provider, +production session or real account data are used. diff --git a/docs/console-performance-charts.md b/docs/console-performance-charts.md index 0de184b4..428575a9 100644 --- a/docs/console-performance-charts.md +++ b/docs/console-performance-charts.md @@ -99,3 +99,59 @@ starts, missing benchmark days, rebasing, deposits/withdrawals, capital-weighted multi-account TWR, unknown flows, incomplete cohorts, empty/single observations and invalid values. All fixtures are synthetic. Loader, render and refresh tests exercise the production components without live account data. + +## Performance API statistics + +The [console API](console-api.md) exposes calendar, summary, return, asset and +current-holdings blocks. Pure statistics are separate from HTTP handlers. Charts +and the Worker share `web/strategy-switch-console/performance_math.js`; the +frontend helper module re-exports its types and functions. + +Daily P/L is `V[t] - V[previous close] - F[t]`. Its displayed daily percentage is +`100 * daily P/L / (V[previous close] + F[t])` when the denominator is positive. +The period's simple-weighted percentage is +`100 * period P/L / (V[start] + sum(F))`, only with complete flows. Period and +monthly TWR use the shared end-flow index above. Maximum drawdown is the largest +`100 * (1 - I[trough] / I[peak])` on that index, with the peak before the trough. +It is zero for a monotonic positive index and unavailable for fewer than two +observations. A deposit during a drawdown does not reset its peak. + +Excess return is primary minus benchmark return in percentage points. Every +comparison uses the shared aligned start and its last exact shared endpoint. +The endpoint is returned so different histories cannot hide different end dates. +The API never labels an unknown-flow curve as TWR or computes qualified drawdown +from raw assets. Best and worst day are ranked by supported daily return, with +the corresponding amount. They are null when daily returns cannot be supported. + +Observation dates retain producer-provided daily labels; the API does not +reinterpret an intraday timestamp as a US session date. Range boundaries use +Asia/Shanghai as above. Stock calendars mark Saturdays and Sundays non-trading. +Binance-only calendars include every calendar day. There is no stored holiday +calendar: an absent weekday is `snapshot_missing`, not a presumed holiday. +The prior stock close must be the immediately preceding weekday; an intervening +missing weekday makes daily change unavailable. No multi-day change is assigned +to a single calendar day. A month with missing required dates has a null total +and return, plus `observed_amount` and observed/expected day counts. The partial +sum is not a full-month result. Positive/negative numeric signs carry no colors; +clients retain the console's existing locale-aware up/down colors. + +| Stored source | Assets/history | Current positions | Cash-flow-qualified daily P/L/TWR | Console fills | +|---|---|---|---|---| +| LongBridge | Broker balances and up to 366 daily snapshots | Not carried by this schema | Unavailable: complete flows absent | Not connected | +| IBKR | Broker balances and up to 366 daily snapshots | Optional `stocks_only`, optional average cost | Unavailable: interval-return reports do not provide daily flows | Not connected | +| Schwab | Broker balances and up to 366 daily snapshots | Optional `strategy_symbols_only`, optional average cost | Unavailable: complete flows absent | Not connected | +| Firstrade | Broker balances and up to 366 daily snapshots | Not carried by this schema | Unavailable: complete flows absent | Not connected | +| Binance | Stored USDT wallet-valuation history | Not a stock-position source | Unavailable: complete flows absent | Not connected | +| Other configured platforms | No connected snapshot-history source | Unavailable | Unavailable | Not connected | + +This table describes source capabilities, not the presence of data in any specific +account. Holdings use only current broker-reported rows, labelled current, +unrealized. `unrealized_pnl = market_value - avg_cost * quantity`; missing cost +produces null with `avg_cost_missing`. These are not period contributions. +There is no daily position history or closed-trade source for attribution or +win-rate statistics. No trade count, fee estimate or placeholder win rate is +returned. Native-currency API amounts remain separate; see the API contract for +mixed-currency percentage curves. + +Definitions are informed by Longbridge's public +[P/L analysis guide](https://longbridge.com/sg/en/support/topics/tradingfaqs/pl-analysis). diff --git a/tests/console_api_contract_validation.mjs b/tests/console_api_contract_validation.mjs new file mode 100644 index 00000000..4641f8fd --- /dev/null +++ b/tests/console_api_contract_validation.mjs @@ -0,0 +1,336 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { consoleApiFixture } from "../web/strategy-switch-console/frontend/scripts/console-api-synthetic.mjs"; +import { + consoleApiResponse, + inbox, +} from "../web/strategy-switch-console/application/console_api/routes.js"; +import { + decisionFields, + actorAlias, + decisionHistoryRows, +} from "../web/strategy-switch-console/application/console_api/presentation.js"; +import { performanceResponse } from "../web/strategy-switch-console/application/console_api/performance_routes.js"; +const schemas = JSON.parse( + readFileSync( + new URL( + "../web/strategy-switch-console/contracts/console-api.schema.json", + import.meta.url, + ), + ), +).$defs; +export function validate(name, data) { + const visit = (schema, value, path) => { + if (schema.const !== undefined) assert.deepEqual(value, schema.const, path); + if (schema.enum) assert.ok(schema.enum.includes(value), path + ": enum"); + if (schema.type) { + const kinds = Array.isArray(schema.type) ? schema.type : [schema.type]; + assert.ok( + kinds.some((t) => + t === "null" + ? value === null + : t === "array" + ? Array.isArray(value) + : t === "integer" + ? Number.isSafeInteger(value) + : t === "number" + ? typeof value === "number" && Number.isFinite(value) + : t === "object" + ? value !== null && + typeof value === "object" && + !Array.isArray(value) + : typeof value === t, + ), + path + ": type", + ); + } + if (schema.pattern) assert.match(value, new RegExp(schema.pattern), path); + for (const key of schema.required || []) + assert.ok(Object.hasOwn(value, key), path + "." + key + ": required"); + if (schema.properties) + for (const [key, sub] of Object.entries(schema.properties)) + if (Object.hasOwn(value, key)) visit(sub, value[key], path + "." + key); + if (schema.items) + value.forEach((item, i) => visit(schema.items, item, `${path}[${i}]`)); + }; + assert.ok(schemas[name], name); + visit(schemas[name], data, name); +} +assert.throws(() => validate("trades", { status: "ok" })); +const endpoints = { + "/api/decisions-inbox": "inbox", + "/api/owner-decisions/history": "decision_history", + "/api/accounts": "accounts", + "/api/account-settings/diff": "settings_diff", + "/api/account-settings/history": "settings_history", + "/api/account-settings/draft": "draft", + ...Object.fromEntries( + ["calendar", "summary", "returns", "assets", "holdings", "trades"].map( + (x) => ["/api/performance/" + x, x], + ), + ), +}; +for (const scenario of [ + "api-ready", + "api-empty", + "api-partial", + "api-stale", + "api-not-connected", + "api-read-failed", + "api-conflict", +]) + for (const [endpoint, name] of Object.entries(endpoints)) { + const fixture = consoleApiFixture( + endpoint, + new URLSearchParams("month=10&year=2026"), + scenario, + endpoint.endsWith("/draft") ? "POST" : "GET", + Date.parse("2026-10-15T12:00:00Z"), + ); + validate( + fixture.status === 409 + ? "conflict" + : fixture.status === 503 + ? endpoint.startsWith("/api/performance/") + ? "performance_unavailable" + : "read_failed" + : name, + fixture.body, + ); + } +const json = (b, status = 200) => Response.json(b, { status }); +const login = async () => ({ + allowed: true, + login: "synthetic-owner", + admin: true, +}); +const emptySource = async () => + json({ data_status: "ready", candidates: [], tickets: [], recoveries: [] }); +const deps = { + json, + readSession: login, + command: async () => ({ rows: [] }), + owner: emptySource, + promotion: emptySource, + recovery: emptySource, + credential: async () => + json({ id: "synthetic-expiry", requires_action: true, phase: "7" }), + accountOptions: async () => ({ + options: { longbridge: [{ key: "synthetic-alpha" }] }, + }), + settings: async () => + json({ + draft: { + status: "current", + revision: 1, + overrides: { reserved_cash_ratio: "0.2" }, + }, + effective: { reserved_cash_ratio: { status: "known", value: "0.1" } }, + }), + audit: async () => [], + saveDraft: async () => + json({ ok: false, error: "account_settings_draft_revision_conflict" }, 409), +}; +let result = await inbox( + new Request("https://console.example/api/decisions-inbox"), + {}, + deps, +); +validate("inbox", result); +assert.equal(result.items.length, 1); +assert.equal(result.items[0].id, "credential:synthetic-expiry"); +assert.equal(result.items[0].priority, "medium"); +result = await inbox( + new Request("https://console.example/api/decisions-inbox"), + {}, + { + ...deps, + owner: async () => { + throw Error("offline"); + }, + }, +); +assert.equal(result.status, "read_failed"); +assert.equal(result.sources[0].status, "read_failed"); +assert.equal( + decisionFields({ recovery: {}, confirmation: {} }, "reconciliation_recovery") + .status, + "decided", +); +assert.equal( + decisionFields( + { ticket_id: "synthetic", expires_at: "2020-01-01" }, + "strategy_promotion", + ).status, + "expired", +); +assert.equal( + decisionFields( + { + ticket_id: "synthetic", + notes: ["audit prose"], + proposed_params: { audit_note: "internal", rebalance_days: 5 }, + }, + "strategy_promotion", + ).diff.length, + 1, +); +const alias = await actorAlias("synthetic-owner"); +assert.match(alias, /^actor-[a-f0-9]{16}$/); +assert.equal(alias, await actorAlias("synthetic-owner")); +const rows = await decisionHistoryRows([ + { + kind: "owner", + subject_id: "fictional", + actor: "synthetic-owner", + action: "approve_limited_live_canary", + decided_at: "2026-10-15T12:00:00Z", + material_key: "a".repeat(64), + }, +]); +assert.equal(rows[0].action, "adopt_intent"); +assert.ok(!JSON.stringify(rows).includes("synthetic-owner")); +for (const [endpoint, name] of Object.entries(endpoints).filter( + ([p]) => !p.startsWith("/api/performance/"), +)) { + const response = await consoleApiResponse( + new Request( + "https://console.example" + endpoint + "?account=synthetic-alpha", + { method: endpoint.endsWith("/draft") ? "POST" : "GET" }, + ), + {}, + { ...deps, command: async () => ({ rows: [], approvals: [] }) }, + ); + validate( + endpoint.endsWith("/draft") ? "conflict" : name, + await response.json(), + ); +} +const failed = await consoleApiResponse( + new Request("https://console.example/api/owner-decisions/history"), + {}, + { + ...deps, + command: async () => { + throw Error("offline"); + }, + }, +); +assert.equal(failed.status, 503); +validate("read_failed", await failed.json()); +assert.equal( + ( + await consoleApiResponse( + new Request( + "https://console.example/api/owner-decisions/history?limit=1000", + ), + {}, + deps, + ) + ).status, + 400, +); +const now = Date.now(), + dates = [ + new Date(now - 86400000).toISOString().slice(0, 10), + new Date(now).toISOString().slice(0, 10), + ]; +const perfDeps = { + json, + readSession: login, + accountOptions: async () => ({ + options: { ibkr: [{ key: "synthetic-alpha", broker_environment: "live" }] }, + }), + facts: async () => + json({ + accounts: [ + { + platform: "ibkr", + account_key: "synthetic-alpha", + binding_status: "bound", + balances: [{ currency: "USD" }], + positions: [ + { + symbol: "SYNTH", + quantity: "1", + market_value: "120", + currency: "USD", + }, + ], + positions_scope: "stocks_only", + }, + ], + }), + history: async () => + json({ + platform: "ibkr", + account_key: "synthetic-alpha", + series: { + currency: "USD", + points: dates.map((date, i) => ({ + observation_date: date, + currency: "USD", + net_assets: String(100 + i), + })), + }, + }), + wallet: async () => { + throw Error("not expected"); + }, + benchmarks: async () => + json({ + points: dates.map((d, i) => ({ + seriesId: "synthetic-index", + observationDate: d, + close: String(100 + i), + })), + }), +}; +for (const part of [ + "calendar", + "summary", + "returns", + "assets", + "holdings", + "trades", +]) { + const response = await performanceResponse( + new Request( + "https://console.example/api/performance/" + + part + + "?scope=synthetic-alpha", + ), + {}, + perfDeps, + ); + assert.equal(response.status, 200); + const body = await response.json(); + validate(part, body); + if (part === "summary") { + assert.equal(body.twr_return_percent, null); + assert.equal(body.max_drawdown.percent, null); + assert.equal(body.value_kind, "asset_change"); + } + if (part === "trades") assert.ok(!("trade_count" in body)); +} +assert.equal( + ( + await performanceResponse( + new Request("https://console.example/api/performance/assets?range=bad"), + {}, + perfDeps, + ) + ).status, + 400, +); +assert.equal( + ( + await performanceResponse( + new Request("https://console.example/api/performance/assets"), + {}, + { ...perfDeps, readSession: async () => null }, + ) + ).status, + 401, +); +console.log("console_api_contract_validation: PASS"); diff --git a/tests/console_api_worker_validation.mjs b/tests/console_api_worker_validation.mjs new file mode 100644 index 00000000..1c26c8f1 --- /dev/null +++ b/tests/console_api_worker_validation.mjs @@ -0,0 +1,264 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { __test } from "../web/strategy-switch-console/worker.js"; +import { validate } from "./console_api_contract_validation.mjs"; +const require = createRequire( + new URL("../web/strategy-switch-console/package.json", import.meta.url), +); +const { Miniflare } = require("miniflare"); +const account = { + key: "synthetic-alpha", + label: "Synthetic alpha", + target_name: "synthetic-alpha", + runtime_status_target_id: "longbridge.synthetic-alpha", + account_selector: "SYNTHETIC", + deployment_selector: "synthetic", + account_scope: "SYNTHETIC", + service_name: "synthetic-service", + supported_domains: ["us_equity"], + broker_environment: "paper", + default_execution_mode: "live", + default_strategy_profile: "synthetic-dca", +}; +const bindings = { + SESSION_SECRET: "synthetic-only-session", + ALLOWED_GITHUB_LOGINS: "synthetic-admin,synthetic-reader", + STRATEGY_SWITCH_ADMIN_LOGINS: "synthetic-admin", + STRATEGY_SWITCH_ACCOUNT_OPTIONS_JSON: JSON.stringify({ + longbridge: [account], + }), + STRATEGY_SWITCH_STRATEGY_PROFILES_JSON: JSON.stringify([ + { + profile: "synthetic-growth", + label: "Synthetic growth", + domain: "us_equity", + allowed_execution_modes: ["paper"], + option_overlay_enabled: true, + }, + ]), +}; +const admin = `qsl_switch_session=${await __test.makeSession("synthetic-admin", [], bindings)}`; +const reader = `qsl_switch_session=${await __test.makeSession("synthetic-reader", [], bindings)}`; +let outbound = 0; +const mf = new Miniflare({ + cf: false, + modules: true, + modulesRules: [{ type: "ESModule", include: ["**/*.js"] }], + scriptPath: fileURLToPath( + new URL("../web/strategy-switch-console/worker.js", import.meta.url), + ), + compatibilityDate: "2026-06-08", + bindings, + durableObjects: { + STRATEGY_SWITCH_RUNTIME_INSTANCES: { + className: "RuntimeInstances", + useSQLite: true, + }, + }, + durableObjectsPersist: await mkdtemp(join(tmpdir(), "console-api-")), + kvNamespaces: ["STRATEGY_SWITCH_CONFIG"], + outboundService: () => { + outbound++; + return new Response("offline", { status: 503 }); + }, +}); +async function call( + path, + { + method = "GET", + body, + cookie = admin, + origin = "https://console.example", + } = {}, +) { + const response = await mf.dispatchFetch("https://console.example" + path, { + method, + headers: { + ...(cookie ? { Cookie: cookie } : {}), + ...(origin ? { Origin: origin } : {}), + ...(body ? { "Content-Type": "application/json" } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + return { status: response.status, body: await response.json() }; +} +try { + assert.equal( + ( + await call("/api/admin/runtime-instances", { + method: "POST", + body: { + action: "initialize", + expected_revision: 0, + confirm: "IMPORT_EXISTING_CONFIG", + }, + }) + ).status, + 200, + ); + const settings = await call( + "/api/account-settings?platform=longbridge&key=synthetic-alpha", + ); + assert.equal(settings.status, 200); + const request = { + platform: "longbridge", + key: "synthetic-alpha", + identity: settings.body.identity, + expected_draft_revision: 0, + overrides: { + strategy_profile: "synthetic-growth", + reserved_cash_floor: "10", + reserved_cash_ratio: "0.15", + income_layer_enabled: false, + option_overlay_enabled: false, + }, + }; + const saved = await call("/api/account-settings/draft", { + method: "POST", + body: request, + }); + assert.equal(saved.status, 200); + validate("draft", saved.body); + assert.equal(saved.body.adopted, false); + assert.equal(saved.body.draft.revision, 1); + assert.deepEqual(saved.body.draft.overrides, request.overrides); + const stale = await call("/api/account-settings/draft", { + method: "POST", + body: request, + }); + assert.equal(stale.status, 409); + assert.equal(stale.body.error, "account_settings_draft_revision_conflict"); + const invalid = await call("/api/account-settings/draft", { + method: "POST", + body: { + ...request, + expected_draft_revision: 1, + overrides: { ...request.overrides, reserved_cash_ratio: "2" }, + }, + }); + assert.equal(invalid.status, 400); + const after = await call( + "/api/account-settings?platform=longbridge&key=synthetic-alpha", + ); + assert.equal(after.body.draft.revision, 1); + assert.deepEqual( + after.body.draft.overrides, + request.overrides, + "invalid field cannot partially save other sections", + ); + for (const forbidden of [ + { risk_preference: "BALANCED_COMPOUNDING" }, + { runtime_target_enabled: true }, + { apply: true }, + ]) + assert.equal( + ( + await call("/api/account-settings/draft", { + method: "POST", + body: { ...request, ...forbidden, expected_draft_revision: 1 }, + }) + ).status, + 400, + ); + assert.equal( + ( + await call("/api/account-settings/draft", { + method: "POST", + body: request, + cookie: reader, + }) + ).status, + 403, + ); + assert.equal( + ( + await call("/api/account-settings/draft", { + method: "POST", + body: request, + origin: "https://different.example", + }) + ).status, + 403, + ); + const diff = await call( + "/api/account-settings/diff?account=synthetic-alpha", + { cookie: reader }, + ); + assert.equal(diff.status, 200); + validate("settings_diff", diff.body); + assert.equal(diff.body.rows.length, 7); + const history = await call( + "/api/account-settings/history?account=synthetic-alpha", + ); + assert.equal(history.status, 200); + validate("settings_history", history.body); + assert.equal(history.body.items.length, 1); + assert.equal(history.body.items[0].event, "draft_saved"); + assert.ok(!JSON.stringify(history.body).includes("synthetic-admin")); + const accounts = await call("/api/accounts"); + assert.equal(accounts.status, 200); + validate("accounts", accounts.body); + assert.equal(accounts.body.accounts[0].pending_draft_count, 4); + for (const [path, schema] of [ + ["/api/owner-decisions/history", "decision_history"], + ["/api/decisions-inbox", "inbox"], + ]) { + const read = await call(path, { cookie: reader }); + assert.equal(read.status, 200); + validate(schema, read.body); + assert.equal((await call(path, { cookie: null })).status, 401); + assert.equal((await call(path, { method: "POST", body: {} })).status, 405); + } + for (const part of [ + "calendar", + "summary", + "returns", + "assets", + "holdings", + "trades", + ]) { + const result = await call("/api/performance/" + part); + assert.equal(result.status, 200); + validate(part, result.body); + } + const legacy = await call("/api/account-settings", { + method: "POST", + body: { + ...request, + expected_draft_revision: 1, + overrides: { reserved_cash_ratio: "0.2" }, + }, + }); + assert.equal(legacy.status, 200); + assert.equal(legacy.body.draft.overrides.reserved_cash_ratio, "0.2"); + assert.equal( + legacy.body.draft.overrides.strategy_profile, + "synthetic-growth", + ); + // Concurrent combined saves share the existing compare-and-swap guard. + const race = await Promise.all( + ["0.25", "0.3"].map((ratio) => + call("/api/account-settings/draft", { + method: "POST", + body: { + ...request, + expected_draft_revision: 2, + overrides: { ...request.overrides, reserved_cash_ratio: ratio }, + }, + }), + ), + ); + assert.deepEqual(race.map((r) => r.status).sort(), [200, 409]); + assert.equal( + outbound, + 0, + "new APIs do not contact upstream providers or dispatch workflows", + ); +} finally { + await mf.dispose(); +} +console.log("console_api_worker_validation: PASS"); diff --git a/tests/console_performance_stats_validation.mjs b/tests/console_performance_stats_validation.mjs new file mode 100644 index 00000000..be86d1bb --- /dev/null +++ b/tests/console_performance_stats_validation.mjs @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { + businessDate, + calendarCells, + closedTradeStats, + dailyChanges, + holdingsRows, + maxDrawdown, + performanceBlocks, +} from "../web/strategy-switch-console/application/console_api/performance.js"; +import { chainReturns } from "../web/strategy-switch-console/performance_math.js"; +const points = [ + { date: "2026-10-01", value: 100, externalFlow: 0 }, + { date: "2026-10-02", value: 200, externalFlow: 100 }, + { date: "2026-10-05", value: 180, externalFlow: 0 }, + { date: "2026-10-06", value: 270, externalFlow: 100 }, + { date: "2026-10-07", value: 280, externalFlow: 0 }, +]; +assert.equal(dailyChanges(points)[1].amount, 0, "deposit is not P/L"); +assert.equal(dailyChanges(points)[1].return_percent, 0); +assert.equal( + dailyChanges([ + { date: "2026-10-02", value: 100, externalFlow: 0 }, + { date: "2026-10-03", value: 200, externalFlow: 100 }, + { date: "2026-10-05", value: 200, externalFlow: 0 }, + ])[2].amount, + 0, + "weekend capital stays investment at the next close", +); +const calendar = calendarCells(points, 2026, 10); +assert.equal(calendar.find((p) => p.date === "2026-10-02").amount, 0); +assert.equal(calendar.find((p) => p.date === "2026-10-08").amount, null); +assert.equal( + calendar.find((p) => p.date === "2026-10-03").unavailable_reason, + "non_trading_weekend", +); +assert.equal( + dailyChanges([ + { date: "2026-10-01", value: 100 }, + { date: "2026-10-05", value: 105 }, + ])[1].amount, + null, + "missing Friday prevents pretending Monday is daily", +); +assert.equal(businessDate(Date.parse("2026-12-31T16:01:00Z")), "2027-01-01"); +assert.equal(businessDate(Date.parse("2026-12-31T15:59:00Z")), "2026-12-31"); +assert.equal(calendarCells([], 2024, 2).length, 29); +assert.equal(calendarCells([], 2026, null).length, 12); +const dd = maxDrawdown(chainReturns(points).index); +assert.ok(Math.abs(dd.percent - 15) < 1e-10); +assert.equal(dd.peak_date, "2026-10-01"); +assert.equal(dd.trough_date, "2026-10-06"); +assert.equal( + maxDrawdown([ + { date: "2026-01-01", value: 1 }, + { date: "2026-01-02", value: 2 }, + ]).percent, + 0, +); +assert.equal(maxDrawdown([]).percent, null); +assert.equal(maxDrawdown(points.slice(0, 1)).percent, null); +assert.equal(closedTradeStats([]).win_rate_percent, null); +const holdings = holdingsRows([ + { + account_key: "synthetic", + platform: "ibkr", + positions_scope: "stocks_only", + positions: [ + { + symbol: "SYNTH", + quantity: "2", + market_value: "250", + avg_cost: "100", + currency: "USD", + }, + { + symbol: "UNKNOWN", + quantity: "1", + market_value: "100", + currency: "USD", + }, + ], + }, +]); +assert.equal(holdings[0].unrealized_pnl, 50); +assert.equal(holdings[1].unrealized_pnl, null); +assert.equal(holdings[1].unavailable_reason, "avg_cost_missing"); +const input = { + accounts: [{ account_key: "synthetic", platform: "ibkr" }], + histories: [{ id: "synthetic", currency: "USD", points }], + range: "ALL", + today: "2026-10-08", + year: 2026, + month: 10, +}; +const blocks = performanceBlocks(input); +assert.ok( + Math.abs(blocks.summary.twr_return_percent - ((280 / 270) * 0.85 - 1) * 100) < + 1e-10, +); +assert.equal(blocks.summary.amount, -20); +assert.equal(blocks.assets.points.length, 5); +assert.ok(!("benchmarks" in blocks.assets)); +assert.equal(blocks.returns.points[0].value, 0); +const mixed = performanceBlocks({ + ...input, + histories: [...input.histories, { id: "other", currency: "HKD", points }], +}); +assert.equal(mixed.returns.per_currency.length, 2); +assert.equal(mixed.returns.per_currency[0].points[0].value, 0); +assert.equal(mixed.summary.unavailable_reason, "mixed_currency"); +assert.equal(mixed.summary.amount, null); +assert.deepEqual(mixed.assets.points, []); +const unknown = performanceBlocks({ + ...input, + histories: [ + { + id: "synthetic", + currency: "USD", + points: points.map(({ externalFlow, ...p }) => p), + }, + ], +}); +assert.equal(unknown.summary.value_kind, "asset_change"); +assert.equal(unknown.summary.twr_return_percent, null); +assert.equal(unknown.summary.max_drawdown.percent, null); +const empty = performanceBlocks({ ...input, histories: [] }); +assert.equal(empty.summary.status, "no_data"); +assert.equal(empty.summary.amount, null); +const single = performanceBlocks({ + ...input, + histories: [{ id: "synthetic", currency: "USD", points: points.slice(0, 1) }], +}); +assert.equal(single.summary.twr_return_percent, null); +const boundaryPoints = [ + { date: "2026-12-31", value: 100, externalFlow: 0 }, + { date: "2027-01-01", value: 110, externalFlow: 0 }, +]; +assert.equal(calendarCells(boundaryPoints, 2027, 1)[0].amount, 10); +const yearPoints = Array.from({ length: 32 }, (_, i) => ({ + date: new Date(Date.UTC(2026, 0, i)).toISOString().slice(0, 10), + value: 100 + i, + externalFlow: 0, +})); +const days = calendarCells(yearPoints, 2026, 1, { crypto: true }); +const months = calendarCells(yearPoints, 2026, null, { crypto: true }); +assert.equal( + months[0].amount, + days.reduce((s, p) => s + p.amount, 0), +); +assert.equal(months[1].amount, null); +console.log("console_performance_stats_validation: PASS"); + +assert.equal( + dailyChanges([ + { date: "2026-10-01", value: 0, externalFlow: 0 }, + { date: "2026-10-02", value: 0, externalFlow: 0 }, + ])[1].unavailable_reason, + "invalid_return_period", +); diff --git a/tests/human_decisions_worker_validation.mjs b/tests/human_decisions_worker_validation.mjs index e58cef7c..3cee6361 100644 --- a/tests/human_decisions_worker_validation.mjs +++ b/tests/human_decisions_worker_validation.mjs @@ -208,6 +208,13 @@ try { const stableEvidence = stableQueue.body.candidates.find((item) => item.candidate.candidate_id === "owner-stable").candidate_evidence_sha256; const stable = await call("/api/owner-decisions", { method: "POST", body: { candidate_id: "owner-stable", decision: "keep_parked", candidate_evidence_sha256: stableEvidence } }); assert.equal(stable.status, 200); + const historyPage = await call("/api/owner-decisions/history?limit=1"); + assert.equal(historyPage.status, 200); + assert.equal(historyPage.body.items.length, 1); + assert.equal(historyPage.body.next_cursor, "1"); + assert.match(historyPage.body.items[0].actor_alias, /^actor-[a-f0-9]{16}$/); + assert.match(historyPage.body.items[0].evidence_sha256, /^[a-f0-9]{64}$/); + assert.equal((await call("/api/owner-decisions/history?limit=1&cursor=1")).body.items.length, 1); assert.equal((await syncControl(ownerSnapshot("owner-stable"))).status, 200); const stableAgain = await call("/api/owner-decisions"); const stableIntent = stableAgain.body.candidates.find((item) => item.candidate.candidate_id === "owner-stable").intent; diff --git a/web/strategy-switch-console/application/approval/owner_decisions.js b/web/strategy-switch-console/application/approval/owner_decisions.js index 641cf3a7..4169ed46 100644 --- a/web/strategy-switch-console/application/approval/owner_decisions.js +++ b/web/strategy-switch-console/application/approval/owner_decisions.js @@ -1,3 +1,4 @@ +import { decisionFields } from "../console_api/presentation.js"; /** * Owner-decision HTTP use cases (GET/POST /api/owner-decisions). * @@ -66,6 +67,7 @@ export async function ownerDecisionQueueResponse(request, env, deps) { ? stored.intent : null; candidates.push({ + ...decisionFields({ candidate, intent }, "owner_decision"), candidate, candidate_evidence_sha256: candidateEvidenceSha256, decision_binding: { kind: "owner", subject_id: candidate.candidate_id, material_sha256: candidateEvidenceSha256 }, diff --git a/web/strategy-switch-console/application/console_api/performance.js b/web/strategy-switch-console/application/console_api/performance.js new file mode 100644 index 00000000..74fd55e2 --- /dev/null +++ b/web/strategy-switch-console/application/console_api/performance.js @@ -0,0 +1,475 @@ +import { + aggregateEquity, + alignReturns, + chainReturns, + cleanPoints, + dateMs, + sliceRange, +} from "../../performance_math.js"; +const DAY = 86400000; +const finite = (value) => + ["string", "number"].includes(typeof value) && + value !== "" && + Number.isFinite(Number(value)) + ? Number(value) + : null; +export const businessDate = (now) => + new Intl.DateTimeFormat("en-CA", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(new Date(now)); +export function maxDrawdown(index) { + const rows = cleanPoints(index); + if (rows.length < 2) + return { + percent: null, + peak_date: null, + trough_date: null, + unavailable_reason: "insufficient_observations", + }; + let peak = rows[0], + worst = 0, + peakDate = peak.date, + troughDate = peak.date; + for (const point of rows) { + if (!(peak.value > 0)) continue; + const loss = (1 - point.value / peak.value) * 100; + if (loss > worst) { + worst = loss; + peakDate = peak.date; + troughDate = point.date; + } + if (point.value > peak.value) peak = point; + } + return { + percent: worst, + peak_date: peakDate, + trough_date: troughDate, + unavailable_reason: null, + }; +} +export function dailyChanges(points, { crypto = false } = {}) { + const rows = cleanPoints(points), + byDate = new Map(rows.map((p) => [p.date, p])); + return rows.map((point) => { + let before = dateMs(point.date) - DAY; + // No market holiday source exists. Only weekends can be classified. + if (!crypto) + while ([0, 6].includes(new Date(before).getUTCDay())) before -= DAY; + const previous = byDate.get(new Date(before).toISOString().slice(0, 10)); + const interval = previous + ? rows.filter((p) => p.date > previous.date && p.date <= point.date) + : [point]; + const known = interval.every((p) => finite(p.externalFlow) !== null); + const flow = known + ? interval.reduce((sum, p) => sum + Number(p.externalFlow), 0) + : null; + const amount = previous + ? point.value - previous.value - (known ? flow : 0) + : null; + // P/L daily convention follows the requested prior-close plus investment denominator. + const denominator = previous ? previous.value + (known ? flow : 0) : null; + return { + date: point.date, + amount, + return_percent: + amount !== null && denominator > 0 && known + ? (amount / denominator) * 100 + : null, + value_kind: known ? "pnl" : "asset_change", + status: !previous + ? "no_data" + : known && denominator > 0 + ? "ok" + : "partial", + unavailable_reason: !previous + ? "previous_snapshot_missing" + : !known + ? "external_cashflow_required" + : denominator > 0 + ? null + : "invalid_return_period", + }; + }); +} +export function calendarCells(points, year, month, options = {}) { + const daily = new Map(dailyChanges(points, options).map((p) => [p.date, p])); + const monthCells = (m) => { + const start = `${year}-${String(m).padStart(2, "0")}-01`, + count = new Date(Date.UTC(year, m, 0)).getUTCDate(); + return Array.from({ length: count }, (_, i) => { + const date = `${start.slice(0, 8)}${String(i + 1).padStart(2, "0")}`; + const weekend = + !options.crypto && + [0, 6].includes(new Date(`${date}T00:00:00Z`).getUTCDay()); + return { + date, + ...(weekend + ? { + amount: null, + return_percent: null, + value_kind: "asset_change", + status: "unavailable", + unavailable_reason: "non_trading_weekend", + } + : daily.get(date) || { + amount: null, + return_percent: null, + value_kind: "asset_change", + status: "no_data", + unavailable_reason: "snapshot_missing", + }), + }; + }); + }; + if (month) return monthCells(month); + return Array.from({ length: 12 }, (_, i) => { + const cells = monthCells(i + 1).filter( + (c) => c.unavailable_reason !== "non_trading_weekend", + ); + const values = cells.filter((c) => c.amount !== null), + complete = values.length === cells.length; + const kind = + values.length && values.every((c) => c.value_kind === "pnl") + ? "pnl" + : "asset_change"; + const monthStart = `${year}-${String(i + 1).padStart(2, "0")}-01`; + const rows = cleanPoints(points); + const baseline = rows.filter((p) => p.date < monthStart).at(-1); + const monthlyPoints = rows.filter((p) => + p.date.startsWith(monthStart.slice(0, 7)), + ); + const twr = chainReturns( + baseline ? [baseline, ...monthlyPoints] : monthlyPoints, + ); + return { + month: `${year}-${String(i + 1).padStart(2, "0")}`, + amount: complete ? values.reduce((s, c) => s + c.amount, 0) : null, + observed_amount: values.length + ? values.reduce((s, c) => s + c.amount, 0) + : null, + return_percent: + complete && + kind === "pnl" && + baseline && + !twr.unknownFlow && + !twr.invalidPeriod + ? (twr.index.at(-1).value - 1) * 100 + : null, + value_kind: kind, + status: !values.length + ? "no_data" + : complete && kind === "pnl" && !twr.invalidPeriod + ? "ok" + : "partial", + unavailable_reason: !complete + ? "incomplete_month" + : kind !== "pnl" + ? "external_cashflow_required" + : twr.invalidPeriod + ? "invalid_return_period" + : null, + coverage: { + observed_days: values.length, + expected_weekdays: cells.length, + }, + }; + }); +} +export function holdingsRows(accounts) { + return accounts + .flatMap((a) => + (a.positions || []).map((p) => { + const cost = finite(p.avg_cost), + quantity = finite(p.quantity), + value = finite(p.market_value); + return { + account_alias: a.account_key, + platform: a.platform, + symbol: p.symbol, + quantity, + market_value: value, + currency: p.currency, + avg_cost: cost, + unrealized_pnl: + cost !== null && quantity !== null && value !== null + ? value - cost * quantity + : null, + unavailable_reason: + cost === null + ? "avg_cost_missing" + : quantity === null || value === null + ? "position_value_missing" + : null, + coverage: a.positions_scope || "unknown", + status: cost === null ? "partial" : "ok", + }; + }), + ) + .sort( + (a, b) => + a.currency.localeCompare(b.currency) || + (b.unrealized_pnl ?? -Infinity) - (a.unrealized_pnl ?? -Infinity), + ); +} +export function closedTradeStats(closedTrades) { + const rows = closedTrades.filter((t) => finite(t.realized_pnl) !== null); + return { + win_rate_percent: rows.length + ? (rows.filter((t) => Number(t.realized_pnl) > 0).length / rows.length) * + 100 + : null, + unavailable_reason: rows.length ? null : "no_closed_trades", + }; +} +export function performanceBlocks({ + accounts, + histories, + benchmarks = [], + range = "ALL", + today, + year, + month, + failed = [], +}) { + const currencies = [...new Set(histories.map((h) => h.currency))]; + const mixed = currencies.length > 1; + const combined = aggregateEquity( + histories.map((h) => ({ id: h.id, points: h.points })), + ); + const allPoints = mixed ? [] : combined.points; + const points = sliceRange(allPoints, range.toLowerCase(), today); + const asOf = points.at(-1)?.date || null; + const chained = chainReturns(points); + const unknownFlow = + points.length < 2 || + points.slice(1).some((p) => finite(p.externalFlow) === null); + const missing = + failed.length || combined.missingAccounts.length || combined.omittedDates; + const reason = mixed + ? "mixed_currency" + : !points.length + ? "snapshot_history_missing" + : chained.invalidPeriod + ? "invalid_return_period" + : chained.unknownFlow + ? "external_cashflow_required" + : points.length < 2 + ? "insufficient_observations" + : null; + const stale = asOf && dateMs(today) - dateMs(asOf) > 3 * DAY; + const status = mixed + ? "unavailable" + : !points.length + ? "no_data" + : stale + ? "stale" + : reason || missing + ? "partial" + : "ok"; + const coverage = { + account_aliases: accounts.map((a) => a.account_key), + currencies, + excluded_accounts: failed, + omitted_dates: combined.omittedDates, + cashflows: unknownFlow + ? "unknown" + : points.length > 1 + ? "complete" + : "unknown", + fx: mixed ? "not_applied" : "native_currency", + trading_dates: accounts.every((a) => a.platform === "binance") + ? "calendar_days" + : "stored_observation_date_weekends_excluded_holidays_unknown", + }; + const meta = { + status, + unavailable_reason: reason, + as_of: asOf, + coverage, + currency: mixed ? null : currencies[0] || null, + value_kind: unknownFlow ? "asset_change" : "pnl", + }; + const availableBenchmarks = benchmarks.map((b) => ({ + ...b, + points: sliceRange(b.points, range.toLowerCase(), today), + })); + const aligned = alignReturns(chained.index, availableBenchmarks); + const qualified = + points.length > 1 && !chained.unknownFlow && !chained.invalidPeriod; + const drawdown = qualified + ? maxDrawdown(chained.index) + : { + percent: null, + peak_date: null, + trough_date: null, + unavailable_reason: reason, + }; + const daily = dailyChanges(allPoints, { + crypto: accounts.every((a) => a.platform === "binance"), + }).filter((d) => d.date >= (points[0]?.date || today) && d.date <= today); + const validDays = daily.filter((d) => d.amount !== null); + const ranked = validDays + .filter((d) => d.return_percent !== null) + .sort((a, b) => b.return_percent - a.return_percent); + const first = points[0], + last = points.at(-1), + flowKnown = + points.length > 1 && + points.slice(1).every((p) => finite(p.externalFlow) !== null); + const netFlow = flowKnown + ? points.slice(1).reduce((s, p) => s + p.externalFlow, 0) + : null; + const amount = + points.length > 1 + ? last.value - first.value - (flowKnown ? netFlow : 0) + : null; + const primaryByDate = new Map(aligned.primary.map((p) => [p.date, p.value])); + const cells = calendarCells(allPoints, year, month, { + crypto: accounts.every((a) => a.platform === "binance"), + }); + const calendarHasValues = cells.some( + (c) => + c.amount !== null || + (c.observed_amount !== undefined && c.observed_amount !== null), + ); + const byCurrency = mixed + ? currencies.map((currency) => { + const group = aggregateEquity( + histories + .filter((h) => h.currency === currency) + .map((h) => ({ id: h.id, points: h.points })), + ); + const result = chainReturns( + sliceRange(group.points, range.toLowerCase(), today), + ); + const alignedGroup = alignReturns(result.index, availableBenchmarks); + return { + currency, + as_of: result.index.at(-1)?.date || null, + coverage: { omitted_dates: group.omittedDates }, + return_kind: result.unknownFlow ? "unadjusted_asset_ratio" : "twr", + status: !result.index.length + ? "no_data" + : result.unknownFlow + ? "partial" + : "ok", + unavailable_reason: result.unknownFlow + ? "external_cashflow_required" + : null, + aligned_start: alignedGroup.start || null, + points: alignedGroup.primary, + benchmarks: alignedGroup.benchmarks, + }; + }) + : []; + return { + calendar: { + ...meta, + status: mixed + ? "unavailable" + : !calendarHasValues + ? "no_data" + : meta.status === "no_data" + ? "partial" + : meta.status, + unavailable_reason: mixed + ? "mixed_currency" + : !calendarHasValues + ? "snapshot_history_missing" + : meta.unavailable_reason, + year, + month: month || null, + cells: cells.map((c) => ({ ...c, currency: meta.currency })), + as_of: allPoints.at(-1)?.date || null, + }, + summary: { + ...meta, + twr_return_percent: qualified + ? (chained.index.at(-1).value - 1) * 100 + : null, + amount, + simple_weighted_return_percent: + flowKnown && first.value + netFlow > 0 + ? (amount / (first.value + netFlow)) * 100 + : null, + max_drawdown: drawdown, + best_day: ranked[0] || null, + worst_day: ranked.at(-1) || null, + excess_returns: aligned.benchmarks.map((b) => { + const end = b.points.filter((p) => primaryByDate.has(p.date)).at(-1); + return { + benchmark: b.id, + start: aligned.start, + end: end?.date || null, + percentage_points: + end && qualified ? primaryByDate.get(end.date) - end.value : null, + unavailable_reason: qualified + ? end + ? null + : "no_common_date" + : reason, + }; + }), + }, + returns: { + ...meta, + aligned_start: aligned.start || null, + return_kind: qualified ? "twr" : "unadjusted_asset_ratio", + points: aligned.primary, + benchmarks: aligned.benchmarks, + per_currency: byCurrency, + no_common_date: aligned.noCommonDate, + benchmark_availability: availableBenchmarks.map((b) => ({ + id: b.id, + status: + b.points.length && !aligned.noCommonDate + ? dateMs(today) - dateMs(b.points.at(-1).date) > 3 * DAY + ? "stale" + : "ok" + : "unavailable", + unavailable_reason: !b.points.length + ? "benchmark_history_missing" + : aligned.noCommonDate + ? "no_common_date" + : null, + as_of: b.points.at(-1)?.date || null, + })), + }, + assets: { ...meta, points }, + holdings: { + status: accounts.some((a) => a.data_status === "stale") + ? "stale" + : accounts.some((a) => a.positions?.length) + ? "partial" + : "no_data", + unavailable_reason: accounts.some((a) => a.data_status === "stale") + ? "positions_stale" + : accounts.some((a) => a.positions?.length) + ? "positions_partial_coverage" + : "positions_not_connected", + as_of: + accounts + .map((a) => a.observed_finished_at) + .filter(Boolean) + .sort() + .at(0) || null, + coverage: accounts.map((a) => ({ + account_alias: a.account_key, + scope: a.positions_scope || "not_connected", + })), + label_key: "performance.current_holdings_unrealized", + value_kind: "pnl", + rows: holdingsRows(accounts), + }, + trades: { + status: "not_connected", + unavailable_reason: "fills_not_connected", + as_of: null, + coverage: "fills_not_connected", + value_kind: "pnl", + }, + }; +} diff --git a/web/strategy-switch-console/application/console_api/performance_routes.js b/web/strategy-switch-console/application/console_api/performance_routes.js new file mode 100644 index 00000000..91dbb38b --- /dev/null +++ b/web/strategy-switch-console/application/console_api/performance_routes.js @@ -0,0 +1,244 @@ +import { MARKET_BENCHMARK_SERIES_IDS } from "../../infrastructure/market_benchmark/market_benchmark.js"; +import { businessDate, performanceBlocks } from "./performance.js"; +const ENDPOINTS = { + calendar: "calendar", + summary: "summary", + returns: "returns", + assets: "assets", + holdings: "holdings", + trades: "trades", +}; +const number = (value) => + typeof value === "string" && + value.trim() !== "" && + Number.isFinite(Number(value)) + ? Number(value) + : null; +export async function performanceResponse(request, env, deps) { + const { json } = deps; + const session = await deps.readSession(request, env); + if (!session?.allowed) + return json({ ok: false, error: "login required" }, 401); + if (request.method !== "GET") + return json({ ok: false, error: "method_not_allowed" }, 405); + const url = new URL(request.url), + endpoint = url.pathname.split("/").at(-1); + if (!ENDPOINTS[endpoint]) return json({ ok: false, error: "not_found" }, 404); + const scope = url.searchParams.get("scope") || "all", + range = url.searchParams.get("range") || "ALL"; + const today = businessDate(Date.now()), + year = Number(url.searchParams.get("year") || today.slice(0, 4)); + const month = url.searchParams.has("month") + ? Number(url.searchParams.get("month")) + : null; + if ( + !["1M", "3M", "YTD", "1Y", "ALL"].includes(range) || + !Number.isInteger(year) || + year < 1970 || + year > 9999 || + (month !== null && (!Number.isInteger(month) || month < 1 || month > 12)) + ) + return json({ ok: false, error: "invalid_performance_query" }, 400); + try { + const config = await deps.accountOptions(env); + const options = Object.entries(config.options || {}).flatMap( + ([platform, rows]) => rows.map((a) => ({ ...a, platform })), + ); + const matches = options.filter((a) => + scope === "all" + ? a.broker_environment === "live" + : a.key === scope && + (!url.searchParams.has("platform") || + a.platform === url.searchParams.get("platform")), + ); + if (scope !== "all" && matches.length !== 1) + return json( + { ok: false, error: "account_alias_required_or_ambiguous" }, + 400, + ); + const makeRequest = (path, params = {}) => { + const u = new URL(path, request.url); + for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); + return new Request(u, { headers: request.headers }); + }; + const factsResponse = await deps.facts( + makeRequest("/api/account-facts"), + env, + ); + const factsBody = factsResponse.ok + ? await factsResponse.json() + : { accounts: [] }; + const accounts = [], + histories = [], + failed = [], + readFailures = []; + let truncated = false; + if (!factsResponse.ok) readFailures.push("account_facts_unreadable"); + for (const option of matches) { + if (option.platform === "binance") { + const response = await deps.wallet( + makeRequest("/api/binance-account-facts/history", { + account_key: option.key, + }), + env, + ); + if (!response.ok) { + readFailures.push(option.key); + failed.push(option.key); + accounts.push({ account_key: option.key, platform: option.platform }); + continue; + } + const body = await response.json(); + if (body.currency !== "USDT") { + failed.push(option.key); + continue; + } + accounts.push({ account_key: option.key, platform: option.platform }); + histories.push({ + id: `${option.platform}:${option.key}`, + currency: "USDT", + points: (body.points || []).flatMap((p) => + number(p.amount) === null + ? [] + : [ + { + date: p.observation_date, + value: number(p.amount), + externalFlow: null, + breakBefore: p.break_before, + }, + ], + ), + }); + continue; + } + const fact = (factsBody.accounts || []).find( + (a) => a.platform === option.platform && a.account_key === option.key, + ); + if ( + !fact || + fact.identity_mismatch || + fact.binding_status !== "bound" || + ["duplicate", "conflict"].includes(fact.aggregation_status) + ) { + failed.push(option.key); + continue; + } + accounts.push(fact); + const currencies = [ + ...new Set((fact.balances || []).map((b) => b.currency)), + ]; + if (!currencies.length) failed.push(option.key); + const accountHistories = []; + for (const currency of currencies) { + const response = await deps.history( + makeRequest("/api/account-facts/history", { + platform: option.platform, + account_key: option.key, + currency, + }), + env, + ); + if (!response.ok) { + readFailures.push(option.key); + failed.push(option.key); + continue; + } + const body = await response.json(); + truncated ||= body.series?.truncated === true; + if ( + body.identity_mismatch || + body.platform !== option.platform || + body.account_key !== option.key || + body.series?.currency !== currency + ) { + failed.push(option.key); + continue; + } + accountHistories.push({ + id: `${option.platform}:${option.key}:${currency}`, + currency, + points: (body.series.points || []).flatMap((p) => + p.currency !== currency || number(p.net_assets) === null + ? [] + : [ + { + date: p.observation_date, + value: number(p.net_assets), + externalFlow: null, + }, + ], + ), + }); + } + if ( + accountHistories.length === currencies.length && + accountHistories.every((h) => h.points.length) + ) + histories.push(...accountHistories); + else failed.push(option.key); + } + let benchmarks = [], + benchmarkFailed = false; + try { + const response = await deps.benchmarks( + makeRequest("/api/market-benchmark"), + env, + ); + if (!response.ok) throw new Error("unavailable"); + const body = await response.json(); + const ids = [ + ...new Set([ + ...MARKET_BENCHMARK_SERIES_IDS, + ...(body.points || []).map((p) => p.seriesId), + ]), + ]; + benchmarks = ids.map((id) => ({ + id, + points: body.points + .filter((p) => p.seriesId === id && number(p.close) !== null) + .map((p) => ({ date: p.observationDate, value: number(p.close) })), + })); + } catch { + benchmarkFailed = true; + } + const blocks = performanceBlocks({ + accounts, + histories, + benchmarks, + range, + today, + year, + month, + failed: [...new Set(failed)], + }); + const block = blocks[endpoint]; + if (["calendar", "summary", "returns", "assets"].includes(endpoint)) { + block.coverage.truncated = truncated; + block.coverage.read_failures = readFailures; + if (readFailures.length && block.status === "no_data") { + block.status = "unavailable"; + block.unavailable_reason = "stored_records_unreadable"; + } + } + if (benchmarkFailed && ["returns", "summary"].includes(endpoint)) { + block.benchmark_status = "unavailable"; + block.benchmark_unavailable_reason = "benchmark_history_unreadable"; + } + return json({ schema_version: "console_api.v1", scope, range, ...block }); + } catch { + return json( + { + schema_version: "console_api.v1", + scope, + range, + status: "unavailable", + unavailable_reason: "stored_records_unreadable", + as_of: null, + coverage: { account_aliases: [] }, + value_kind: "asset_change", + }, + 503, + ); + } +} diff --git a/web/strategy-switch-console/application/console_api/presentation.js b/web/strategy-switch-console/application/console_api/presentation.js new file mode 100644 index 00000000..dc6ff0b6 --- /dev/null +++ b/web/strategy-switch-console/application/console_api/presentation.js @@ -0,0 +1,206 @@ +/** Display-safe projections. Legacy evidence payloads are never display text. */ +export const SETTINGS_FIELDS = { + strategy_profile: "strategy", + dca_mode: "dca", + dca_base_investment_usd: "dca", + reserved_cash_floor: "cash_reserve", + reserved_cash_ratio: "cash_reserve", + income_layer_enabled: "income_layer", + option_overlay_enabled: "options_layer", +}; +const time = (value) => + typeof value === "string" && Number.isFinite(Date.parse(value)) + ? value + : null; +const scalar = (value) => + typeof value === "boolean" || + (typeof value === "number" && Number.isFinite(value)) || + (typeof value === "string" && + value.length <= 80 && + /^[a-zA-Z0-9_.:+/-]+$/.test(value)) + ? value + : null; +export function settingsDiff(settings) { + const overrides = settings.draft?.overrides || {}; + return Object.entries(SETTINGS_FIELDS).map(([field, section]) => { + const known = settings.effective?.[field]?.status === "known"; + const current = known ? settings.effective[field].value : null; + const overridden = Object.hasOwn(overrides, field); + return { + section, + field, + label_key: `settings.${field}`, + current, + draft: overridden ? overrides[field] : current, + affects_live: true, + current_status: known ? "known" : "unknown", + overridden, + changed: overridden && (!known || overrides[field] !== current), + }; + }); +} +export function decisionFields(entry, category, now = Date.now()) { + const data = entry.candidate || entry.recovery || entry; + const expires = time(data.expires_at || entry.expires_at); + const freshness = + entry.freshness?.status || + entry.freshness?.data_status || + data.freshness?.status || + "unknown"; + const decided = !!( + entry.intent || + entry.confirmation || + entry.rejection || + data.human_decision + ); + const expired = + (expires && Date.parse(expires) < now) || + ["stale", "expired"].includes(freshness); + const diff = []; + const row = (field, before, after, affects = true) => { + const old = scalar(before), + next = scalar(after); + if (old !== null || next !== null) + diff.push({ + field, + label_key: `decisions.${field.split(".")[0]}`, + before: old, + after: next, + affects_live: affects, + }); + }; + row( + "strategy", + data.current_strategy_profile, + data.strategy_profile || data.proposed_strategy_profile, + ); + row( + "version", + data.current_version, + data.proposed_version || data.version || data.strategy_revision, + ); + for (const key of Object.keys(data.proposed_params || {}).sort()) { + if ( + /^[a-z][a-z0-9_]{0,63}$/.test(key) && + !/hash|sha|audit|note|reason|job|task|commit|path|url|secret|token/i.test( + key, + ) + ) { + row( + `parameters.${key}`, + data.current_params?.[key], + data.proposed_params[key], + ); + } + } + row("shadow_passed", undefined, data.shadow_passed, false); + const comparison = data.research_summary?.comparison; + for (const group of ["baseline", "candidate"]) + for (const [key, value] of Object.entries(comparison?.[group] || {})) { + if ( + typeof value === "number" && + Number.isFinite(value) && + /^[a-z][a-z0-9_]{0,63}$/.test(key) + ) + row(`shadow.${group}.${key}`, undefined, value, false); + } + return { + category, + priority: + category === "reconciliation_recovery" + ? "high" + : category === "credential_maintenance" && + ["30", "7", "1", "expired"].includes(data.phase) + ? "medium" + : "normal", + created_at: time(data.created_at || data.first_observed_at), + expires_at: expires, + evidence_freshness: { + status: freshness, + as_of: time(data.last_observed_at || data.observed_at), + }, + status: decided ? "decided" : expired ? "expired" : "pending", + affects_live: + category === "reconciliation_recovery" || + (category === "owner_decision" && + data.recommendation?.code === "owner_live_decision") || + (category === "strategy_promotion" && + data.confirmation_execution_mode === "live"), + diff, + }; +} +export function decorateQueue(payload, field, category) { + return { + ...payload, + [field]: (payload[field] || []).map((item) => ({ + ...item, + ...decisionFields(item, category), + })), + }; +} +export function canonicalItem(entry, category) { + const data = entry.candidate || entry.recovery || entry; + const id = + category === "credential_maintenance" + ? `credential:${data.id}` + : `${category}:${data.candidate_id || data.recovery_id || data.ticket_id}`; + return { + id, + ...decisionFields(entry, category), + title_key: `decisions.${category}`, + account_alias: data.account_key || data.confirmation_account_key || null, + platform: scalar(data.platform || data.confirmation_target_platform), + decision_binding: entry.decision_binding || null, + }; +} +export async function actorAlias(actor) { + if (!actor) return null; + const hash = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(String(actor)), + ); + return `actor-${[...new Uint8Array(hash)] + .slice(0, 8) + .map((x) => x.toString(16).padStart(2, "0")) + .join("")}`; +} +export function pageQuery(url) { + const limit = Number(url.searchParams.get("limit") || 25); + const cursor = url.searchParams.get("cursor") || ""; + if ( + !Number.isSafeInteger(limit) || + limit < 1 || + limit > 100 || + (cursor && !/^\d+$/.test(cursor)) + ) + throw new Error("invalid_pagination"); + const offset = Number(cursor || 0); + if (!Number.isSafeInteger(offset) || offset < 0 || offset > 100000) + throw new Error("invalid_pagination"); + return { limit, offset }; +} +export async function decisionHistoryRows(rows) { + const categories = { + owner: "owner_decision", + promotion: "strategy_promotion", + recovery: "reconciliation_recovery", + }; + return Promise.all( + rows.map(async (row) => ({ + item_id: `${categories[row.kind]}:${row.subject_id}`, + category: categories[row.kind], + actor_alias: await actorAlias(row.actor), + time: row.decided_at, + action: [ + "accept", + "adopt_candidate", + "confirm", + "approve", + "approve_limited_live_canary", + ].includes(row.action) + ? "adopt_intent" + : "decline_intent", + evidence_sha256: row.material_key, + })), + ); +} diff --git a/web/strategy-switch-console/application/console_api/routes.js b/web/strategy-switch-console/application/console_api/routes.js new file mode 100644 index 00000000..cc984e6c --- /dev/null +++ b/web/strategy-switch-console/application/console_api/routes.js @@ -0,0 +1,252 @@ +import { + actorAlias, + canonicalItem, + decisionHistoryRows, + pageQuery, + settingsDiff, +} from "./presentation.js"; + +export async function consoleApiResponse(request, env, deps) { + const { json, readSession, command } = deps; + const url = new URL(request.url), + path = url.pathname; + const session = await readSession(request, env); + if (!session?.allowed) + return json({ ok: false, error: "login required" }, 401); + if (path === "/api/account-settings/draft") { + if (request.method !== "POST") + return json({ ok: false, error: "method_not_allowed" }, 405); + // The existing handler owns origin/admin/identity checks and the atomic save. + return deps.saveDraft(request, env); + } + if (request.method !== "GET") + return json({ ok: false, error: "method_not_allowed" }, 405); + let page; + try { + page = pageQuery(url); + } catch { + return json({ ok: false, error: "invalid_pagination" }, 400); + } + try { + if (path === "/api/owner-decisions/history") { + const result = await command(env, { + action: "console_decision_history", + actor: session.login, + ...page, + }); + return json({ + status: "ok", + items: await decisionHistoryRows(result.rows.slice(0, page.limit)), + next_cursor: + result.rows.length > page.limit + ? String(page.offset + page.limit) + : null, + coverage: "durable_human_decision_records", + }); + } + if (path === "/api/decisions-inbox") + return json(await inbox(request, env, deps)); + const config = await deps.accountOptions(env); + const accounts = Object.entries(config.options || {}).flatMap( + ([platform, rows]) => rows.map((row) => ({ ...row, platform })), + ); + if (path === "/api/accounts") { + const meta = await command(env, { + action: "console_account_metadata", + actor: session.login, + }); + const queue = await inbox(request, env, deps); + return json({ + status: queue.status === "read_failed" ? "partial" : "ok", + coverage: "configured_accounts_explicit_decision_bindings", + unassigned_decision_count: queue.items.filter( + (i) => !i.account_alias && i.status === "pending", + ).length, + accounts: accounts.map((a) => { + const row = meta.rows.find( + (r) => r.platform === a.platform && r.account_key === a.key, + ); + return { + account_alias: a.key, + platform: a.platform, + pending_draft_count: row?.pending_draft_count || 0, + pending_decision_count: + queue.status !== "ok" + ? null + : queue.items.filter( + (i) => + i.account_alias === a.key && + (!i.platform || i.platform === a.platform) && + i.status === "pending", + ).length, + last_change_at: row?.last_change_at || null, + }; + }), + }); + } + const alias = url.searchParams.get("account"), + platform = url.searchParams.get("platform"); + const key = url.searchParams.get("key"); + const matches = accounts.filter( + (a) => (!platform || a.platform === platform) && a.key === (alias || key), + ); + if (matches.length !== 1) + return json( + { ok: false, error: "account_alias_required_or_ambiguous" }, + 400, + ); + const account = matches[0]; + if (path === "/api/account-settings/diff") { + const readUrl = new URL("/api/account-settings", request.url); + readUrl.searchParams.set("platform", account.platform); + readUrl.searchParams.set("key", account.key); + const response = await deps.settings( + new Request(readUrl, { headers: request.headers }), + env, + ); + if (!response.ok) return response; + const settings = await response.json(); + return json({ + status: + settings.draft.status === "identity_conflict" ? "partial" : "ok", + account_alias: account.key, + platform: account.platform, + draft_revision: settings.draft.revision, + identity_status: settings.draft.status, + rows: settingsDiff(settings), + no_order: true, + execution_authority_granted: false, + }); + } + if (path === "/api/account-settings/history") { + const result = await command(env, { + action: "console_settings_history", + actor: session.login, + platform: account.platform, + key: account.key, + }); + const audit = await deps.audit(env); + const saves = audit.filter( + (row) => + row.action === "save_account_settings" && + row.platform === account.platform && + row.key === account.key && + Number.isInteger(row.draft_revision), + ); + const items = await Promise.all( + [ + ...saves.map((row) => ({ + event: "draft_saved", + time: row.ts, + actor: row.login, + draft_revision: row.draft_revision ?? null, + source: "bounded_audit_log", + })), + ...result.approvals.map((row) => ({ + event: "approved", + time: row.approved_at, + actor: row.approved_by, + draft_revision: row.draft_revision, + source: "profile_application", + })), + ].map(async (row) => { + const { actor, ...rest } = row; + return { ...rest, actor_alias: await actorAlias(actor) }; + }), + ); + items.sort((a, b) => b.time.localeCompare(a.time)); + return json({ + status: "partial", + account_alias: account.key, + platform: account.platform, + items: items.slice(page.offset, page.offset + page.limit), + next_cursor: + items.length > page.offset + page.limit + ? String(page.offset + page.limit) + : null, + coverage: "bounded_audit_log_and_profile_applications", + availability: { + draft_saved: { + status: "partial", + unavailable_reason: "bounded_audit_log", + }, + approved: { status: "ok", unavailable_reason: null }, + effect_verification: { + status: "unavailable", + unavailable_reason: "effect_verification_not_recorded", + }, + }, + }); + } + return json({ ok: false, error: "not_found" }, 404); + } catch { + return json( + { + status: "read_failed", + unavailable_reason: "stored_records_unreadable", + }, + 503, + ); + } +} +export async function inbox(request, env, deps) { + const definitions = [ + ["owner", "owner_decision", "candidates"], + ["promotion", "strategy_promotion", "tickets"], + ["recovery", "reconciliation_recovery", "recoveries"], + ["credential", "credential_maintenance", null], + ]; + const results = await Promise.all( + definitions.map(async ([source, category, field]) => { + try { + const response = await deps[source](request, env); + if (!response.ok) throw new Error("source_read_failed"); + const body = await response.json(); + const failed = (body.errors || []).some((e) => + /unavailable|invalid|unreadable|failed/.test(e), + ); + const unavailable = ["unavailable", "partial"].includes( + body.data_status, + ); + const rows = field + ? body[field] || [] + : body.requires_action + ? [body] + : []; + return { + source, + status: failed + ? "read_failed" + : unavailable + ? "unavailable" + : body.data_status === "stale" + ? "stale" + : "ok", + items: rows.map((row) => canonicalItem(row, category)), + }; + } catch { + return { source, status: "read_failed", items: [] }; + } + }), + ); + const unique = new Map( + results.flatMap((r) => r.items).map((item) => [item.id, item]), + ); + const priority = { high: 0, medium: 1, normal: 2 }; + return { + status: results.some((r) => r.status === "read_failed") + ? "read_failed" + : results.some((r) => r.status !== "ok") + ? "partial" + : "ok", + sources: results.map(({ source, status }) => ({ source, status })), + items: [...unique.values()].sort( + (a, b) => + priority[a.priority] - priority[b.priority] || + (a.created_at || "").localeCompare(b.created_at || ""), + ), + coverage: "existing_decision_sources", + no_order: true, + execution_authority_granted: false, + }; +} diff --git a/web/strategy-switch-console/contracts/console-api.schema.json b/web/strategy-switch-console/contracts/console-api.schema.json new file mode 100644 index 00000000..b6a47676 --- /dev/null +++ b/web/strategy-switch-console/contracts/console-api.schema.json @@ -0,0 +1,1574 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "inbox": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial", + "read_failed" + ] + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "status": { + "enum": [ + "ok", + "stale", + "unavailable", + "read_failed" + ] + } + }, + "required": [ + "source", + "status" + ] + } + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "title_key": { + "type": "string" + }, + "account_alias": { + "type": [ + "string", + "null" + ] + }, + "platform": { + "type": [ + "string", + "null" + ] + }, + "decision_binding": { + "type": [ + "object", + "null" + ] + }, + "category": { + "enum": [ + "reconciliation_recovery", + "strategy_promotion", + "owner_decision", + "credential_maintenance" + ] + }, + "priority": { + "enum": [ + "high", + "medium", + "normal" + ] + }, + "created_at": { + "type": [ + "string", + "null" + ] + }, + "expires_at": { + "type": [ + "string", + "null" + ] + }, + "evidence_freshness": { + "type": "object", + "properties": { + "status": { + "type": "string" + }, + "as_of": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "status", + "as_of" + ] + }, + "status": { + "enum": [ + "pending", + "decided", + "expired" + ] + }, + "affects_live": { + "type": "boolean" + }, + "diff": { + "type": "array", + "items": { + "type": "object", + "properties": { + "field": { + "type": "string" + }, + "label_key": { + "type": "string" + }, + "before": { + "type": [ + "string", + "number", + "boolean", + "null" + ] + }, + "after": { + "type": [ + "string", + "number", + "boolean", + "null" + ] + }, + "affects_live": { + "type": "boolean" + } + }, + "required": [ + "field", + "label_key", + "before", + "after", + "affects_live" + ] + } + } + }, + "required": [ + "id", + "title_key", + "account_alias", + "platform", + "decision_binding", + "category", + "priority", + "created_at", + "expires_at", + "evidence_freshness", + "status", + "affects_live", + "diff" + ] + } + }, + "coverage": { + "type": "string" + }, + "no_order": { + "const": true + }, + "execution_authority_granted": { + "const": false + } + }, + "required": [ + "status", + "sources", + "items", + "coverage", + "no_order", + "execution_authority_granted" + ] + }, + "decision_history": { + "type": "object", + "properties": { + "status": { + "const": "ok" + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "item_id": { + "type": "string" + }, + "category": { + "enum": [ + "reconciliation_recovery", + "strategy_promotion", + "owner_decision", + "credential_maintenance" + ] + }, + "actor_alias": { + "type": [ + "string", + "null" + ] + }, + "time": { + "type": "string" + }, + "action": { + "enum": [ + "adopt_intent", + "decline_intent" + ] + }, + "evidence_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "item_id", + "category", + "actor_alias", + "time", + "action", + "evidence_sha256" + ] + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + }, + "coverage": { + "type": "string" + } + }, + "required": [ + "status", + "items", + "next_cursor", + "coverage" + ] + }, + "settings_diff": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial" + ] + }, + "account_alias": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "draft_revision": { + "type": "integer" + }, + "identity_status": { + "type": "string" + }, + "rows": { + "type": "array", + "items": { + "type": "object", + "properties": { + "section": { + "enum": [ + "strategy", + "dca", + "cash_reserve", + "income_layer", + "options_layer" + ] + }, + "field": { + "type": "string" + }, + "label_key": { + "type": "string" + }, + "current": { + "type": [ + "string", + "number", + "boolean", + "null" + ] + }, + "draft": { + "type": [ + "string", + "number", + "boolean", + "null" + ] + }, + "affects_live": { + "type": "boolean" + }, + "current_status": { + "enum": [ + "known", + "unknown" + ] + }, + "overridden": { + "type": "boolean" + }, + "changed": { + "type": "boolean" + } + }, + "required": [ + "section", + "field", + "label_key", + "current", + "draft", + "affects_live", + "current_status", + "overridden", + "changed" + ] + } + }, + "no_order": { + "const": true + }, + "execution_authority_granted": { + "const": false + } + }, + "required": [ + "status", + "account_alias", + "platform", + "draft_revision", + "identity_status", + "rows", + "no_order", + "execution_authority_granted" + ] + }, + "settings_history": { + "type": "object", + "properties": { + "status": { + "const": "partial" + }, + "account_alias": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "event": { + "enum": [ + "draft_saved", + "approved" + ] + }, + "time": { + "type": "string" + }, + "actor_alias": { + "type": [ + "string", + "null" + ] + }, + "draft_revision": { + "type": [ + "number", + "null" + ] + }, + "source": { + "type": "string" + } + }, + "required": [ + "event", + "time", + "actor_alias", + "draft_revision", + "source" + ] + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + }, + "coverage": { + "type": "string" + }, + "availability": { + "type": "object", + "properties": { + "draft_saved": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "status", + "unavailable_reason" + ] + }, + "approved": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "status", + "unavailable_reason" + ] + }, + "effect_verification": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "status", + "unavailable_reason" + ] + } + }, + "required": [ + "draft_saved", + "approved", + "effect_verification" + ] + } + }, + "required": [ + "status", + "account_alias", + "platform", + "items", + "next_cursor", + "coverage", + "availability" + ] + }, + "accounts": { + "type": "object", + "properties": { + "status": { + "enum": [ + "ok", + "partial" + ] + }, + "coverage": { + "type": "string" + }, + "unassigned_decision_count": { + "type": "integer" + }, + "accounts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "account_alias": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "pending_draft_count": { + "type": "integer" + }, + "pending_decision_count": { + "type": [ + "integer", + "null" + ] + }, + "last_change_at": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "account_alias", + "platform", + "pending_draft_count", + "pending_decision_count", + "last_change_at" + ] + } + } + }, + "required": [ + "status", + "coverage", + "unassigned_decision_count", + "accounts" + ] + }, + "draft": { + "type": "object", + "properties": { + "ok": { + "const": true + }, + "platform": { + "type": "string" + }, + "key": { + "type": "string" + }, + "instance_revision": { + "type": "integer" + }, + "identity": { + "type": "object" + }, + "draft": { + "type": "object", + "properties": { + "status": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "identity": {}, + "current_identity": {}, + "overrides": { + "type": "object" + } + }, + "required": [ + "status", + "revision", + "identity", + "current_identity", + "overrides" + ] + }, + "effective": { + "type": "object" + }, + "adopted": { + "const": false + }, + "no_order": { + "const": true + }, + "execution_authority_granted": { + "const": false + } + }, + "required": [ + "ok", + "platform", + "key", + "instance_revision", + "identity", + "draft", + "effective", + "adopted", + "no_order", + "execution_authority_granted" + ] + }, + "read_failed": { + "type": "object", + "properties": { + "status": { + "const": "read_failed" + }, + "unavailable_reason": { + "const": "stored_records_unreadable" + } + }, + "required": [ + "status", + "unavailable_reason" + ] + }, + "conflict": { + "type": "object", + "properties": { + "ok": { + "const": false + }, + "error": { + "type": "string" + } + }, + "required": [ + "ok", + "error" + ] + }, + "calendar": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "year": { + "type": "integer" + }, + "month": { + "type": [ + "integer", + "null" + ] + }, + "cells": { + "type": "array", + "items": { + "type": "object", + "properties": { + "amount": { + "type": [ + "number", + "null" + ] + }, + "return_percent": { + "type": [ + "number", + "null" + ] + }, + "currency": { + "type": [ + "string", + "null" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "amount", + "return_percent", + "currency", + "status", + "value_kind", + "unavailable_reason" + ] + } + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind", + "year", + "month", + "cells" + ] + }, + "summary": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "twr_return_percent": { + "type": [ + "number", + "null" + ] + }, + "amount": { + "type": [ + "number", + "null" + ] + }, + "simple_weighted_return_percent": { + "type": [ + "number", + "null" + ] + }, + "max_drawdown": { + "type": "object", + "properties": { + "percent": { + "type": [ + "number", + "null" + ] + }, + "peak_date": { + "type": [ + "string", + "null" + ] + }, + "trough_date": { + "type": [ + "string", + "null" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "percent", + "peak_date", + "trough_date", + "unavailable_reason" + ] + }, + "best_day": { + "type": [ + "object", + "null" + ] + }, + "worst_day": { + "type": [ + "object", + "null" + ] + }, + "excess_returns": { + "type": "array", + "items": { + "type": "object", + "properties": { + "benchmark": { + "type": "string" + }, + "start": { + "type": "string" + }, + "end": { + "type": [ + "string", + "null" + ] + }, + "percentage_points": { + "type": [ + "number", + "null" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "benchmark", + "start", + "end", + "percentage_points", + "unavailable_reason" + ] + } + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind", + "twr_return_percent", + "amount", + "simple_weighted_return_percent", + "max_drawdown", + "best_day", + "worst_day", + "excess_returns" + ] + }, + "returns": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "aligned_start": { + "type": [ + "string", + "null" + ] + }, + "return_kind": { + "enum": [ + "twr", + "unadjusted_asset_ratio" + ] + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "date", + "value" + ] + } + }, + "benchmarks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "date", + "value" + ] + } + } + }, + "required": [ + "id", + "points" + ] + } + }, + "no_common_date": { + "type": "boolean" + }, + "benchmark_availability": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "status", + "unavailable_reason", + "as_of" + ] + } + }, + "per_currency": { + "type": "array", + "items": { + "type": "object", + "required": [ + "currency", + "status", + "return_kind", + "aligned_start", + "points", + "benchmarks", + "as_of", + "coverage" + ], + "properties": { + "currency": { + "type": "string" + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "return_kind": { + "enum": [ + "twr", + "unadjusted_asset_ratio" + ] + }, + "aligned_start": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": { + "type": "object" + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "date", + "value" + ] + } + }, + "benchmarks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "date", + "value" + ] + } + } + }, + "required": [ + "id", + "points" + ] + } + } + } + } + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind", + "aligned_start", + "return_kind", + "points", + "benchmarks", + "no_common_date", + "benchmark_availability", + "per_currency" + ] + }, + "assets": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "date", + "value" + ] + } + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind", + "points" + ] + }, + "holdings": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + }, + "label_key": { + "const": "performance.current_holdings_unrealized" + }, + "rows": { + "type": "array", + "items": { + "type": "object", + "properties": { + "account_alias": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "symbol": { + "type": "string" + }, + "quantity": { + "type": [ + "number", + "null" + ] + }, + "market_value": { + "type": [ + "number", + "null" + ] + }, + "currency": { + "type": "string" + }, + "avg_cost": { + "type": [ + "number", + "null" + ] + }, + "unrealized_pnl": { + "type": [ + "number", + "null" + ] + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "coverage": { + "type": "string" + }, + "status": { + "enum": [ + "ok", + "partial", + "stale", + "no_data", + "not_connected", + "unavailable" + ] + } + }, + "required": [ + "account_alias", + "platform", + "symbol", + "quantity", + "market_value", + "currency", + "avg_cost", + "unrealized_pnl", + "unavailable_reason", + "coverage", + "status" + ] + } + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind", + "label_key", + "rows" + ] + }, + "trades": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "const": "not_connected" + }, + "unavailable_reason": { + "const": "fills_not_connected" + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind" + ] + }, + "performance_unavailable": { + "type": "object", + "properties": { + "schema_version": { + "const": "console_api.v1" + }, + "scope": { + "type": "string" + }, + "range": { + "enum": [ + "1M", + "3M", + "YTD", + "1Y", + "ALL" + ] + }, + "status": { + "const": "unavailable" + }, + "unavailable_reason": { + "type": [ + "string", + "null" + ] + }, + "as_of": { + "type": [ + "string", + "null" + ] + }, + "coverage": {}, + "value_kind": { + "enum": [ + "pnl", + "asset_change" + ] + } + }, + "required": [ + "schema_version", + "scope", + "range", + "status", + "unavailable_reason", + "as_of", + "coverage", + "value_kind" + ] + } + } +} diff --git a/web/strategy-switch-console/frontend/scripts/console-api-synthetic.mjs b/web/strategy-switch-console/frontend/scripts/console-api-synthetic.mjs new file mode 100644 index 00000000..89d8f864 --- /dev/null +++ b/web/strategy-switch-console/frontend/scripts/console-api-synthetic.mjs @@ -0,0 +1,294 @@ +// Fictional local-only API examples. No Worker, credentials or provider access. +import { performanceBlocks } from "../../application/console_api/performance.js"; +import { + canonicalItem, + settingsDiff, +} from "../../application/console_api/presentation.js"; +export function consoleApiFixture( + path, + query, + scenario = "api-ready", + method = "GET", + now = Date.now(), +) { + const paths = [ + "/api/decisions-inbox", + "/api/owner-decisions/history", + "/api/accounts", + "/api/account-settings/diff", + "/api/account-settings/history", + "/api/account-settings/draft", + ]; + if (!paths.includes(path) && !path.startsWith("/api/performance/")) + return undefined; + if ( + method !== "GET" && + !(path === "/api/account-settings/draft" && method === "POST") + ) + return { status: 405, body: { ok: false, error: "synthetic_read_only" } }; + if (scenario === "api-read-failed") + return { + status: 503, + body: path.startsWith("/api/performance/") + ? { + schema_version: "console_api.v1", + scope: "all", + range: "ALL", + status: "unavailable", + unavailable_reason: "stored_records_unreadable", + as_of: null, + coverage: {}, + value_kind: "asset_change", + } + : { + status: "read_failed", + unavailable_reason: "stored_records_unreadable", + }, + }; + const empty = scenario === "api-empty", + date = new Date(now - (scenario === "api-stale" ? 10 : 0) * 86400000) + .toISOString() + .slice(0, 10); + const at = `${date}T12:00:00Z`; + const item = canonicalItem( + { + ticket_id: "synthetic-proposal", + strategy_profile: "synthetic-growth", + created_at: at, + proposed_params: { rebalance_days: 20 }, + shadow_passed: true, + }, + "strategy_promotion", + ); + const recovery = canonicalItem( + { + recovery: { + recovery_id: "synthetic-recovery", + platform: "longbridge", + strategy_profile: "synthetic-balanced", + first_observed_at: at, + last_observed_at: at, + }, + freshness: { data_status: scenario === "api-stale" ? "stale" : "ready" }, + }, + "reconciliation_recovery", + ); + const credential = canonicalItem( + { + id: "synthetic-credential", + phase: "7", + expires_at: new Date(now + 7 * 86400000).toISOString(), + }, + "credential_maintenance", + ); + const settings = { + ok: true, + platform: "longbridge", + key: "synthetic-alpha", + instance_revision: 1, + identity: { platform: "longbridge", key: "synthetic-alpha" }, + draft: { + status: "current", + revision: 2, + identity: {}, + current_identity: {}, + overrides: { + strategy_profile: "synthetic-growth", + reserved_cash_ratio: "0.15", + income_layer_enabled: false, + }, + }, + effective: { + strategy_profile: { status: "known", value: "synthetic-balanced" }, + reserved_cash_ratio: { status: "known", value: "0.1" }, + }, + adopted: false, + no_order: true, + execution_authority_granted: false, + }; + const status = scenario === "api-partial" ? "partial" : "ok"; + if (path === "/api/decisions-inbox") + return { + body: { + status, + sources: [ + { source: "owner", status: "ok" }, + { source: "promotion", status: "ok" }, + { + source: "recovery", + status: scenario === "api-stale" ? "stale" : "ok", + }, + { source: "credential", status: "ok" }, + ], + items: empty ? [] : [recovery, item, credential], + coverage: "synthetic", + no_order: true, + execution_authority_granted: false, + }, + }; + if (path === "/api/owner-decisions/history") + return { + body: { + status: "ok", + items: empty + ? [] + : [ + { + item_id: item.id, + category: item.category, + actor_alias: "actor-synthetic", + time: at, + action: "decline_intent", + evidence_sha256: "a".repeat(64), + }, + ], + next_cursor: null, + coverage: "synthetic", + }, + }; + if (path === "/api/accounts") + return { + body: { + status, + coverage: "synthetic", + unassigned_decision_count: 1, + accounts: empty + ? [] + : [ + { + account_alias: "synthetic-alpha", + platform: "longbridge", + pending_draft_count: 3, + pending_decision_count: 1, + last_change_at: at, + }, + ], + }, + }; + if (path === "/api/account-settings/diff") + return { + body: { + status: "ok", + account_alias: settings.key, + platform: settings.platform, + draft_revision: 2, + identity_status: "current", + rows: empty ? [] : settingsDiff(settings), + no_order: true, + execution_authority_granted: false, + }, + }; + if (path === "/api/account-settings/draft") + return scenario === "api-conflict" + ? { + status: 409, + body: { + ok: false, + error: "account_settings_draft_revision_conflict", + }, + } + : { body: settings }; + if (path === "/api/account-settings/history") + return { + body: { + status: "partial", + account_alias: settings.key, + platform: settings.platform, + items: empty + ? [] + : [ + { + event: "draft_saved", + time: at, + actor_alias: "actor-synthetic", + draft_revision: 2, + source: "synthetic", + }, + { + event: "approved", + time: at, + actor_alias: "actor-synthetic", + draft_revision: 1, + source: "synthetic", + }, + ], + next_cursor: null, + coverage: "synthetic", + availability: { + draft_saved: { + status: "partial", + unavailable_reason: "bounded_audit_log", + }, + approved: { status: "ok", unavailable_reason: null }, + effect_verification: { + status: "unavailable", + unavailable_reason: "effect_verification_not_recorded", + }, + }, + }, + }; + const dates = Array.from({ length: 10 }, (_, i) => + new Date(Date.parse(`${date}T00:00:00Z`) - (9 - i) * 86400000) + .toISOString() + .slice(0, 10), + ); + const points = empty + ? [] + : dates + .filter((d) => ![0, 6].includes(new Date(`${d}T00:00:00Z`).getUTCDay())) + .map((d, i) => ({ + date: d, + value: 1000 + i * 10 + (i >= 3 ? 500 : 0), + externalFlow: scenario === "api-partial" ? null : i === 3 ? 500 : 0, + })); + const accounts = [ + { + account_key: "synthetic-alpha", + platform: "longbridge", + observed_finished_at: at, + positions_scope: "stocks_only", + positions: empty + ? [] + : [ + { + symbol: "SYNTH_A", + currency: "USD", + quantity: "5", + market_value: "550", + avg_cost: "100", + }, + { + symbol: "SYNTH_B", + currency: "USD", + quantity: "2", + market_value: "200", + }, + ], + }, + ]; + const blocks = performanceBlocks({ + accounts, + histories: [{ id: "synthetic-alpha", currency: "USD", points }], + benchmarks: [ + { + id: "synthetic-index", + points: points.map((p, i) => ({ date: p.date, value: 100 + i })), + }, + ], + range: query.get("range") || "ALL", + today: new Date(now).toISOString().slice(0, 10), + year: Number(query.get("year") || date.slice(0, 4)), + month: query.has("month") ? Number(query.get("month")) : null, + }); + const block = blocks[path.split("/").at(-1)]; + return block + ? { + body: { + schema_version: "console_api.v1", + scope: query.get("scope") || "all", + range: query.get("range") || "ALL", + ...block, + }, + } + : { status: 404, body: { ok: false, error: "not_found" } }; +} diff --git a/web/strategy-switch-console/frontend/scripts/dev-synthetic.mjs b/web/strategy-switch-console/frontend/scripts/dev-synthetic.mjs index c033e625..9a6dde73 100644 --- a/web/strategy-switch-console/frontend/scripts/dev-synthetic.mjs +++ b/web/strategy-switch-console/frontend/scripts/dev-synthetic.mjs @@ -1,3 +1,4 @@ +import { consoleApiFixture } from './console-api-synthetic.mjs'; import { createServer } from 'vite'; import { readFile } from 'node:fs/promises'; import { performanceFixture } from './performance-synthetic.mjs'; @@ -23,6 +24,8 @@ const vite = await createServer({ root, envDir: false, server: { host: '127.0.0. requests.push({ path: url.pathname, method: req.method, scenario }); res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'no-store'); + const apiFixture = consoleApiFixture(url.pathname, url.searchParams, scenario, req.method); + if (apiFixture !== undefined) { res.statusCode = apiFixture.status || 200; res.end(JSON.stringify(apiFixture.body)); return; } if (req.method !== 'GET') { res.statusCode = 405; res.end(JSON.stringify({ error: 'synthetic_audit_read_only' })); return; } const performance = performanceFixture(url.pathname, url.searchParams, scenario); if (performance !== undefined) { diff --git a/web/strategy-switch-console/frontend/src/api/contracts.ts b/web/strategy-switch-console/frontend/src/api/contracts.ts new file mode 100644 index 00000000..da136646 --- /dev/null +++ b/web/strategy-switch-console/frontend/src/api/contracts.ts @@ -0,0 +1,310 @@ +/** Public display contracts. Opaque bindings are passed back unchanged, never rendered. */ +export type Status = + "ok" | "partial" | "stale" | "no_data" | "not_connected" | "unavailable"; +export type Reason = + | "external_cashflow_required" + | "fills_not_connected" + | "avg_cost_missing" + | "mixed_currency" + | "snapshot_history_missing" + | "snapshot_missing" + | "previous_snapshot_missing" + | "non_trading_weekend" + | "incomplete_month" + | "insufficient_observations" + | "invalid_return_period" + | "positions_partial_coverage" + | "positions_not_connected" + | "positions_stale" + | "benchmark_history_unreadable" + | "position_value_missing" + | "no_common_date" + | "benchmark_history_missing" + | "stored_records_unreadable" + | "effect_verification_not_recorded" + | "bounded_audit_log" + | "no_closed_trades"; +export type Scalar = string | number | boolean | null; +export type Category = + | "reconciliation_recovery" + | "strategy_promotion" + | "owner_decision" + | "credential_maintenance"; +export interface DecisionDiff { + field: string; + label_key: string; + before: Scalar; + after: Scalar; + affects_live: boolean; +} +export interface DecisionFields { + category: Category; + priority: "high" | "medium" | "normal"; + created_at: string | null; + expires_at: string | null; + evidence_freshness: { status: string; as_of: string | null }; + status: "pending" | "decided" | "expired"; + affects_live: boolean; + diff: DecisionDiff[]; +} +export interface InboxItem extends DecisionFields { + id: string; + title_key: string; + account_alias: string | null; + platform: string | null; + decision_binding: { + kind: string; + subject_id: string; + material_sha256: string; + review_binding?: unknown; + } | null; +} +export interface InboxResponse { + status: "ok" | "partial" | "read_failed"; + sources: { + source: string; + status: "ok" | "stale" | "unavailable" | "read_failed"; + }[]; + items: InboxItem[]; + coverage: string; + no_order: true; + execution_authority_granted: false; +} +export interface DecisionHistoryItem { + item_id: string; + category: Category; + actor_alias: string | null; + time: string; + action: "adopt_intent" | "decline_intent"; + evidence_sha256: string; +} +export interface DecisionHistoryResponse { + status: "ok"; + items: DecisionHistoryItem[]; + next_cursor: string | null; + coverage: string; +} +export interface ReadFailed { + status: "read_failed"; + unavailable_reason: "stored_records_unreadable"; +} +export type SettingsSection = + "strategy" | "dca" | "cash_reserve" | "income_layer" | "options_layer"; +export type DraftField = + | "strategy_profile" + | "dca_mode" + | "dca_base_investment_usd" + | "reserved_cash_floor" + | "reserved_cash_ratio" + | "income_layer_enabled" + | "option_overlay_enabled"; +export interface SettingsDiffRow { + section: SettingsSection; + field: DraftField; + label_key: string; + current: Scalar; + draft: Scalar; + affects_live: boolean; + current_status: "known" | "unknown"; + overridden: boolean; + changed: boolean; +} +export interface SettingsDiffResponse { + status: "ok" | "partial"; + account_alias: string; + platform: string; + draft_revision: number; + identity_status: string; + rows: SettingsDiffRow[]; + no_order: true; + execution_authority_granted: false; +} +export interface CombinedDraftRequest { + platform: string; + key: string; + identity: Record; + expected_draft_revision: number; + acknowledge_identity_conflict?: boolean; + overrides: Partial>; +} +/** Same response as the legacy POST /api/account-settings. Retain the whole payload for conflict checks. */ +export interface CombinedDraftResponse { + ok: true; + platform: string; + key: string; + instance_revision: number; + identity: Record; + draft: { + status: string; + revision: number; + identity: unknown; + current_identity: unknown; + overrides: Partial>; + }; + effective: Record; + adopted: false; + no_order: true; + execution_authority_granted: false; + [key: string]: unknown; +} +export interface SettingsHistoryResponse { + status: "partial"; + account_alias: string; + platform: string; + items: { + event: "draft_saved" | "approved"; + time: string; + actor_alias: string | null; + draft_revision: number | null; + source: string; + }[]; + next_cursor: string | null; + coverage: string; + availability: Record< + "draft_saved" | "approved" | "effect_verification", + { status: Status; unavailable_reason: Reason | null } + >; +} +export interface AccountsResponse { + status: "ok" | "partial"; + coverage: string; + unassigned_decision_count: number; + accounts: { + account_alias: string; + platform: string; + pending_draft_count: number; + pending_decision_count: number | null; + last_change_at: string | null; + }[]; +} +export type Range = "1M" | "3M" | "YTD" | "1Y" | "ALL"; +export interface PerformanceCoverage { + account_aliases: string[]; + currencies?: string[]; + excluded_accounts?: string[]; + omitted_dates?: number; + cashflows?: "unknown" | "complete"; + fx?: "not_applied" | "native_currency"; + trading_dates?: string; + truncated?: boolean; + read_failures?: string[]; +} +export interface PerformanceMeta { + schema_version: "console_api.v1"; + scope: string; + range: Range; + status: Status; + unavailable_reason: Reason | null; + as_of: string | null; + value_kind: "pnl" | "asset_change"; + coverage: + | PerformanceCoverage + | { account_alias: string; scope: string }[] + | "fills_not_connected"; + currency?: string | null; +} +export interface Point { + date: string; + value: number; + breakBefore?: boolean; +} +export interface CalendarCell { + date?: string; + month?: string; + amount: number | null; + return_percent: number | null; + currency: string | null; + status: Status; + value_kind: "pnl" | "asset_change"; + unavailable_reason: Reason | null; + observed_amount?: number | null; + coverage?: { observed_days: number; expected_weekdays: number }; +} +export interface CalendarResponse extends PerformanceMeta { + year: number; + month: number | null; + cells: CalendarCell[]; +} +export interface DailyChange { + date: string; + amount: number | null; + return_percent: number | null; + value_kind: "pnl" | "asset_change"; + status: Status; + unavailable_reason: Reason | null; +} +export interface SummaryResponse extends PerformanceMeta { + twr_return_percent: number | null; + amount: number | null; + simple_weighted_return_percent: number | null; + max_drawdown: { + percent: number | null; + peak_date: string | null; + trough_date: string | null; + unavailable_reason: Reason | null; + }; + best_day: DailyChange | null; + worst_day: DailyChange | null; + excess_returns: { + benchmark: string; + start: string; + end: string | null; + percentage_points: number | null; + unavailable_reason: Reason | null; + }[]; +} +export interface ReturnsResponse extends PerformanceMeta { + aligned_start: string | null; + return_kind: "twr" | "unadjusted_asset_ratio"; + points: Point[]; + benchmarks: { id: string; points: Point[] }[]; + no_common_date: boolean; + per_currency: { + currency: string; + return_kind: string; + status: Status; + unavailable_reason: Reason | null; + aligned_start: string | null; + points: Point[]; + benchmarks: { id: string; points: Point[] }[]; + }[]; + benchmark_availability: { + id: string; + status: Status; + unavailable_reason: Reason | null; + as_of: string | null; + }[]; +} +export interface AssetsResponse extends PerformanceMeta { + points: Point[]; +} +export interface HoldingsResponse extends PerformanceMeta { + label_key: "performance.current_holdings_unrealized"; + rows: { + account_alias: string; + platform: string; + symbol: string; + quantity: number | null; + market_value: number | null; + currency: string; + avg_cost: number | null; + unrealized_pnl: number | null; + unavailable_reason: Reason | null; + coverage: string; + status: Status; + }[]; +} +export interface TradeStatsResponse extends PerformanceMeta { + status: "not_connected"; + unavailable_reason: "fills_not_connected"; +} +export interface ApiError { + ok: false; + error: string; + no_order?: true; + execution_authority_granted?: false; +} + +export interface PerformanceUnavailable extends PerformanceMeta { + status: "unavailable"; +} diff --git a/web/strategy-switch-console/frontend/src/performanceMath.ts b/web/strategy-switch-console/frontend/src/performanceMath.ts index d00f90a3..91ce88d0 100644 --- a/web/strategy-switch-console/frontend/src/performanceMath.ts +++ b/web/strategy-switch-console/frontend/src/performanceMath.ts @@ -1,124 +1,2 @@ -/** Pure chart calculations. See docs/console-performance-charts.md. */ -export type PerformanceRange = "1m" | "3m" | "ytd" | "1y" | "all"; -export const PERFORMANCE_RANGES = ["1m", "3m", "ytd", "1y", "all"] as const; -export type ValuePoint = { date: string; value: number; breakBefore?: boolean }; -// Signed external flow at the END of (previous observation, this observation]. -// null/undefined means unknown; zero is accepted only as explicit evidence. -export type EquityPoint = ValuePoint & { externalFlow?: number | null }; -export type AccountEquity = { id: string; points: EquityPoint[] }; -const DAY = 86_400_000; - -export function dateMs(date: string): number { - if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return NaN; - const ms = Date.parse(`${date}T00:00:00Z`); - return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === date ? ms : NaN; -} - -export function rangeStart(range: PerformanceRange, today: string): string { - const ms = dateMs(today); - if (!Number.isFinite(ms) || range === "all") return "0000-01-01"; - if (range === "ytd") return `${today.slice(0, 4)}-01-01`; - const date = new Date(ms); - const day = date.getUTCDate(); - date.setUTCDate(1); - date.setUTCMonth(date.getUTCMonth() - (range === "1m" ? 1 : range === "3m" ? 3 : 12)); - const last = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate(); - date.setUTCDate(Math.min(day, last)); - return date.toISOString().slice(0, 10); -} - -/** Conflicting duplicate dates are omitted, never arbitrarily picked. */ -export function cleanPoints(points: readonly T[]): T[] { - const dates = new Map(); - for (const point of points) { - if (!Number.isFinite(dateMs(point.date)) || !Number.isFinite(point.value)) continue; - const prior = dates.get(point.date); - if (prior === undefined) dates.set(point.date, point); - else if (prior === null || JSON.stringify(prior) !== JSON.stringify(point)) dates.set(point.date, null); - } - return [...dates.values()].filter((p): p is T => p !== null).sort((a, b) => a.date.localeCompare(b.date)); -} - -export function sliceRange(points: readonly T[], range: PerformanceRange, today: string): T[] { - const start = rangeStart(range, today); - return cleanPoints(points).filter(p => p.date >= start && p.date <= today); -} - -export function hasGap(previous: ValuePoint, point: ValuePoint): boolean { - return point.breakBefore === true || dateMs(point.date) - dateMs(previous.date) > DAY; -} - -/** Rebase a positive index/price to percentage return; never fill missing dates. */ -export function rebase(points: readonly ValuePoint[], start?: string): ValuePoint[] { - const rows = cleanPoints(points).filter(p => !start || p.date >= start); - const base = rows[0]?.value; - if (!(base > 0)) return []; - return rows.map((p, i) => ({ ...p, value: i === 0 ? 0 : (p.value / base - 1) * 100, - breakBefore: i > 0 && hasGap(rows[i - 1], p) })); -} - -/** End-flow TWR: 1+r = (V_end - F_end) / V_previous. */ -export function chainReturns(points: readonly EquityPoint[]): { - index: ValuePoint[]; unknownFlow: boolean; invalidPeriod: boolean; -} { - const rows = cleanPoints(points); - const index: ValuePoint[] = []; - let growth = 1; - let unknownFlow = false; - let invalidPeriod = false; - if (rows.length && !(rows[0].value > 0)) return { index, unknownFlow, invalidPeriod: true }; - for (let i = 0; i < rows.length; i++) { - const point = rows[i]; - if (i > 0) { - const previous = rows[i - 1]; - const known = typeof point.externalFlow === "number" && Number.isFinite(point.externalFlow); - unknownFlow ||= !known; - // Unknown-flow series is explicitly an unadjusted estimate in the UI. - const end = known ? point.value - point.externalFlow! : point.value; - if (!(previous.value > 0) || end < 0) { invalidPeriod = true; break; } - growth *= end / previous.value; - if (!Number.isFinite(growth)) { invalidPeriod = true; break; } - } - index.push({ date: point.date, value: growth, breakBefore: i > 0 && hasGap(rows[i - 1], point) }); - } - return { index, unknownFlow, invalidPeriod }; -} - -/** Fixed cohort: no changing membership, carry-forward, or missing-account zeros. */ -export function aggregateEquity(accounts: readonly AccountEquity[]): { - points: EquityPoint[]; missingAccounts: string[]; omittedDates: number; -} { - const normalized = accounts.map(a => ({ id: a.id, points: cleanPoints(a.points) })); - const missingAccounts = normalized.filter(a => !a.points.length).map(a => a.id); - const members = normalized.filter(a => a.points.length); - const maps = members.map(a => new Map(a.points.map((p, i) => [p.date, { p, i }]))); - const dates = [...new Set(members.flatMap(a => a.points.map(p => p.date)))].sort(); - const points: EquityPoint[] = []; - let omittedDates = 0; - for (const date of dates) { - const values = maps.map(m => m.get(date)); - if (values.some(v => !v)) { omittedDates++; continue; } - const previous = points.at(-1); - const flowKnown = values.every((v, i) => v && Number.isFinite(v.p.externalFlow) - && (!previous || members[i].points[v.i - 1]?.date === previous.date)); - points.push({ date, value: values.reduce((sum, v) => sum + v!.p.value, 0), - externalFlow: flowKnown ? values.reduce((sum, v) => sum + v!.p.externalFlow!, 0) : null, - breakBefore: !!previous && (dateMs(date) - dateMs(previous.date) > DAY || values.some(v => v!.p.breakBefore)) }); - } - return { points, missingAccounts, omittedDates }; -} - -/** Baseline never changes when the user hides a legend entry. */ -export function alignReturns(primary: readonly ValuePoint[], comparisons: readonly { id: string; points: ValuePoint[] }[]) { - const own = cleanPoints(primary); - const available = comparisons.map(s => ({ ...s, points: cleanPoints(s.points) })).filter(s => s.points.length); - const dates = available.map(s => new Set(s.points.map(p => p.date))); - const common = own.find(p => p.value > 0 && dates.every(d => d.has(p.date)))?.date; - const start = common || own[0]?.date; - return { - start, - primary: rebase(own, start), - benchmarks: common ? available.map(s => ({ ...s, points: rebase(s.points, common) })) : [], - noCommonDate: available.length > 0 && !common, - }; -} +/** Shared Worker/frontend calculations. See docs/console-performance-charts.md. */ +export * from '../../performance_math.js'; diff --git a/web/strategy-switch-console/performance_math.d.ts b/web/strategy-switch-console/performance_math.d.ts new file mode 100644 index 00000000..224c2e64 --- /dev/null +++ b/web/strategy-switch-console/performance_math.d.ts @@ -0,0 +1,48 @@ +/** Pure chart calculations. See docs/console-performance-charts.md. */ +export type PerformanceRange = "1m" | "3m" | "ytd" | "1y" | "all"; +export declare const PERFORMANCE_RANGES: readonly ["1m", "3m", "ytd", "1y", "all"]; +export type ValuePoint = { + date: string; + value: number; + breakBefore?: boolean; +}; +export type EquityPoint = ValuePoint & { + externalFlow?: number | null; +}; +export type AccountEquity = { + id: string; + points: EquityPoint[]; +}; +export declare function dateMs(date: string): number; +export declare function rangeStart(range: PerformanceRange, today: string): string; +/** Conflicting duplicate dates are omitted, never arbitrarily picked. */ +export declare function cleanPoints(points: readonly T[]): T[]; +export declare function sliceRange(points: readonly T[], range: PerformanceRange, today: string): T[]; +export declare function hasGap(previous: ValuePoint, point: ValuePoint): boolean; +/** Rebase a positive index/price to percentage return; never fill missing dates. */ +export declare function rebase(points: readonly ValuePoint[], start?: string): ValuePoint[]; +/** End-flow TWR: 1+r = (V_end - F_end) / V_previous. */ +export declare function chainReturns(points: readonly EquityPoint[]): { + index: ValuePoint[]; + unknownFlow: boolean; + invalidPeriod: boolean; +}; +/** Fixed cohort: no changing membership, carry-forward, or missing-account zeros. */ +export declare function aggregateEquity(accounts: readonly AccountEquity[]): { + points: EquityPoint[]; + missingAccounts: string[]; + omittedDates: number; +}; +/** Baseline never changes when the user hides a legend entry. */ +export declare function alignReturns(primary: readonly ValuePoint[], comparisons: readonly { + id: string; + points: ValuePoint[]; +}[]): { + start: string; + primary: ValuePoint[]; + benchmarks: { + points: ValuePoint[]; + id: string; + }[]; + noCommonDate: boolean; +}; diff --git a/web/strategy-switch-console/performance_math.js b/web/strategy-switch-console/performance_math.js new file mode 100644 index 00000000..c9c9e4fe --- /dev/null +++ b/web/strategy-switch-console/performance_math.js @@ -0,0 +1,121 @@ +export const PERFORMANCE_RANGES = ["1m", "3m", "ytd", "1y", "all"]; +const DAY = 86_400_000; +export function dateMs(date) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) + return NaN; + const ms = Date.parse(`${date}T00:00:00Z`); + return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === date ? ms : NaN; +} +export function rangeStart(range, today) { + const ms = dateMs(today); + if (!Number.isFinite(ms) || range === "all") + return "0000-01-01"; + if (range === "ytd") + return `${today.slice(0, 4)}-01-01`; + const date = new Date(ms); + const day = date.getUTCDate(); + date.setUTCDate(1); + date.setUTCMonth(date.getUTCMonth() - (range === "1m" ? 1 : range === "3m" ? 3 : 12)); + const last = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate(); + date.setUTCDate(Math.min(day, last)); + return date.toISOString().slice(0, 10); +} +/** Conflicting duplicate dates are omitted, never arbitrarily picked. */ +export function cleanPoints(points) { + const dates = new Map(); + for (const point of points) { + if (!Number.isFinite(dateMs(point.date)) || !Number.isFinite(point.value)) + continue; + const prior = dates.get(point.date); + if (prior === undefined) + dates.set(point.date, point); + else if (prior === null || JSON.stringify(prior) !== JSON.stringify(point)) + dates.set(point.date, null); + } + return [...dates.values()].filter((p) => p !== null).sort((a, b) => a.date.localeCompare(b.date)); +} +export function sliceRange(points, range, today) { + const start = rangeStart(range, today); + return cleanPoints(points).filter(p => p.date >= start && p.date <= today); +} +export function hasGap(previous, point) { + return point.breakBefore === true || dateMs(point.date) - dateMs(previous.date) > DAY; +} +/** Rebase a positive index/price to percentage return; never fill missing dates. */ +export function rebase(points, start) { + const rows = cleanPoints(points).filter(p => !start || p.date >= start); + const base = rows[0]?.value; + if (!(base > 0)) + return []; + return rows.map((p, i) => ({ ...p, value: i === 0 ? 0 : (p.value / base - 1) * 100, + breakBefore: i > 0 && hasGap(rows[i - 1], p) })); +} +/** End-flow TWR: 1+r = (V_end - F_end) / V_previous. */ +export function chainReturns(points) { + const rows = cleanPoints(points); + const index = []; + let growth = 1; + let unknownFlow = false; + let invalidPeriod = false; + if (rows.length && !(rows[0].value > 0)) + return { index, unknownFlow, invalidPeriod: true }; + for (let i = 0; i < rows.length; i++) { + const point = rows[i]; + if (i > 0) { + const previous = rows[i - 1]; + const known = typeof point.externalFlow === "number" && Number.isFinite(point.externalFlow); + unknownFlow ||= !known; + // Unknown-flow series is explicitly an unadjusted estimate in the UI. + const end = known ? point.value - point.externalFlow : point.value; + if (!(previous.value > 0) || end < 0) { + invalidPeriod = true; + break; + } + growth *= end / previous.value; + if (!Number.isFinite(growth)) { + invalidPeriod = true; + break; + } + } + index.push({ date: point.date, value: growth, breakBefore: i > 0 && hasGap(rows[i - 1], point) }); + } + return { index, unknownFlow, invalidPeriod }; +} +/** Fixed cohort: no changing membership, carry-forward, or missing-account zeros. */ +export function aggregateEquity(accounts) { + const normalized = accounts.map(a => ({ id: a.id, points: cleanPoints(a.points) })); + const missingAccounts = normalized.filter(a => !a.points.length).map(a => a.id); + const members = normalized.filter(a => a.points.length); + const maps = members.map(a => new Map(a.points.map((p, i) => [p.date, { p, i }]))); + const dates = [...new Set(members.flatMap(a => a.points.map(p => p.date)))].sort(); + const points = []; + let omittedDates = 0; + for (const date of dates) { + const values = maps.map(m => m.get(date)); + if (values.some(v => !v)) { + omittedDates++; + continue; + } + const previous = points.at(-1); + const flowKnown = values.every((v, i) => v && Number.isFinite(v.p.externalFlow) + && (!previous || members[i].points[v.i - 1]?.date === previous.date)); + points.push({ date, value: values.reduce((sum, v) => sum + v.p.value, 0), + externalFlow: flowKnown ? values.reduce((sum, v) => sum + v.p.externalFlow, 0) : null, + breakBefore: !!previous && (dateMs(date) - dateMs(previous.date) > DAY || values.some(v => v.p.breakBefore)) }); + } + return { points, missingAccounts, omittedDates }; +} +/** Baseline never changes when the user hides a legend entry. */ +export function alignReturns(primary, comparisons) { + const own = cleanPoints(primary); + const available = comparisons.map(s => ({ ...s, points: cleanPoints(s.points) })).filter(s => s.points.length); + const dates = available.map(s => new Set(s.points.map(p => p.date))); + const common = own.find(p => p.value > 0 && dates.every(d => d.has(p.date)))?.date; + const start = common || own[0]?.date; + return { + start, + primary: rebase(own, start), + benchmarks: common ? available.map(s => ({ ...s, points: rebase(s.points, common) })) : [], + noCommonDate: available.length > 0 && !common, + }; +} diff --git a/web/strategy-switch-console/worker.js b/web/strategy-switch-console/worker.js index 9b285bd0..7b49daad 100644 --- a/web/strategy-switch-console/worker.js +++ b/web/strategy-switch-console/worker.js @@ -1,3 +1,6 @@ +import { performanceResponse } from "./application/console_api/performance_routes.js"; +import { consoleApiResponse } from "./application/console_api/routes.js"; +import { decorateQueue, decisionFields } from "./application/console_api/presentation.js"; // deploy: 2026-06-30 — config driven by platform-config.json import { CredentialMaintenanceError, initializeCredentialMaintenance, credentialMaintenanceCommand } from "./credentialMaintenance.js"; import { V2_ASSETS, V2_PAGE_HTML } from "./v2_asset_map.js"; @@ -772,6 +775,22 @@ export default { } if (url.pathname === "/login") return await startLogin(request, env); if (url.pathname === "/callback") return await finishLogin(request, env); + if (url.pathname.startsWith("/api/performance/")) { + return await performanceResponse(request, env, { + json, readSession, accountOptions: loadAccountOptionsConfig, facts: accountFactsResponse, + history: (req, e) => accountFactsHistoryResponse(req, e, new URL(req.url)), + wallet: (req, e) => binanceWalletHistoryResponse(req, e, new URL(req.url)), benchmarks: marketBenchmarkResponse, + }); + } + if (["/api/decisions-inbox", "/api/owner-decisions/history", "/api/accounts", "/api/account-settings/diff", "/api/account-settings/history", "/api/account-settings/draft"].includes(url.pathname)) { + return await consoleApiResponse(request, env, { + json, readSession, command: runtimeInstanceCommand, accountOptions: loadAccountOptionsConfig, + settings: accountSettingsResponse, saveDraft: saveCombinedAccountDraft, + owner: ownerDecisionQueueResponse, promotion: researchPromotionTicketsResponse, + recovery: reconciliationRecoveryResponse, credential: (req, e) => credentialMaintenanceResponse(req, e, new URL("/api/credential-maintenance", req.url)), + audit: loadAuditLog, + }); + } if (url.pathname === "/api/session") return json(await sessionPayload(request, env)); if (url.pathname === OVERVIEW_FX_PROXY_PATH) return await overviewFxResponse(request); if (url.pathname === MARKET_BENCHMARK_API_PATH && (request.method === "GET" || request.method === "HEAD")) { @@ -1075,7 +1094,8 @@ async function credentialMaintenanceResponse(request, env, url) { if (text.length > 1024) throw new HttpError("invalid_credential_maintenance_request", 400); try { body = JSON.parse(text); } catch { throw new HttpError("invalid_credential_maintenance_request", 400); } } - return json(await runtimeInstanceCommand(env, { action, body })); + const result = await runtimeInstanceCommand(env, { action, body }); + return json(!machine && request.method === "GET" ? { ...result, ...decisionFields(result, "credential_maintenance") } : result); } let ux1ModuleEpoch = ""; @@ -3899,6 +3919,9 @@ export class RuntimeInstances { if (ACCOUNT_DIAGNOSIS_DO_ACTIONS.has(command?.action)) { return json(await this.accountDiagnosisCommand(command)); } + if (["console_decision_history", "console_settings_history", "console_account_metadata"].includes(command?.action)) { + return json(this.consoleReadCommand(command)); + } if (HUMAN_DECISION_DO_ACTIONS.has(command?.action)) { return json(this.humanDecisionCommand(command)); } @@ -4119,6 +4142,29 @@ export class RuntimeInstances { }); } + consoleReadCommand(command) { + if (!command.actor) throw new HttpError("runtime_instance_actor_required", 400); + if (command.action === "console_decision_history") { + const { limit, offset } = command; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0 || offset > 100000) throw new HttpError("invalid_pagination", 400); + return { rows: this.sql.exec("SELECT kind, subject_id, material_key, action, actor, decided_at FROM human_decision_record ORDER BY decided_at DESC, request_key DESC LIMIT ? OFFSET ?", limit + 1, offset).toArray() }; + } + if (command.action === "console_settings_history") { + this.existingAccountInstance(command.platform, command.key); + return { approvals: this.sql.exec("SELECT approved_at, approved_by, draft_revision FROM account_setting_profile_application WHERE platform = ? AND account_key = ? ORDER BY approved_at DESC", command.platform, command.key).toArray() }; + } + const drafts = this.sql.exec("SELECT platform, account_key, overrides_json, updated_at FROM account_setting_draft").toArray(); + const approvals = this.sql.exec("SELECT platform, account_key, MAX(approved_at) AS approved_at FROM account_setting_profile_application GROUP BY platform, account_key").toArray(); + return { rows: this.read().instances.map(item => { + const draft = drafts.find(row => row.platform === item.platform && row.account_key === item.key); + const approval = approvals.find(row => row.platform === item.platform && row.account_key === item.key); + return { platform: item.platform, account_key: item.key, + pending_draft_count: draft ? new Set(Object.keys(JSON.parse(draft.overrides_json)).map(field => field.startsWith("dca_") ? "dca" : field.startsWith("reserved_") ? "cash" : field)).size : 0, + last_change_at: [draft?.updated_at, approval?.approved_at, item.updated_at].filter(Boolean).sort().at(-1) || null, + }; + }) }; + } + humanDecisionCommand(command) { return this.storage.transactionSync(() => { if (!command || typeof command.actor !== "string" || !command.actor) { @@ -5184,6 +5230,18 @@ function assertAccountDraftPatch(profiles, observed, patch, trustedProfile, opti } } +async function saveCombinedAccountDraft(request, env) { + requireSameOrigin(request, { requireOrigin: true }); + const session = await readSession(request, env); + if (!session) return json({ ok: false, error: "login required" }, 401); + if (!session.admin) return json({ ok: false, error: "admin required" }, 403); + let raw; + try { raw = await readBoundedJson(request, 16 * 1024); } catch (error) { return json({ ok: false, error: "invalid_account_setting_overrides" }, error.status || 400); } + const allowed = ["platform", "key", "identity", "expected_draft_revision", "acknowledge_identity_conflict", "overrides"]; + if (!raw || Array.isArray(raw) || Object.keys(raw).some(key => !allowed.includes(key)) || !Object.hasOwn(raw, "overrides")) return json({ ok: false, error: "invalid_account_setting_overrides" }, 400); + return saveAccountSettings(new Request(request.url, { method: "POST", headers: request.headers, body: JSON.stringify(raw) }), env); +} + async function saveAccountSettings(request, env) { requireSameOrigin(request, { requireOrigin: true }); const session = await readSession(request, env); @@ -7543,7 +7601,7 @@ async function reconciliationRecoveryResponse(request, env) { const exact = await exactHumanDecisionResponse(request, env, session, "recovery"); if (exact) return exact; if (!hasConfigStore(env)) return json(emptyReconciliationRecoveryPayload("snapshot_unavailable")); - return json(await aggregateReconciliationRecoverySources(env)); + return json(decorateQueue(await aggregateReconciliationRecoverySources(env), "recoveries", "reconciliation_recovery")); } async function syncBinancePrivateScopeResponse(request, env) { @@ -11270,7 +11328,7 @@ async function researchPromotionTicketsResponse(request, env) { schema_version: RESEARCH_PROMOTION_QUEUE_SCHEMA, data_status: hasConfigStore(env) ? (invalidTickets.length ? "partial" : "ready") : "unavailable", computed_at: new Date().toISOString(), - tickets: awaiting.map(attachRiskEnvelopeView), + tickets: decorateQueue({ tickets: awaiting.map(attachRiskEnvelopeView) }, "tickets", "strategy_promotion").tickets, applications, ...(invalidTickets.length ? { invalid_tickets: invalidTickets } : {}), summary: {