unrip/test/operator-dashboard.test.mjs
philipp 2e95c95246
All checks were successful
deploy / deploy (push) Successful in 1m0s
Persist quote lifecycle statistics
Proof: Added PostgreSQL-backed quote lifecycle statistics for all-time, monthly, weekly, daily, hourly, and five-minute windows; wired authenticated dashboard API, live WebSocket counters, history-writer refresh before pruning, and dashboard controls; validated with targeted tests, full npm test, and operator dashboard build.

Assumptions: Unique quote counts are keyed by durable quote_id, quote windows use the first durable lifecycle timestamp in UTC with Monday UTC weeks, and missing identifiers or timestamps are represented as unavailable evidence instead of fabricated quote identities.

Still fake: Fee-aware PnL, cashflow, oracle-deviation, size distribution, matched-only analytics, and reconstruction of already-pruned detail remain outside this turn.
2026-06-12 20:02:09 +02:00

2599 lines
86 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {
DASHBOARD_WEBSOCKET_MAX_BUFFERED_BYTES,
applyDashboardLiveEvent,
buildDashboardBootstrap,
buildDashboardControlErrorResponse,
buildLiveStatusBar,
buildQuoteLifecycleLookupResponse,
buildProfitabilitySummary,
createDashboardLiveState,
deriveQuoteLifecycleRows,
isDashboardWebSocketBackpressured,
resolveDashboardControl,
resolveDashboardControlTimeoutMs,
} from '../src/core/operator-dashboard.mjs';
import { formatAge, formatAgeFromTimestamp } from '../src/operator-dashboard/static/lib/format.js';
import {
createSelectedLifecycleInvestigation,
shouldRefreshSelectedFromDurable,
updateSelectedLifecycleFromLiveRows,
updateSelectedLifecycleFromLookup,
} from '../src/operator-dashboard/static/lib/quoteLifecycleInvestigator.js';
import { dashboardReducer } from '../src/operator-dashboard/static/state/dashboardReducer.js';
import {
buildDashboardSessionToken,
parseBasicAuthorizationHeader,
resolveDashboardRequestAuth,
} from '../src/core/operator-dashboard-auth.mjs';
import { loadQuoteLifecycleLookupEvidence } from '../src/lib/postgres.mjs';
function buildConfig() {
const tradingBtc = {
assetId: 'nep141:btc.omft.near',
symbol: 'BTC',
decimals: 8,
chain: 'btc:mainnet',
};
const tradingEure = {
assetId: 'nep141:eure.omft.near',
symbol: 'EURe',
decimals: 18,
chain: 'eth:100',
};
return {
activePair: `${tradingBtc.assetId}->${tradingEure.assetId}`,
operatorDashboardQuoteLimit: 10,
kafkaTopicNormSwapDemand: 'norm.swap_demand',
kafkaTopicDecisionTradeDecision: 'decision.trade_decision',
kafkaTopicCmdExecuteTrade: 'cmd.execute_trade',
kafkaTopicRefMarketPrice: 'ref.market_price',
kafkaTopicStateIntentInventory: 'state.intent_inventory',
kafkaTopicOpsAlert: 'ops.alert',
kafkaTopicOpsEnvironmentStatus: 'ops.environment_status',
kafkaTopicExecTradeResult: 'exec.trade_result',
tradingBtc,
tradingEure,
assetRegistry: new Map([
[tradingBtc.assetId, tradingBtc],
[tradingEure.assetId, tradingEure],
]),
};
}
function buildDualBtcConfig() {
const tradingBtc = {
assetId: 'nep141:nbtc.bridge.near',
symbol: 'BTC',
label: 'BTC / nBTC reserve',
decimals: 8,
chain: 'btc:mainnet',
};
const legacyBtc = {
assetId: 'nep141:btc.omft.near',
symbol: 'BTC',
label: 'BTC / legacy OMFT',
decimals: 8,
chain: 'btc:mainnet',
};
const tradingEure = {
assetId: 'nep141:eure.omft.near',
symbol: 'EURe',
decimals: 18,
chain: 'eth:100',
};
return {
...buildConfig(),
activePair: `${tradingBtc.assetId}->${tradingEure.assetId}`,
tradingBtc,
tradingBtcAssets: [tradingBtc, legacyBtc],
tradingEure,
trackedAssets: [tradingBtc, legacyBtc, tradingEure],
assetRegistry: new Map([
[tradingBtc.assetId, tradingBtc],
[legacyBtc.assetId, legacyBtc],
[tradingEure.assetId, tradingEure],
]),
};
}
test('profitability summary separates baseline, hold, market move, and portfolio comparison', () => {
const summary = buildProfitabilitySummary({
metric: {
computed_at: '2026-04-04T09:05:00.000Z',
baseline_anchor_at: '2026-04-04T08:00:00.000Z',
baseline_status: 'active',
payload: {
current_portfolio_value_eure: '110',
baseline_portfolio_value_eure_at_baseline_price: '100',
baseline_portfolio_value_eure_at_current_price: '105',
},
},
submissionSummary: {
total: 4,
last_submission_at: '2026-04-04T09:00:00.000Z',
},
});
assert.equal(summary.pnl_vs_deposit_baseline_eure, '10');
assert.equal(summary.pnl_vs_simple_hold_eure, '5');
assert.equal(summary.market_move_contribution_eure, '5');
assert.equal(summary.portfolio_vs_simple_hold_eure, '5');
assert.equal(summary.trading_contribution_eure, null);
assert.match(summary.caveats.join(' '), /not realized per-trade PnL/i);
assert.equal(summary.computed_at, '2026-04-04T09:05:00.000Z');
assert.equal(summary.recent_submission_count, 4);
assert.equal(summary.last_submission_at, '2026-04-04T09:00:00.000Z');
});
test('profitability summary flags cash-flow-adjusted benchmarks after later funding changes', () => {
const summary = buildProfitabilitySummary({
metric: {
computed_at: '2026-04-07T15:43:30.463Z',
baseline_anchor_at: '2026-04-02T18:10:43.569Z',
baseline_status: 'active',
payload: {
current_portfolio_value_eure: '144.627100025978799978',
baseline_portfolio_value_eure_at_baseline_price: '141.7921998',
baseline_portfolio_value_eure_at_current_price: '142.8458998',
external_cash_flows: {
flow_count: 2,
deposit_count: 1,
withdrawal_count: 1,
latest_effective_at: '2026-04-07T15:20:54.757Z',
net_value_eure_at_flow_time: '23.9999998',
},
},
},
submissionSummary: {
total: 7,
last_submission_at: '2026-04-02T20:17:44.768Z',
},
});
assert.equal(summary.external_flow_adjusted, true);
assert.equal(summary.external_flow_count, 2);
assert.equal(summary.pnl_vs_deposit_baseline_eure, '2.834900225978799978');
assert.equal(summary.pnl_vs_simple_hold_eure, '1.781200225978799978');
assert.equal(summary.market_move_contribution_eure, '1.0537');
assert.match(summary.caveats[0], /external cash flows/);
});
test('request creation controls get enough upstream time for relay quote and status waits', () => {
const preflight = resolveDashboardControl({
service: 'trade-executor',
action: 'intent-request-preflight',
});
const submit = resolveDashboardControl({
service: 'trade-executor',
action: 'intent-request-submit',
});
const refresh = resolveDashboardControl({
service: 'inventory-sync',
action: 'refresh',
});
const config = {
operatorDashboardUpstreamTimeoutMs: 3000,
intentRequestQuoteTimeoutMs: 10000,
intentRequestPublishTimeoutMs: 10000,
intentRequestStatusTimeoutMs: 10000,
};
assert.equal(resolveDashboardControlTimeoutMs({ control: preflight, config }), 12000);
assert.equal(resolveDashboardControlTimeoutMs({ control: submit, config }), 25000);
assert.equal(resolveDashboardControlTimeoutMs({ control: refresh, config }), 3000);
});
test('dashboard control errors become structured responses instead of uncaught failures', () => {
const control = resolveDashboardControl({
service: 'trade-executor',
action: 'intent-request-preflight',
});
const timeout = new DOMException('The operation was aborted due to timeout', 'TimeoutError');
const response = buildDashboardControlErrorResponse(timeout, { control });
assert.equal(response.statusCode, 504);
assert.equal(response.payload.ok, false);
assert.equal(response.payload.error, 'control_timeout');
assert.equal(response.payload.control.action, 'intent-request-preflight');
assert.match(response.payload.reason, /timeout/i);
});
test('dashboard websocket backpressure guard drops lagging clients before OOM', () => {
assert.equal(
isDashboardWebSocketBackpressured({
bufferedAmount: DASHBOARD_WEBSOCKET_MAX_BUFFERED_BYTES,
}),
false,
);
assert.equal(
isDashboardWebSocketBackpressured({
bufferedAmount: DASHBOARD_WEBSOCKET_MAX_BUFFERED_BYTES + 1,
}),
true,
);
assert.equal(isDashboardWebSocketBackpressured({}), false);
});
test('control routing only resolves the allowlisted safe dashboard actions', () => {
const refresh = resolveDashboardControl({
service: 'liquidity-manager',
action: 'refresh',
});
const armExecutor = resolveDashboardControl({
service: 'trade-executor',
action: 'arm',
});
const resumeExecutor = resolveDashboardControl({
service: 'trade-executor',
action: 'resume',
});
const requestPreflight = resolveDashboardControl({
service: 'trade-executor',
action: 'intent-request-preflight',
});
const requestSubmit = resolveDashboardControl({
service: 'trade-executor',
action: 'intent-request-submit',
});
const risky = resolveDashboardControl({
service: 'strategy-engine',
action: 'arm',
});
assert.equal(refresh?.path, '/refresh');
assert.equal(refresh?.risk_class, 'safe');
assert.equal(armExecutor?.path, '/arm');
assert.equal(armExecutor?.label, 'Arm Executor');
assert.equal(resumeExecutor?.path, '/resume');
assert.equal(resumeExecutor?.label, 'Resume Executor Intake');
assert.equal(requestPreflight?.path, '/intent-request/preflight');
assert.equal(requestPreflight?.risk_class, 'safe');
assert.equal(requestSubmit?.path, '/intent-request/submit');
assert.equal(requestSubmit?.risk_class, 'live_funds');
assert.equal(risky, null);
});
test('dashboard bootstrap exposes quote lifecycle retention and rollup storage truth', () => {
const payload = buildDashboardBootstrap({
config: buildDualBtcConfig(),
auth: { authenticated: true },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentQuoteOutcomes: [],
quoteLifecycleRetention: {
retention_mode: 'normal',
detail_retention_ms: 30 * 60 * 1000,
raw_retention_ms: 30 * 60 * 1000,
rollup_required_until: '2026-06-06T10:30:00.000Z',
rollup_fresh: true,
policy: {
policy_key: 'quote_lifecycle_default',
raw_retention_ms: 30 * 60 * 1000,
},
latest_run: {
completed_at: '2026-06-06T11:00:00.000Z',
pruned_counts: {
deletedCount: 7,
tables: [{ table: 'trade_decisions', deletedCount: 7 }],
},
},
storage: {
database: { total_bytes: 1000 },
tables: [{ table: 'trade_decisions', total_bytes: 500, approximate_rows: 20 }],
},
rollups: {
latest_rollup_at: '2026-06-06T10:59:00.000Z',
rollup_row_count: 3,
},
preserved_successful_quote_count: 2,
},
quoteLifecycleRollups: [{
rollup_id: 'rollup-1',
window_end: '2026-06-06T10:30:00.000Z',
pair: 'a->b',
result_code: 'submission_failed',
outcome_status: 'relay_failed',
quote_count: 4,
completed_count: 0,
}],
quoteLifecycleStatistics: {
persisted: {
source: 'persisted',
generated_at: '2026-06-06T11:00:00.000Z',
rows: [{
grain: 'all_time',
quote_count: 4,
bucket_counts: { submission_failed: 4 },
}],
},
live: {
source: 'live_recent',
generated_at: '2026-06-06T11:00:01.000Z',
rows: [{
grain: 'five_minute',
quote_count: 1,
bucket_counts: { awaiting_executor: 1 },
}],
},
},
recentIntentRequests: [],
recentAlertTransitions: [],
recentEnvironmentStatuses: [],
serviceSnapshots: [{
service: 'history-writer',
label: 'History Writer',
reachable: true,
state: {
database_connectivity: true,
retention_mode: 'normal',
},
health: { ok: true },
}],
});
assert.equal(payload.system.persistence.retention_summary.retention_mode, 'normal');
assert.equal(payload.system.persistence.preserved_successful_quote_count, 2);
assert.equal(payload.system.persistence.quote_lifecycle_rollups[0].rollup_id, 'rollup-1');
assert.equal(payload.strategy.strategy_state.maker_competitiveness.persisted_rollup_count, 1);
assert.equal(payload.strategy.strategy_state.quote_lifecycle_statistics.persisted.rows[0].quote_count, 4);
assert.equal(payload.strategy.strategy_state.quote_lifecycle_statistics.live.rows[0].bucket_counts.awaiting_executor, 1);
});
test('basic auth resolves operator identity and reuses a session cookie', () => {
const authorizationHeader = `Basic ${Buffer.from('admin:secret-password').toString('base64')}`;
const first = resolveDashboardRequestAuth({
mode: 'basic',
authorizationHeader,
username: 'admin',
password: 'secret-password',
});
const token = buildDashboardSessionToken({
username: 'admin',
password: 'secret-password',
});
const second = resolveDashboardRequestAuth({
mode: 'basic',
cookieHeader: `operator_dashboard_session=${token}`,
username: 'admin',
password: 'secret-password',
});
assert.equal(parseBasicAuthorizationHeader(authorizationHeader).username, 'admin');
assert.equal(first.authenticated, true);
assert.equal(first.setSessionCookie, true);
assert.equal(second.authenticated, true);
assert.equal(second.via, 'session_cookie');
});
test('live status bar preserves initial upstream status during websocket session ready', () => {
const config = buildConfig();
const state = createDashboardLiveState({
config,
nearIntentsStatus: {
status: 'disrupted',
label: 'upstream paused',
observed_at: '2026-04-16T12:40:00.000Z',
decisive_reason: '1Click quoting paused.',
},
});
const statusBar = buildLiveStatusBar(state);
assert.equal(statusBar.near_intents_upstream_label, 'upstream paused');
assert.equal(statusBar.near_intents_upstream_reason, '1Click quoting paused.');
});
test('live quote updates stay capped and publish lifecycle rows without refresh', () => {
const config = buildConfig();
const state = createDashboardLiveState({
config,
recentSubmissionCount: 2,
lastSubmissionAt: '2026-04-04T08:00:00.000Z',
});
let latestQuoteUpdates = [];
for (let index = 0; index < 11; index += 1) {
latestQuoteUpdates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicNormSwapDemand,
event: {
observed_at: `2026-04-04T08:00:${String(index).padStart(2, '0')}.000Z`,
ingested_at: `2026-04-04T08:00:${String(index).padStart(2, '0')}.000Z`,
payload: {
quote_id: `quote-${index}`,
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
pair: config.activePair,
request_kind: 'exact_in',
amount_in: '100',
amount_out: '200',
},
},
});
}
const quoteLifecycleUpdate = latestQuoteUpdates.find((update) => update.type === 'quote_lifecycle.updated');
assert.equal(state.recent_quotes.length, 10);
assert.equal(state.recent_quotes[0].quote_id, 'quote-10');
assert.equal(state.recent_quotes.at(-1).quote_id, 'quote-1');
assert.equal(latestQuoteUpdates[0].type, 'quotes.recent');
assert.equal(quoteLifecycleUpdate.recent_lifecycle_rows[0].quote_id, 'quote-10');
assert.equal(quoteLifecycleUpdate.recent_lifecycle_rows[0].lifecycle_state, 'observed');
assert.ok(quoteLifecycleUpdate.recent_lifecycle_rows[0].live_flash_at);
const submittedUpdates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicExecTradeResult,
event: {
observed_at: '2026-04-04T08:30:00.000Z',
ingested_at: '2026-04-04T08:30:00.000Z',
payload: {
command_id: 'cmd-quote-10',
decision_id: 'decision-quote-10',
quote_id: 'quote-10',
pair: config.activePair,
status: 'submitted',
result_code: 'quote_response_ok',
executor_timing: {
command_event_age_ms: 3,
current_salt_ms: 42,
sign_ms: 1.5,
relay_response_ms: 111,
executor_total_ms: 157,
},
},
},
});
const submittedLifecycleUpdate = submittedUpdates.find((update) => update.type === 'quote_lifecycle.updated');
assert.equal(state.recent_submission_count, 3);
assert.equal(state.last_submission_at, '2026-04-04T08:30:00.000Z');
assert.ok(submittedUpdates.find((update) => update.type === 'status_bar.updated'));
assert.equal(submittedLifecycleUpdate.recent_lifecycle_rows[0].quote_id, 'quote-10');
assert.equal(submittedLifecycleUpdate.recent_lifecycle_rows[0].lifecycle_state, 'submitted');
assert.deepEqual(submittedLifecycleUpdate.recent_lifecycle_rows[0].execution.timing, {
command_event_age_ms: 3,
current_salt_ms: 42,
sign_ms: 1.5,
relay_response_ms: 111,
executor_total_ms: 157,
});
assert.doesNotMatch(
`${submittedLifecycleUpdate.recent_lifecycle_rows[0].lifecycle_label} ${submittedLifecycleUpdate.recent_lifecycle_rows[0].reason_text}`,
/completed|successful trade|asset delta/i,
);
});
test('live decision, command, and executor result events advance lifecycle rows without bootstrap reload', () => {
const config = buildConfig();
const state = createDashboardLiveState({ config });
applyDashboardLiveEvent(state, {
topic: config.kafkaTopicNormSwapDemand,
event: {
observed_at: '2026-04-04T09:00:00.000Z',
ingested_at: '2026-04-04T09:00:00.000Z',
payload: {
quote_id: 'quote-live',
pair: config.activePair,
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
amount_in: '100',
amount_out: '200',
},
},
});
const decisionUpdates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicDecisionTradeDecision,
event: {
observed_at: '2026-04-04T09:00:01.000Z',
ingested_at: '2026-04-04T09:00:01.000Z',
payload: {
decision_id: 'decision-live',
quote_id: 'quote-live',
pair: config.activePair,
decision: 'actionable',
decision_reason: 'actionable',
gross_edge_pct: '0.49',
eure_notional: '5',
},
},
});
assert.equal(decisionUpdates[0].recent_lifecycle_rows[0].lifecycle_state, 'evaluated');
assert.equal(decisionUpdates[0].recent_lifecycle_rows[0].reason_code, 'strategy_approved');
const commandUpdates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicCmdExecuteTrade,
event: {
observed_at: '2026-04-04T09:00:02.000Z',
ingested_at: '2026-04-04T09:00:02.000Z',
payload: {
command_id: 'cmd-live',
decision_id: 'decision-live',
quote_id: 'quote-live',
pair: config.activePair,
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
quote_output: {
amount_in: '101',
amount_out: '201',
},
},
},
});
assert.equal(commandUpdates[0].recent_lifecycle_rows[0].lifecycle_state, 'command_emitted');
assert.equal(commandUpdates[0].recent_lifecycle_rows[0].submitted_terms.amount_in_units, '101');
const blockedUpdates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicExecTradeResult,
event: {
observed_at: '2026-04-04T09:00:03.000Z',
ingested_at: '2026-04-04T09:00:03.000Z',
payload: {
command_id: 'cmd-live',
decision_id: 'decision-live',
quote_id: 'quote-live',
pair: config.activePair,
status: 'rejected',
result_code: 'executor_disarmed',
note: 'executor is disarmed',
},
},
});
assert.equal(blockedUpdates.length, 1);
assert.equal(blockedUpdates[0].type, 'quote_lifecycle.updated');
assert.equal(blockedUpdates[0].recent_lifecycle_rows[0].lifecycle_state, 'blocked');
assert.equal(blockedUpdates[0].recent_lifecycle_rows[0].lifecycle_label, 'Blocked before submit');
assert.notEqual(blockedUpdates[0].recent_lifecycle_rows[0].lifecycle_label, 'Rejected by strategy');
});
test('socket lifecycle messages replace strategy rows without page refresh', () => {
const dashboard = {
funds: { recent_quotes: [] },
status_bar: {},
strategy: {
strategy_state: {
recent_lifecycle_rows: [],
},
},
};
const state = {
dashboard,
session: { authenticated: true },
page: 'strategy',
};
const next = dashboardReducer(state, {
type: 'socket.message.received',
payload: {
type: 'quote_lifecycle.updated',
recent_lifecycle_rows: [{
quote_id: 'quote-live',
lifecycle_state: 'observed',
live_flash_at: '2026-04-04T09:00:00.000Z',
}],
},
});
assert.equal(next.dashboard.strategy.strategy_state.recent_lifecycle_rows[0].quote_id, 'quote-live');
assert.equal(next.dashboard.strategy.strategy_state.recent_lifecycle_rows[0].live_flash_at, '2026-04-04T09:00:00.000Z');
});
test('socket lifecycle statistics update live counts while preserving persisted totals', () => {
const dashboard = {
funds: { recent_quotes: [] },
status_bar: {},
strategy: {
strategy_state: {
recent_lifecycle_rows: [],
quote_lifecycle_statistics: {
persisted: {
source: 'persisted',
rows: [{
grain: 'all_time',
quote_count: 12,
bucket_counts: { success: 2 },
}],
},
live: {
source: 'live_recent',
rows: [],
},
},
},
},
};
const state = {
dashboard,
session: { authenticated: true },
page: 'strategy-lifecycle',
};
const next = dashboardReducer(state, {
type: 'socket.message.received',
payload: {
type: 'quote_lifecycle.updated',
recent_lifecycle_rows: [],
quote_lifecycle_statistics: {
source: 'live_recent',
rows: [{
grain: 'five_minute',
quote_count: 1,
bucket_counts: { awaiting_executor: 1 },
}],
},
},
});
assert.equal(next.dashboard.strategy.strategy_state.quote_lifecycle_statistics.persisted.rows[0].quote_count, 12);
assert.equal(next.dashboard.strategy.strategy_state.quote_lifecycle_statistics.live.rows[0].quote_count, 1);
assert.equal(
next.dashboard.strategy.strategy_state.quote_lifecycle_statistics.live.rows[0].bucket_counts.awaiting_executor,
1,
);
});
test('selected awaiting executor quote remains inspectable after live rows move and refreshes from durable result', () => {
const config = buildConfig();
const awaiting = buildQuoteLifecycleLookupResponse({
config,
identifier: 'quote-follow',
evidence: {
lookup_at: '2026-06-12T10:00:00.000Z',
matched_identifier_type: 'quote_id',
matched_identifiers: {
quote_ids: ['quote-follow'],
decision_ids: ['decision-follow'],
command_ids: ['cmd-follow'],
},
recentTradeDecisions: [{
observed_at: '2026-06-12T09:59:58.000Z',
payload: {
quote_id: 'quote-follow',
decision_id: 'decision-follow',
pair: config.activePair,
decision: 'actionable',
decision_reason: 'actionable',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-06-12T09:59:59.000Z',
command_id: 'cmd-follow',
decision_id: 'decision-follow',
quote_id: 'quote-follow',
pair: config.activePair,
}],
},
});
assert.equal(awaiting.ok, true);
assert.equal(awaiting.lifecycle_row.lifecycle_state, 'command_emitted');
assert.equal(awaiting.lifecycle_row.lifecycle_label, 'Awaiting executor');
const selected = createSelectedLifecycleInvestigation(awaiting.lifecycle_row, {
now: '2026-06-12T10:00:00.000Z',
});
const afterLiveMove = updateSelectedLifecycleFromLiveRows(selected, [{
quote_id: 'quote-newer',
lifecycle_state: 'observed',
}], {
now: '2026-06-12T10:00:02.000Z',
});
assert.equal(afterLiveMove.row.quote_id, 'quote-follow');
assert.equal(afterLiveMove.row.lifecycle_state, 'command_emitted');
assert.equal(shouldRefreshSelectedFromDurable(afterLiveMove, [{ quote_id: 'quote-newer' }]), true);
const later = buildQuoteLifecycleLookupResponse({
config,
identifier: 'cmd-follow',
evidence: {
lookup_at: '2026-06-12T10:00:04.000Z',
matched_identifier_type: 'command_id',
matched_identifiers: {
quote_ids: ['quote-follow'],
decision_ids: ['decision-follow'],
command_ids: ['cmd-follow'],
},
recentExecuteTradeCommands: [{
observed_at: '2026-06-12T09:59:59.000Z',
command_id: 'cmd-follow',
decision_id: 'decision-follow',
quote_id: 'quote-follow',
pair: config.activePair,
}],
recentExecutionResults: [{
command_id: 'cmd-follow',
decision_id: 'decision-follow',
quote_id: 'quote-follow',
pair: config.activePair,
result_at: '2026-06-12T10:00:03.000Z',
status: 'failed',
result_code: 'submission_failed',
failure_category: 'quote_not_found_or_finished',
note: 'relay no longer has the quote',
}],
},
});
const refreshed = updateSelectedLifecycleFromLookup(afterLiveMove, later, {
identifier: 'cmd-follow',
now: '2026-06-12T10:00:04.000Z',
});
assert.equal(refreshed.source, 'durable_lookup');
assert.equal(refreshed.row.quote_id, 'quote-follow');
assert.equal(refreshed.row.lifecycle_state, 'failed');
assert.equal(refreshed.row.reason_code, 'quote_not_found_or_finished');
assert.match(refreshed.row.reason_text, /not found or already finished/i);
});
test('quote lifecycle lookup response matches quote, decision, and command identifiers from durable evidence', () => {
const config = buildConfig();
const evidence = {
lookup_at: '2026-06-12T10:10:00.000Z',
matched_identifiers: {
quote_ids: ['quote-lookup'],
decision_ids: ['decision-lookup'],
command_ids: ['cmd-lookup'],
},
recentQuotes: [{
quote_id: 'quote-lookup',
pair: config.activePair,
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
amount_in: '100',
amount_out: '200',
observed_at: '2026-06-12T10:09:57.000Z',
}],
recentTradeDecisions: [{
observed_at: '2026-06-12T10:09:58.000Z',
payload: {
quote_id: 'quote-lookup',
decision_id: 'decision-lookup',
pair: config.activePair,
decision: 'actionable',
decision_reason: 'actionable',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-06-12T10:09:59.000Z',
command_id: 'cmd-lookup',
decision_id: 'decision-lookup',
quote_id: 'quote-lookup',
pair: config.activePair,
}],
};
const byQuote = buildQuoteLifecycleLookupResponse({
config,
identifier: 'quote-lookup',
evidence: { ...evidence, matched_identifier_type: 'quote_id' },
});
const byDecision = buildQuoteLifecycleLookupResponse({
config,
identifier: 'decision-lookup',
evidence: { ...evidence, matched_identifier_type: 'decision_id' },
});
const byCommand = buildQuoteLifecycleLookupResponse({
config,
identifier: 'cmd-lookup',
evidence: { ...evidence, matched_identifier_type: 'command_id' },
});
assert.equal(byQuote.lifecycle_row.quote_id, 'quote-lookup');
assert.equal(byDecision.lifecycle_row.decision_id, 'decision-lookup');
assert.equal(byCommand.lifecycle_row.command_id, 'cmd-lookup');
assert.equal(byQuote.lookup.matched_identifier_type, 'quote_id');
assert.equal(byDecision.lookup.matched_identifier_type, 'decision_id');
assert.equal(byCommand.lookup.matched_identifier_type, 'command_id');
});
test('postgres quote lifecycle lookup loader links durable quote, decision, and command evidence', async () => {
const queries = [];
const pool = {
async query(sql, params = []) {
queries.push({ sql, params });
if (sql.includes('WITH candidates')) {
return {
rows: [{
matched_identifier_type: 'decision_id',
quote_id: 'quote-loader',
decision_id: 'decision-loader',
command_id: 'cmd-loader',
matched_at: '2026-06-12T10:20:00.000Z',
}],
};
}
if (sql.includes('FROM swap_demand_events')) {
return {
rows: [{
observed_at: '2026-06-12T10:19:57.000Z',
ingested_at: '2026-06-12T10:19:57.000Z',
payload: {
quote_id: 'quote-loader',
pair: 'btc->eure',
asset_in: 'btc',
asset_out: 'eure',
amount_in: '100',
amount_out: '200',
},
}],
};
}
if (sql.includes('FROM trade_decisions')) {
return {
rows: [{
observed_at: '2026-06-12T10:19:58.000Z',
ingested_at: '2026-06-12T10:19:58.000Z',
payload: {
quote_id: 'quote-loader',
decision_id: 'decision-loader',
decision: 'actionable',
decision_reason: 'actionable',
},
}],
};
}
if (sql.includes('FROM execute_trade_commands')) {
return {
rows: [{
observed_at: '2026-06-12T10:19:59.000Z',
ingested_at: '2026-06-12T10:19:59.000Z',
payload: {
quote_id: 'quote-loader',
decision_id: 'decision-loader',
command_id: 'cmd-loader',
},
}],
};
}
if (sql.includes('FROM trade_execution_results r')) {
return {
rows: [{
result_observed_at: '2026-06-12T10:20:01.000Z',
result_ingested_at: '2026-06-12T10:20:01.000Z',
result_payload: {
quote_id: 'quote-loader',
decision_id: 'decision-loader',
command_id: 'cmd-loader',
status: 'failed',
result_code: 'submission_failed',
failure_category: 'quote_not_found_or_finished',
},
command_ingested_at: '2026-06-12T10:19:59.000Z',
command_payload: {
quote_id: 'quote-loader',
decision_id: 'decision-loader',
command_id: 'cmd-loader',
},
decision_payload: {
quote_id: 'quote-loader',
decision_id: 'decision-loader',
},
outcome_payload: null,
}],
};
}
if (sql.includes('FROM quote_outcome_attributions')) {
return { rows: [] };
}
return { rows: [] };
},
};
const evidence = await loadQuoteLifecycleLookupEvidence(pool, {
identifier: 'decision-loader',
});
assert.equal(evidence.found, true);
assert.equal(evidence.matched_identifier_type, 'decision_id');
assert.deepEqual(evidence.matched_identifiers, {
quote_ids: ['quote-loader'],
decision_ids: ['decision-loader'],
command_ids: ['cmd-loader'],
});
assert.equal(evidence.recentQuotes[0].quote_id, 'quote-loader');
assert.equal(evidence.recentTradeDecisions[0].payload.decision_id, 'decision-loader');
assert.equal(evidence.recentExecuteTradeCommands[0].command_id, 'cmd-loader');
assert.equal(evidence.recentExecutionResults[0].failure_category, 'quote_not_found_or_finished');
assert.equal(queries[0].params[0], 'decision-loader');
});
test('dashboard age formatting uses seconds first and exact timestamp deltas', () => {
assert.equal(formatAge(999), '999 ms');
assert.equal(formatAge(1_500), '1s');
assert.equal(formatAge(65_000), '1m 5s');
assert.equal(
formatAgeFromTimestamp('2026-04-04T08:00:00.000Z', Date.parse('2026-04-04T08:01:05.000Z')),
'1m 5s',
);
});
test('live dashboard ignores ops alert events so alert severity cannot re-enter operator state', () => {
const config = buildConfig();
const state = createDashboardLiveState({ config });
const updates = applyDashboardLiveEvent(state, {
topic: 'ops.alert',
event: {
observed_at: '2026-04-04T08:30:00.000Z',
ingested_at: '2026-04-04T08:30:00.000Z',
payload: {
alert_code: 'near_intents_publish_stale',
status: 'raised',
severity: 'critical',
service_scope: 'near-intents-ingest',
},
},
});
assert.deepEqual(updates, []);
assert.equal(state.active_alerts.size, 0);
assert.equal(buildLiveStatusBar(state).active_alert_count, 0);
assert.equal(buildLiveStatusBar(state).highest_alert_severity, null);
});
test('lifecycle derivation keeps executor blocking distinct from strategy rejection', () => {
const rows = deriveQuoteLifecycleRows({
recentQuotes: [{
quote_id: 'quote-1',
pair: 'btc->eure',
request_kind: 'exact_in',
observed_at: '2026-04-09T09:00:00.000Z',
}],
recentTradeDecisions: [{
observed_at: '2026-04-09T09:00:01.000Z',
payload: {
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
decision: 'actionable',
decision_reason: 'actionable',
gross_edge_pct: '1.2',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-04-09T09:00:02.000Z',
command_id: 'command-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
}],
recentExecutionResults: [{
command_id: 'command-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
result_at: '2026-04-09T09:00:03.000Z',
status: 'rejected',
result_code: 'executor_disarmed',
note: 'executor is disarmed',
}],
});
assert.equal(rows[0].lifecycle_state, 'blocked');
assert.equal(rows[0].lifecycle_label, 'Blocked before submit');
assert.equal(rows[0].reason_code, 'executor_disarmed');
assert.notEqual(rows[0].lifecycle_state, 'rejected');
});
test('lifecycle derivation never upgrades submitted evidence into completion or asset movement', () => {
const rows = deriveQuoteLifecycleRows({
recentTradeDecisions: [{
observed_at: '2026-04-09T09:10:01.000Z',
payload: {
decision_id: 'decision-2',
quote_id: 'quote-2',
pair: 'btc->eure',
decision: 'actionable',
decision_reason: 'actionable',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-04-09T09:10:02.000Z',
command_id: 'command-2',
decision_id: 'decision-2',
quote_id: 'quote-2',
pair: 'btc->eure',
}],
recentExecutionResults: [{
command_id: 'command-2',
decision_id: 'decision-2',
quote_id: 'quote-2',
pair: 'btc->eure',
result_at: '2026-04-09T09:10:03.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
}],
});
assert.equal(rows[0].lifecycle_state, 'submitted');
assert.equal(rows[0].lifecycle_label, 'Submitted');
assert.match(rows[0].reason_text, /no durable venue outcome/i);
assert.notEqual(rows[0].lifecycle_state, 'completed');
assert.doesNotMatch(`${rows[0].lifecycle_label} ${rows[0].reason_text}`.toLowerCase(), /asset delta|realized/);
});
test('strategy approval no longer renders the forbidden actionable label', () => {
const rows = deriveQuoteLifecycleRows({
recentTradeDecisions: [{
observed_at: '2026-04-09T09:20:01.000Z',
payload: {
decision_id: 'decision-3',
quote_id: 'quote-3',
pair: 'btc->eure',
decision: 'actionable',
decision_reason: 'actionable',
},
}],
});
assert.equal(rows[0].lifecycle_state, 'evaluated');
assert.equal(rows[0].lifecycle_label, 'Approved by strategy');
assert.notEqual(rows[0].lifecycle_label, 'Actionable');
assert.equal(rows[0].reason_code, 'strategy_approved');
});
test('bootstrap aggregation keeps Funds as default and carries live control state', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: {
computed_at: '2026-04-04T09:05:00.000Z',
baseline_anchor_at: '2026-04-04T08:00:00.000Z',
baseline_status: 'active',
payload: {
current_portfolio_value_eure: '110',
baseline_portfolio_value_eure_at_baseline_price: '100',
baseline_portfolio_value_eure_at_current_price: '105',
},
},
inventorySnapshot: {
ingested_at: '2026-04-04T09:00:00.000Z',
payload: {
synced_at: '2026-04-04T09:00:00.000Z',
reconciliation_status: 'ok',
spendable: {
[config.tradingBtc.assetId]: '100000000',
[config.tradingEure.assetId]: '1000000000000000000',
},
pending_inbound: {
[config.tradingBtc.assetId]: '0',
[config.tradingEure.assetId]: '0',
},
pending_outbound: {
[config.tradingBtc.assetId]: '0',
[config.tradingEure.assetId]: '0',
},
},
},
marketPrice: {
ingested_at: '2026-04-04T09:00:00.000Z',
payload: {
observed_at: '2026-04-04T09:00:00.000Z',
eure_per_btc: '100',
},
},
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 0,
total_pages: 1,
items: [],
},
submissionSummary: {
total: 1,
last_submission_at: '2026-04-04T09:30:00.000Z',
},
fundingObservations: [
{
payload: {
funding_observation_id: 'fund-1',
asset_id: config.tradingBtc.assetId,
chain: config.tradingBtc.chain,
funding_handle: 'btc-address',
tx_hash: 'tx-1',
status: 'CREDITED',
amount: '100000000',
confirmations: 3,
first_seen_at: '2026-04-04T07:30:00.000Z',
last_seen_at: '2026-04-04T07:40:00.000Z',
credited_at: '2026-04-04T07:45:00.000Z',
},
},
],
recentTradeDecisions: [
{
observed_at: '2026-04-04T09:10:00.000Z',
ingested_at: '2026-04-04T09:10:01.000Z',
payload: {
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
decision: 'rejected',
decision_reason: 'strategy_disarmed',
},
},
],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'liquidity-manager',
label: 'Liquidity Manager',
base_url: 'http://liquidity-manager',
reachable: true,
health: { ok: true },
state: {
paused: false,
funding_observer_paused: false,
withdrawals_frozen: true,
withdrawal_defaults: {
[config.tradingBtc.assetId]: 'btc-destination',
},
deposit_addresses: {
[config.tradingBtc.chain]: {
address: 'btc-address',
refreshed_at: '2026-04-04T09:00:00.000Z',
},
},
tracked_withdrawals: {},
},
},
{
service: 'ops-sentinel',
label: 'Ops Sentinel',
base_url: 'http://ops-sentinel',
reachable: true,
health: { ok: true },
state: {
active_alerts: [],
recent_transitions: [],
},
},
{
service: 'strategy-engine',
label: 'Strategy Engine',
base_url: 'http://strategy-engine',
reachable: true,
health: { ok: true },
state: {
armed: true,
paused: false,
threshold_pct: 2,
max_notional_eure: 5,
latest_decision: {
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
decision: 'rejected',
decision_reason: 'strategy_disarmed',
},
recent_decisions: [{
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
decision: 'rejected',
decision_reason: 'strategy_disarmed',
}],
skipped_counts: {},
},
},
{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: {
armed: true,
paused: false,
draining: false,
in_flight_count: 0,
submitted_count: 1,
},
},
{
service: 'history-writer',
label: 'History Writer',
base_url: 'http://history-writer',
reachable: true,
health: { ok: true },
state: {
database_connectivity: true,
offsets: {},
},
},
],
});
assert.equal(bootstrap.default_page, 'funds');
assert.equal(bootstrap.funds.profitability.computed_at, '2026-04-04T09:05:00.000Z');
assert.equal(bootstrap.funds.profitability.last_submission_at, '2026-04-04T09:30:00.000Z');
assert.equal(bootstrap.funds.funding.control_state.withdrawals_frozen, true);
assert.equal(bootstrap.funds.funding.handles[0].address, 'btc-address');
assert.deepEqual(bootstrap.funds.recent_submission_terms, []);
assert.deepEqual(bootstrap.funds.submission_ledger.items, []);
assert.equal(bootstrap.status_bar.strategy_armed, true);
assert.equal(bootstrap.status_bar.executor_armed, true);
assert.equal(bootstrap.status_bar.recent_submission_count, 1);
assert.equal(bootstrap.strategy.strategy_state.recent_decisions[0].decision_at, '2026-04-04T09:10:00.000Z');
assert.equal(bootstrap.strategy.strategy_state.recent_decisions[0].decision_reason, 'strategy_disarmed');
assert.equal(bootstrap.strategy.strategy_state.recent_lifecycle_rows[0].lifecycle_state, 'rejected');
assert.equal(bootstrap.strategy.strategy_state.recent_lifecycle_rows[0].reason_code, 'strategy_disarmed');
});
test('bootstrap balances and funding handles distinguish nBTC reserve from legacy BTC', () => {
const config = buildDualBtcConfig();
const bootstrap = buildDashboardBootstrap({
config,
inventorySnapshot: {
ingested_at: '2026-05-07T13:45:00.000Z',
payload: {
synced_at: '2026-05-07T13:45:00.000Z',
reconciliation_status: 'ok',
spendable: {
[config.tradingBtc.assetId]: '100000',
'nep141:btc.omft.near': '201051',
[config.tradingEure.assetId]: '0',
},
pending_inbound: {},
pending_outbound: {},
},
},
marketPrice: {
payload: {
observed_at: '2026-05-07T13:45:00.000Z',
eure_per_btc: '50000',
},
},
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0 },
fundingObservations: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentAlertTransitions: [],
serviceSnapshots: [{
service: 'liquidity-manager',
state: {
withdrawals_frozen: true,
deposit_addresses: {
'btc:mainnet': {
address: 'bc1qdeposit',
refreshed_at: '2026-05-07T13:44:00.000Z',
},
},
},
}],
});
assert.deepEqual(bootstrap.funds.balances.items.map((item) => item.label), [
'BTC / nBTC reserve',
'BTC / legacy OMFT',
'EURe',
]);
assert.deepEqual(bootstrap.funds.funding.handles[0].asset_ids, [
'nep141:nbtc.bridge.near',
'nep141:btc.omft.near',
]);
assert.equal(bootstrap.funds.funding.handles[0].label, 'btc:mainnet funding handle');
assert.equal(
bootstrap.strategy.asset_catalog.items.find((item) => item.asset_id === 'nep141:nbtc.bridge.near').deposit_address,
'bc1qdeposit',
);
assert.equal(
bootstrap.strategy.asset_catalog.items.find((item) => item.asset_id === 'nep141:btc.omft.near').deposit_address,
'bc1qdeposit',
);
});
test('bootstrap balances exclude imported catalog assets that are not inventory-enabled', () => {
const config = buildDualBtcConfig();
const importedOnlyAsset = {
assetId: 'nep141:sol-imported-token.near',
symbol: 'CATALOG',
label: 'Catalog-only token',
decimals: 6,
chain: 'sol',
supported: true,
enabledForInventory: false,
};
config.assetRegistry = new Map([
...config.assetRegistry,
[importedOnlyAsset.assetId, importedOnlyAsset],
]);
const bootstrap = buildDashboardBootstrap({
config,
inventorySnapshot: {
ingested_at: '2026-05-12T19:45:00.000Z',
payload: {
synced_at: '2026-05-12T19:45:00.000Z',
reconciliation_status: 'ok',
spendable: {
[config.tradingBtc.assetId]: '100000',
[importedOnlyAsset.assetId]: '999999',
},
pending_inbound: {},
pending_outbound: {},
},
},
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0 },
fundingObservations: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentAlertTransitions: [],
serviceSnapshots: [],
});
assert.deepEqual(bootstrap.funds.balances.items.map((item) => item.asset_id), [
'nep141:nbtc.bridge.near',
'nep141:btc.omft.near',
'nep141:eure.omft.near',
]);
assert.equal(
bootstrap.strategy.asset_catalog.items.some((item) => item.asset_id === importedOnlyAsset.assetId),
true,
);
});
test('bootstrap balances reuse portfolio metric valuation for tracked USDC', () => {
const config = buildDualBtcConfig();
const usdcAsset = {
assetId: 'nep141:eth-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.omft.near',
symbol: 'USDC',
label: 'USDC',
decimals: 6,
chain: 'eth:1',
enabledForInventory: true,
};
config.trackedAssets = [...config.trackedAssets, usdcAsset];
config.assetRegistry.set(usdcAsset.assetId, usdcAsset);
const bootstrap = buildDashboardBootstrap({
config,
portfolioMetric: {
computed_at: '2026-05-18T15:49:19.436Z',
baseline_anchor_at: '2026-04-02T18:10:43.569Z',
baseline_status: 'active',
payload: {
current_portfolio_value_eure: '344.233277302186441562',
current_inventory: {
valued_assets: [{
asset_id: usdcAsset.assetId,
amount: '366.39517',
value_eure: '314.632199818186441562',
valuation_source: 'btc_usdc_reference',
}],
},
},
},
inventorySnapshot: {
ingested_at: '2026-05-18T15:49:19.000Z',
payload: {
synced_at: '2026-05-18T15:49:19.000Z',
reconciliation_status: 'ok',
spendable: {
[config.tradingBtc.assetId]: '45186',
[config.tradingEure.assetId]: '0',
[usdcAsset.assetId]: '366395170',
},
pending_inbound: {},
pending_outbound: {},
},
},
marketPrice: {
payload: {
observed_at: '2026-05-18T15:49:19.000Z',
eure_per_btc: '65509.40000000',
},
},
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0 },
fundingObservations: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentAlertTransitions: [],
serviceSnapshots: [],
});
const usdcRow = bootstrap.funds.balances.items.find((item) => item.asset_id === usdcAsset.assetId);
assert.equal(usdcRow.spendable, '366.39517');
assert.equal(usdcRow.eur_value_eure, '314.632199818186441562');
assert.equal(usdcRow.eur_value_source, 'btc_usdc_reference');
assert.equal(bootstrap.status_bar.current_total_portfolio_value_eure, '344.233277302186441562');
});
test('bootstrap keeps no-trade counts without shipping non-rendered row payloads', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0 },
fundingObservations: [],
recentTradeDecisions: [{
observed_at: '2026-05-12T19:40:00.000Z',
payload: {
decision_id: 'decision-rejected',
quote_id: 'quote-rejected',
pair: config.activePair,
decision: 'rejected',
decision_reason: 'below_threshold',
raw_solver_payload: Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`field_${index}`, index])),
},
}],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentAlertTransitions: [],
serviceSnapshots: [],
});
const funnel = bootstrap.strategy.strategy_state.trade_funnel;
assert.equal(funnel.no_trade_count, 1);
assert.deepEqual(funnel.no_trade_rows, []);
});
test('bootstrap normalizes actionable decision vocabulary before exposing it to the dashboard', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: { authenticated: true, subject: 'local-operator', mode: 'stub', roles: ['operator'] },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 1,
total_pages: 1,
items: [{
quote_id: 'quote-1',
pair: config.activePair,
observed_at: '2026-04-04T09:10:03.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
decision_reason: 'actionable',
}],
},
submissionSummary: {
total: 1,
last_submission_at: '2026-04-04T09:10:03.000Z',
},
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [{
observed_at: '2026-04-04T09:10:00.000Z',
payload: {
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
decision: 'actionable',
decision_reason: 'actionable',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-04-04T09:10:01.000Z',
command_id: 'cmd-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
}],
recentExecutionResults: [{
command_id: 'cmd-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: config.activePair,
result_at: '2026-04-04T09:10:03.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
}],
recentAlertTransitions: [],
serviceSnapshots: [],
});
assert.equal(bootstrap.funds.submission_ledger.items[0].decision_reason, 'strategy_approved');
assert.equal(bootstrap.strategy.strategy_state.recent_decisions[0].decision, 'approved');
assert.equal(bootstrap.strategy.strategy_state.recent_lifecycle_rows[0].reason_code, 'quote_response_ok');
assert.equal(bootstrap.strategy.strategy_state.trade_funnel.successful_trade_count, 0);
assert.equal(bootstrap.strategy.strategy_state.trade_funnel.unresolved_submission_count, 1);
assert.equal(bootstrap.strategy.strategy_state.trade_funnel.counts.submitted, 1);
assert.match(bootstrap.strategy.strategy_state.trade_funnel.caveat, /No quote currently has linked terminal outcome/);
assert.doesNotMatch(JSON.stringify(bootstrap), /Actionable/);
});
test('submitted lifecycle evidence never becomes completed by itself', () => {
const rows = deriveQuoteLifecycleRows({
recentExecutionResults: [
{
command_id: 'cmd-submitted',
quote_id: 'quote-submitted',
result_at: '2026-04-09T09:00:00.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
},
],
});
const completed = rows.filter((row) => row.lifecycle_state === 'completed');
const submitted = rows.filter((row) => row.lifecycle_state === 'submitted');
assert.equal(completed.length, 0);
assert.equal(submitted.length, 1);
assert.equal(submitted[0].quote_id, 'quote-submitted');
assert.equal(submitted[0].has_settlement_evidence, false);
assert.doesNotMatch(`${submitted[0].lifecycle_label} ${submitted[0].reason_text}`, /completed|successful trade|asset delta/i);
});
test('quote lifecycle recency is anchored to quote or submission time, not later outcome recompute', () => {
const rows = deriveQuoteLifecycleRows({
recentTradeDecisions: [{
observed_at: '2026-04-13T22:33:18.000Z',
payload: {
decision_id: 'decision-current',
quote_id: 'quote-current',
pair: 'btc->eure',
decision: 'actionable',
decision_reason: 'actionable',
gross_edge_pct: '0.490000',
},
}],
recentExecutionResults: [{
command_id: 'cmd-current',
decision_id: 'decision-current',
quote_id: 'quote-current',
pair: 'btc->eure',
result_at: '2026-04-13T22:33:19.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
}],
recentQuoteOutcomes: [{
command_id: 'cmd-old',
decision_id: 'decision-old',
quote_id: 'quote-old-two-percent',
pair: 'btc->eure',
gross_edge_pct: '2.000000',
eure_notional: '75.58',
submitted_at: '2026-04-09T23:36:35.566Z',
command_at: '2026-04-09T23:36:35.352Z',
outcome_status: 'not_filled',
outcome_reason: 'deadline_elapsed_without_settlement',
outcome_observed_at: '2026-04-13T22:35:33.295Z',
outcome_source: 'submission_deadline_and_inventory_snapshots',
attribution_status: 'unattributed',
attributed_inventory_delta: null,
}],
limit: null,
});
assert.equal(rows[0].quote_id, 'quote-current');
assert.equal(rows[0].gross_edge_pct, '0.490000');
const oldRow = rows.find((row) => row.quote_id === 'quote-old-two-percent');
assert.equal(oldRow.quote_activity_at, '2026-04-09T23:36:35.352Z');
assert.equal(oldRow.latest_stage_at, '2026-04-13T22:35:33.295Z');
assert.equal(oldRow.lifecycle_state, 'not_filled');
});
test('successful trade rows require completed outcome with linked settled inventory evidence', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [{
command_id: 'cmd-submitted',
quote_id: 'quote-submitted',
result_at: '2026-04-09T09:00:00.000Z',
status: 'submitted',
result_code: 'quote_response_ok',
}],
recentQuoteOutcomes: [
{
command_id: 'cmd-completed',
quote_id: 'quote-completed',
pair: config.activePair,
gross_edge_pct: '0.49',
eure_notional: '50',
outcome_status: 'completed',
outcome_reason: 'matched_inventory_delta',
outcome_observed_at: '2026-04-09T09:01:00.000Z',
outcome_source: 'intent_inventory_spendable_delta',
attribution_status: 'heuristic_match',
attribution_method: 'exact_asset_delta_within_window',
attributed_inventory_delta: {
observed_at: '2026-04-09T09:01:00.000Z',
delta_units: {
[config.tradingBtc.assetId]: '37014',
[config.tradingEure.assetId]: '-21000021200021200022',
},
},
},
{
command_id: 'cmd-completed-no-delta',
quote_id: 'quote-completed-no-delta',
pair: config.activePair,
gross_edge_pct: '99',
eure_notional: '100',
outcome_status: 'completed',
outcome_reason: 'settled',
outcome_observed_at: '2026-04-09T09:02:00.000Z',
outcome_source: 'venue_status_without_settlement',
attribution_status: 'unattributed',
attribution_method: null,
attributed_inventory_delta: null,
},
],
recentAlertTransitions: [],
serviceSnapshots: [],
});
const funnel = bootstrap.strategy.strategy_state.trade_funnel;
assert.equal(funnel.successful_trade_count, 1);
assert.equal(funnel.successful_trades[0].quote_id, 'quote-completed');
assert.equal(funnel.successful_trade_gross_edge_estimate_eure, '0.245');
assert.equal(funnel.successful_trade_gross_edge_estimate_count, 1);
assert.match(funnel.successful_trades[0].settlement_summary.text, /\+0\.00037014 BTC/);
assert.equal(funnel.counts.submitted, 1);
assert.equal(funnel.counts.completed, 2);
});
test('executor blocking is distinct from strategy rejection', () => {
const [row] = deriveQuoteLifecycleRows({
recentTradeDecisions: [{
observed_at: '2026-04-09T09:00:01.000Z',
payload: {
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
decision: 'actionable',
decision_reason: 'actionable',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-04-09T09:00:02.000Z',
command_id: 'cmd-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
}],
recentExecutionResults: [{
command_id: 'cmd-1',
decision_id: 'decision-1',
quote_id: 'quote-1',
pair: 'btc->eure',
result_at: '2026-04-09T09:00:03.000Z',
status: 'rejected',
result_code: 'executor_disarmed',
note: 'executor is disarmed',
}],
});
assert.equal(row.lifecycle_state, 'blocked');
assert.equal(row.lifecycle_label, 'Blocked before submit');
assert.equal(row.reason_code, 'executor_disarmed');
assert.notEqual(row.lifecycle_label, 'Rejected by strategy');
});
test('system service state ignores sentinel alert severity and keeps alert surfaces empty', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 0,
total_pages: 1,
items: [],
},
submissionSummary: {
total: 0,
last_submission_at: null,
},
fundingObservations: [],
recentTradeDecisions: [],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'near-intents-ingest',
label: 'Intents Ingest',
base_url: 'http://near-intents-ingest',
reachable: true,
health: { ok: true },
state: {
ingest: {
connected: true,
last_message_at: '2026-04-04T09:00:00.000Z',
last_matching_quote_at: '2026-04-04T09:00:00.000Z',
last_published_at: '2026-04-03T02:12:00.000Z',
},
},
},
{
service: 'ops-sentinel',
label: 'Ops Sentinel',
base_url: 'http://ops-sentinel',
reachable: true,
health: { ok: true },
state: {
active_alerts: [{
alert_code: 'near_intents_publish_stale',
status: 'raised',
severity: 'critical',
reason: 'published quote freshness is stale',
service_scope: 'near-intents-ingest',
pair: config.activePair,
raised_at: '2026-04-04T09:30:00.000Z',
first_raised_at: '2026-04-04T09:30:00.000Z',
cleared_at: null,
last_evaluated_at: '2026-04-04T09:30:00.000Z',
details: {
publish_age_ms: 110_880_000,
},
}],
recent_transitions: [],
service_health: [{
service: 'near-intents-ingest',
status: 'warning',
label: 'no recent quotes',
reachable: true,
paused: false,
armed: null,
health_ok: false,
highest_alert_severity: 'critical',
reasons: ['connected, no recent quotes for active pair'],
freshness_at: '2026-04-03T02:12:00.000Z',
freshness_age_ms: 110_880_000,
}],
},
},
],
});
const ingest = bootstrap.system.service_health.find((service) => service.service === 'near-intents-ingest');
assert.equal(ingest.health_ok, true);
assert.equal(ingest.health_status, 'online');
assert.equal(ingest.health_label, 'online');
assert.deepEqual(ingest.health_reasons, []);
assert.equal(bootstrap.status_bar.highest_alert_severity, null);
assert.deepEqual(bootstrap.system.alerts.active, []);
assert.deepEqual(bootstrap.system.alerts.recent, []);
});
test('ingest disconnected renders as basic reachability state without alert severity', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 0,
total_pages: 1,
items: [],
},
submissionSummary: {
total: 0,
last_submission_at: null,
},
fundingObservations: [],
recentTradeDecisions: [],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'near-intents-ingest',
label: 'Intents Ingest',
base_url: 'http://near-intents-ingest',
reachable: true,
health: { ok: false, connected: false, reason: 'websocket disconnected' },
state: {
ingest: {
connected: false,
last_message_at: '2026-04-04T09:00:00.000Z',
},
},
},
{
service: 'ops-sentinel',
label: 'Ops Sentinel',
base_url: 'http://ops-sentinel',
reachable: true,
health: { ok: true },
state: {
active_alerts: [{
alert_code: 'near_intents_ingest_disconnected',
status: 'raised',
severity: 'critical',
reason: 'websocket disconnected',
service_scope: 'near-intents-ingest',
pair: config.activePair,
raised_at: '2026-04-04T09:30:00.000Z',
first_raised_at: '2026-04-04T09:30:00.000Z',
cleared_at: null,
last_evaluated_at: '2026-04-04T09:30:00.000Z',
details: {},
}],
recent_transitions: [],
service_health: [{
service: 'near-intents-ingest',
status: 'critical',
label: 'disconnected',
reachable: true,
paused: false,
armed: null,
health_ok: false,
highest_alert_severity: 'critical',
reasons: ['websocket disconnected', 'critical alert active (near_intents_ingest_disconnected)'],
freshness_at: '2026-04-04T09:00:00.000Z',
freshness_age_ms: 60_000,
}],
},
},
],
});
const ingest = bootstrap.system.service_health.find((service) => service.service === 'near-intents-ingest');
assert.equal(ingest.health_status, 'reachable');
assert.equal(ingest.health_label, 'reachable');
assert.deepEqual(ingest.health_reasons, []);
});
test('recent alert history remains empty even when sentinel exposes flapping transitions', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 0,
total_pages: 1,
items: [],
},
submissionSummary: {
total: 0,
last_submission_at: null,
},
fundingObservations: [],
recentTradeDecisions: [],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'ops-sentinel',
label: 'Ops Sentinel',
base_url: 'http://ops-sentinel',
reachable: true,
health: { ok: true },
state: {
active_alerts: [],
recent_transitions: [
{
alert_code: 'near_intents_quotes_stale',
status: 'raised',
severity: 'critical',
reason: 'quote truth stale',
service_scope: 'near-intents-ingest',
pair: config.activePair,
raised_at: '2026-04-04T09:33:00.000Z',
first_raised_at: '2026-04-04T09:30:00.000Z',
cleared_at: null,
last_evaluated_at: '2026-04-04T09:33:00.000Z',
details: {},
},
{
alert_code: 'near_intents_quotes_stale',
status: 'cleared',
severity: 'critical',
reason: 'quote truth stale',
service_scope: 'near-intents-ingest',
pair: config.activePair,
raised_at: '2026-04-04T09:31:00.000Z',
first_raised_at: '2026-04-04T09:30:00.000Z',
cleared_at: '2026-04-04T09:32:00.000Z',
last_evaluated_at: '2026-04-04T09:32:00.000Z',
details: {},
},
{
alert_code: 'near_intents_quotes_stale',
status: 'raised',
severity: 'critical',
reason: 'quote truth stale',
service_scope: 'near-intents-ingest',
pair: config.activePair,
raised_at: '2026-04-04T09:31:00.000Z',
first_raised_at: '2026-04-04T09:30:00.000Z',
cleared_at: null,
last_evaluated_at: '2026-04-04T09:31:00.000Z',
details: {},
},
],
},
},
],
});
assert.deepEqual(bootstrap.system.alerts.recent, []);
});
test('funding summary includes credited bridge deposits without observer-backed funding observations', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: {
authenticated: true,
subject: 'local-operator',
mode: 'stub',
roles: ['operator'],
},
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: {
page: 1,
page_size: 20,
total: 0,
total_pages: 1,
items: [],
},
submissionSummary: {
total: 0,
last_submission_at: null,
},
fundingObservations: [],
recentDepositStatuses: [
{
observed_at: null,
ingested_at: '2026-05-07T14:07:23.107Z',
payload: {
action_type: 'deposit_status_observed',
chain: config.tradingEure.chain,
asset_id: config.tradingEure.assetId,
status: 'COMPLETED',
details: {
tx_hash: 'eth-tx-1',
address: '0xdeposit',
amount: '24999999800000000000',
},
},
},
],
recentTradeDecisions: [],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'liquidity-manager',
label: 'Liquidity Manager',
base_url: 'http://liquidity-manager',
reachable: true,
health: { ok: true },
state: {
paused: false,
funding_observer_paused: false,
withdrawals_frozen: true,
withdrawal_defaults: {},
deposit_addresses: {
[config.tradingEure.chain]: {
address: '0xdeposit',
refreshed_at: '2026-04-07T15:20:10.000Z',
},
},
deposits: {
eurDeposit: {
tx_hash: 'eth-tx-1',
chain: config.tradingEure.chain,
asset_id: config.tradingEure.assetId,
amount: '24999999800000000000',
address: '0xdeposit',
status: 'COMPLETED',
created_at: '2026-04-07T15:20:19.909Z',
},
},
tracked_withdrawals: {},
last_refresh_at: '2026-05-07T14:07:23.107Z',
},
},
{
service: 'ops-sentinel',
label: 'Ops Sentinel',
base_url: 'http://ops-sentinel',
reachable: true,
health: { ok: true },
state: {
active_alerts: [],
recent_transitions: [],
},
},
{
service: 'strategy-engine',
label: 'Strategy Engine',
base_url: 'http://strategy-engine',
reachable: true,
health: { ok: true },
state: {
armed: true,
paused: false,
recent_decisions: [],
skipped_counts: {},
},
},
{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: {
armed: true,
paused: false,
draining: false,
in_flight_count: 0,
submitted_count: 0,
},
},
{
service: 'history-writer',
label: 'History Writer',
base_url: 'http://history-writer',
reachable: true,
health: { ok: true },
state: {
database_connectivity: true,
offsets: {},
},
},
],
});
assert.equal(bootstrap.funds.funding.latest_observed_at, '2026-04-07T15:20:19.909Z');
assert.equal(bootstrap.funds.funding.credited_deposits[0].asset_id, config.tradingEure.assetId);
assert.equal(bootstrap.funds.funding.credited_deposits[0].amount, '24.9999998');
assert.equal(bootstrap.funds.funding.recent_observations[0].tx_hash, 'eth-tx-1');
assert.equal(bootstrap.funds.funding.recent_observations[0].last_seen_at, '2026-04-07T15:20:19.909Z');
assert.equal(bootstrap.funds.recent_deposits[0].tx_hash, 'eth-tx-1');
});
test('bootstrap lifecycle rows preserve quote terms, submitted terms, and gross edge estimate', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: { authenticated: true, subject: 'local-operator', mode: 'stub', roles: ['operator'] },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [{
quote_id: 'quote-terms-1',
pair: config.activePair,
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
request_kind: 'exact_in',
amount_in: '123208',
amount_out: null,
observed_at: '2026-04-09T09:00:00.000Z',
}],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [{
observed_at: '2026-04-09T09:00:01.000Z',
payload: {
decision_id: 'decision-terms-1',
quote_id: 'quote-terms-1',
pair: config.activePair,
decision: 'actionable',
decision_reason: 'actionable',
gross_edge_pct: '1.5',
inventory_asset: config.tradingEure.assetId,
inventory_required: '76000000000000000000',
inventory_spendable: '80000000000000000000',
inventory_pending_outbound: '1000000000000000000',
inventory_available: '79000000000000000000',
eure_notional: '100',
},
}],
recentExecuteTradeCommands: [{
observed_at: '2026-04-09T09:00:02.000Z',
payload: {
command_id: 'cmd-terms-1',
decision_id: 'decision-terms-1',
quote_id: 'quote-terms-1',
pair: config.activePair,
request_kind: 'exact_in',
asset_in: config.tradingBtc.assetId,
asset_out: config.tradingEure.assetId,
amount_in: '123208',
amount_out: '76000000000000000000',
},
}],
recentExecutionResults: [],
recentQuoteOutcomes: [],
recentAlertTransitions: [],
serviceSnapshots: [],
});
const row = bootstrap.strategy.strategy_state.recent_lifecycle_rows[0];
assert.equal(row.quote_id, 'quote-terms-1');
assert.equal(row.request_terms.amount_in, '0.00123208');
assert.equal(row.request_terms.asset_in_symbol, 'BTC');
assert.equal(row.submitted_terms.amount_out, '76');
assert.equal(row.submitted_terms.asset_out_symbol, 'EURe');
assert.equal(row.maker_terms.send_amount, '76');
assert.equal(row.maker_terms.send_asset_symbol, 'EURe');
assert.equal(row.maker_terms.receive_amount, '0.00123208');
assert.equal(row.maker_terms.receive_asset_symbol, 'BTC');
assert.equal(row.maker_terms.delta_text, '-76 EURe / +0.00123208 BTC');
assert.equal(row.inventory_check.required, '76');
assert.equal(row.inventory_check.available, '79');
assert.equal(row.inventory_check.spendable, '80');
assert.equal(row.inventory_check.pending_outbound, '1');
assert.equal(row.gross_edge_value_eure, '1.5');
});
test('own request dashboard rows do not label relay accepted evidence as completed trade', () => {
const config = buildConfig();
const bootstrap = buildDashboardBootstrap({
config,
auth: { authenticated: true, subject: 'local-operator', mode: 'stub', roles: ['operator'] },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentQuoteOutcomes: [],
recentIntentRequests: [{
request_id: 'request-accepted-only',
idempotency_key: 'idem-accepted-only',
submission_id: 'submission-accepted-only',
intent_hash: 'intent-hash-accepted-only',
quote_hash: 'quote-hash-accepted-only',
created_at: '2026-04-12T10:00:00.000Z',
submitted_at: '2026-04-12T10:00:01.000Z',
state: 'awaiting_settlement',
state_label: 'Awaiting settlement',
reason_code: 'accepted_by_relay_without_settlement',
reason_text: 'Relay accepted the signed request. This is not settlement.',
source_asset_id: config.tradingEure.assetId,
source_symbol: 'EURe',
source_decimals: 18,
destination_asset_id: config.tradingBtc.assetId,
destination_symbol: 'BTC',
destination_decimals: 8,
source_amount_units: '5000000000000000000',
expected_destination_amount_units: '10000',
min_destination_amount_units: '9800',
quoted_destination_amount_units: '10000',
slippage_bps: 200,
submission_status: 'accepted_by_relay',
relay_status: 'PENDING',
outcome_status: 'awaiting_settlement',
attribution_status: 'unattributed',
attribution_method: null,
attributed_inventory_delta: null,
has_settlement_evidence: false,
live_submit_capable: false,
lifecycle: {
preflight: { state: 'draft' },
submission: { status: 'accepted_by_relay' },
outcome: { outcome_status: 'awaiting_settlement' },
},
}],
recentAlertTransitions: [],
serviceSnapshots: [{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: { armed: true, paused: false },
}],
});
const row = bootstrap.funds.intent_requests.items[0];
assert.equal(row.state, 'awaiting_settlement');
assert.equal(row.state_label, 'Awaiting settlement');
assert.equal(row.submission_status, 'accepted_by_relay');
assert.equal(row.has_settlement_evidence, false);
assert.equal(row.settlement_summary.text, 'No settled inventory delta is linked to this request.');
assert.doesNotMatch(
[row.state_label, row.reason_text, row.settlement_summary.text].join(' '),
/successful trade|completed trade|asset delta/i,
);
});
test('dashboard surfaces NEAR upstream disruption without calling submitted work completed', () => {
const config = buildConfig();
const nearIntentsStatus = {
source: 'near_intents_status_page',
status: 'disrupted',
label: 'upstream paused',
observed_at: '2026-04-16T12:40:00.000Z',
decisive_reason: '1Click Quoting is temporarily stopped: The protocol is paused.',
current_incident_count: 1,
affected_services: ['Cross-Chain Bridging'],
quoting_stopped: true,
};
const dashboard = buildDashboardBootstrap({
config,
auth: { authenticated: true },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [{
command_id: 'cmd-submitted',
decision_id: 'decision-submitted',
quote_id: 'quote-submitted',
status: 'submitted',
result_code: 'quote_response_ok',
}],
recentQuoteOutcomes: [],
recentIntentRequests: [],
recentAlertTransitions: [],
nearIntentsStatus,
serviceSnapshots: [
{
service: 'near-intents-ingest',
label: 'NEAR Intents Ingest',
base_url: 'http://near-intents-ingest',
reachable: true,
health: { ok: true },
state: { ingest: { connected: false, last_message_at: null } },
},
{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: { relay: { connected: false } },
},
{
service: 'history-writer',
label: 'History Writer',
base_url: 'http://history-writer',
reachable: true,
health: { ok: true },
state: {},
},
],
});
assert.equal(dashboard.status_bar.near_intents_upstream_status, 'disrupted');
assert.equal(dashboard.status_bar.near_intents_upstream_label, 'upstream paused');
assert.match(dashboard.status_bar.near_intents_upstream_reason, /protocol is paused/);
const services = Object.fromEntries(
dashboard.system.service_health.map((service) => [service.service, service]),
);
assert.equal(services['near-intents-ingest'].health_status, 'upstream_paused');
assert.equal(services['near-intents-ingest'].health_label, 'upstream paused');
assert.equal(services['near-intents-ingest'].health_ok, false);
assert.match(services['near-intents-ingest'].health_reasons[0], /1Click Quoting/);
assert.equal(services['near-intents-ingest'].upstream_status.status, 'disrupted');
assert.equal(services['trade-executor'].health_status, 'upstream_paused');
assert.equal(services['trade-executor'].upstream_status.quoting_stopped, true);
assert.equal(services['history-writer'].health_status, 'online');
assert.equal(services['history-writer'].upstream_status, null);
});
test('dashboard does not pause relay services for unrelated destination-chain incident', () => {
const config = buildConfig();
const nearIntentsStatus = {
source: 'near_intents_status_page',
status: 'operational',
label: 'operational',
observed_at: '2026-05-07T15:55:00.000Z',
decisive_reason: 'NEAR Intents status page has 1 active incident(s), but none match this deployment scope.',
current_incident_count: 0,
affected_services: [],
observed_incident_count: 1,
observed_affected_services: ['Other Blockchains'],
unrelated_incident_count: 1,
quoting_stopped: false,
};
const dashboard = buildDashboardBootstrap({
config,
auth: { authenticated: true },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentQuoteOutcomes: [],
recentIntentRequests: [],
recentAlertTransitions: [],
nearIntentsStatus,
serviceSnapshots: [
{
service: 'near-intents-ingest',
label: 'NEAR Intents Ingest',
base_url: 'http://near-intents-ingest',
reachable: true,
health: { ok: true },
state: { ingest: { connected: true, last_message_at: '2026-05-07T15:54:59.000Z' } },
},
{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: { relay: { connected: true, last_message_at: '2026-05-07T15:54:59.000Z' } },
},
],
});
assert.equal(dashboard.status_bar.near_intents_upstream_status, 'operational');
assert.match(dashboard.status_bar.near_intents_upstream_reason, /none match this deployment scope/);
const services = Object.fromEntries(
dashboard.system.service_health.map((service) => [service.service, service]),
);
assert.equal(services['near-intents-ingest'].health_status, 'online');
assert.equal(services['near-intents-ingest'].health_label, 'online');
assert.equal(services['near-intents-ingest'].health_ok, true);
assert.equal(services['trade-executor'].health_status, 'online');
assert.equal(services['trade-executor'].health_label, 'online');
assert.equal(services['trade-executor'].upstream_status.status, 'operational');
assert.equal(services['trade-executor'].upstream_status.unrelated_incident_count, 1);
});
test('dashboard service summary exposes executor salt cache and queue delay truth', () => {
const config = buildConfig();
const dashboard = buildDashboardBootstrap({
config,
auth: { authenticated: true },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentQuoteOutcomes: [],
recentIntentRequests: [],
recentAlertTransitions: [],
serviceSnapshots: [
{
service: 'trade-executor',
label: 'Trade Executor',
base_url: 'http://trade-executor',
reachable: true,
health: { ok: true },
state: {
relay: { connected: true, last_message_at: '2026-06-12T10:00:00.000Z' },
verifier_salt_cache: {
configured: true,
has_cached_salt: true,
salt_fresh: true,
salt_age_ms: 42,
last_refresh_completed_at: '2026-06-12T09:59:59.950Z',
last_refresh_duration_ms: 25,
refresh_in_flight: false,
},
executor_queue_delay: {
status: 'warning',
latest_ms: 25,
max_ms: 1_250,
p90_ms: 1_250,
p99_ms: 1_250,
},
salt_unavailable_reject_count: 1,
last_salt_unavailable_at: '2026-06-12T09:59:00.000Z',
},
},
],
});
const executor = dashboard.system.service_health.find((service) => service.service === 'trade-executor');
assert.equal(executor.summary.verifier_salt_cache.salt_fresh, true);
assert.equal(executor.summary.verifier_salt_cache.salt_age_ms, 42);
assert.equal(executor.summary.executor_queue_delay.status, 'warning');
assert.equal(executor.summary.executor_queue_delay.max_ms, 1_250);
assert.equal(executor.summary.salt_unavailable_reject_count, 1);
});
test('bootstrap exposes deduped environment status history as environmental conditions', () => {
const config = buildConfig();
const dashboard = buildDashboardBootstrap({
config,
auth: { authenticated: true },
portfolioMetric: null,
inventorySnapshot: null,
marketPrice: null,
recentQuotes: [],
submissionPage: { page: 1, page_size: 20, total: 0, total_pages: 1, items: [] },
submissionSummary: { total: 0, last_submission_at: null },
fundingObservations: [],
recentDepositStatuses: [],
recentTradeDecisions: [],
recentExecuteTradeCommands: [],
recentExecutionResults: [],
recentQuoteOutcomes: [],
recentIntentRequests: [],
recentAlertTransitions: [],
recentEnvironmentStatuses: [{
observed_at: '2026-04-16T12:40:00.000Z',
ingested_at: '2026-04-16T12:40:01.000Z',
payload: {
environment_status_id: 'env-1',
environment_key: 'near_intents_status_page',
status: 'disrupted',
label: 'upstream paused',
status_fingerprint: 'fp-1',
observed_at: '2026-04-16T12:40:00.000Z',
changed_at: '2026-04-16T12:40:00.000Z',
decisive_reason: '1Click quoting paused.',
},
}],
serviceSnapshots: [
{
service: 'near-intents-ingest',
label: 'NEAR Intents Ingest',
base_url: 'http://near-intents-ingest',
reachable: true,
health: { ok: true },
state: {},
},
{
service: 'history-writer',
label: 'History Writer',
base_url: 'http://history-writer',
reachable: true,
health: { ok: true },
state: {
last_environment_status_write_at: '2026-04-16T12:40:01.000Z',
last_environment_status_duplicate_at: '2026-04-16T12:41:01.000Z',
},
},
],
});
assert.equal(dashboard.status_bar.near_intents_upstream_label, 'upstream paused');
assert.equal(dashboard.system.environment_status.current.status_fingerprint, 'fp-1');
assert.equal(dashboard.system.environment_status.recent_changes.length, 1);
assert.equal(dashboard.system.persistence.last_environment_status_write_at, '2026-04-16T12:40:01.000Z');
assert.equal(dashboard.system.persistence.last_environment_status_duplicate_at, '2026-04-16T12:41:01.000Z');
});
test('live environment status updates status bar and dashboard history without refresh', () => {
const config = buildConfig();
const state = createDashboardLiveState({ config });
const updates = applyDashboardLiveEvent(state, {
topic: config.kafkaTopicOpsEnvironmentStatus,
event: {
observed_at: '2026-04-16T12:40:00.000Z',
ingested_at: '2026-04-16T12:40:01.000Z',
payload: {
environment_status_id: 'env-live-1',
environment_key: 'near_intents_status_page',
status: 'disrupted',
label: 'upstream paused',
status_fingerprint: 'fp-live-1',
observed_at: '2026-04-16T12:40:00.000Z',
changed_at: '2026-04-16T12:40:00.000Z',
decisive_reason: '1Click quoting paused.',
},
},
});
assert.equal(updates[0].type, 'status_bar.updated');
assert.equal(updates[0].status_bar.near_intents_upstream_label, 'upstream paused');
assert.equal(updates[1].type, 'environment_status.updated');
assert.equal(updates[1].environment_status.payload.status_fingerprint, 'fp-live-1');
const dashboard = {
funds: { profitability: {} },
status_bar: {},
system: { environment_status: { recent_changes: [] } },
};
const reduced = dashboardReducer({ dashboard, session: { authenticated: true } }, {
type: 'socket.message.received',
payload: updates[1],
});
assert.equal(reduced.dashboard.system.environment_status.current.status_fingerprint, 'fp-live-1');
assert.equal(reduced.dashboard.system.environment_status.recent_changes.length, 1);
});