pandora-cli-skills 1.1.42 → 1.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +19 -0
  2. package/README_FOR_SHARING.md +21 -0
  3. package/SKILL.md +34 -5
  4. package/cli/lib/arb_command_service.cjs +239 -17
  5. package/cli/lib/arbitrage_service.cjs +187 -3
  6. package/cli/lib/brier_score_service.cjs +271 -0
  7. package/cli/lib/command_executor_service.cjs +6 -1
  8. package/cli/lib/command_router.cjs +6 -0
  9. package/cli/lib/error_recovery_service.cjs +155 -0
  10. package/cli/lib/forecast_store.cjs +361 -0
  11. package/cli/lib/lifecycle_command_service.cjs +42 -4
  12. package/cli/lib/mcp_tool_registry.cjs +58 -1
  13. package/cli/lib/mirror_command_service.cjs +3 -3
  14. package/cli/lib/mirror_econ_service.cjs +409 -1
  15. package/cli/lib/mirror_handlers/deploy.cjs +2 -2
  16. package/cli/lib/mirror_handlers/simulate.cjs +1 -1
  17. package/cli/lib/model_command_service.cjs +99 -0
  18. package/cli/lib/model_diagnose_service.cjs +204 -0
  19. package/cli/lib/model_handlers/calibrate.cjs +233 -0
  20. package/cli/lib/model_handlers/correlation.cjs +458 -0
  21. package/cli/lib/model_handlers/diagnose.cjs +47 -0
  22. package/cli/lib/model_handlers/score_brier.cjs +119 -0
  23. package/cli/lib/model_store.cjs +292 -0
  24. package/cli/lib/odds_command_service.cjs +168 -0
  25. package/cli/lib/pandora_deploy_service.cjs +4 -2
  26. package/cli/lib/parsers/mirror_deploy_flags.cjs +7 -2
  27. package/cli/lib/parsers/mirror_go_flags.cjs +7 -2
  28. package/cli/lib/parsers/mirror_hedge_calc_flags.cjs +7 -2
  29. package/cli/lib/parsers/mirror_remaining_flags.cjs +64 -2
  30. package/cli/lib/parsers/model_flags.cjs +446 -0
  31. package/cli/lib/parsers/odds_flags.cjs +19 -0
  32. package/cli/lib/parsers/simulate_flags.cjs +310 -0
  33. package/cli/lib/parsers/watch_flags.cjs +64 -0
  34. package/cli/lib/quant/abm_market.cjs +282 -0
  35. package/cli/lib/quant/copula.cjs +407 -0
  36. package/cli/lib/quant/importance_sampling.cjs +224 -0
  37. package/cli/lib/quant/mc_stats.cjs +186 -0
  38. package/cli/lib/quant/particle_filter.cjs +305 -0
  39. package/cli/lib/quant/rng.cjs +214 -0
  40. package/cli/lib/quant/variance_reduction.cjs +156 -0
  41. package/cli/lib/schema_command_service.cjs +279 -1
  42. package/cli/lib/shared/constants.cjs +6 -0
  43. package/cli/lib/simulate_command_service.cjs +140 -0
  44. package/cli/lib/simulate_handlers/agents.cjs +194 -0
  45. package/cli/lib/simulate_handlers/common.cjs +361 -0
  46. package/cli/lib/simulate_handlers/mc.cjs +212 -0
  47. package/cli/lib/simulate_handlers/particle_filter.cjs +370 -0
  48. package/cli/lib/sports_model_input_service.cjs +29 -0
  49. package/cli/lib/watch_command_service.cjs +114 -0
  50. package/cli/pandora.cjs +168 -143
  51. package/package.json +2 -2
  52. package/references/creation-script.md +1 -1
  53. package/tests/cli/cli.integration.test.cjs +588 -2
  54. package/tests/cli/mcp.integration.test.cjs +176 -0
  55. package/tests/unit/abm_market.test.cjs +226 -0
  56. package/tests/unit/brier_scoring.test.cjs +74 -0
  57. package/tests/unit/brier_watch_command.test.cjs +121 -0
  58. package/tests/unit/combinatorial_arb.test.cjs +171 -0
  59. package/tests/unit/mirror_simulate_mc.test.cjs +152 -0
  60. package/tests/unit/model_calibrate.test.cjs +142 -0
  61. package/tests/unit/model_correlation.test.cjs +147 -0
  62. package/tests/unit/model_diagnose.test.cjs +83 -0
  63. package/tests/unit/new-features.test.cjs +82 -0
  64. package/tests/unit/quant_core.test.cjs +104 -0
  65. package/tests/unit/quant_models.test.cjs +85 -0
  66. package/tests/unit/quant_stores.test.cjs +134 -0
  67. package/tests/unit/simulate_command_service.test.cjs +91 -0
  68. package/tests/unit/simulate_flags.test.cjs +185 -0
  69. package/tests/unit/simulate_handlers.test.cjs +103 -0
package/README.md CHANGED
@@ -130,6 +130,25 @@ pandora --output json lifecycle resolve --id <lifecycle-id> --confirm
130
130
  - `pandora schema`
131
131
  - `pandora mcp`
132
132
 
133
+ ## Quant ABM Baseline (Module Contract)
134
+
135
+ - Deterministic ABM engine: `cli/lib/quant/abm_market.cjs`.
136
+ - Simulate-agents handler module: `cli/lib/simulate_handlers/agents.cjs`.
137
+ - Supported handler flags:
138
+ - `--n-informed` or `--n_informed`
139
+ - `--n-noise` or `--n_noise`
140
+ - `--n-mm` or `--n_mm`
141
+ - `--n-steps` or `--n_steps`
142
+ - `--seed`
143
+ - ABM payload fields include:
144
+ - `convergenceError`
145
+ - `spreadTrajectory[]`
146
+ - `volume` (`total`, `averagePerStep`, `byAgentType`)
147
+ - `pnlByAgentType`
148
+ - `runtimeBounds` (`complexity`, `estimatedAgentDecisions`, `estimatedWorkUnits`)
149
+ - Runtime bound metadata is documented as `O(n_steps * (n_informed + n_noise))`.
150
+ - Unit coverage for this baseline is in `tests/unit/abm_market.test.cjs`.
151
+
133
152
  ## Docs
134
153
 
135
154
  - Full command contract and workflows: [`SKILL.md`](./SKILL.md)
@@ -136,6 +136,27 @@ Prerequisite: Node.js `>=18`.
136
136
  - `pandora resolve`
137
137
  - `pandora lp add|remove|positions`
138
138
 
139
+ ## Quant ABM baseline (current implementation)
140
+ - Deterministic ABM engine module:
141
+ - `cli/lib/quant/abm_market.cjs`
142
+ - Simulate-agents handler module:
143
+ - `cli/lib/simulate_handlers/agents.cjs`
144
+ - Handler parser accepts:
145
+ - `--n-informed|--n_informed`
146
+ - `--n-noise|--n_noise`
147
+ - `--n-mm|--n_mm`
148
+ - `--n-steps|--n_steps`
149
+ - `--seed`
150
+ - ABM output fields include:
151
+ - `convergenceError`
152
+ - `spreadTrajectory[]`
153
+ - `volume` (`total`, `averagePerStep`, `byAgentType`)
154
+ - `pnlByAgentType`
155
+ - `runtimeBounds` with complexity `O(n_steps * (n_informed + n_noise))`
156
+ - Coverage notes:
157
+ - `tests/unit/abm_market.test.cjs` validates deterministic seed behavior, required ABM metrics, parser/handler behavior, and runtime-bound calculations.
158
+ - `package.json` `test:unit` includes the ABM suite in default unit execution.
159
+
139
160
  ## Agent-native expansion details
140
161
 
141
162
  ### MCP server (`pandora mcp`)
package/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: pandora-cli-skills
3
3
  summary: Canonical skill and operator guide for Pandora CLI including mirror, polymarket, resolve, and LP flows.
4
- version: 1.1.42
4
+ version: 1.1.44
5
5
  ---
6
6
 
7
7
  # Pandora CLI & Skills
@@ -80,6 +80,29 @@ npm link
80
80
  - `max_daily_loss_usd` is enforced as daily live notional (`counters.liveNotionalUsdc`).
81
81
  - `max_open_markets` is enforced as daily live operation count (`counters.liveOps`).
82
82
 
83
+ ## Quant ABM baseline (module contract)
84
+ - Deterministic ABM core:
85
+ - `cli/lib/quant/abm_market.cjs`
86
+ - Simulate-agents handler:
87
+ - `cli/lib/simulate_handlers/agents.cjs`
88
+ - Handler flags:
89
+ - `--n-informed|--n_informed`
90
+ - `--n-noise|--n_noise`
91
+ - `--n-mm|--n_mm`
92
+ - `--n-steps|--n_steps`
93
+ - `--seed`
94
+ - ABM payload fields:
95
+ - `convergenceError`
96
+ - `spreadTrajectory[]`
97
+ - `volume` (`total`, `averagePerStep`, `byAgentType`)
98
+ - `pnlByAgentType`
99
+ - `runtimeBounds` (`complexity`, `estimatedAgentDecisions`, `estimatedWorkUnits`)
100
+ - Runtime complexity metadata: `O(n_steps * (n_informed + n_noise))`.
101
+ - Unit coverage:
102
+ - `tests/unit/abm_market.test.cjs`
103
+ - Note:
104
+ - This section documents the current module + handler contract. Top-level simulate namespace routing can consume this handler when wired by command service.
105
+
83
106
  ## Complete command + flag reference (authoritative)
84
107
  This section mirrors live CLI help output so agent runs can rely on one source of truth.
85
108
 
@@ -93,7 +116,7 @@ pandora [--output table|json] markets list [--limit <n>] [--after <cursor>] [--b
93
116
  pandora [--output table|json] markets get [--id <id> ...] [--stdin]
94
117
  pandora [--output table|json] sports books list|events list|events live|odds snapshot|odds bulk|consensus|create plan|create run|sync once|sync run|sync start|sync stop|sync status|resolve plan [flags]
95
118
  pandora [--output table|json] lifecycle start --config <path>|status --id <id>|resolve --id <id> --confirm
96
- pandora arb scan --markets <csv> --output ndjson [--min-net-spread-pct <n>] [--fee-pct-per-leg <n>] [--amount-usdc <n>] [--iterations <n>] [--interval-ms <ms>]
119
+ pandora arb scan --markets <csv> --output ndjson|json [--min-net-spread-pct <n>] [--fee-pct-per-leg <n>] [--amount-usdc <n>] [--iterations <n>] [--interval-ms <ms>]
97
120
  pandora [--output table|json] odds record --competition <id> --interval <sec> [--max-samples <n>] [--event-id <id>] [--venues pandora_amm,polymarket]
98
121
  pandora [--output table|json] odds history --event-id <id> --output csv|json [--limit <n>]
99
122
  pandora [--output table|json] polls list [--limit <n>] [--after <cursor>] [--before <cursor>] [--order-by <field>] [--order-direction asc|desc] [--chain-id <id>] [--creator <address>] [--status <int>] [--category <int>] [--question-contains <text>] [--where-json <json>]
@@ -131,12 +154,12 @@ Mirror subcommand detail:
131
154
  ```text
132
155
  browse --min-yes-pct <n> --max-yes-pct <n> --min-volume-24h <n> [--closes-after <date>] [--closes-before <date>] [--question-contains <text>] [--limit <n>] [--chain-id <id>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>]
133
156
  plan --source polymarket --polymarket-market-id <id>|--polymarket-slug <slug> [--chain-id <id>] [--target-slippage-bps <n>] [--turnover-target <n>] [--depth-slippage-bps <n>] [--safety-multiplier <n>] [--min-liquidity-usdc <n>] [--max-liquidity-usdc <n>] [--with-rules] [--include-similarity] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>]
134
- deploy --plan-file <path>|--polymarket-market-id <id>|--polymarket-slug <slug> --dry-run|--execute [--liquidity-usdc <n>] [--fee-tier 500|3000|10000] [--max-imbalance <n>] [--arbiter <address>] [--category <n>] [--chain-id <id>] [--rpc-url <url>] [--private-key <hex>] [--oracle <address>] [--factory <address>] [--usdc <address>] [--distribution-yes <parts>] [--distribution-no <parts>] [--sources <url...>] [--min-close-lead-seconds <n>] [--manifest-file <path>] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>]
157
+ deploy --plan-file <path>|--polymarket-market-id <id>|--polymarket-slug <slug> --dry-run|--execute [--liquidity-usdc <n>] [--fee-tier <500-50000>] [--max-imbalance <n>] [--arbiter <address>] [--category <n>] [--chain-id <id>] [--rpc-url <url>] [--private-key <hex>] [--oracle <address>] [--factory <address>] [--usdc <address>] [--distribution-yes <parts>] [--distribution-no <parts>] [--sources <url...>] [--min-close-lead-seconds <n>] [--manifest-file <path>] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>]
135
158
  verify --pandora-market-address <address>|--market-address <address> --polymarket-market-id <id>|--polymarket-slug <slug> [--trust-deploy] [--manifest-file <path>] [--include-similarity] [--with-rules] [--allow-rule-mismatch] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>]
136
159
  lp-explain --liquidity-usdc <n> [--source-yes-pct <0-100>] [--distribution-yes <parts>] [--distribution-no <parts>]
137
160
  hedge-calc [--reserve-yes-usdc <n> --reserve-no-usdc <n>] [--excess-yes-usdc <n>] [--excess-no-usdc <n>] [--polymarket-yes-pct <0-100>] [--hedge-ratio <n>] [--hedge-cost-bps <n>] [--volume-scenarios <csv>] [--pandora-market-address <address>|--market-address <address> --polymarket-market-id <id>|--polymarket-slug <slug>] [--trust-deploy] [--manifest-file <path>]
138
- simulate --liquidity-usdc <n> [--source-yes-pct <0-100>] [--target-yes-pct <0-100>] [--distribution-yes <parts>] [--distribution-no <parts>] [--fee-tier 500|3000|10000] [--volume-scenarios <csv>] [--hedge-ratio <n>] [--hedge-cost-bps <n>] [--polymarket-yes-pct <0-100>]
139
- go --polymarket-market-id <id>|--polymarket-slug <slug> [--liquidity-usdc <n>] [--fee-tier 500|3000|10000] [--max-imbalance <n>] [--arbiter <address>] [--category <n>] [--paper|--dry-run|--execute-live|--execute] [--auto-sync] [--sync-once] [--sync-interval-ms <ms>] [--hedge-ratio <n>] [--no-hedge] [--max-rebalance-usdc <n>] [--max-hedge-usdc <n>] [--max-open-exposure-usdc <n>] [--max-trades-per-day <n>] [--cooldown-ms <ms>] [--chain-id <id>] [--rpc-url <url>] [--private-key <hex>] [--funder <address>] [--usdc <address>] [--oracle <address>] [--factory <address>] [--sources <url...>] [--manifest-file <path>] [--trust-deploy] [--skip-gate] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>] [--with-rules] [--include-similarity] [--min-close-lead-seconds <n>]
161
+ simulate --liquidity-usdc <n> [--source-yes-pct <0-100>] [--target-yes-pct <0-100>] [--distribution-yes <parts>] [--distribution-no <parts>] [--fee-tier <500-50000>] [--volume-scenarios <csv>] [--hedge-ratio <n>] [--hedge-cost-bps <n>] [--polymarket-yes-pct <0-100>]
162
+ go --polymarket-market-id <id>|--polymarket-slug <slug> [--liquidity-usdc <n>] [--fee-tier <500-50000>] [--max-imbalance <n>] [--arbiter <address>] [--category <n>] [--paper|--dry-run|--execute-live|--execute] [--auto-sync] [--sync-once] [--sync-interval-ms <ms>] [--hedge-ratio <n>] [--no-hedge] [--max-rebalance-usdc <n>] [--max-hedge-usdc <n>] [--max-open-exposure-usdc <n>] [--max-trades-per-day <n>] [--cooldown-ms <ms>] [--chain-id <id>] [--rpc-url <url>] [--private-key <hex>] [--funder <address>] [--usdc <address>] [--oracle <address>] [--factory <address>] [--sources <url...>] [--manifest-file <path>] [--trust-deploy] [--skip-gate] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>] [--with-rules] [--include-similarity] [--min-close-lead-seconds <n>]
140
163
  sync run|once|start --pandora-market-address <address>|--market-address <address> --polymarket-market-id <id>|--polymarket-slug <slug> [--paper|--dry-run|--execute-live|--execute] [--private-key <hex>] [--funder <address>] [--usdc <address>] [--trust-deploy] [--manifest-file <path>] [--skip-gate] [--daemon] [--stream|--no-stream] [--interval-ms <ms>] [--drift-trigger-bps <n>] [--hedge-trigger-usdc <n>] [--hedge-ratio <n>] [--no-hedge] [--max-rebalance-usdc <n>] [--max-hedge-usdc <n>] [--max-open-exposure-usdc <n>] [--max-trades-per-day <n>] [--cooldown-ms <ms>] [--depth-slippage-bps <n>] [--min-time-to-close-sec <n>] [--iterations <n>] [--state-file <path>] [--kill-switch-file <path>] [--chain-id <id>] [--rpc-url <url>] [--polymarket-host <url>] [--polymarket-gamma-url <url>] [--polymarket-gamma-mock-url <url>] [--polymarket-mock-url <url>] [--webhook-url <url>] [--telegram-bot-token <token>] [--telegram-chat-id <id>] [--discord-webhook-url <url>]
141
164
  status --state-file <path>|--strategy-hash <hash> [--with-live] [--pandora-market-address <address>|--market-address <address>] [--polymarket-market-id <id>|--polymarket-slug <slug>]
142
165
  close --pandora-market-address <address>|--market-address <address> --polymarket-market-id <id>|--polymarket-slug <slug> --dry-run|--execute
@@ -443,6 +466,12 @@ Common structured error codes for automation:
443
466
  - `INDEXER_HTTP_ERROR` / `INDEXER_TIMEOUT`: indexer transport failure.
444
467
  - `MIRROR_*`: mirror pipeline/service failures (plan/deploy/verify/sync/go/status).
445
468
  - `POLYMARKET_*`: Polymarket resolution/auth/order/preflight failures.
469
+ - `RISK_*`: risk state/guardrail/panic failures (`RISK_PANIC_ACTIVE`, `RISK_GUARDRAIL_BLOCKED`, etc.).
470
+ - `LIFECYCLE_*`: lifecycle state-machine file operations (`LIFECYCLE_EXISTS`, `LIFECYCLE_NOT_FOUND`).
471
+ - `ODDS_*`: odds record/history storage and connector failures.
472
+ - `ARB_*`: arb scan parsing/execution output-mode failures.
473
+ - `CONFIG_*`: config read/parse failures (for example `CONFIG_FILE_NOT_FOUND`).
474
+ - `MCP_FILE_ACCESS_BLOCKED`: MCP-mode file path denied outside workspace root.
446
475
  - `WEBHOOK_DELIVERY_FAILED`: webhook hard-fail when `--fail-on-webhook-error` is set.
447
476
 
448
477
  Error envelope:
@@ -14,7 +14,7 @@ const ARB_MARKET_FIELDS = [
14
14
  ];
15
15
 
16
16
  const ARB_USAGE =
17
- 'pandora arb scan --markets <csv> --output ndjson [--min-net-spread-pct <n>] [--fee-pct-per-leg <n>] [--amount-usdc <n>] [--interval-ms <ms>] [--iterations <n>] [--indexer-url <url>] [--timeout-ms <ms>]';
17
+ 'pandora arb scan --markets <csv> --output ndjson|json [--min-net-spread-pct <n>] [--fee-pct-per-leg <n>] [--slippage-pct-per-leg <n>] [--amount-usdc <n>] [--combinatorial] [--max-bundle-size <n>] [--interval-ms <ms>] [--iterations <n>] [--indexer-url <url>] [--timeout-ms <ms>]';
18
18
 
19
19
  function requireDep(deps, name) {
20
20
  if (!deps || typeof deps[name] !== 'function') {
@@ -139,6 +139,114 @@ function buildArbOpportunities(options) {
139
139
  return opportunities;
140
140
  }
141
141
 
142
+ function enumerateCombinations(items, size, onCombination) {
143
+ if (!Array.isArray(items) || !Number.isInteger(size) || size < 1 || size > items.length) return;
144
+ if (typeof onCombination !== 'function') return;
145
+
146
+ const selected = [];
147
+ function walk(startIndex) {
148
+ if (selected.length === size) {
149
+ onCombination(selected.slice());
150
+ return;
151
+ }
152
+ const remaining = size - selected.length;
153
+ const maxStart = items.length - remaining;
154
+ for (let index = startIndex; index <= maxStart; index += 1) {
155
+ selected.push(items[index]);
156
+ walk(index + 1);
157
+ selected.pop();
158
+ }
159
+ }
160
+ walk(0);
161
+ }
162
+
163
+ /**
164
+ * Build bundle-level combinatorial opportunities across provided markets.
165
+ * @param {object} options
166
+ * @returns {object[]}
167
+ */
168
+ function buildCombinatorialArbOpportunities(options) {
169
+ const marketSnapshots = Array.isArray(options.marketSnapshots)
170
+ ? options.marketSnapshots.filter((item) => item && Number.isFinite(item.yesPct))
171
+ : [];
172
+ if (marketSnapshots.length < 3) return [];
173
+
174
+ const minNetSpreadPct = Number.isFinite(options.minNetSpreadPct) ? Number(options.minNetSpreadPct) : 0;
175
+ const feePctPerLeg = Number.isFinite(options.feePctPerLeg) ? Number(options.feePctPerLeg) : 0;
176
+ const slippagePctPerLeg = Number.isFinite(options.slippagePctPerLeg) ? Number(options.slippagePctPerLeg) : 0;
177
+ const amountUsdc = Number.isFinite(options.amountUsdc) ? Number(options.amountUsdc) : 0;
178
+ const requestedMaxBundleSize = Number.isInteger(options.maxBundleSize) ? options.maxBundleSize : 4;
179
+ const maxBundleSize = Math.max(3, Math.min(requestedMaxBundleSize, marketSnapshots.length));
180
+
181
+ const opportunities = [];
182
+ for (let bundleSize = 3; bundleSize <= maxBundleSize; bundleSize += 1) {
183
+ enumerateCombinations(marketSnapshots, bundleSize, (bundle) => {
184
+ const bundleMarketIds = bundle.map((item) => item.id);
185
+ const sumYesPct = roundNumber(bundle.reduce((total, item) => total + Number(item.yesPct), 0), 6);
186
+ const sumNoPct = roundNumber(bundle.reduce((total, item) => total + (100 - Number(item.yesPct)), 0), 6);
187
+ const feeImpactPct = roundNumber(bundleSize * feePctPerLeg, 6);
188
+ const slippageImpactPct = roundNumber(bundleSize * slippagePctPerLeg, 6);
189
+
190
+ const evaluate = (strategy) => {
191
+ const grossEdgePct = strategy === 'buy_yes_bundle' ? roundNumber(100 - sumYesPct, 6) : roundNumber(sumYesPct - 100, 6);
192
+ if (grossEdgePct <= 0) return;
193
+
194
+ const netSpreadPct = roundNumber(grossEdgePct - feeImpactPct - slippageImpactPct, 6);
195
+ if (netSpreadPct <= 0 || netSpreadPct < minNetSpreadPct) return;
196
+
197
+ const payoutPct = strategy === 'buy_yes_bundle' ? 100 : roundNumber((bundleSize - 1) * 100, 6);
198
+ const totalEntryPct = strategy === 'buy_yes_bundle' ? sumYesPct : sumNoPct;
199
+ const grossProfitUsdc = roundNumber((amountUsdc * grossEdgePct) / 100, 6);
200
+ const profitUsdc = roundNumber((amountUsdc * netSpreadPct) / 100, 6);
201
+
202
+ opportunities.push({
203
+ opportunityType: 'combinatorial',
204
+ strategy,
205
+ pair: `bundle:${bundleMarketIds.join('|')}:${strategy}`,
206
+ bundleMarketIds,
207
+ bundleSize,
208
+ legs: bundle.map((item) => ({
209
+ marketId: item.id,
210
+ yesPct: roundNumber(item.yesPct, 6),
211
+ noPct: roundNumber(100 - item.yesPct, 6),
212
+ })),
213
+ sumYesPct,
214
+ sumNoPct,
215
+ totalEntryPct,
216
+ payoutPct,
217
+ grossSpreadPct: grossEdgePct,
218
+ grossEdgePct,
219
+ feePctPerLeg: roundNumber(feePctPerLeg, 6),
220
+ slippagePctPerLeg: roundNumber(slippagePctPerLeg, 6),
221
+ feeImpactPct,
222
+ slippageImpactPct,
223
+ netSpreadPct,
224
+ netSpread: roundNumber(netSpreadPct / 100, 8),
225
+ amountUsdc: roundNumber(amountUsdc, 6),
226
+ grossProfitUsdc,
227
+ profitUsdc,
228
+ profit: profitUsdc,
229
+ });
230
+ };
231
+
232
+ evaluate('buy_yes_bundle');
233
+ evaluate('buy_no_bundle');
234
+ });
235
+ }
236
+
237
+ opportunities.sort((left, right) => {
238
+ if (right.netSpreadPct !== left.netSpreadPct) {
239
+ return right.netSpreadPct - left.netSpreadPct;
240
+ }
241
+ if (right.bundleSize !== left.bundleSize) {
242
+ return right.bundleSize - left.bundleSize;
243
+ }
244
+ return left.pair.localeCompare(right.pair);
245
+ });
246
+
247
+ return opportunities;
248
+ }
249
+
142
250
  /**
143
251
  * Parse `arb scan` command flags.
144
252
  * @param {string[]} args
@@ -159,7 +267,10 @@ function parseArbScanFlags(args, deps) {
159
267
  output: 'ndjson',
160
268
  minNetSpreadPct: 0,
161
269
  feePctPerLeg: 0,
270
+ slippagePctPerLeg: 0,
162
271
  amountUsdc: 100,
272
+ combinatorial: false,
273
+ maxBundleSize: 4,
163
274
  intervalMs: 5_000,
164
275
  iterations: null,
165
276
  };
@@ -187,11 +298,25 @@ function parseArbScanFlags(args, deps) {
187
298
  i += 1;
188
299
  continue;
189
300
  }
301
+ if (token === '--slippage-pct-per-leg') {
302
+ options.slippagePctPerLeg = parseNumber(requireFlagValue(rest, i, '--slippage-pct-per-leg'), '--slippage-pct-per-leg');
303
+ i += 1;
304
+ continue;
305
+ }
190
306
  if (token === '--amount-usdc') {
191
307
  options.amountUsdc = parsePositiveNumber(requireFlagValue(rest, i, '--amount-usdc'), '--amount-usdc');
192
308
  i += 1;
193
309
  continue;
194
310
  }
311
+ if (token === '--combinatorial') {
312
+ options.combinatorial = true;
313
+ continue;
314
+ }
315
+ if (token === '--max-bundle-size') {
316
+ options.maxBundleSize = parsePositiveInteger(requireFlagValue(rest, i, '--max-bundle-size'), '--max-bundle-size');
317
+ i += 1;
318
+ continue;
319
+ }
195
320
  if (token === '--interval-ms') {
196
321
  options.intervalMs = parsePositiveInteger(requireFlagValue(rest, i, '--interval-ms'), '--interval-ms');
197
322
  i += 1;
@@ -210,8 +335,8 @@ function parseArbScanFlags(args, deps) {
210
335
  throw new CliError('MISSING_REQUIRED_FLAG', 'arb scan requires at least two markets via --markets <csv>.');
211
336
  }
212
337
 
213
- if (options.output !== 'ndjson') {
214
- throw new CliError('INVALID_FLAG_VALUE', 'arb scan currently supports only --output ndjson.');
338
+ if (!['ndjson', 'json'].includes(options.output)) {
339
+ throw new CliError('INVALID_FLAG_VALUE', 'arb scan supports --output ndjson|json.');
215
340
  }
216
341
 
217
342
  if (options.minNetSpreadPct < 0) {
@@ -222,6 +347,14 @@ function parseArbScanFlags(args, deps) {
222
347
  throw new CliError('INVALID_FLAG_VALUE', '--fee-pct-per-leg must be >= 0.');
223
348
  }
224
349
 
350
+ if (options.slippagePctPerLeg < 0) {
351
+ throw new CliError('INVALID_FLAG_VALUE', '--slippage-pct-per-leg must be >= 0.');
352
+ }
353
+
354
+ if (!Number.isInteger(options.maxBundleSize) || options.maxBundleSize < 3) {
355
+ throw new CliError('INVALID_FLAG_VALUE', '--max-bundle-size must be an integer >= 3.');
356
+ }
357
+
225
358
  options.markets = Array.from(
226
359
  new Set(
227
360
  options.markets
@@ -234,6 +367,10 @@ function parseArbScanFlags(args, deps) {
234
367
  throw new CliError('INVALID_ARGS', 'arb scan requires at least two distinct market ids.');
235
368
  }
236
369
 
370
+ if (options.combinatorial && options.markets.length < 3) {
371
+ throw new CliError('INVALID_ARGS', 'arb scan --combinatorial requires at least three distinct market ids.');
372
+ }
373
+
237
374
  return options;
238
375
  }
239
376
 
@@ -291,8 +428,30 @@ function createRunArbCommand(deps) {
291
428
  parsePositiveInteger,
292
429
  });
293
430
 
431
+ const mcpMode = String(process.env.PANDORA_MCP_MODE || '').trim() === '1';
432
+ if (mcpMode && options.output !== 'json') {
433
+ throw new CliError('MCP_LONG_RUNNING_MODE_BLOCKED', 'arb scan via MCP requires --output json and a bounded iteration count.', {
434
+ toolName: 'arb.scan',
435
+ hints: ['Use arb.scan with --output json --iterations 1 when calling via MCP.'],
436
+ });
437
+ }
438
+
439
+ if (options.output === 'json' && !Number.isInteger(options.iterations)) {
440
+ options.iterations = 1;
441
+ }
442
+
443
+ if (options.output === 'json' && Number.isInteger(options.iterations) && options.iterations > 1) {
444
+ const code = mcpMode ? 'MCP_LONG_RUNNING_MODE_BLOCKED' : 'INVALID_FLAG_VALUE';
445
+ throw new CliError(code, 'arb scan --output json supports only --iterations 1.', {
446
+ toolName: 'arb.scan',
447
+ hints: ['Use --output ndjson for streaming multi-iteration scans.'],
448
+ });
449
+ }
450
+
294
451
  const maxIterations = Number.isInteger(options.iterations) ? options.iterations : Number.POSITIVE_INFINITY;
295
452
  let iteration = 0;
453
+ const iterationSnapshots = [];
454
+ let emittedCombinatorialCount = 0;
296
455
 
297
456
  while (iteration < maxIterations) {
298
457
  iteration += 1;
@@ -300,37 +459,100 @@ function createRunArbCommand(deps) {
300
459
  buildGraphqlGetQuery,
301
460
  graphqlRequest,
302
461
  });
303
- const snapshots = buildMarketSnapshots(markets, options.markets);
304
- const opportunities = buildArbOpportunities({
305
- marketSnapshots: snapshots,
462
+ const marketSnapshots = buildMarketSnapshots(markets, options.markets);
463
+ const pairwiseOpportunities = buildArbOpportunities({
464
+ marketSnapshots,
306
465
  minNetSpreadPct: options.minNetSpreadPct,
307
466
  feePctPerLeg: options.feePctPerLeg,
308
467
  amountUsdc: options.amountUsdc,
309
468
  });
469
+ const combinatorialOpportunities = options.combinatorial
470
+ ? buildCombinatorialArbOpportunities({
471
+ marketSnapshots,
472
+ minNetSpreadPct: options.minNetSpreadPct,
473
+ feePctPerLeg: options.feePctPerLeg,
474
+ slippagePctPerLeg: options.slippagePctPerLeg,
475
+ amountUsdc: options.amountUsdc,
476
+ maxBundleSize: options.maxBundleSize,
477
+ })
478
+ : [];
479
+ emittedCombinatorialCount += combinatorialOpportunities.length;
480
+ const opportunities = [...pairwiseOpportunities, ...combinatorialOpportunities].sort((left, right) => {
481
+ if (right.netSpreadPct !== left.netSpreadPct) {
482
+ return right.netSpreadPct - left.netSpreadPct;
483
+ }
484
+ return String(left.pair || '').localeCompare(String(right.pair || ''));
485
+ });
310
486
 
311
- for (const opportunity of opportunities) {
312
- // eslint-disable-next-line no-console
313
- console.log(
314
- JSON.stringify({
315
- type: 'arb.scan.opportunity',
316
- timestamp: new Date().toISOString(),
317
- iteration,
318
- indexerUrl,
319
- ...opportunity,
320
- }),
321
- );
487
+ if (options.output === 'ndjson') {
488
+ for (const opportunity of opportunities) {
489
+ // eslint-disable-next-line no-console
490
+ console.log(
491
+ JSON.stringify({
492
+ type: 'arb.scan.opportunity',
493
+ timestamp: new Date().toISOString(),
494
+ iteration,
495
+ indexerUrl,
496
+ ...opportunity,
497
+ }),
498
+ );
499
+ }
500
+ } else {
501
+ iterationSnapshots.push({
502
+ iteration,
503
+ observedAt: new Date().toISOString(),
504
+ count: opportunities.length,
505
+ pairwiseCount: pairwiseOpportunities.length,
506
+ combinatorialCount: combinatorialOpportunities.length,
507
+ opportunities,
508
+ });
322
509
  }
323
510
 
324
511
  if (iteration < maxIterations) {
325
512
  await sleepMs(options.intervalMs);
326
513
  }
327
514
  }
515
+
516
+ if (options.output === 'json') {
517
+ const diagnostics = [];
518
+ if (options.combinatorial && emittedCombinatorialCount === 0) {
519
+ diagnostics.push('No combinatorial bundles cleared net spread thresholds for this run.');
520
+ }
521
+
522
+ const payload = {
523
+ action: 'scan',
524
+ indexerUrl,
525
+ iterationsCompleted: iteration,
526
+ requestedIterations: options.iterations,
527
+ intervalMs: options.intervalMs,
528
+ filters: {
529
+ markets: options.markets,
530
+ minNetSpreadPct: options.minNetSpreadPct,
531
+ feePctPerLeg: options.feePctPerLeg,
532
+ slippagePctPerLeg: options.slippagePctPerLeg,
533
+ amountUsdc: options.amountUsdc,
534
+ combinatorial: options.combinatorial,
535
+ maxBundleSize: options.maxBundleSize,
536
+ },
537
+ opportunities: iterationSnapshots.flatMap((row) => row.opportunities),
538
+ snapshots: iterationSnapshots,
539
+ diagnostics,
540
+ };
541
+
542
+ if (context.outputMode === 'json') {
543
+ emitSuccess(context.outputMode, 'arb.scan', payload);
544
+ } else {
545
+ // eslint-disable-next-line no-console
546
+ console.log(JSON.stringify(payload, null, 2));
547
+ }
548
+ }
328
549
  };
329
550
  }
330
551
 
331
552
  module.exports = {
332
553
  ARB_USAGE,
333
554
  buildArbOpportunities,
555
+ buildCombinatorialArbOpportunities,
334
556
  createRunArbCommand,
335
557
  parseArbScanFlags,
336
558
  };