@rune-kit/rune 2.1.1 → 2.2.1

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 (157) hide show
  1. package/README.md +40 -34
  2. package/compiler/__tests__/pack-split.test.js +145 -0
  3. package/compiler/adapters/antigravity.js +1 -1
  4. package/compiler/adapters/codex.js +77 -0
  5. package/compiler/adapters/cursor.js +1 -1
  6. package/compiler/adapters/generic.js +1 -1
  7. package/compiler/adapters/index.js +4 -0
  8. package/compiler/adapters/opencode.js +86 -0
  9. package/compiler/adapters/windsurf.js +1 -1
  10. package/compiler/bin/rune.js +10 -7
  11. package/compiler/doctor.js +42 -0
  12. package/compiler/emitter.js +64 -10
  13. package/compiler/parser.js +42 -3
  14. package/compiler/transformer.js +10 -6
  15. package/compiler/transforms/branding.js +1 -1
  16. package/compiler/transforms/compliance.js +40 -0
  17. package/extensions/ai-ml/PACK.md +38 -474
  18. package/extensions/ai-ml/skills/ai-agents.md +172 -0
  19. package/extensions/ai-ml/skills/code-sandbox.md +187 -0
  20. package/extensions/ai-ml/skills/deep-research.md +146 -0
  21. package/extensions/ai-ml/skills/embedding-search.md +66 -0
  22. package/extensions/ai-ml/skills/fine-tuning-guide.md +74 -0
  23. package/extensions/ai-ml/skills/llm-architect.md +125 -0
  24. package/extensions/ai-ml/skills/llm-integration.md +64 -0
  25. package/extensions/ai-ml/skills/prompt-patterns.md +72 -0
  26. package/extensions/ai-ml/skills/rag-patterns.md +66 -0
  27. package/extensions/ai-ml/skills/web-extraction.md +114 -0
  28. package/extensions/analytics/PACK.md +19 -484
  29. package/extensions/analytics/skills/ab-testing.md +72 -0
  30. package/extensions/analytics/skills/dashboard-patterns.md +83 -0
  31. package/extensions/analytics/skills/data-validation.md +68 -0
  32. package/extensions/analytics/skills/funnel-analysis.md +81 -0
  33. package/extensions/analytics/skills/sql-patterns.md +57 -0
  34. package/extensions/analytics/skills/statistical-analysis.md +79 -0
  35. package/extensions/analytics/skills/tracking-setup.md +71 -0
  36. package/extensions/backend/PACK.md +44 -618
  37. package/extensions/backend/skills/api-patterns.md +84 -0
  38. package/extensions/backend/skills/async-pipeline.md +193 -0
  39. package/extensions/backend/skills/auth-patterns.md +97 -0
  40. package/extensions/backend/skills/background-jobs.md +133 -0
  41. package/extensions/backend/skills/caching-patterns.md +108 -0
  42. package/extensions/backend/skills/cli-generation.md +133 -0
  43. package/extensions/backend/skills/database-patterns.md +87 -0
  44. package/extensions/backend/skills/middleware-patterns.md +104 -0
  45. package/extensions/chrome-ext/PACK.md +19 -921
  46. package/extensions/chrome-ext/skills/cws-preflight.md +143 -0
  47. package/extensions/chrome-ext/skills/cws-publish.md +104 -0
  48. package/extensions/chrome-ext/skills/ext-ai-integration.md +251 -0
  49. package/extensions/chrome-ext/skills/ext-messaging.md +139 -0
  50. package/extensions/chrome-ext/skills/ext-storage.md +133 -0
  51. package/extensions/chrome-ext/skills/mv3-scaffold.md +164 -0
  52. package/extensions/content/PACK.md +43 -335
  53. package/extensions/content/skills/blog-patterns.md +88 -0
  54. package/extensions/content/skills/cms-integration.md +131 -0
  55. package/extensions/content/skills/content-scoring.md +107 -0
  56. package/extensions/content/skills/i18n.md +83 -0
  57. package/extensions/content/skills/mdx-authoring.md +137 -0
  58. package/extensions/content/skills/reference.md +1014 -0
  59. package/extensions/content/skills/seo-patterns.md +67 -0
  60. package/extensions/content/skills/video-repurpose.md +153 -0
  61. package/extensions/devops/PACK.md +38 -457
  62. package/extensions/devops/skills/chaos-testing.md +67 -0
  63. package/extensions/devops/skills/ci-cd.md +75 -0
  64. package/extensions/devops/skills/docker.md +58 -0
  65. package/extensions/devops/skills/edge-serverless.md +163 -0
  66. package/extensions/devops/skills/infra-as-code.md +158 -0
  67. package/extensions/devops/skills/kubernetes.md +110 -0
  68. package/extensions/devops/skills/monitoring.md +57 -0
  69. package/extensions/devops/skills/server-setup.md +64 -0
  70. package/extensions/devops/skills/ssl-domain.md +42 -0
  71. package/extensions/ecommerce/PACK.md +62 -226
  72. package/extensions/ecommerce/skills/cart-system.md +79 -0
  73. package/extensions/ecommerce/skills/inventory-mgmt.md +102 -0
  74. package/extensions/ecommerce/skills/order-management.md +126 -0
  75. package/extensions/ecommerce/skills/payment-integration.md +472 -0
  76. package/extensions/ecommerce/skills/shopify-dev.md +69 -0
  77. package/extensions/ecommerce/skills/subscription-billing.md +93 -0
  78. package/extensions/ecommerce/skills/tax-compliance.md +117 -0
  79. package/extensions/gamedev/PACK.md +66 -317
  80. package/extensions/gamedev/skills/asset-pipeline.md +74 -0
  81. package/extensions/gamedev/skills/audio-system.md +129 -0
  82. package/extensions/gamedev/skills/camera-system.md +87 -0
  83. package/extensions/gamedev/skills/ecs.md +98 -0
  84. package/extensions/gamedev/skills/game-loops.md +72 -0
  85. package/extensions/gamedev/skills/input-system.md +199 -0
  86. package/extensions/gamedev/skills/multiplayer.md +180 -0
  87. package/extensions/gamedev/skills/particles.md +105 -0
  88. package/extensions/gamedev/skills/physics-engine.md +89 -0
  89. package/extensions/gamedev/skills/scene-management.md +146 -0
  90. package/extensions/gamedev/skills/threejs-patterns.md +90 -0
  91. package/extensions/gamedev/skills/webgl.md +71 -0
  92. package/extensions/mobile/PACK.md +56 -223
  93. package/extensions/mobile/skills/app-store-connect.md +152 -0
  94. package/extensions/mobile/skills/app-store-prep.md +66 -0
  95. package/extensions/mobile/skills/deep-linking.md +109 -0
  96. package/extensions/mobile/skills/flutter.md +60 -0
  97. package/extensions/mobile/skills/ios-build-pipeline.md +142 -0
  98. package/extensions/mobile/skills/native-bridge.md +66 -0
  99. package/extensions/mobile/skills/ota-updates.md +97 -0
  100. package/extensions/mobile/skills/push-notifications.md +111 -0
  101. package/extensions/mobile/skills/react-native.md +82 -0
  102. package/extensions/saas/PACK.md +26 -720
  103. package/extensions/saas/skills/billing-integration.md +121 -0
  104. package/extensions/saas/skills/feature-flags.md +130 -0
  105. package/extensions/saas/skills/multi-tenant.md +103 -0
  106. package/extensions/saas/skills/onboarding-flow.md +139 -0
  107. package/extensions/saas/skills/subscription-flow.md +95 -0
  108. package/extensions/saas/skills/team-management.md +144 -0
  109. package/extensions/security/PACK.md +10 -448
  110. package/extensions/security/skills/api-security.md +140 -0
  111. package/extensions/security/skills/compliance.md +68 -0
  112. package/extensions/security/skills/owasp-audit.md +64 -0
  113. package/extensions/security/skills/pentest-patterns.md +77 -0
  114. package/extensions/security/skills/secret-mgmt.md +65 -0
  115. package/extensions/security/skills/supply-chain.md +65 -0
  116. package/extensions/trading/PACK.md +18 -535
  117. package/extensions/trading/skills/chart-components.md +55 -0
  118. package/extensions/trading/skills/experiment-loop.md +125 -0
  119. package/extensions/trading/skills/fintech-patterns.md +47 -0
  120. package/extensions/trading/skills/indicator-library.md +58 -0
  121. package/extensions/trading/skills/quant-analysis.md +111 -0
  122. package/extensions/trading/skills/realtime-data.md +58 -0
  123. package/extensions/trading/skills/trade-logic.md +104 -0
  124. package/extensions/ui/PACK.md +34 -853
  125. package/extensions/ui/skills/a11y-audit.md +91 -0
  126. package/extensions/ui/skills/animation-patterns.md +106 -0
  127. package/extensions/ui/skills/component-patterns.md +75 -0
  128. package/extensions/ui/skills/design-decision.md +98 -0
  129. package/extensions/ui/skills/design-system.md +68 -0
  130. package/extensions/ui/skills/landing-patterns.md +155 -0
  131. package/extensions/ui/skills/palette-picker.md +162 -0
  132. package/extensions/ui/skills/react-health.md +90 -0
  133. package/extensions/ui/skills/type-system.md +125 -0
  134. package/extensions/ui/skills/web-vitals.md +153 -0
  135. package/extensions/zalo/PACK.md +117 -0
  136. package/extensions/zalo/skills/zalo-oa-mcp.md +317 -0
  137. package/extensions/zalo/skills/zalo-oa-messaging.md +429 -0
  138. package/extensions/zalo/skills/zalo-oa-setup.md +236 -0
  139. package/extensions/zalo/skills/zalo-oa-webhook.md +189 -0
  140. package/extensions/zalo/skills/zalo-personal-messaging.md +194 -0
  141. package/extensions/zalo/skills/zalo-personal-setup.md +153 -0
  142. package/extensions/zalo/skills/zalo-rate-guard.md +219 -0
  143. package/package.json +5 -2
  144. package/skills/brainstorm/SKILL.md +63 -1
  145. package/skills/cook/SKILL.md +89 -6
  146. package/skills/debug/SKILL.md +5 -0
  147. package/skills/fix/SKILL.md +5 -0
  148. package/skills/mcp-builder/SKILL.md +48 -1
  149. package/skills/neural-memory/SKILL.md +362 -0
  150. package/skills/plan/SKILL.md +3 -0
  151. package/skills/rescue/SKILL.md +5 -0
  152. package/skills/review/SKILL.md +44 -5
  153. package/skills/review-intake/SKILL.md +17 -1
  154. package/skills/skill-router/SKILL.md +106 -8
  155. package/skills/team/SKILL.md +24 -1
  156. package/skills/test/SKILL.md +18 -0
  157. package/skills/verification/SKILL.md +40 -1
@@ -0,0 +1,125 @@
1
+ ---
2
+ name: "experiment-loop"
3
+ pack: "@rune/trading"
4
+ description: "Scientific method for trading strategy development — hypothesize → implement → backtest → analyze → refine. Prevents the #1 strategy development failure: changing parameters randomly without tracking what was tested, what worked, and why."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # experiment-loop
10
+
11
+ Scientific method for trading strategy development — hypothesize → implement → backtest → analyze → refine. Prevents the #1 strategy development failure: changing parameters randomly without tracking what was tested, what worked, and why.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — Define hypothesis**
16
+ Every strategy change starts as a falsifiable hypothesis:
17
+ ```
18
+ HYPOTHESIS: [What you believe]
19
+ EVIDENCE: [Why you believe it — chart observation, backtest anomaly, market regime]
20
+ TEST: [How to verify — specific backtest config, date range, token set]
21
+ SUCCESS CRITERIA: [Measurable threshold — "win rate > 55% AND max drawdown < 15%"]
22
+ FAILURE CRITERIA: [When to reject — "win rate < 45% OR drawdown > 25%"]
23
+ ```
24
+
25
+ Check `.rune/experiments/` for prior experiments on the same component. If a similar hypothesis was already tested and rejected, flag it: "This was tested in experiment #12 and rejected because [reason]. Proceed anyway?"
26
+
27
+ **Step 2 — Implement variant**
28
+ Create the strategy variant in an isolated branch or config:
29
+ - Use `Grep` to find the parameter or logic being changed
30
+ - Create a named variant (e.g., `rsi_entry_v6_longer_period`) — NEVER modify the production logic directly
31
+ - Document the exact change: "Changed RSI period from 7 to 14, challenge threshold from 65 to 60"
32
+ - If logic change (not just parameter): ensure backtest engine mirrors the change (production-backtest sync from `trade-logic`)
33
+
34
+ **Step 3 — Run backtest**
35
+ Execute backtest against the defined test conditions:
36
+ - Use `Bash` to run the backtest command with the variant config
37
+ - Capture results: total PnL, win rate, max drawdown, Sharpe ratio, number of trades
38
+ - Compare against the control (current production parameters)
39
+ - Record execution time and date range
40
+
41
+ **Step 4 — Analyze results**
42
+ Structured analysis against success/failure criteria:
43
+
44
+ ```
45
+ EXPERIMENT #14: RSI Period 14 vs 7
46
+ STATUS: REJECTED ❌
47
+
48
+ RESULTS:
49
+ | Metric | Control (v5) | Variant (v6) | Δ |
50
+ |---------------|-------------|-------------|---------|
51
+ | Total PnL | $20,445 | $18,200 | -$2,245 |
52
+ | Win Rate | 58.3% | 52.1% | -6.2% |
53
+ | Max Drawdown | 12.4% | 14.8% | +2.4% |
54
+ | Sharpe Ratio | 1.42 | 1.18 | -0.24 |
55
+ | Trade Count | 156 | 89 | -67 |
56
+
57
+ CONCLUSION: Longer RSI period reduces signal frequency by 43% without
58
+ improving quality. Win rate dropped below 55% threshold. REJECTED.
59
+
60
+ INSIGHT: RSI 7 captures mean-reversion signals faster on 15m timeframe.
61
+ Longer periods may suit 4H+ timeframes (not tested — add to backlog).
62
+ ```
63
+
64
+ **Step 5 — Record and route**
65
+ Save experiment to `.rune/experiments/<number>-<name>.md`:
66
+ - If **ACCEPTED**: update production parameters → run `trade-logic` to sync manifest → commit
67
+ - If **REJECTED**: record conclusion and insight → add derived hypotheses to backlog
68
+ - If **INCONCLUSIVE**: define additional test conditions or longer date range → re-run
69
+ - Link to the experiment from `trade-logic` manifest: "RSI Entry v5: validated by experiment #14"
70
+
71
+ Update experiment index `.rune/experiments/index.md`:
72
+ ```
73
+ | # | Hypothesis | Component | Status | Key Metric | Date |
74
+ |---|-----------|-----------|--------|------------|------|
75
+ | 14 | RSI 14 > RSI 7 | rsi_entry | ❌ Rejected | WR 52% < 55% | 2025-03-15 |
76
+ | 13 | EMA 120 wick exit | ema_follow | ✅ Accepted | PnL +$2,036 | 2025-03-10 |
77
+ ```
78
+
79
+ #### Example
80
+
81
+ ```python
82
+ # Experiment runner pattern
83
+ from dataclasses import dataclass
84
+ from decimal import Decimal
85
+
86
+ @dataclass(frozen=True)
87
+ class ExperimentConfig:
88
+ name: str
89
+ hypothesis: str
90
+ variant_params: dict[str, str | int | float]
91
+ control_params: dict[str, str | int | float]
92
+ date_range: tuple[str, str]
93
+ tokens: list[str]
94
+ success_criteria: dict[str, tuple[str, float]] # metric: (operator, threshold)
95
+
96
+ @dataclass(frozen=True)
97
+ class ExperimentResult:
98
+ config: ExperimentConfig
99
+ control_metrics: dict[str, Decimal]
100
+ variant_metrics: dict[str, Decimal]
101
+ status: str # 'accepted' | 'rejected' | 'inconclusive'
102
+ conclusion: str
103
+ insights: list[str]
104
+
105
+ def evaluate_experiment(result: ExperimentResult) -> str:
106
+ """Evaluate variant against success criteria."""
107
+ for metric, (op, threshold) in result.config.success_criteria.items():
108
+ variant_val = result.variant_metrics.get(metric, Decimal('0'))
109
+ if op == '>' and variant_val <= Decimal(str(threshold)):
110
+ return 'rejected'
111
+ if op == '<' and variant_val >= Decimal(str(threshold)):
112
+ return 'rejected'
113
+ return 'accepted'
114
+
115
+ # Usage:
116
+ # config = ExperimentConfig(
117
+ # name="rsi_period_14",
118
+ # hypothesis="RSI 14 captures better signals than RSI 7 on 15m",
119
+ # variant_params={"rsi_period": 14, "challenge_threshold": 60},
120
+ # control_params={"rsi_period": 7, "challenge_threshold": 65},
121
+ # date_range=("2024-09-01", "2025-03-01"),
122
+ # tokens=["BTCUSDT", "ETHUSDT", "SOLUSDT"],
123
+ # success_criteria={"win_rate": (">", 0.55), "max_drawdown": ("<", 0.15)},
124
+ # )
125
+ ```
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: "fintech-patterns"
3
+ pack: "@rune/trading"
4
+ description: "Financial application patterns — safe money handling with Decimal/BigInt, transaction processing, audit trails, regulatory compliance, and PnL calculations."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # fintech-patterns
10
+
11
+ Financial application patterns — safe money handling with Decimal/BigInt, transaction processing, audit trails, regulatory compliance, and PnL calculations. Prevents the #1 fintech bug: float arithmetic on money.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — Detect money handling code**
16
+ Use `Grep` to scan for raw float arithmetic on price/amount/balance fields: `Grep pattern="(price|amount|balance|pnl)\s*[\+\-\*\/]" glob="**/*.ts"`. Flag any result not wrapped in Decimal or BigInt.
17
+
18
+ **Step 2 — Enforce Decimal/BigInt boundaries**
19
+ Use `Read` on each flagged file to identify entry points (API response parsing, user input). Replace raw number literals with `new Decimal(value)` at parse time. All arithmetic must flow through Decimal operations until final display.
20
+
21
+ **Step 3 — Implement audit trail and verify rounding**
22
+ Use `Bash` to run `tsc --noEmit` confirming no implicit `any` on financial fields. Add an immutable audit log entry on every mutation (create, fill, cancel). Verify rounding mode is `ROUND_HALF_EVEN` (banker's rounding) for all display formatting.
23
+
24
+ #### Example
25
+
26
+ ```typescript
27
+ import Decimal from 'decimal.js';
28
+
29
+ Decimal.set({ rounding: Decimal.ROUND_HALF_EVEN });
30
+
31
+ // NEVER: const fee = price * 0.001
32
+ // ALWAYS: Decimal arithmetic — exact, auditable
33
+ function calculateFee(price: string, quantity: string, feeRate: string): Decimal {
34
+ return new Decimal(price)
35
+ .times(new Decimal(quantity))
36
+ .times(new Decimal(feeRate))
37
+ .toDecimalPlaces(8);
38
+ }
39
+
40
+ function formatUSD(value: Decimal): string {
41
+ return new Intl.NumberFormat('en-US', {
42
+ style: 'currency',
43
+ currency: 'USD',
44
+ minimumFractionDigits: 2,
45
+ }).format(value.toNumber());
46
+ }
47
+ ```
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: "indicator-library"
3
+ pack: "@rune/trading"
4
+ description: "Technical indicator implementations — SMA, EMA, RSI, MACD, Bollinger Bands, VWAP. Streaming calculation patterns that update incrementally on each new tick rather than recomputing the full history."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # indicator-library
10
+
11
+ Technical indicator implementations — SMA, EMA, RSI, MACD, Bollinger Bands, VWAP. Streaming calculation patterns that update incrementally on each new tick rather than recomputing the full history.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — Select indicators and initialize state**
16
+ Use `Read` on the product spec or existing chart config to identify required indicators. For each, allocate a rolling window buffer sized to the longest period (e.g., 200 for SMA-200). Initialize with historical OHLCV data fetched via REST before the WebSocket feed opens.
17
+
18
+ **Step 2 — Streaming incremental calculation**
19
+ On each new tick from `realtime-data`, push the close price into the rolling buffer and evict the oldest value. Recompute only the current indicator value — not the full series. For RSI, maintain running average gains/losses using Wilder smoothing. Use `Bash` to run unit tests comparing streaming output against a reference batch computation.
20
+
21
+ **Step 3 — Overlay on chart component**
22
+ Create a `LineSeries` on the chart instance from `chart-components` for each indicator. On each streaming update, call `indicatorSeries.update({ time, value })`. Use `Grep` to confirm indicator series are cleaned up (`chart.removeSeries(s)`) when the symbol or timeframe changes to prevent memory leaks.
23
+
24
+ #### Example
25
+
26
+ ```typescript
27
+ class StreamingSMA {
28
+ private readonly window: number[] = [];
29
+
30
+ constructor(private readonly period: number) {}
31
+
32
+ update(price: number): number | null {
33
+ this.window.push(price);
34
+ if (this.window.length > this.period) {
35
+ this.window.shift();
36
+ }
37
+ if (this.window.length < this.period) return null;
38
+ const sum = this.window.reduce((acc, v) => acc + v, 0);
39
+ return sum / this.period;
40
+ }
41
+ }
42
+
43
+ class StreamingEMA {
44
+ private ema: number | null = null;
45
+ private readonly k: number;
46
+
47
+ constructor(private readonly period: number) {
48
+ this.k = 2 / (period + 1);
49
+ }
50
+
51
+ update(price: number): number | null {
52
+ this.ema = this.ema === null
53
+ ? price
54
+ : price * this.k + this.ema * (1 - this.k);
55
+ return this.ema;
56
+ }
57
+ }
58
+ ```
@@ -0,0 +1,111 @@
1
+ ---
2
+ name: "quant-analysis"
3
+ pack: "@rune/trading"
4
+ description: "Quantitative analysis patterns — portfolio metrics, risk calculations, statistical edge detection, Monte Carlo simulation, and position sizing models."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # quant-analysis
10
+
11
+ Quantitative analysis patterns — portfolio metrics, risk calculations, statistical edge detection, Monte Carlo simulation, and position sizing models.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — Define analysis scope**
16
+ Determine what the user needs: portfolio-level metrics (Sharpe, Sortino, max drawdown, VaR), strategy-level analysis (win rate, profit factor, expectancy, risk-of-ruin), or position sizing (Kelly criterion, fixed fractional, volatility-adjusted). Load trade history from data source (CSV, database query, API response).
17
+
18
+ **Step 2 — Calculate core metrics**
19
+ For portfolio analysis:
20
+ - **Sharpe Ratio**: (mean return - risk-free rate) / std(returns). Annualize with √252.
21
+ - **Sortino Ratio**: (mean return - risk-free rate) / downside_std. Only penalizes downside volatility.
22
+ - **Max Drawdown**: Largest peak-to-trough decline. Include recovery time.
23
+ - **Value at Risk (VaR)**: 95th/99th percentile loss using historical simulation or parametric method.
24
+ - **Calmar Ratio**: Annualized return / max drawdown. > 1.0 = good risk-adjusted return.
25
+
26
+ For strategy analysis:
27
+ - **Expectancy**: (win_rate × avg_win) - (loss_rate × avg_loss). Must be positive.
28
+ - **Profit Factor**: gross_profit / gross_loss. > 1.5 = viable, > 2.0 = strong.
29
+ - **Risk of Ruin**: probability of losing X% of capital given win rate and risk per trade.
30
+
31
+ **Step 3 — Monte Carlo simulation**
32
+ Run 10,000 random resamples of the trade sequence to estimate:
33
+ - Probability of reaching profit target within N trades
34
+ - Confidence interval for max drawdown (95th percentile)
35
+ - Optimal position size that maximizes geometric growth (Kelly fraction)
36
+
37
+ Emit results as structured data + visualization-ready format for `chart-components`.
38
+
39
+ **Step 4 — Position sizing recommendation**
40
+ Based on Monte Carlo results, recommend:
41
+ - **Conservative**: Half-Kelly (50% of optimal Kelly fraction)
42
+ - **Moderate**: Full Kelly
43
+ - **Aggressive**: 1.5x Kelly (with warning about increased ruin probability)
44
+
45
+ Save analysis to `.rune/trading/quant-analysis-<date>.md`.
46
+
47
+ #### Example
48
+
49
+ ```typescript
50
+ import Decimal from 'decimal.js';
51
+
52
+ interface TradeResult {
53
+ pnl: Decimal;
54
+ entryPrice: Decimal;
55
+ exitPrice: Decimal;
56
+ size: Decimal;
57
+ duration: number; // minutes
58
+ }
59
+
60
+ interface QuantMetrics {
61
+ totalTrades: number;
62
+ winRate: Decimal;
63
+ profitFactor: Decimal;
64
+ expectancy: Decimal;
65
+ sharpeRatio: Decimal;
66
+ sortinoRatio: Decimal;
67
+ maxDrawdown: Decimal;
68
+ maxDrawdownDuration: number;
69
+ calmarRatio: Decimal;
70
+ valueAtRisk95: Decimal;
71
+ kellyFraction: Decimal;
72
+ riskOfRuin: Decimal;
73
+ }
74
+
75
+ function calculateExpectancy(trades: TradeResult[]): Decimal {
76
+ const wins = trades.filter(t => t.pnl.gt(0));
77
+ const losses = trades.filter(t => t.pnl.lte(0));
78
+ const winRate = new Decimal(wins.length).div(trades.length);
79
+ const avgWin = wins.length > 0
80
+ ? wins.reduce((sum, t) => sum.plus(t.pnl), new Decimal(0)).div(wins.length)
81
+ : new Decimal(0);
82
+ const avgLoss = losses.length > 0
83
+ ? losses.reduce((sum, t) => sum.plus(t.pnl.abs()), new Decimal(0)).div(losses.length)
84
+ : new Decimal(0);
85
+ return winRate.mul(avgWin).minus(new Decimal(1).minus(winRate).mul(avgLoss));
86
+ }
87
+
88
+ function kellyFraction(winRate: Decimal, avgWinLossRatio: Decimal): Decimal {
89
+ // Kelly: f* = (p * b - q) / b where p=winRate, q=1-p, b=avgWin/avgLoss
90
+ const q = new Decimal(1).minus(winRate);
91
+ return winRate.mul(avgWinLossRatio).minus(q).div(avgWinLossRatio);
92
+ }
93
+
94
+ // Monte Carlo: resample trades 10,000 times
95
+ function monteCarloDrawdown(trades: TradeResult[], simulations = 10000): Decimal {
96
+ const drawdowns: Decimal[] = [];
97
+ for (let i = 0; i < simulations; i++) {
98
+ const shuffled = [...trades].sort(() => Math.random() - 0.5);
99
+ let peak = new Decimal(0), maxDd = new Decimal(0), equity = new Decimal(0);
100
+ for (const t of shuffled) {
101
+ equity = equity.plus(t.pnl);
102
+ if (equity.gt(peak)) peak = equity;
103
+ const dd = peak.minus(equity).div(peak.gt(0) ? peak : new Decimal(1));
104
+ if (dd.gt(maxDd)) maxDd = dd;
105
+ }
106
+ drawdowns.push(maxDd);
107
+ }
108
+ drawdowns.sort((a, b) => a.cmp(b));
109
+ return drawdowns[Math.floor(simulations * 0.95)]; // 95th percentile
110
+ }
111
+ ```
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: "realtime-data"
3
+ pack: "@rune/trading"
4
+ description: "Real-time data architecture — WebSocket lifecycle management, auto-reconnect with exponential backoff, event normalization, rate limiting, and TanStack Query cache invalidation."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # realtime-data
10
+
11
+ Real-time data architecture — WebSocket lifecycle management, auto-reconnect with exponential backoff, event normalization, rate limiting, and TanStack Query cache invalidation.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — WebSocket setup and event normalization**
16
+ Use `Read` on existing data-fetching files to understand current polling or REST patterns. Replace with a WebSocket client class that emits typed, normalized events regardless of upstream message format. Define a `NormalizedTick` interface at the boundary.
17
+
18
+ **Step 2 — Implement exponential backoff reconnect**
19
+ In the WebSocket class, add a reconnect handler: attempt 1 after 1 s, attempt 2 after 2 s, attempt 3 after 4 s, cap at 30 s. Use `Bash` to run unit tests covering disconnect and reconnect sequences. Track `reconnectAttempts` in state; reset to 0 on successful open.
20
+
21
+ **Step 3 — Wire to TanStack Query cache invalidation**
22
+ On each normalized event received, call `queryClient.setQueryData(['ticker', symbol], tick)` for optimistic updates or `queryClient.invalidateQueries(['orderbook', symbol])` for full refresh. Use `Grep` to confirm no stale `setInterval` polling remains alongside the new WebSocket feed.
23
+
24
+ #### Example
25
+
26
+ ```typescript
27
+ class TradingWebSocket {
28
+ private ws: WebSocket | null = null;
29
+ private reconnectAttempts = 0;
30
+ private readonly MAX_DELAY_MS = 30_000;
31
+
32
+ connect(url: string, onTick: (tick: NormalizedTick) => void): void {
33
+ this.ws = new WebSocket(url);
34
+
35
+ this.ws.onmessage = (event) => {
36
+ const raw = JSON.parse(event.data as string);
37
+ onTick(this.normalize(raw));
38
+ };
39
+
40
+ this.ws.onclose = () => {
41
+ const delay = Math.min(
42
+ 1000 * 2 ** this.reconnectAttempts,
43
+ this.MAX_DELAY_MS,
44
+ );
45
+ this.reconnectAttempts += 1;
46
+ setTimeout(() => this.connect(url, onTick), delay);
47
+ };
48
+
49
+ this.ws.onopen = () => { this.reconnectAttempts = 0; };
50
+ }
51
+
52
+ private normalize(raw: unknown): NormalizedTick {
53
+ // map exchange-specific shape to shared interface
54
+ const r = raw as Record<string, unknown>;
55
+ return { symbol: String(r['s']), price: String(r['p']), ts: Date.now() };
56
+ }
57
+ }
58
+ ```
@@ -0,0 +1,104 @@
1
+ ---
2
+ name: "trade-logic"
3
+ pack: "@rune/trading"
4
+ description: "Trading logic preservation and reasoning — entry/exit spec management, indicator parameter registry, strategy state tracking, and backtest result linkage. Prevents the #1 trading bot failure: AI sessions overwriting working logic without understanding it."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # trade-logic
10
+
11
+ Trading logic preservation and reasoning — entry/exit spec management, indicator parameter registry, strategy state tracking, and backtest result linkage. Prevents the #1 trading bot failure: AI sessions overwriting working logic without understanding it.
12
+
13
+ #### Workflow
14
+
15
+ **Step 1 — Load trading logic context**
16
+ Check if `logic-guardian` (L2) has a manifest loaded. If `.rune/logic-manifest.json` exists, read it and extract trading-specific components (ENTRY_LOGIC, EXIT_LOGIC, FILTER, INDICATOR). If no manifest exists, trigger `logic-guardian` Phase 3 to generate one with trading-aware scanning.
17
+
18
+ Trading-specific file patterns to scan:
19
+ - `**/scenarios/**`, `**/signals/**`, `**/strategies/**` — entry/exit logic
20
+ - `**/trailing/**`, `**/exit/**`, `**/stoploss/**` — exit engine components
21
+ - `**/indicators/**`, `**/core/indicators*` — technical indicator implementations
22
+ - `**/backtest/**`, `**/engine*` — backtesting mirrors of production logic
23
+ - `**/config/settings*`, `**/config/token*` — parameter source of truth
24
+
25
+ **Step 2 — Build trading logic spec**
26
+ For each trading component, extract a structured spec:
27
+
28
+ ```
29
+ COMPONENT: RSI Entry Detector
30
+ TYPE: ENTRY_LOGIC
31
+ STATUS: ACTIVE (production)
32
+ LAYERS: [which layer in the trading pipeline this belongs to]
33
+
34
+ ENTRY CONDITIONS:
35
+ 1. TrendPass ticket exists with available fires
36
+ 2. RSI_MA crosses threshold (65 LONG / 35 SHORT)
37
+ 3. Previous RSI in entry zone (30-55 LONG / 45-70 SHORT)
38
+ 4. RSI crosses RSI_MA + 40% TF filter + EMA filter
39
+
40
+ PARAMETERS:
41
+ - rsi_period: 7 (source: settings.py)
42
+ - challenge_threshold_long: 65 (source: settings.py)
43
+ - entry_zone_long: [30, 55] (source: settings.py)
44
+
45
+ DEPENDENCIES: trend_pass.tracker, core.indicators
46
+ MIRROR: backtest/engine.py (must stay in sync with production)
47
+ ```
48
+
49
+ **Step 3 — Enforce production-backtest sync**
50
+ For trading bots, production logic and backtest logic MUST be mirrors. Scan for:
51
+ - Production file: `src/worker/production_worker.py` or equivalent
52
+ - Backtest file: `backtest/engine.py` or equivalent
53
+ - Compare entry/exit function signatures and conditional branches
54
+ - Flag any divergence: "Production uses condition X but backtest doesn't"
55
+
56
+ **Step 4 — Parameter registry**
57
+ Build a parameter registry linking every configurable threshold to its source:
58
+ - Single source of truth file (e.g., `settings.py`)
59
+ - Per-token overrides (e.g., `token_config.py`, `final_config.json`)
60
+ - Scan for hardcoded magic numbers in logic files that should be in config
61
+ - Flag: "Hardcoded value 65 in detect.py:L42 — should reference settings.CHALLENGE_THRESHOLD_LONG"
62
+
63
+ **Step 5 — Strategy state machine documentation**
64
+ If the trading logic uses a multi-step state machine (e.g., 3-step RSI entry):
65
+ - Document each state and its transition conditions
66
+ - Generate a state diagram in text format
67
+ - Save to manifest as `state_machine` field on the component
68
+
69
+ ```
70
+ State Machine: RSI Entry
71
+ [IDLE] --ticket_exists--> [STEP1_CHALLENGE]
72
+ [STEP1_CHALLENGE] --rsi_ma_crosses_threshold--> [STEP2_ZONE_CHECK]
73
+ [STEP2_ZONE_CHECK] --prev_rsi_in_zone--> [STEP3_ENTRY_POINT]
74
+ [STEP3_ENTRY_POINT] --rsi_crosses_rsi_ma + filters--> [SIGNAL_EMITTED]
75
+ [any_step] --ticket_expired--> [IDLE]
76
+ ```
77
+
78
+ **Step 6 — Backtest result linkage**
79
+ Link logic components to their backtest performance:
80
+ - Scan `backtest/scan_results/` or equivalent for result files
81
+ - Associate each strategy variant with its performance metrics
82
+ - Record in manifest: "RSI Entry v5 with EMA Follow: $20,445 over 6mo backtest"
83
+ - Flag if logic was modified AFTER the latest backtest: "Logic changed since last backtest — results may be invalid"
84
+
85
+ #### Example
86
+
87
+ ```python
88
+ # trade-logic generates this spec from code analysis:
89
+ # COMPONENT: EMA Follow Exit
90
+ # TYPE: EXIT_LOGIC
91
+ # STATUS: ACTIVE
92
+ # BUG_HISTORY: 2026-02-22 fixed wick detection (was using close, now uses candle_low/high)
93
+ #
94
+ # EXIT CONDITION:
95
+ # if candle_wick crosses EMA120 -> exit position
96
+ # (NOT candle_close — this was the V4 bug)
97
+ #
98
+ # PARAMETERS:
99
+ # ema_period: 120 (source: settings.py)
100
+ # use_wick: True (source: settings.py, changed from False in V4)
101
+ #
102
+ # MIRROR: backtest/exit_checker.py:check_ema_follow()
103
+ # BACKTEST: $22,481 (x2.0 adaptive variant, validated 2026-02-22)
104
+ ```