"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(strategy-dev-manager): add Strategy Development Manager skill with artifact store and decay monitoring
shadowinlife5b8aaaf1240f
diff --git a/agent/src/skills/strategy-dev-manager/SKILL.md b/agent/src/skills/strategy-dev-manager/SKILL.mdnew file mode 100644index 000000000..9036e781b--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/SKILL.md@@ -0,0 +1,218 @@+---+name: strategy-dev-manager+description: "Strategy Development Manager: convert academic papers and research reports into validated factors and strategies with automated backtesting, persistent storage, and decay monitoring."+category: research+---++# Strategy Development Manager++## Purpose++SDM orchestrates the full lifecycle from academic paper or research report to validated factor or strategy. It ingests documents, extracts quantitative signals, implements and backtests them through the existing tool chain, evaluates results against statistical thresholds, and monitors long-term decay. SDM does not reinvent any step. It delegates to the tools already available (read_document, factor_analysis, backtest, alpha_bench, and the hypothesis/autopilot stack) and adds a thin coordination layer with persistent artifact tracking.++Use this skill whenever a user wants to go from "here is a paper" to "I have a working, monitored factor or strategy in the system."++## When to Use++Decision tree for routing user requests:++- User provides a paper or report path → **Phase 1: INGEST**+- User says "extract factors from this paper" → **Phase 2: EXTRACT**+- User says "implement and backtest" or "run the backtest" → **Phase 3: IMPLEMENT**+- User says "evaluate results" or "check if it works" → **Phase 4: EVALUATE**+- User says "check decay" or "monitor factors" → **Phase 5: MONITOR**+- User says "disable factor" → `sdm_status(action="disable", artifact_id=...)`+- User says "enable factor" → `sdm_status(action="enable", artifact_id=...)`+- User says "list my factors" or "show status" → `sdm_status(action="list")`++When the user's intent spans multiple phases (for example "read this paper and build a factor"), run the phases sequentially from INGEST through EVALUATE.++## Workflow++### Phase 1: INGEST++Parse the source document and classify its content.++1. Call `read_document(paper_path)` to extract the full text from the PDF or report.+2. Classify the paper type:+ - **factor-research**: the paper proposes one or more cross-sectional factors with formulas (for example Jegadeesh and Titman 1993, Fama-French 1993)+ - **strategy**: the paper describes entry/exit rules, position sizing, and risk management (for example Avramov and Chordia 2006, turtle trading)+ - **mixed**: the paper contains both factor definitions and strategy rules+3. Extract key information from the parsed text:+ - Methodology description+ - Mathematical formulas (preserve LaTeX notation)+ - Variable definitions and data requirements+ - Universe and time period studied+ - Performance metrics reported in the paper++### Phase 2: EXTRACT++Turn the parsed content into structured artifact definitions.++1. **For factors**, extract:+ - `name`: short identifier (for example "momentum_12_1")+ - `formula_latex`: the mathematical formula as written in the paper+ - `variables`: list of input variables and their meanings+ - `columns_required`: OHLCV columns or fundamental fields needed+ - `universe`: target market (for example "equity_us", "equity_cn")+ - `decay_horizon`: recommended holding period in trading days++2. **For strategies**, extract:+ - `name`: short identifier+ - `entry_rules`: conditions that trigger a long or short position+ - `exit_rules`: conditions that close a position+ - `position_sizing`: how to allocate capital across selected instruments+ - `risk_management`: stop-loss, max drawdown, exposure limits+ - `universe`: target market+ - `columns_required`: data fields needed++3. **Deduplication check**: call `alpha_bench` or check `sdm_status(action="list")` to see if a similar artifact already exists. If the Pearson IC between the new factor and an existing alpha exceeds 0.99, treat it as a duplicate and stop. IC between 0.90 and 0.99 may be a variant worth keeping with a note.++4. **Register the artifact**: call `sdm_register(artifact_type, name, universe, ...)` to persist the extracted definition with status "extracted".++### Phase 3: IMPLEMENT++Build the SignalEngine, run the backtest, and link results.++1. Call `create_hypothesis(title, thesis, universe, signal_definition)` to create a research hypothesis that tracks this work.+2. Call `generate_backtest_config(hypothesis_id, start_date, end_date)` to produce the `config.json` for the backtest runner.+3. Call `scaffold_signal_engine(hypothesis_id, run_dir)` to generate the skeleton `signal_engine.py` in the run directory.+4. Implement the full `signal_engine.py` using the appropriate template from `templates/`:+ - Factor artifacts → `templates/factor_signal_engine.py`+ - Strategy artifacts → `templates/strategy_signal_engine.py`+5. Validate syntax: `bash("python -c \"import ast; ast.parse(open('code/signal_engine.py').read()); print('OK')\"")`+6. Call `backtest(run_dir)` to execute the backtest.+7. Call `link_autopilot_backtest(hypothesis_id, run_dir)` to link the run results back to the hypothesis.+8. Call `sdm_status(action="detail", artifact_id=...)` and update the artifact status to "benching".++### Phase 4: EVALUATE++Judge the backtest output against quality thresholds.++1. **For factors**: call `factor_analysis` with the factor CSV and return CSV. Check:+ - IC mean > 0.03 (basic predictive power)+ - IR > 0.5 (stable effectiveness)+ - IC positive ratio > 55% (directional stability)++2. **For strategies**: read `artifacts/metrics.csv` and `run_card.json`. Check:+ - Sharpe ratio > 0.5 (minimum acceptable)+ - Max drawdown < 30% (risk tolerance)+ - Win rate and profit factor for additional context++3. **If the artifact is alive** (meets thresholds):+ - For factors: register into `factors/zoo/` and update status to "active"+ - For strategies: update status to "active" with the run metrics attached++4. **If the artifact is dead** (fails thresholds):+ - Update status to "disabled" with a reason string+ - Record what failed (for example "IC mean 0.012, below 0.03 threshold")++5. Record bench results via `sdm_status` update so the history is queryable.++### Phase 5: MONITOR++Track artifact health over time and handle decay.++1. Call `sdm_decay_scan(universe=...)` for batch monitoring across all active artifacts in a universe.+2. Review decay signals per artifact:+ - **healthy**: all metrics above "Healthy" thresholds (see `references/decay_thresholds.md`)+ - **warning**: metrics have dropped into the "Warning" band+ - **decayed**: metrics are in the "Decayed" band+ - **critical**: metrics are in the "Critical" band+3. Auto-transitions follow the state machine:+ - `active` → `monitoring` when any metric enters "Warning"+ - `monitoring` → `decayed` when metrics stay in "Decayed" for 3+ consecutive scans+ - `decayed` → `disabled` when metrics enter "Critical"+ - `monitoring` → `active` when metrics recover to "Healthy" for 2+ consecutive scans+4. Recovery: a decayed artifact can be re-evaluated by re-running Phase 3 with updated parameters.+5. Generate a decay report summarizing all artifact statuses and recent transitions.++## Tool Reference++| Tool | Phase | Purpose |+|------|-------|---------|+| `read_document` | 1 | Parse PDF papers and reports |+| `sdm_register` | 2 | Register extracted factor or strategy |+| `sdm_status` | 2, 3, 4, 5 | Query or update artifact lifecycle status |+| `alpha_bench` | 2 | Deduplication check against existing alphas |+| `create_hypothesis` | 3 | Create a research hypothesis |+| `generate_backtest_config` | 3 | Generate backtest config.json |+| `scaffold_signal_engine` | 3 | Generate SignalEngine skeleton |+| `backtest` | 3 | Execute the backtest |+| `link_autopilot_backtest` | 3 | Link backtest results to hypothesis |+| `factor_analysis` | 4 | IC/IR analysis for factor artifacts |+| `sdm_decay_scan` | 5 | Batch decay monitoring |++## SignalEngine Contract++The generated `signal_engine.py` MUST satisfy the backtest runner contract:++```python+class SignalEngine:+ def __init__(self):+ """No-arg constructor. All parameters must have defaults."""+ ...++ def generate(self, data_map: dict[str, pd.DataFrame]) -> dict[str, pd.Series]:+ """+ Args:+ data_map: symbol -> DataFrame (columns: open, high, low, close, volume,+ DatetimeIndex). May include extra fields from config.extra_fields+ or config.fundamental_fields.+ Returns:+ symbol -> signal Series (float, clipped to [-1.0, 1.0])+ 1.0 = fully long, 0.5 = half position, 0.0 = flat, -1.0 = fully short+ """+ ...+```++Hard constraints:+- Class MUST be named `SignalEngine`+- Constructor MUST take no arguments (all params have defaults)+- Signal Series index must align exactly with the input DataFrame index+- Include all required imports (numpy, pandas, typing)+- Do not hardcode dates or stock codes+- Do not include an `if __name__ == "__main__"` block+- Pure pandas/numpy implementation, no external signal libraries++## Quality Checklist++Self-check before marking any phase complete:++- [ ] Paper type correctly classified (factor-research / strategy / mixed)+- [ ] Factor formula matches the paper text (no LLM hallucination)+- [ ] Deduplication check passed (IC < 0.99 against existing alphas)+- [ ] SignalEngine passes AST validation+- [ ] Backtest completed without errors+- [ ] IC/IR or Sharpe meets minimum thresholds+- [ ] Artifact registered in the strategy store with correct status++## Common Pitfalls++### Formula Hallucination+LLMs may generate plausible-looking formulas that do not appear in the paper. ALWAYS cross-check the extracted formula against the original document text. If the paper uses notation you cannot parse, ask the user to confirm.++### Factor Deduplication+IC > 0.99 means the factor is a duplicate. IC between 0.90 and 0.99 may be a variant. Use judgment: if the formula is structurally different but produces similar signals, note it as a variant rather than rejecting it outright.++### Decay Baseline+Decay monitoring requires at least 3 bench history entries to establish a baseline. A newly registered artifact with only one backtest cannot be meaningfully scanned for decay.++### Template Mismatch+Strategy-type artifacts need the strategy SignalEngine template (with entry/exit/position logic), not the factor template. Using the wrong template produces a SignalEngine that compiles but generates meaningless signals.++### Look-Ahead Bias+Factor values must use data from day T and earlier. Returns must use data from T+1 onward. The `delta(df, d)` operator enforces `d >= 1` to prevent lookahead. Never use `Ref(df, -n)` style negative shifts.++## Templates++Two SignalEngine templates are provided in `templates/`:++- `factor_signal_engine.py`: for factor-type artifacts. Computes a cross-sectional factor value per instrument per date, then ranks and clips to [-1.0, 1.0].+- `strategy_signal_engine.py`: for strategy-type artifacts. Implements entry/exit rules with position sizing and risk management.++## References++- Decay thresholds and state machine: `references/decay_thresholds.md`+- Example workflows: `examples.md`+- Base operators for factor computation: `src/factors/base.py` (rank, zscore, scale, ts_mean, ts_std, ts_rank, ts_corr, ts_cov, ts_max, ts_min, ts_argmax, ts_argmin, delta, decay_linear, signed_power, safe_div, vwap)diff --git a/agent/src/skills/strategy-dev-manager/examples.md b/agent/src/skills/strategy-dev-manager/examples.mdnew file mode 100644index 000000000..58dc69305--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/examples.md@@ -0,0 +1,278 @@+# Strategy Development Manager: Example Workflows++## Example 1: Paper to Factor++**Scenario**: Extracting a momentum factor from Jegadeesh and Titman (1993), "Returns to Buying Winners and Selling Losers."++### Phase 1: INGEST++```+read_document(paper_path="papers/jegadeesh_titman_1993.pdf")+```++Output: full text extracted. Classification: **factor-research**.++Key information extracted:+- Methodology: sort stocks by past 3-12 month returns, buy winners, sell losers+- Formula: `R_mom = cumulative_return(t-12, t-1)` with 1-month skip+- Variables: past returns, skip period, formation period+- Universe: US equities (NYSE/AMEX/NASDAQ)+- Reported performance: ~1% monthly excess return++### Phase 2: EXTRACT++Structured extraction:++```python+factor_def = {+ "name": "momentum_12_1",+ "formula_latex": "R_{mom} = \\prod_{i=t-12}^{t-1}(1 + r_i) - 1",+ "variables": {+ "formation_period": 12,+ "skip_period": 1,+ "return_type": "cumulative"+ },+ "columns_required": ["close"],+ "universe": "equity_us",+ "decay_horizon": 21+}+```++Deduplication check:++```+alpha_bench(zoo="academic", universe="equity_us", period="2015-2025")+```++Result: the existing `academic_carhart_momentum` alpha has IC 0.92 with our formula. This is a variant (not a duplicate, since IC < 0.99), so we proceed with a note.++Register:++```+sdm_register(+ artifact_type="factor",+ name="momentum_12_1",+ universe="equity_us",+ formula_latex="R_{mom} = \\prod_{i=t-12}^{t-1}(1 + r_i) - 1",+ columns_required=["close"],+ decay_horizon=21,+ source_paper="Jegadeesh & Titman (1993)",+ notes="Variant of Carhart momentum with explicit 1-month skip"+)+```++### Phase 3: IMPLEMENT++```+create_hypothesis(+ title="Jegadeesh-Titman 12-1 Momentum Factor",+ thesis="Stocks with high cumulative returns over the past 12 months (skipping the most recent month) will continue to outperform in the next month.",+ universe="equity_us",+ signal_definition="Cross-sectional rank of 12-month cumulative return, skipping month t-1"+)+```++```+generate_backtest_config(+ hypothesis_id="hyp_001",+ start_date="2015-01-01",+ end_date="2025-01-01"+)+```++```+scaffold_signal_engine(hypothesis_id="hyp_001", run_dir="runs/hyp_001")+```++Then implement `signal_engine.py` using the factor template, filling in the momentum computation:++```python+# Inside generate():+for symbol, df in data_map.items():+ # 12-month cumulative return, skip most recent month+ ret_12m = df["close"].pct_change(12).shift(1)+ ret_1m = df["close"].pct_change(1)+ mom_signal = ret_12m - ret_1m # skip the most recent month+ signals[symbol] = mom_signal+```++```+backtest(run_dir="runs/hyp_001")+```++```+link_autopilot_backtest(hypothesis_id="hyp_001", run_dir="runs/hyp_001")+```++```+sdm_status(action="update", artifact_id="momentum_12_1", status="benching")+```++### Phase 4: EVALUATE++```+factor_analysis(+ factor_csv="runs/hyp_001/artifacts/factor.csv",+ return_csv="runs/hyp_001/artifacts/return.csv",+ output_dir="runs/hyp_001/artifacts/analysis"+)+```++Results:+- IC mean: 0.042 (> 0.03 threshold)+- IR: 0.68 (> 0.5 threshold)+- IC positive ratio: 58% (> 55% threshold)++Verdict: **alive**. Register as active:++```+sdm_status(action="update", artifact_id="momentum_12_1", status="active",+ metrics={"ic_mean": 0.042, "ir": 0.68, "ic_positive_ratio": 0.58})+```++---++## Example 2: Paper to Strategy++**Scenario**: Implementing a mean-reversion strategy from Avramov and Chordia (2006), "Predicting Stock Returns Using Transaction Activity."++### Phase 1: INGEST++```+read_document(paper_path="papers/avramov_chordia_2006.pdf")+```++Output: full text extracted. Classification: **strategy**.++Key information extracted:+- Methodology: use order flow imbalance to predict short-term mean reversion+- Entry rule: buy when normalized order flow is below -2 standard deviations (heavy selling), sell when above +2 standard deviations+- Exit rule: hold for 5 trading days or exit when order flow normalizes+- Position sizing: equal-weight across selected stocks, max 10 positions+- Risk management: 5% stop-loss per position+- Universe: US equities, large-cap++### Phase 2: EXTRACT++Structured extraction:++```python+strategy_def = {+ "name": "order_flow_mean_reversion",+ "entry_rules": [+ "normalized_order_flow < -2.0 (heavy selling, buy signal)",+ "normalized_order_flow > 2.0 (heavy buying, sell signal)"+ ],+ "exit_rules": [+ "hold_days >= 5 (time-based exit)",+ "abs(normalized_order_flow) < 0.5 (flow normalized, exit)",+ "position_pnl < -0.05 (stop-loss)"+ ],+ "position_sizing": "equal_weight, max_positions=10",+ "risk_management": {"stop_loss_pct": 0.05, "max_positions": 10},+ "universe": "equity_us",+ "columns_required": ["close", "volume"],+ "source_paper": "Avramov & Chordia (2006)"+}+```++Deduplication check:++```+sdm_status(action="list", artifact_type="strategy", universe="equity_us")+```++No existing strategy matches. Register:++```+sdm_register(+ artifact_type="strategy",+ name="order_flow_mean_reversion",+ universe="equity_us",+ entry_rules=strategy_def["entry_rules"],+ exit_rules=strategy_def["exit_rules"],+ position_sizing="equal_weight",+ columns_required=["close", "volume"],+ source_paper="Avramov & Chordia (2006)"+)+```++### Phase 3: IMPLEMENT++```+create_hypothesis(+ title="Order Flow Mean Reversion Strategy",+ thesis="Stocks experiencing extreme order flow imbalances (measured by volume-weighted price pressure) will revert in the short term.",+ universe="equity_us",+ signal_definition="Buy when normalized volume-pressure is below -2 std, sell when above +2 std, hold 5 days"+)+```++```+generate_backtest_config(+ hypothesis_id="hyp_002",+ start_date="2018-01-01",+ end_date="2025-01-01"+)+```++```+scaffold_signal_engine(hypothesis_id="hyp_002", run_dir="runs/hyp_002")+```++Then implement `signal_engine.py` using the strategy template, filling in the order flow logic:++```python+# Inside generate():+for symbol, df in data_map.items():+ # Volume-weighted price pressure as order flow proxy+ vwap_proxy = (df["volume"] * df["close"]).rolling(20).sum() / df["volume"].rolling(20).sum()+ price_pressure = (df["close"] - vwap_proxy) / df["close"].rolling(20).std()++ # Entry: extreme selling pressure -> buy signal+ buy_signal = (price_pressure < -2.0).astype(float)+ sell_signal = (price_pressure > 2.0).astype(float)++ # Hold for 5 days using a simple decay+ raw_signal = buy_signal - sell_signal+ signals[symbol] = raw_signal.rolling(5).max() * raw_signal+```++```+backtest(run_dir="runs/hyp_002")+```++```+link_autopilot_backtest(hypothesis_id="hyp_002", run_dir="runs/hyp_002")+```++```+sdm_status(action="update", artifact_id="order_flow_mean_reversion", status="benching")+```++### Phase 4: EVALUATE++Read `runs/hyp_002/artifacts/metrics.csv` and `run_card.json`:++Results:+- Sharpe ratio: 0.82 (> 0.5 threshold)+- Max drawdown: 18.3% (< 30% threshold)+- Win rate: 54%+- Profit factor: 1.35++Verdict: **alive**. Update status:++```+sdm_status(action="update", artifact_id="order_flow_mean_reversion", status="active",+ metrics={"sharpe": 0.82, "max_drawdown": 0.183, "win_rate": 0.54})+```++### Phase 5: MONITOR (later)++After several weeks of live benching:++```+sdm_decay_scan(universe="equity_us")+```++Output shows `order_flow_mean_reversion` with status "healthy" (all metrics above thresholds). The momentum factor from Example 1 shows "warning" on IC ratio (dropped to 0.62). No action needed yet, but the next scan will determine if it transitions to "monitoring."diff --git a/agent/src/skills/strategy-dev-manager/references/decay_thresholds.md b/agent/src/skills/strategy-dev-manager/references/decay_thresholds.mdnew file mode 100644index 000000000..62a83e19d--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/references/decay_thresholds.md@@ -0,0 +1,46 @@+# Decay Monitoring Thresholds++## State Machine++```+created → benching → active → monitoring → decayed → disabled+ ↑ │+ └───────────┘ (recovery: IC ratio > 0.7)+```++## Decay Signal Evaluation++Each metric is evaluated independently. The **worst** signal across all provided metrics determines the overall decay signal.++| Metric | Healthy | Warning | Decayed | Critical |+|--------|---------|---------|---------|----------|+| IC Ratio (rolling/baseline) | > 0.7 | 0.5 – 0.7 | 0.3 – 0.5 | < 0.3 |+| IR (rolling window) | > 1.0 | 0.5 – 1.0 | 0.1 – 0.5 | < 0.1 |+| IC Positive Ratio | > 55% | 45% – 55% | 35% – 45% | < 35% |+| Sharpe (strategy only) | > 1.0 | 0.5 – 1.0 | 0.0 – 0.5 | < 0.0 |++## State Transition Rules++| Transition | Condition | Consecutive Requirement |+|------------|-----------|------------------------|+| active → monitoring | WARNING or worse | 3 consecutive periodic benches |+| monitoring → decayed | DECAYED or worse | 2 additional consecutive checks |+| monitoring → active | HEALTHY | 1 reading (recovery) |+| decayed → disabled | CRITICAL | 3 monitoring periods |+| disabled → active | Manual enable | — |++## Trigger Modes++1. **Manual**: Agent calls `sdm_decay_scan(universe=...)` tool+2. **Scheduled**: `ScheduledResearchExecutor` configured with periodic scan job+3. **Passive**: Each `alpha_bench` run updates the scanned factor's decay snapshot++## Baseline Calculation++- Baseline IC mean = average of all `bench_history` entries with `bench_type='initial'` or the first 5 `periodic` entries+- Rolling IC mean = average of the most recent N entries (configurable via `rolling_window_days`)+- IC ratio = rolling_ic_mean / baseline_ic_mean++## Configuration++All thresholds are configurable via `DecayThresholds` dataclass in `src/strategy_store/decay.py`.diff --git a/agent/src/skills/strategy-dev-manager/references/scheduled_decay_scan.md b/agent/src/skills/strategy-dev-manager/references/scheduled_decay_scan.mdnew file mode 100644index 000000000..093e3544c--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/references/scheduled_decay_scan.md@@ -0,0 +1,176 @@+# Scheduled Decay Scan Configuration++## Overview++Periodic decay scanning ensures that factor performance degradation is detected early, before it silently erodes strategy returns. The `ScheduledResearchExecutor` provides a background polling loop that fires research prompts on a cron or interval schedule. By configuring a scheduled job with a decay-scan prompt, operators automate the `sdm_decay_scan` workflow without manual intervention.++Each scheduled fire creates a fresh agent session that runs the configured prompt through the standard tool registry. The agent calls `sdm_decay_scan`, evaluates decay signals against the thresholds defined in `decay_thresholds.md`, applies warranted state transitions, and produces a summary report.++## Configuration++### Enable the scheduler++The background executor is **off by default**. Start the server with the environment flag:++```bash+VIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899+```++Without this flag, the `/scheduled-runs` endpoints still record jobs but nothing fires.++### Create a weekly decay scan job++```bash+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{+ "prompt": "Run a decay scan on all active factors in the CSI300 universe. For any factors showing decay signals, generate a summary report.",+ "schedule": "0 2 * * 1",+ "config": {}+ }'+```++The API returns a job record with `id`, `status`, `next_run_at`, and the full schedule definition. Jobs persist under `~/.vibe-trading/` and survive server restarts.++### Create a multi-universe scan++For operators tracking factors across multiple universes, create separate jobs per universe:++```bash+# CSI300 weekly scan+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{+ "prompt": "Run a decay scan on all active factors in the CSI300 universe. Generate a decay report with status transitions.",+ "schedule": "0 2 * * 1",+ "config": {}+ }'++# S&P 500 weekly scan (offset by one day)+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{+ "prompt": "Run a decay scan on all active factors in the SP500 universe. Generate a decay report with status transitions.",+ "schedule": "0 2 * * 2",+ "config": {}+ }'+```++### Authentication++When `API_AUTH_KEY` is configured, include the bearer token:++```bash+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer <your-api-key>" \+ -d '{ ... }'+```++## Schedule Examples++The `schedule` field accepts two formats:++| Format | Example | Description |+|--------|---------|-------------|+| Interval (ms) | `"21600000"` | Every 6 hours (6 * 60 * 60 * 1000) |+| Cron (5-field) | `"0 2 * * 1"` | Monday at 02:00 UTC |++Cron fields: `minute hour day-of-month month day-of-week`. Each field accepts a number, `*` (any), or `*/n` (step).++### Common cron patterns for decay scanning++| Pattern | Schedule | Use case |+|---------|----------|----------|+| Weekly (Monday 2am UTC) | `0 2 * * 1` | Standard weekly scan for most factor portfolios |+| Monthly (1st, 3am UTC) | `0 3 1 * *` | Low-frequency monitoring for stable, long-horizon factors |+| Daily (midnight UTC) | `0 0 * * *` | High-frequency monitoring during volatile regimes |+| Bi-weekly (1st and 15th) | `0 2 1,15 * *` | Balanced cadence for mixed-horizon portfolios |+| Every 6 hours (interval) | `21600000` | Continuous monitoring for live-trading factor stacks |++## What Happens on Each Scan++When the executor fires a scheduled decay scan job, the agent session performs the following steps:++1. **Invoke `sdm_decay_scan`** -- Calls the decay scan tool with the configured universe (e.g., `sdm_decay_scan(universe="CSI300")`).++2. **Evaluate decay signals** -- For each active factor, computes rolling IC mean, IR, IC positive ratio, and Sharpe ratio. Compares each metric against the thresholds defined in `decay_thresholds.md`.++3. **Classify factor health** -- Assigns each factor to one of five categories:+ - **Healthy**: All metrics above healthy thresholds+ - **Warning**: At least one metric in the warning band+ - **Decayed**: At least one metric in the decayed band+ - **Critical**: At least one metric in the critical band+ - **Insufficient data**: Not enough bench history for reliable evaluation++4. **Apply state transitions** -- Factors meeting the consecutive-reading requirements (see `decay_thresholds.md` State Transition Rules) are transitioned to their next state (e.g., `active` to `monitoring`, `monitoring` to `decayed`).++5. **Generate a summary report** -- Produces a structured report with counts per category, a transitions table, and recommendations. See `templates/decay_report.md` for the report format.++## Monitoring Scan Results++### List scheduled jobs++```bash+curl http://localhost:8899/scheduled-runs+```++Returns all configured jobs with their current status, `last_run_at`, and `next_run_at` timestamps.++### Check scan history via the agent++After a scan completes, the agent stores results as artifacts. Query them with:++```+sdm_status(action="detail", artifact_id="<scan_artifact_id>")+```++This returns the full decay scan output including per-factor metrics, applied transitions, and the generated report.++### Cancel a scheduled job++```bash+curl -X DELETE http://localhost:8899/scheduled-runs/<job_id>+```++Cancelled jobs are marked terminal and never re-dispatched.++## Tuning Scan Frequency++Choose scan intervals based on the factor's `decay_horizon` metadata and the portfolio's sensitivity to performance degradation:++| Factor type | Recommended schedule | Rationale |+|-------------|---------------------|-----------|+| Short-horizon (holding period < 5 days) | Daily (`0 0 * * *`) | Decay can manifest within a single trading week |+| Medium-horizon (5-20 days) | Weekly (`0 2 * * 1`) | Balances detection speed with noise reduction |+| Long-horizon (> 20 days) | Monthly (`0 3 1 * *`) | Monthly rebalance cadence aligns with evaluation window |+| Live-trading factors | Every 6 hours (`21600000`) | Minimize exposure to degraded factors in production |++### General guidance++- **Avoid over-scanning**: Each scan consumes agent iterations and data-loader calls. Daily scans on a 500-factor universe are expensive; reserve them for live-trading portfolios.+- **Align with rebalance cycles**: A factor that rebalances monthly gains little from weekly scans -- the transition would not take effect until the next rebalance anyway.+- **Stagger multi-universe jobs**: Offset scan times across universes to avoid concurrent data-loader pressure on shared sources (e.g., tushare rate limits).+- **Monitor scan duration**: If a scan consistently takes longer than the interval between fires, the executor will queue dispatches. Increase the interval or narrow the universe.++## Job Lifecycle++```+POST /scheduled-runs+ |+ v+ [PENDING] --(executor tick, is_due=true)--> [RUNNING]+ | |+ | dispatch success: [COMPLETED]+ | dispatch failure: [FAILED]+ | |+ | next_run_at advanced, re-enters+ | PENDING for the next fire+ |+ DELETE /scheduled-runs/<id>+ |+ v+ [CANCELLED] (terminal, never re-dispatched)+```++Failed jobs are terminal. To retry, create a new job with the same prompt and schedule.diff --git a/agent/src/skills/strategy-dev-manager/references/strategy_extraction_guide.md b/agent/src/skills/strategy-dev-manager/references/strategy_extraction_guide.mdnew file mode 100644index 000000000..7d9935fce--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/references/strategy_extraction_guide.md@@ -0,0 +1,271 @@+# Strategy Extraction Guide++This guide supplements SKILL.md Phase 2 (EXTRACT) for strategy-type artifacts. It provides a structured methodology for extracting complete, implementable trading strategies from academic papers and research reports.++## 1. Strategy Components to Extract++A complete strategy consists of 5 components. Every extraction must identify or explicitly mark each as "not specified in paper."++### 1.1 Signal Logic++The core indicator or model that generates buy/sell signals.++- **Indicator type**: moving average, RSI, MACD, Bollinger Bands, custom formula, machine learning model+- **Mathematical formula**: preserve LaTeX notation from the paper+- **Input variables**: OHLCV columns, fundamental fields, alternative data+- **Lookback period**: number of bars or days used in computation+- **Signal output**: continuous score, binary flag, ranked cross-sectional value++### 1.2 Entry Rules++Conditions for opening a position.++- **Signal threshold**: the value at which the signal triggers entry (for example, RSI < 30)+- **Confirmation filters**: additional conditions that must be met (for example, volume > 2x average)+- **Timing rules**: specific days, times, or rebalance frequencies+- **Direction**: long-only, short-only, or long/short++### 1.3 Exit Rules++Conditions for closing a position.++- **Profit target**: close when unrealized PnL exceeds a threshold (for example, +5%)+- **Stop-loss**: close when unrealized loss exceeds a threshold (for example, -3%)+- **Time-based exit**: close after N bars regardless of PnL+- **Signal reversal**: close when the signal crosses back (for example, RSI > 70)+- **Trailing stop**: dynamic stop that follows price++### 1.4 Position Sizing++How much capital to allocate per trade.++- **Fixed fraction**: constant percentage of portfolio per position+- **Equal weight**: 1/N allocation across N selected instruments+- **Kelly criterion**: optimal bet size based on win rate and payoff ratio+- **Volatility targeting**: size inversely proportional to realized volatility+- **Maximum position**: cap on any single instrument's weight++### 1.5 Risk Management++Portfolio-level constraints beyond individual trade stops.++- **Maximum drawdown limit**: halt trading if portfolio drawdown exceeds threshold+- **Correlation constraints**: limit exposure to correlated instruments+- **Sector exposure caps**: maximum weight in any single sector+- **Leverage limits**: maximum gross or net exposure+- **Turnover constraints**: maximum rebalance turnover per period++## 2. Extraction Methodology++Follow these steps in order when extracting a strategy from a paper.++### Step 1: Identify the Strategy Type++Classify the strategy into one of the standard categories:++| Category | Description | Example Papers |+|----------|-------------|----------------|+| Trend-following | Ride persistent price trends | Moving average crossovers, breakout systems |+| Mean-reversion | Bet on price returning to a mean | RSI oversold/overbought, pairs trading |+| Momentum | Buy past winners, sell past losers | Jegadeesh and Titman (1993) |+| Carry | Earn yield differential | FX carry, bond carry |+| Value | Buy cheap, sell expensive | Fama-French (1993), Piotroski F-Score |+| Multi-factor | Combine multiple signals | Composite scoring models |++### Step 2: Extract the Signal Generation Logic++Locate the section of the paper that describes how signals are computed.++- Extract the exact mathematical formula (preserve LaTeX)+- Identify all input variables and their definitions+- Note the lookback period or window size+- Determine whether the signal is continuous or discrete+- Check whether the signal is cross-sectional (ranked across instruments) or time-series (absolute level)++### Step 3: Extract Entry Conditions++Find the rules that determine when to open a position.++- Identify the signal threshold value and its direction (above or below)+- Note any confirmation filters (volume, volatility, regime filters)+- Record timing rules (daily rebalance, weekly, monthly, event-driven)+- Determine if entry is immediate or requires confirmation over multiple bars++### Step 4: Extract Exit Conditions++Find the rules that determine when to close a position.++- Identify profit targets (fixed percentage, trailing, or signal-based)+- Identify stop-loss levels (fixed percentage, ATR-based, or time-based)+- Note any time-based exits (maximum holding period)+- Check for signal-reversal exits (signal crosses back through threshold)++### Step 5: Extract Position Sizing Rules++Find how the paper allocates capital to each trade.++- If the paper specifies a sizing method, extract the formula and parameters+- If the paper uses equal-weight portfolios, note the number of instruments+- If the paper uses volatility targeting, extract the target volatility and lookback+- If not specified, default to equal-weight (see Section 5)++### Step 6: Extract Risk Management Parameters++Find portfolio-level risk constraints.++- Maximum drawdown limits+- Sector or industry exposure caps+- Leverage constraints+- Correlation or concentration limits+- If not specified, apply conservative defaults (see Section 5)++### Step 7: Identify Required Data Inputs++List all data columns needed to implement the strategy.++- **OHLCV**: open, high, low, close, volume (always required)+- **Fundamental fields**: earnings, book value, revenue (for value/quality strategies)+- **Alternative data**: sentiment, options flow, macro indicators+- Verify that the required columns are available in the target universe's data loader++### Step 8: Map to SignalEngine Template Parameters++Translate the extracted components into the `strategy_signal_engine.py` template parameters.++| Extracted Component | SignalEngine Parameter | Notes |+|---------------------|----------------------|-------|+| Signal threshold for entry | `entry_threshold` | Normalize to [0, 1] range where possible |+| Signal threshold for exit | `exit_threshold` | May be negative for reversal exits |+| Stop-loss level | `stop_loss` | Expressed as negative decimal (for example, -0.05 for 5%) |+| Lookback window | `lookback` | Integer number of bars |+| Maximum position weight | `max_position` | 1.0 for full position, fraction for partial |++## 3. Common Strategy Patterns++Reference table mapping typical paper descriptions to SignalEngine parameters.++| Paper Description | SignalEngine Parameter | Example Value |+|-------------------|----------------------|---------------|+| "buy when RSI < 30" | `entry_threshold` | 0.3 (signal = -RSI/100, enter when signal < -0.3) |+| "sell when RSI > 70" | `exit_threshold` | -0.7 (exit when signal > 0.7, or -(-0.7)) |+| "sell when profit > 5%" | profit target in exit logic | 0.05 |+| "stop loss at 3%" | `stop_loss` | -0.03 |+| "20-day lookback" | `lookback` | 20 |+| "equal weight portfolio of 10 stocks" | `max_position` | 0.1 (1.0 / 10) |+| "rebalance monthly" | timing rule in generate() | ~21 trading days |+| "volatility target of 15%" | volatility scaling factor | 0.15 / realized_vol |+| "buy when MA20 > MA50" | dual-MA crossover logic | lookback=20 and lookback=50 |+| "hold for 5 days" | time-based exit | 5 bars |+| "trailing stop at 2x ATR" | dynamic stop in exit logic | 2.0 * ATR(14) |++## 4. Quality Checks++Before registering a strategy artifact, verify all of the following.++### 4.1 Completeness++- [ ] All 5 components identified (Signal Logic, Entry Rules, Exit Rules, Position Sizing, Risk Management)+- [ ] Components not found in the paper are explicitly marked "not specified in paper" with defaults applied+- [ ] Required data columns are listed and available in the target universe++### 4.2 Implementability++- [ ] Entry rules are unambiguous: a clear boolean condition that can be coded+- [ ] Exit rules are unambiguous: at least one exit condition is defined+- [ ] Signal formula uses only data available at time T (no look-ahead bias)+- [ ] All numeric thresholds have concrete values (not "approximately" or "around")++### 4.3 Data Availability++- [ ] Required OHLCV columns are available in the target universe's loader+- [ ] Fundamental fields (if needed) are available through the configured provider+- [ ] The lookback period does not exceed the available history length++### 4.4 Look-Ahead Bias Check++- [ ] Signal values on day T use only data from day T and earlier+- [ ] Returns are computed from T+1 onward (never same-day)+- [ ] No negative shifts or forward-looking references in the formula+- [ ] The `delta(df, d)` operator uses `d >= 1`++### 4.5 Deduplication++- [ ] Check `sdm_status(action="list")` for existing strategies with similar logic+- [ ] If Pearson correlation between the new strategy's signals and an existing strategy exceeds 0.99, treat as duplicate+- [ ] Correlation between 0.90 and 0.99 may be a variant worth keeping with a note++## 5. Handling Incomplete Strategies++Academic papers frequently omit one or more strategy components. Apply the following defaults and always document them in the artifact's `signal_definition` field.++### 5.1 Missing Position Sizing++**Default**: Equal-weight allocation across all selected instruments.++```+max_position = 1.0 / n_stocks+```++If the number of stocks is not specified, use `max_position = 1.0` (full position per instrument) and note the assumption.++### 5.2 Missing Risk Management++**Default**: Conservative risk limits.++| Parameter | Default Value | Rationale |+|-----------|--------------|-----------|+| Stop-loss | -5% per trade | Limits single-trade loss |+| Maximum drawdown | 20% portfolio-level | Halts trading during severe drawdowns |+| Maximum position | 10% per instrument | Prevents concentration |+| Leverage | 1.0x (no leverage) | Avoids amplified losses |++### 5.3 Missing Exit Rules++**Default**: Signal reversal exit.++Close the position when the entry signal reverses direction (for example, if entry was triggered by signal < -threshold, exit when signal > +threshold). If no clear reversal is defined, use a time-based exit of 20 trading days.++### 5.4 Missing Entry Timing++**Default**: Daily evaluation with immediate entry when conditions are met.++If the paper does not specify rebalance frequency, evaluate entry conditions at the close of each trading day and enter at the next day's open.++### 5.5 Missing Stop-Loss++**Default**: -5% fixed stop-loss from entry price.++This is a safety net. Document that the paper did not specify a stop-loss and the default was applied.++### 5.6 Documentation Requirement++Every default applied must be recorded in the artifact registration:++```+signal_definition: "Mean-reversion strategy from Avramov & Chordia (2006).+ Entry: normalized return < -0.3. Exit: normalized return > 0.1 or stop-loss.+ Defaults applied: stop-loss=-5% (not in paper), position sizing=equal-weight (not in paper)."+```++## 6. Extraction Output Format++The final extraction output should follow this structure for registration via `sdm_register`:++```+artifact_type: strategy+name: <short_identifier>+universe: <target_market>+columns_required:+ - open+ - high+ - low+ - close+ - volume+ - <additional columns>+entry_rules: <clear boolean condition>+exit_rules: <clear boolean condition or list of conditions>+position_sizing: <method and parameters>+risk_management: <constraints or "defaults applied: ...">+signal_definition: <full description including defaults>+source_paper: <paper title and authors>+```diff --git a/agent/src/skills/strategy-dev-manager/references/strategy_metrics.md b/agent/src/skills/strategy-dev-manager/references/strategy_metrics.mdnew file mode 100644index 000000000..26d662722--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/references/strategy_metrics.md@@ -0,0 +1,213 @@+# Strategy Evaluation Metrics++This document defines strategy-specific evaluation metrics that supplement the factor-focused IC/IR metrics in `decay_thresholds.md`. Factor-type artifacts use IC ratio, IR, and IC positive ratio as primary metrics. Strategy-type artifacts use risk-adjusted return metrics as defined below.++## 1. Strategy Evaluation Metrics++### 1.1 Primary Metrics++| Metric | Formula | Healthy | Warning | Decayed | Critical |+|--------|---------|---------|---------|---------|----------|+| Sharpe Ratio | (R - Rf) / sigma | > 1.0 | 0.5 - 1.0 | 0.0 - 0.5 | < 0.0 |+| Sortino Ratio | (R - Rf) / sigma_downside | > 1.5 | 1.0 - 1.5 | 0.5 - 1.0 | < 0.5 |+| Calmar Ratio | Annual Return / Max Drawdown | > 2.0 | 1.0 - 2.0 | 0.0 - 1.0 | < 0.0 |+| Max Drawdown | peak-to-trough decline | < 15% | 15% - 25% | 25% - 40% | > 40% |++### 1.2 Secondary Metrics++| Metric | Formula | Healthy | Warning | Decayed | Critical |+|--------|---------|---------|---------|---------|----------|+| Win Rate | winning trades / total trades | > 55% | 45% - 55% | 35% - 45% | < 35% |+| Profit Factor | gross profit / gross loss | > 1.5 | 1.2 - 1.5 | 1.0 - 1.2 | < 1.0 |+| Avg Trade Duration | mean holding period in bars | per strategy type | -- | -- | -- |++### 1.3 Metric Definitions++**Sharpe Ratio**: The excess return per unit of total risk. Uses annualized return minus the risk-free rate, divided by annualized standard deviation of returns. The primary metric for strategy health assessment.++```+Sharpe = (R_annual - Rf_annual) / sigma_annual+```++Where R_annual is the annualized portfolio return, Rf_annual is the annualized risk-free rate, and sigma_annual is the annualized standard deviation of daily returns multiplied by sqrt(252).++**Sortino Ratio**: Similar to Sharpe but penalizes only downside volatility. More appropriate for strategies with asymmetric return distributions.++```+Sortino = (R_annual - Rf_annual) / sigma_downside_annual+```++Where sigma_downside is the standard deviation of negative daily returns only.++**Calmar Ratio**: Annualized return divided by the maximum drawdown over the evaluation period. Captures the return-to-drawdown tradeoff.++```+Calmar = R_annual / |MaxDD|+```++Where MaxDD is the largest peak-to-trough decline expressed as a negative decimal.++**Max Drawdown**: The largest peak-to-trough decline in portfolio value during the evaluation period.++```+MaxDD = min over t of (V_t - max(V_0..V_t)) / max(V_0..V_t)+```++**Win Rate**: The fraction of closed trades that produced a positive return.++```+Win Rate = count(trades with PnL > 0) / count(all closed trades)+```++**Profit Factor**: The ratio of total gross profit to total gross loss across all closed trades.++```+Profit Factor = sum(positive PnL) / |sum(negative PnL)|+```++**Avg Trade Duration**: The mean number of bars (trading days) between entry and exit across all closed trades. This metric has no universal threshold; it is evaluated relative to the strategy's stated holding horizon.++### 1.4 Evaluation Priority++When evaluating a strategy backtest, check metrics in this order:++1. **Sharpe Ratio** -- primary gate; must exceed 0.5 for the artifact to be considered alive+2. **Max Drawdown** -- risk tolerance gate; must be below 30% for the artifact to be considered alive+3. **Sortino Ratio** -- secondary confirmation of risk-adjusted performance+4. **Win Rate and Profit Factor** -- additional context for strategy characterization++A strategy fails the minimum threshold if Sharpe < 0.5 OR Max Drawdown > 30%.++## 2. Strategy Decay Monitoring++### 2.1 How Strategy Decay Differs from Factor Decay++Factor decay and strategy decay use different primary signals:++| Aspect | Factor Decay | Strategy Decay |+|--------|-------------|----------------|+| Primary metric | IC ratio (rolling / baseline) | Sharpe ratio (rolling window) |+| What decays | Predictive power of the factor | Risk-adjusted return of the strategy |+| Detection speed | Fast (IC is computed per period) | Slower (Sharpe requires return accumulation) |+| Additional signals | IC positive ratio drop | Drawdown depth increase, win rate drop, trade frequency change |++### 2.2 Strategy-Specific Decay Signals++Beyond the Sharpe ratio, monitor these additional signals for strategy decay:++| Signal | Description | Threshold |+|--------|-------------|-----------|+| Increasing drawdown depth | Rolling max drawdown is deepening over successive windows | Each window deeper than the last for 3+ windows |+| Decreasing win rate | Rolling win rate is declining | Drop of > 10 percentage points from baseline |+| Increasing trade frequency | Number of trades per period is rising without return improvement | > 50% increase in trade count with flat or lower Sharpe |+| Decreasing profit factor | Rolling profit factor is declining | Drop below 1.0 (net losing) |++### 2.3 Strategy State Transition Rules++Strategy artifacts use the same state machine as factor artifacts but with strategy-specific transition conditions:++```+active -> monitoring: rolling Sharpe < 0.5 for 3 consecutive monitoring periods+monitoring -> decayed: rolling Sharpe < 0.0 for 2 additional consecutive periods+decayed -> disabled: negative Sharpe for 3 monitoring periods+monitoring -> active: rolling Sharpe > 1.0 for 2 consecutive periods (recovery)+```++| Transition | Condition | Consecutive Requirement |+|------------|-----------|------------------------|+| active -> monitoring | Rolling Sharpe < 0.5 OR Max DD > 25% | 3 consecutive monitoring periods |+| monitoring -> decayed | Rolling Sharpe < 0.0 OR Max DD > 40% | 2 additional consecutive periods |+| monitoring -> active | Rolling Sharpe > 1.0 AND Max DD < 15% | 2 consecutive periods (recovery) |+| decayed -> disabled | Rolling Sharpe < 0.0 | 3 monitoring periods |+| disabled -> active | Manual enable via `sdm_status(action="enable")` | -- |++### 2.4 Combined Metric Evaluation++When multiple metrics are available, the worst signal determines the overall state:++- If Sharpe is "Healthy" but Max Drawdown is "Warning", the overall signal is "Warning"+- If Sharpe is "Decayed" but all other metrics are "Healthy", the overall signal is "Decayed"+- This conservative approach prevents a single deteriorating metric from being masked by others++## 3. Benchmark Comparison++Strategy metrics should be evaluated in context by comparing against relevant benchmarks.++### 3.1 Required Benchmarks++| Benchmark | Purpose | When to Use |+|-----------|---------|-------------|+| Buy-and-hold | Baseline return of the target universe | Always |+| Risk-free rate | Reference for Sharpe/Sortino computation | Always |+| Equal-weight portfolio | Naive diversification baseline | Multi-instrument strategies |++### 3.2 Optional Benchmarks++| Benchmark | Purpose | When to Use |+|-----------|---------|-------------|+| Existing strategies in same category | Relative performance comparison | When similar strategies exist in the store |+| Market index (SPY, CSI 300, etc.) | Broad market comparison | Universe-specific |+| Inverse strategy | Check if the strategy is just shorting the market | When Sharpe is negative |++### 3.3 Comparison Metrics++When comparing a strategy against a benchmark, compute:++- **Excess return**: Strategy annual return minus benchmark annual return+- **Information ratio**: Excess return divided by tracking error (standard deviation of excess returns)+- **Beta**: Strategy return sensitivity to benchmark return+- **Alpha**: Strategy return minus (Rf + Beta * (Benchmark return - Rf))++A strategy with positive excess return and Information Ratio > 0.5 provides value beyond the benchmark.++## 4. Rolling Window Configuration++The rolling window for strategy decay monitoring should match the strategy's rebalance frequency.++### 4.1 Recommended Windows++| Strategy Horizon | Rebalance Frequency | Rolling Window | Rationale |+|-----------------|--------------------|----------------|-----------|+| Short-horizon | Daily | 60 trading days (~3 months) | Enough trades for statistical significance |+| Medium-horizon | Weekly or monthly | 120 trading days (~6 months) | Captures multiple rebalance cycles |+| Long-horizon | Quarterly | 252 trading days (~1 year) | Full market cycle coverage |++### 4.2 Window Selection Rules++- If the strategy's average trade duration is < 5 days, use the 60-day window+- If the strategy's average trade duration is 5-20 days, use the 120-day window+- If the strategy's average trade duration is > 20 days, use the 252-day window+- When in doubt, use the 120-day window as the default++### 4.3 Minimum Sample Size++A rolling window must contain a minimum number of trades for the metrics to be meaningful:++| Metric | Minimum Trades | Rationale |+|--------|---------------|-----------|+| Sharpe Ratio | 30 trades | Central limit theorem threshold |+| Win Rate | 50 trades | Binomial proportion stability |+| Profit Factor | 30 trades | Ratio stability |+| Max Drawdown | No minimum | Always computable from equity curve |++If the rolling window contains fewer trades than the minimum, the metric is reported but flagged as "insufficient sample" and excluded from state transition evaluation.++## 5. Configuration++All thresholds in this document are configurable via the `DecayThresholds` dataclass in `src/strategy_store/decay.py`. Strategy-specific overrides can be set per artifact during registration:++```+sdm_register(+ artifact_type="strategy",+ name="mean_reversion_rsi",+ universe="equity_us",+ sharpe_healthy=1.0,+ sharpe_warning=0.5,+ sharpe_decayed=0.0,+ max_dd_healthy=0.15,+ max_dd_warning=0.25,+ max_dd_decayed=0.40,+ rolling_window_days=120,+ ...+)+```diff --git a/agent/src/skills/strategy-dev-manager/templates/decay_report.md b/agent/src/skills/strategy-dev-manager/templates/decay_report.mdnew file mode 100644index 000000000..31ce2a795--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/templates/decay_report.md@@ -0,0 +1,43 @@+# Decay Scan Report++**Date**: {SCAN_DATE}+**Universe**: {UNIVERSE}+**Scan Type**: {MANUAL/SCHEDULED}++## Summary++| Metric | Value |+|--------|-------|+| Total artifacts scanned | {TOTAL_SCANNED} |+| Healthy | {HEALTHY_COUNT} |+| Warning | {WARNING_COUNT} |+| Decayed | {DECAYED_COUNT} |+| Critical | {CRITICAL_COUNT} |+| Insufficient data | {INSUFFICIENT_COUNT} |++## Status Transitions Applied++| Artifact | Name | From | To | Reason |+|----------|------|------|----|--------|+{TRANSITIONS_TABLE}++## Detailed Results++### Healthy Factors++{HEALTHY_DETAILS}++### Warning Factors (approaching decay thresholds)++{WARNING_DETAILS}++### Decayed/Critical Factors (action required)++{DECAYED_DETAILS}++## Recommendations++{RECOMMENDATIONS}++---+*Generated by Strategy Development Manager -- sdm_decay_scan*diff --git a/agent/src/skills/strategy-dev-manager/templates/factor_signal_engine.py b/agent/src/skills/strategy-dev-manager/templates/factor_signal_engine.pynew file mode 100644index 000000000..00e1c060a--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/templates/factor_signal_engine.py@@ -0,0 +1,82 @@+"""Factor SignalEngine template for Strategy Development Manager.++Generated by sdm_register for factor: {FACTOR_NAME}+Source: {SOURCE_PAPER}+Formula: {FORMULA_LATEX}++This template satisfies the backtest runner SignalEngine contract:+- Class named SignalEngine+- No-arg constructor (all params have defaults)+- generate(data_map) -> dict[str, pd.Series]+"""++from __future__ import annotations++import pandas as pd+++class SignalEngine:+ """Cross-sectional factor signal engine.++ Computes factor values and converts to position signals.+ """++ def __init__(+ self,+ lookback: int = 20,+ neutralize: bool = True,+ ) -> None:+ self.lookback = lookback+ self.neutralize = neutralize++ def generate(self, data_map: dict[str, pd.DataFrame]) -> dict[str, pd.Series]:+ """Generate factor-based position signals.++ Args:+ data_map: symbol -> OHLCV DataFrame with columns+ [open, high, low, close, volume] indexed by date.++ Returns:+ symbol -> pd.Series of target signals (float, clipped to [-1, 1]).+ """+ signals: dict[str, pd.Series] = {}++ # Step 1: Compute raw factor values for each symbol+ factor_values: dict[str, pd.Series] = {}+ for symbol, df in data_map.items():+ # TODO: Replace with actual factor formula from paper+ # Example: 12-month momentum (Jegadeesh & Titman 1993)+ factor_values[symbol] = (+ df["close"].pct_change(self.lookback)+ )++ # Step 2: Cross-sectional ranking+ all_dates = sorted(+ {date for fv in factor_values.values() for date in fv.index}+ )+ for date in all_dates:+ cross_section = {+ sym: fv.loc[date]+ for sym, fv in factor_values.items()+ if date in fv.index and pd.notna(fv.loc[date])+ }+ if len(cross_section) < 5:+ continue++ # Rank-based signal: top quintile = +1, bottom quintile = -1+ ranked = pd.Series(cross_section).rank(pct=True)+ for symbol, rank in ranked.items():+ if symbol not in signals:+ signals[symbol] = pd.Series(dtype=float)+ # Linear mapping: rank 0 -> -1, rank 1 -> +1+ signal_val = 2.0 * rank - 1.0+ signals[symbol] = pd.concat([+ signals[symbol],+ pd.Series([signal_val], index=[date]),+ ])++ # Step 3: Clip signals to [-1, 1]+ for symbol in signals:+ signals[symbol] = signals[symbol].clip(-1.0, 1.0)++ return signalsdiff --git a/agent/src/skills/strategy-dev-manager/templates/strategy_signal_engine.py b/agent/src/skills/strategy-dev-manager/templates/strategy_signal_engine.pynew file mode 100644index 000000000..3a6bfc735--- /dev/null+++ b/agent/src/skills/strategy-dev-manager/templates/strategy_signal_engine.py@@ -0,0 +1,92 @@+"""Strategy SignalEngine template for Strategy Development Manager.++Generated by sdm_register for strategy: {STRATEGY_NAME}+Source: {SOURCE_PAPER}+Signal definition: {SIGNAL_DEFINITION}++Entry rules: {ENTRY_RULES}+Exit rules: {EXIT_RULES}+Position sizing: {POSITION_SIZING}++This template satisfies the backtest runner SignalEngine contract.+"""++from __future__ import annotations++import pandas as pd+++class SignalEngine:+ """Rule-based strategy signal engine.++ Implements entry/exit rules with position sizing from the source paper.+ """++ def __init__(+ self,+ entry_threshold: float = 0.3,+ exit_threshold: float = -0.1,+ max_position: float = 1.0,+ stop_loss: float = -0.05,+ lookback: int = 20,+ ) -> None:+ self.entry_threshold = entry_threshold+ self.exit_threshold = exit_threshold+ self.max_position = max_position+ self.stop_loss = stop_loss+ self.lookback = lookback++ def generate(self, data_map: dict[str, pd.DataFrame]) -> dict[str, pd.Series]:+ """Generate strategy position signals.++ Args:+ data_map: symbol -> OHLCV DataFrame.++ Returns:+ symbol -> pd.Series of target positions (float, clipped to [-1, 1]).+ """+ signals: dict[str, pd.Series] = {}++ for symbol, df in data_map.items():+ position = pd.Series(0.0, index=df.index, dtype=float)++ # TODO: Replace with actual strategy logic from paper+ # Example: Mean-reversion strategy (Avramov & Chordia 2006)++ # Compute signal indicator+ returns = df["close"].pct_change(self.lookback)+ volatility = df["close"].pct_change().rolling(self.lookback).std()++ # Normalized signal: return / volatility+ normalized = returns / volatility.replace(0, float("nan"))++ # Entry: when normalized signal crosses below -entry_threshold (buy dip)+ # Exit: when normalized signal crosses above exit_threshold (take profit)+ in_position = False+ entry_price = 0.0++ for i, date in enumerate(df.index):+ if i < self.lookback:+ continue++ sig = normalized.loc[date] if date in normalized.index else 0.0+ price = df["close"].loc[date]++ if not in_position:+ # Entry condition+ if pd.notna(sig) and sig < -self.entry_threshold:+ in_position = True+ entry_price = price+ position.loc[date] = self.max_position+ else:+ # Exit conditions+ pnl = (price - entry_price) / entry_price+ if (pd.notna(sig) and sig > self.exit_threshold) or pnl < self.stop_loss:+ in_position = False+ position.loc[date] = 0.0+ else:+ position.loc[date] = self.max_position++ signals[symbol] = position.clip(-1.0, 1.0)++ return signalsdiff --git a/agent/src/strategy_store/__init__.py b/agent/src/strategy_store/__init__.pynew file mode 100644index 000000000..dd300e360--- /dev/null+++ b/agent/src/strategy_store/__init__.py@@ -0,0 +1,21 @@+"""Strategy Development Manager — artifact store and decay monitoring."""++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ BenchCategory,+ BenchResult,+ DecaySignal,+ DecaySnapshot,+)++__all__ = [+ "Artifact",+ "ArtifactStatus",+ "ArtifactType",+ "BenchCategory",+ "BenchResult",+ "DecaySignal",+ "DecaySnapshot",+]diff --git a/agent/src/strategy_store/_shared.py b/agent/src/strategy_store/_shared.pynew file mode 100644index 000000000..48801f3b9--- /dev/null+++ b/agent/src/strategy_store/_shared.py@@ -0,0 +1,21 @@+"""Shared store singleton for SDM tools.++All SDM tools (sdm_register, sdm_status, sdm_decay_scan) import+``get_store()`` from this module to share a single ``SqliteStrategyStore``+instance. The SQLite backend provides WAL-mode persistence with FK+constraints and schema migrations via ``PRAGMA user_version``.+"""++from __future__ import annotations++from src.strategy_store.sqlite_store import SqliteStrategyStore++_store: SqliteStrategyStore | None = None+++def get_store() -> SqliteStrategyStore:+ """Return the process-wide strategy store singleton."""+ global _store+ if _store is None:+ _store = SqliteStrategyStore()+ return _storediff --git a/agent/src/strategy_store/decay.py b/agent/src/strategy_store/decay.pynew file mode 100644index 000000000..cdd2786fd--- /dev/null+++ b/agent/src/strategy_store/decay.py@@ -0,0 +1,273 @@+"""Decay state machine — pure logic for evaluating factor/strategy health."""++from __future__ import annotations++from dataclasses import dataclass++from src.strategy_store.models import (+ ArtifactStatus,+ DecaySignal,+)+++@dataclass(frozen=True)+class DecayThresholds:+ """Configurable thresholds for decay evaluation."""++ # IC Ratio (rolling / baseline) thresholds+ ic_ratio_healthy: float = 0.7+ ic_ratio_warning: float = 0.5+ ic_ratio_decayed: float = 0.3++ # IR (rolling window) thresholds+ ir_healthy: float = 1.0+ ir_warning: float = 0.5+ ir_decayed: float = 0.1++ # IC Positive Ratio thresholds+ ic_pos_ratio_healthy: float = 0.55+ ic_pos_ratio_warning: float = 0.45+ ic_pos_ratio_decayed: float = 0.35++ # Sharpe thresholds (for strategies)+ sharpe_healthy: float = 1.0+ sharpe_warning: float = 0.5+ sharpe_decayed: float = 0.0++ # Consecutive signal counts for state transitions+ warnings_for_monitoring: int = 3 # active → monitoring+ warnings_for_decayed: int = 2 # monitoring → decayed (additional)+ critical_for_disabled: int = 3 # decayed → disabled+++# Ordered worst → best for comparison+_SIGNAL_ORDER: list[DecaySignal] = [+ DecaySignal.CRITICAL,+ DecaySignal.DECAYED,+ DecaySignal.WARNING,+ DecaySignal.HEALTHY,+]+++def _worst(a: DecaySignal, b: DecaySignal) -> DecaySignal:+ """Return the worse of two signals."""+ return a if _SIGNAL_ORDER.index(a) <= _SIGNAL_ORDER.index(b) else b+++def _classify(+ value: float,+ healthy: float,+ warning: float,+ decayed: float,+) -> DecaySignal:+ """Classify a single metric value against three descending thresholds.++ Thresholds are ordered high→low (healthy > warning > decayed).+ A value at or above `healthy` is HEALTHY; between healthy and warning+ is WARNING; between warning and decayed is DECAYED; below decayed+ is CRITICAL.+ """+ if value >= healthy:+ return DecaySignal.HEALTHY+ if value >= warning:+ return DecaySignal.WARNING+ if value >= decayed:+ return DecaySignal.DECAYED+ return DecaySignal.CRITICAL+++class DecayEvaluator:+ """Evaluates factor/strategy health and determines status transitions.++ Pure logic — no I/O, no database access. Feed it metrics and get decisions.+ """++ def __init__(self, thresholds: DecayThresholds | None = None) -> None:+ self._t = thresholds or DecayThresholds()++ def evaluate_decay(+ self,+ *,+ ic_ratio: float | None = None,+ ir: float | None = None,+ ic_positive_ratio: float | None = None,+ sharpe: float | None = None,+ ) -> DecaySignal:+ """Evaluate a single set of metrics and return the decay signal.++ Uses the WORST signal across all provided metrics.+ For factors: uses ic_ratio, ir, ic_positive_ratio.+ For strategies: uses sharpe (and optionally ic_ratio if available).++ Args:+ ic_ratio: rolling_ic_mean / baseline_ic_mean (factor health).+ ir: Information Ratio over rolling window.+ ic_positive_ratio: fraction of periods with positive IC.+ sharpe: Sharpe ratio (strategy health).++ Returns:+ DecaySignal: HEALTHY, WARNING, DECAYED, or CRITICAL.+ """+ signals: list[DecaySignal] = []++ if ic_ratio is not None:+ signals.append(+ _classify(+ ic_ratio,+ self._t.ic_ratio_healthy,+ self._t.ic_ratio_warning,+ self._t.ic_ratio_decayed,+ )+ )++ if ir is not None:+ signals.append(+ _classify(+ ir,+ self._t.ir_healthy,+ self._t.ir_warning,+ self._t.ir_decayed,+ )+ )++ if ic_positive_ratio is not None:+ signals.append(+ _classify(+ ic_positive_ratio,+ self._t.ic_pos_ratio_healthy,+ self._t.ic_pos_ratio_warning,+ self._t.ic_pos_ratio_decayed,+ )+ )++ if sharpe is not None:+ signals.append(+ _classify(+ sharpe,+ self._t.sharpe_healthy,+ self._t.sharpe_warning,+ self._t.sharpe_decayed,+ )+ )++ if not signals:+ return DecaySignal.HEALTHY++ result = signals[0]+ for s in signals[1:]:+ result = _worst(result, s)+ return result++ def should_transition(+ self,+ current_status: ArtifactStatus,+ consecutive_signals: list[DecaySignal],+ ) -> ArtifactStatus | None:+ """Determine if a status transition should occur.++ Args:+ current_status: Current artifact status.+ consecutive_signals: Recent decay signals (newest last).++ Returns:+ New ArtifactStatus if transition should occur, None otherwise.++ Transition rules:+ - active → monitoring: WARNING or worse for ``warnings_for_monitoring``+ consecutive readings.+ - monitoring → decayed: DECAYED or worse for ``warnings_for_decayed``+ consecutive readings.+ - monitoring → active: HEALTHY for 1 reading (recovery).+ - decayed → disabled: CRITICAL for ``critical_for_disabled``+ consecutive readings.+ """+ if not consecutive_signals:+ return None++ if current_status == ArtifactStatus.ACTIVE:+ return self._check_active_to_monitoring(consecutive_signals)++ if current_status == ArtifactStatus.MONITORING:+ return self._check_monitoring_transition(consecutive_signals)++ if current_status == ArtifactStatus.DECAYED:+ return self._check_decayed_to_disabled(consecutive_signals)++ return None++ def _check_active_to_monitoring(+ self, signals: list[DecaySignal]+ ) -> ArtifactStatus | None:+ """active → monitoring: WARNING+ for warnings_for_monitoring consecutive."""+ needed = self._t.warnings_for_monitoring+ tail = signals[-needed:] if len(signals) >= needed else signals+ if len(tail) < needed:+ return None+ if all(s != DecaySignal.HEALTHY for s in tail):+ return ArtifactStatus.MONITORING+ return None++ def _check_monitoring_transition(+ self, signals: list[DecaySignal]+ ) -> ArtifactStatus | None:+ """monitoring → active (recovery) or monitoring → decayed."""+ latest = signals[-1]++ # Recovery: single HEALTHY reading+ if latest == DecaySignal.HEALTHY:+ return ArtifactStatus.ACTIVE++ # Decay: DECAYED or worse for warnings_for_decayed consecutive+ needed = self._t.warnings_for_decayed+ tail = signals[-needed:] if len(signals) >= needed else signals+ if len(tail) < needed:+ return None+ if all(s in (DecaySignal.DECAYED, DecaySignal.CRITICAL) for s in tail):+ return ArtifactStatus.DECAYED+ return None++ def _check_decayed_to_disabled(+ self, signals: list[DecaySignal]+ ) -> ArtifactStatus | None:+ """decayed → disabled: CRITICAL for critical_for_disabled consecutive."""+ needed = self._t.critical_for_disabled+ tail = signals[-needed:] if len(signals) >= needed else signals+ if len(tail) < needed:+ return None+ if all(s == DecaySignal.CRITICAL for s in tail):+ return ArtifactStatus.DISABLED+ return None++ def evaluate_and_transition(+ self,+ current_status: ArtifactStatus,+ *,+ ic_ratio: float | None = None,+ ir: float | None = None,+ ic_positive_ratio: float | None = None,+ sharpe: float | None = None,+ prior_signals: list[DecaySignal] | None = None,+ ) -> tuple[DecaySignal, ArtifactStatus | None]:+ """Convenience: evaluate metrics and determine transition in one call.++ Args:+ current_status: Current artifact status.+ ic_ratio: rolling_ic_mean / baseline_ic_mean.+ ir: Information Ratio over rolling window.+ ic_positive_ratio: fraction of periods with positive IC.+ sharpe: Sharpe ratio.+ prior_signals: Previously accumulated signals (new signal appended).++ Returns:+ Tuple of (decay_signal, new_status_or_None).+ """+ signal = self.evaluate_decay(+ ic_ratio=ic_ratio,+ ir=ir,+ ic_positive_ratio=ic_positive_ratio,+ sharpe=sharpe,+ )+ history = list(prior_signals or [])+ history.append(signal)+ new_status = self.should_transition(current_status, history)+ return signal, new_statusdiff --git a/agent/src/strategy_store/models.py b/agent/src/strategy_store/models.pynew file mode 100644index 000000000..22dbd197e--- /dev/null+++ b/agent/src/strategy_store/models.py@@ -0,0 +1,120 @@+"""Data models for strategy development artifacts and decay monitoring."""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum+++class ArtifactType(str, Enum):+ """Type of research artifact."""++ FACTOR = "factor"+ STRATEGY = "strategy"+++class ArtifactStatus(str, Enum):+ """Lifecycle states for a research artifact."""++ CREATED = "created"+ BENCHING = "benching"+ ACTIVE = "active"+ MONITORING = "monitoring"+ DECAYED = "decayed"+ DISABLED = "disabled"+++class DecaySignal(str, Enum):+ """Decay health signal for an artifact."""++ HEALTHY = "healthy"+ WARNING = "warning"+ DECAYED = "decayed"+ CRITICAL = "critical"+++class BenchCategory(str, Enum):+ """Backtest evaluation category."""++ ALIVE = "alive"+ REVERSED = "reversed"+ DEAD = "dead"+ CONFIRMED_ALIVE = "confirmed_alive"+ NOISE = "noise"+++@dataclass(frozen=True)+class Artifact:+ """Persisted research artifact record."""++ id: str+ type: ArtifactType+ name: str+ universe: str+ source_paper: str | None = None+ source_url: str | None = None+ # Factor-specific+ formula_latex: str | None = None+ theme: tuple[str, ...] = ()+ columns_required: tuple[str, ...] = ()+ decay_horizon: int = 20+ # Strategy-specific+ signal_definition: str | None = None+ entry_rules: str | None = None+ exit_rules: str | None = None+ position_sizing: str | None = None+ # Common+ signal_engine_path: str | None = None+ run_dir: str | None = None+ hypothesis_id: str | None = None+ # Lifecycle+ status: ArtifactStatus = ArtifactStatus.CREATED+ created_at: str = ""+ updated_at: str = ""+ disabled_at: str | None = None+ disabled_reason: str | None = None+++@dataclass(frozen=True)+class BenchResult:+ """Backtest result for an artifact."""++ id: int | None = None+ artifact_id: str = ""+ bench_type: str = "initial"+ # Factor metrics+ ic_mean: float | None = None+ ic_std: float | None = None+ ir: float | None = None+ ic_positive_ratio: float | None = None+ t_stat: float | None = None+ # Strategy metrics+ sharpe: float | None = None+ annual_return: float | None = None+ max_drawdown: float | None = None+ calmar: float | None = None+ # Evaluation+ category: BenchCategory | None = None+ # Time window+ train_start: str | None = None+ train_end: str | None = None+ test_start: str | None = None+ test_end: str | None = None+ run_dir: str | None = None+ created_at: str = ""+++@dataclass(frozen=True)+class DecaySnapshot:+ """Point-in-time decay monitoring snapshot."""++ id: int | None = None+ artifact_id: str = ""+ rolling_ic_mean: float | None = None+ rolling_ir: float | None = None+ baseline_ic_mean: float | None = None+ ic_ratio: float | None = None+ decay_signal: DecaySignal | None = None+ consecutive_warnings: int = 0+ detail: str | None = None+ created_at: str = ""diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.pynew file mode 100644index 000000000..b4a297d1d--- /dev/null+++ b/agent/src/strategy_store/sqlite_store.py@@ -0,0 +1,585 @@+"""SQLite-backed strategy/factor artifact store.++Satisfies ``StrategyStoreProtocol``. Uses WAL mode for concurrent reads,+FK constraints for referential integrity, and ``PRAGMA user_version``+for schema migrations.+"""++from __future__ import annotations++import json+import os+import sqlite3+import threading+import uuid+from contextlib import contextmanager+from datetime import datetime, timezone+from functools import wraps+from pathlib import Path+from typing import Callable, Sequence, TypeVar++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ BenchCategory,+ BenchResult,+ DecaySignal,+ DecaySnapshot,+)++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++_DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "strategy_store.db"+_DB_PATH_ENV = "VIBE_TRADING_STRATEGY_STORE_DB_PATH"++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _now_iso() -> str:+ """Return the current UTC time as an ISO-8601 string."""+ return datetime.now(timezone.utc).isoformat()+++def _new_artifact_id() -> str:+ """Generate a unique artifact identifier."""+ return f"art_{uuid.uuid4().hex[:12]}"+++def _json_dumps(value: object) -> str:+ """Serialize *value* to a compact JSON string."""+ return json.dumps(value, ensure_ascii=False, sort_keys=True)+++def _json_loads(value: str | None, default: object) -> object:+ """Deserialize a JSON string, returning *default* when empty."""+ if not value:+ return default+ return json.loads(value)+++def _default_db_path() -> Path:+ """Return the configured strategy-store database path."""+ raw_path = os.getenv(_DB_PATH_ENV, "").strip()+ if raw_path:+ return Path(raw_path).expanduser()+ return _DEFAULT_DB_PATH+++F = TypeVar("F", bound=Callable)+++def _synchronized(method: F) -> F:+ """Serialize access to the shared SQLite connection."""++ @wraps(method)+ def wrapper(self, *args, **kwargs): # type: ignore[no-untyped-def]+ with self._lock:+ return method(self, *args, **kwargs)++ return wrapper # type: ignore[return-value]+++# ---------------------------------------------------------------------------+# SqliteStrategyStore+# ---------------------------------------------------------------------------+++class SqliteStrategyStore:+ """SQLite-backed strategy/factor artifact store.++ Satisfies ``StrategyStoreProtocol``. Uses WAL mode for concurrent reads,+ FK constraints for referential integrity, and ``PRAGMA user_version``+ for schema migrations.+ """++ def __init__(self, db_path: Path | str | None = None) -> None:+ """Initialize the strategy store.++ Args:+ db_path: SQLite database path. When omitted,+ ``VIBE_TRADING_STRATEGY_STORE_DB_PATH`` can override the+ default ``~/.vibe-trading/strategy_store.db``.+ """+ self.db_path = (+ Path(db_path) if db_path is not None else _default_db_path()+ )+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)+ self._conn.row_factory = sqlite3.Row+ self._conn.execute("PRAGMA foreign_keys=ON")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA synchronous=NORMAL")+ self._lock = threading.RLock()+ self._init_db()++ # -- Schema bootstrap ---------------------------------------------------++ def _init_db(self) -> None:+ """Create schema if needed, set PRAGMAs."""+ with self._lock:+ self._conn.executescript(+ """+ CREATE TABLE IF NOT EXISTS artifacts (+ id TEXT PRIMARY KEY,+ type TEXT NOT NULL CHECK(type IN ('factor', 'strategy')),+ name TEXT NOT NULL UNIQUE,+ source_paper TEXT,+ source_url TEXT,+ formula_latex TEXT,+ theme TEXT,+ columns_required TEXT,+ decay_horizon INTEGER DEFAULT 20,+ signal_definition TEXT,+ entry_rules TEXT,+ exit_rules TEXT,+ position_sizing TEXT,+ universe TEXT NOT NULL,+ signal_engine_path TEXT,+ run_dir TEXT,+ hypothesis_id TEXT,+ status TEXT NOT NULL DEFAULT 'created'+ CHECK(status IN (+ 'created','benching','active',+ 'monitoring','decayed','disabled')),+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ disabled_at TEXT,+ disabled_reason TEXT+ );++ CREATE TABLE IF NOT EXISTS bench_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ artifact_id TEXT NOT NULL+ REFERENCES artifacts(id) ON DELETE CASCADE,+ bench_type TEXT NOT NULL+ CHECK(bench_type IN ('initial','periodic','manual')),+ ic_mean REAL,+ ic_std REAL,+ ir REAL,+ ic_positive_ratio REAL,+ t_stat REAL,+ sharpe REAL,+ annual_return REAL,+ max_drawdown REAL,+ calmar REAL,+ category TEXT+ CHECK(category IN (+ 'alive','reversed','dead',+ 'confirmed_alive','noise')),+ train_start TEXT,+ train_end TEXT,+ test_start TEXT,+ test_end TEXT,+ run_dir TEXT,+ created_at TEXT NOT NULL+ );++ CREATE TABLE IF NOT EXISTS decay_snapshots (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ artifact_id TEXT NOT NULL+ REFERENCES artifacts(id) ON DELETE CASCADE,+ rolling_ic_mean REAL,+ rolling_ir REAL,+ baseline_ic_mean REAL,+ ic_ratio REAL,+ decay_signal TEXT+ CHECK(decay_signal IN (+ 'healthy','warning','decayed','critical')),+ consecutive_warnings INTEGER DEFAULT 0,+ detail TEXT,+ created_at TEXT NOT NULL+ );++ CREATE INDEX IF NOT EXISTS idx_artifacts_status+ ON artifacts(status);+ CREATE INDEX IF NOT EXISTS idx_artifacts_type+ ON artifacts(type);+ CREATE INDEX IF NOT EXISTS idx_bench_artifact+ ON bench_history(artifact_id, created_at);+ CREATE INDEX IF NOT EXISTS idx_decay_artifact+ ON decay_snapshots(artifact_id, created_at);+ """+ )+ if self._conn.execute("PRAGMA user_version").fetchone()[0] < 1:+ self._conn.execute("PRAGMA user_version=1")+ self._conn.commit()++ # -- Write transaction --------------------------------------------------++ @contextmanager+ def _write_transaction(self):+ """Open an immediate write transaction for cross-connection safety."""+ self._conn.execute("BEGIN IMMEDIATE")+ try:+ yield+ except Exception:+ self._conn.rollback()+ raise+ else:+ self._conn.commit()++ # -- Row converters -----------------------------------------------------++ @staticmethod+ def _row_to_artifact(row: sqlite3.Row) -> Artifact:+ """Convert a database row to an ``Artifact`` dataclass."""+ return Artifact(+ id=row["id"],+ type=ArtifactType(row["type"]),+ name=row["name"],+ universe=row["universe"],+ source_paper=row["source_paper"],+ source_url=row["source_url"],+ formula_latex=row["formula_latex"],+ theme=tuple(_json_loads(row["theme"], [])),+ columns_required=tuple(_json_loads(row["columns_required"], [])),+ decay_horizon=row["decay_horizon"],+ signal_definition=row["signal_definition"],+ entry_rules=row["entry_rules"],+ exit_rules=row["exit_rules"],+ position_sizing=row["position_sizing"],+ signal_engine_path=row["signal_engine_path"],+ run_dir=row["run_dir"],+ hypothesis_id=row["hypothesis_id"],+ status=ArtifactStatus(row["status"]),+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ disabled_at=row["disabled_at"],+ disabled_reason=row["disabled_reason"],+ )++ @staticmethod+ def _row_to_bench_result(row: sqlite3.Row) -> BenchResult:+ """Convert a database row to a ``BenchResult`` dataclass."""+ category = row["category"]+ return BenchResult(+ id=row["id"],+ artifact_id=row["artifact_id"],+ bench_type=row["bench_type"],+ ic_mean=row["ic_mean"],+ ic_std=row["ic_std"],+ ir=row["ir"],+ ic_positive_ratio=row["ic_positive_ratio"],+ t_stat=row["t_stat"],+ sharpe=row["sharpe"],+ annual_return=row["annual_return"],+ max_drawdown=row["max_drawdown"],+ calmar=row["calmar"],+ category=BenchCategory(category) if category else None,+ train_start=row["train_start"],+ train_end=row["train_end"],+ test_start=row["test_start"],+ test_end=row["test_end"],+ run_dir=row["run_dir"],+ created_at=row["created_at"],+ )++ @staticmethod+ def _row_to_decay_snapshot(row: sqlite3.Row) -> DecaySnapshot:+ """Convert a database row to a ``DecaySnapshot`` dataclass."""+ signal = row["decay_signal"]+ return DecaySnapshot(+ id=row["id"],+ artifact_id=row["artifact_id"],+ rolling_ic_mean=row["rolling_ic_mean"],+ rolling_ir=row["rolling_ir"],+ baseline_ic_mean=row["baseline_ic_mean"],+ ic_ratio=row["ic_ratio"],+ decay_signal=DecaySignal(signal) if signal else None,+ consecutive_warnings=row["consecutive_warnings"],+ detail=row["detail"],+ created_at=row["created_at"],+ )++ # -- Artifact CRUD ------------------------------------------------------++ @_synchronized+ def register_artifact(self, artifact: Artifact) -> str:+ """Register a new artifact. Returns the artifact_id."""+ now = _now_iso()+ artifact_id = artifact.id or _new_artifact_id()+ created_at = artifact.created_at or now++ with self._write_transaction():+ self._conn.execute(+ """+ INSERT INTO artifacts (+ id, type, name, source_paper, source_url, formula_latex,+ theme, columns_required, decay_horizon, signal_definition,+ entry_rules, exit_rules, position_sizing, universe,+ signal_engine_path, run_dir, hypothesis_id, status,+ created_at, updated_at, disabled_at, disabled_reason+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ artifact_id,+ artifact.type.value,+ artifact.name,+ artifact.source_paper,+ artifact.source_url,+ artifact.formula_latex,+ _json_dumps(list(artifact.theme)),+ _json_dumps(list(artifact.columns_required)),+ artifact.decay_horizon,+ artifact.signal_definition,+ artifact.entry_rules,+ artifact.exit_rules,+ artifact.position_sizing,+ artifact.universe,+ artifact.signal_engine_path,+ artifact.run_dir,+ artifact.hypothesis_id,+ artifact.status.value,+ created_at,+ now,+ artifact.disabled_at,+ artifact.disabled_reason,+ ),+ )+ return artifact_id++ @_synchronized+ def get_artifact(self, artifact_id: str) -> Artifact | None:+ """Get a single artifact by ID. Returns ``None`` if not found."""+ row = self._conn.execute(+ "SELECT * FROM artifacts WHERE id = ?", (artifact_id,)+ ).fetchone()+ return self._row_to_artifact(row) if row else None++ @_synchronized+ def list_artifacts(+ self,+ *,+ type: ArtifactType | None = None,+ status: ArtifactStatus | None = None,+ universe: str | None = None,+ limit: int = 100,+ ) -> Sequence[Artifact]:+ """List artifacts with optional filters, newest first."""+ clauses: list[str] = []+ params: list[object] = []++ if type is not None:+ clauses.append("type = ?")+ params.append(type.value)+ if status is not None:+ clauses.append("status = ?")+ params.append(status.value)+ if universe is not None:+ clauses.append("universe = ?")+ params.append(universe)++ where = ""+ if clauses:+ where = "WHERE " + " AND ".join(clauses)++ rows = self._conn.execute(+ f"SELECT * FROM artifacts {where} ORDER BY created_at DESC LIMIT ?",+ [*params, limit],+ ).fetchall()+ return [self._row_to_artifact(row) for row in rows]++ @_synchronized+ def update_status(+ self,+ artifact_id: str,+ status: ArtifactStatus,+ *,+ reason: str | None = None,+ ) -> Artifact | None:+ """Transition an artifact to a new status.++ Sets ``disabled_at`` when transitioning to ``DISABLED``.+ Clears it when transitioning away.+ Returns the updated artifact, or ``None`` if not found.+ """+ existing = self.get_artifact(artifact_id)+ if existing is None:+ return None++ now = _now_iso()+ disabled_at: str | None = None+ disabled_reason: str | None = None++ if status is ArtifactStatus.DISABLED:+ disabled_at = now+ disabled_reason = reason if reason is not None else existing.disabled_reason+ elif existing.status is ArtifactStatus.DISABLED:+ # Clear disabled fields when moving out of DISABLED.+ disabled_at = None+ disabled_reason = None+ else:+ # Preserve existing disabled fields.+ disabled_at = existing.disabled_at+ disabled_reason = existing.disabled_reason++ with self._write_transaction():+ self._conn.execute(+ """+ UPDATE artifacts+ SET status = ?, updated_at = ?, disabled_at = ?, disabled_reason = ?+ WHERE id = ?+ """,+ (status.value, now, disabled_at, disabled_reason, artifact_id),+ )+ return self.get_artifact(artifact_id)++ @_synchronized+ def update_artifact(self, artifact: Artifact) -> Artifact | None:+ """Replace an artifact record. Returns updated artifact or ``None``."""+ existing = self.get_artifact(artifact.id)+ if existing is None:+ return None++ now = _now_iso()+ with self._write_transaction():+ self._conn.execute(+ """+ UPDATE artifacts+ SET type = ?, name = ?, source_paper = ?, source_url = ?,+ formula_latex = ?, theme = ?, columns_required = ?,+ decay_horizon = ?, signal_definition = ?,+ entry_rules = ?, exit_rules = ?, position_sizing = ?,+ universe = ?, signal_engine_path = ?, run_dir = ?,+ hypothesis_id = ?, status = ?, updated_at = ?,+ disabled_at = ?, disabled_reason = ?+ WHERE id = ?+ """,+ (+ artifact.type.value,+ artifact.name,+ artifact.source_paper,+ artifact.source_url,+ artifact.formula_latex,+ _json_dumps(list(artifact.theme)),+ _json_dumps(list(artifact.columns_required)),+ artifact.decay_horizon,+ artifact.signal_definition,+ artifact.entry_rules,+ artifact.exit_rules,+ artifact.position_sizing,+ artifact.universe,+ artifact.signal_engine_path,+ artifact.run_dir,+ artifact.hypothesis_id,+ artifact.status.value,+ now,+ artifact.disabled_at,+ artifact.disabled_reason,+ artifact.id,+ ),+ )+ return self.get_artifact(artifact.id)++ # -- Bench history ------------------------------------------------------++ @_synchronized+ def record_bench(self, result: BenchResult) -> int:+ """Record a bench result. Returns the result ID."""+ now = _now_iso()+ created_at = result.created_at or now+ category_value = result.category.value if result.category else None++ with self._write_transaction():+ cursor = self._conn.execute(+ """+ INSERT INTO bench_history (+ artifact_id, bench_type, ic_mean, ic_std, ir,+ ic_positive_ratio, t_stat, sharpe, annual_return,+ max_drawdown, calmar, category,+ train_start, train_end, test_start, test_end,+ run_dir, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ result.artifact_id,+ result.bench_type,+ result.ic_mean,+ result.ic_std,+ result.ir,+ result.ic_positive_ratio,+ result.t_stat,+ result.sharpe,+ result.annual_return,+ result.max_drawdown,+ result.calmar,+ category_value,+ result.train_start,+ result.train_end,+ result.test_start,+ result.test_end,+ result.run_dir,+ created_at,+ ),+ )+ return cursor.lastrowid # type: ignore[return-value]++ @_synchronized+ def get_bench_history(+ self, artifact_id: str, *, limit: int = 50+ ) -> Sequence[BenchResult]:+ """Get bench history for an artifact, newest first."""+ rows = self._conn.execute(+ """+ SELECT * FROM bench_history+ WHERE artifact_id = ?+ ORDER BY created_at DESC+ LIMIT ?+ """,+ (artifact_id, limit),+ ).fetchall()+ return [self._row_to_bench_result(row) for row in rows]++ # -- Decay snapshots ----------------------------------------------------++ @_synchronized+ def record_decay_snapshot(self, snapshot: DecaySnapshot) -> int:+ """Record a decay monitoring snapshot. Returns the snapshot ID."""+ now = _now_iso()+ created_at = snapshot.created_at or now+ signal_value = snapshot.decay_signal.value if snapshot.decay_signal else None++ with self._write_transaction():+ cursor = self._conn.execute(+ """+ INSERT INTO decay_snapshots (+ artifact_id, rolling_ic_mean, rolling_ir,+ baseline_ic_mean, ic_ratio, decay_signal,+ consecutive_warnings, detail, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ snapshot.artifact_id,+ snapshot.rolling_ic_mean,+ snapshot.rolling_ir,+ snapshot.baseline_ic_mean,+ snapshot.ic_ratio,+ signal_value,+ snapshot.consecutive_warnings,+ snapshot.detail,+ created_at,+ ),+ )+ return cursor.lastrowid # type: ignore[return-value]++ @_synchronized+ def get_decay_history(+ self, artifact_id: str, *, limit: int = 20+ ) -> Sequence[DecaySnapshot]:+ """Get decay snapshots for an artifact, newest first."""+ rows = self._conn.execute(+ """+ SELECT * FROM decay_snapshots+ WHERE artifact_id = ?+ ORDER BY created_at DESC+ LIMIT ?+ """,+ (artifact_id, limit),+ ).fetchall()+ return [self._row_to_decay_snapshot(row) for row in rows]diff --git a/agent/src/strategy_store/store.py b/agent/src/strategy_store/store.pynew file mode 100644index 000000000..fa72437f5--- /dev/null+++ b/agent/src/strategy_store/store.py@@ -0,0 +1,310 @@+"""Strategy and factor artifact store — Protocol + in-memory reference implementation.++The ``StrategyStoreProtocol`` defines the abstract interface for persisting+strategy/factor artifacts, bench results, and decay snapshots. Concrete+backends (SQLite, DuckDB, JSON, …) will be decided by the community via+GitHub Issue #455.++``InMemoryStrategyStore`` is a fully functional reference implementation backed+by Python dicts and lists, suitable for tests and as a template for concrete+backends.+"""++from __future__ import annotations++import copy+import threading+import uuid+from dataclasses import replace+from datetime import datetime, timezone+from functools import wraps+from typing import Callable, Sequence, TypeVar, runtime_checkable+from typing import Protocol++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ BenchResult,+ DecaySnapshot,+ DecaySignal,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _now_iso() -> str:+ """Return the current UTC time as an ISO-8601 string."""+ return datetime.now(timezone.utc).isoformat()+++def _new_artifact_id() -> str:+ """Generate a unique artifact identifier."""+ return f"art_{uuid.uuid4().hex[:12]}"+++F = TypeVar("F", bound=Callable)+++def _synchronized(method: F) -> F:+ """Serialize access to shared in-memory state."""++ @wraps(method)+ def wrapper(self, *args, **kwargs): # type: ignore[no-untyped-def]+ with self._lock:+ return method(self, *args, **kwargs)++ return wrapper # type: ignore[return-value]+++# ---------------------------------------------------------------------------+# Protocol — abstract store interface+# ---------------------------------------------------------------------------+++@runtime_checkable+class StrategyStoreProtocol(Protocol):+ """Abstract interface for the strategy/factor artifact store.++ Concrete implementations may use SQLite, DuckDB, JSON, or any other backend.+ The community will decide on the production backend via GitHub Issue #455.+ """++ # --- Artifact CRUD ---++ def register_artifact(self, artifact: Artifact) -> str:+ """Register a new artifact. Returns the artifact_id."""+ ...++ def get_artifact(self, artifact_id: str) -> Artifact | None:+ """Get a single artifact by ID. Returns None if not found."""+ ...++ def list_artifacts(+ self,+ *,+ type: ArtifactType | None = None,+ status: ArtifactStatus | None = None,+ universe: str | None = None,+ limit: int = 100,+ ) -> Sequence[Artifact]:+ """List artifacts with optional filters."""+ ...++ def update_status(+ self,+ artifact_id: str,+ status: ArtifactStatus,+ *,+ reason: str | None = None,+ ) -> Artifact | None:+ """Transition an artifact to a new status. Returns updated artifact or None."""+ ...++ def update_artifact(self, artifact: Artifact) -> Artifact | None:+ """Replace an artifact record. Returns updated artifact or None if not found."""+ ...++ # --- Bench history ---++ def record_bench(self, result: BenchResult) -> int:+ """Record a bench result. Returns the result ID."""+ ...++ def get_bench_history(+ self, artifact_id: str, *, limit: int = 50+ ) -> Sequence[BenchResult]:+ """Get bench history for an artifact, newest first."""+ ...++ # --- Decay snapshots ---++ def record_decay_snapshot(self, snapshot: DecaySnapshot) -> int:+ """Record a decay monitoring snapshot. Returns the snapshot ID."""+ ...++ def get_decay_history(+ self, artifact_id: str, *, limit: int = 20+ ) -> Sequence[DecaySnapshot]:+ """Get decay snapshots for an artifact, newest first."""+ ...+++# ---------------------------------------------------------------------------+# In-memory reference implementation+# ---------------------------------------------------------------------------+++class InMemoryStrategyStore:+ """Dict/list-backed reference implementation of ``StrategyStoreProtocol``.++ Thread-safe via ``threading.RLock``. Intended for tests and as a template+ for concrete persistent backends.+ """++ def __init__(self) -> None:+ self._lock = threading.RLock()+ self._artifacts: dict[str, Artifact] = {}+ self._bench_results: list[BenchResult] = []+ self._decay_snapshots: list[DecaySnapshot] = []+ self._bench_counter: int = 0+ self._decay_counter: int = 0++ # -- Artifact CRUD -------------------------------------------------------++ @_synchronized+ def register_artifact(self, artifact: Artifact) -> str:+ """Register a new artifact, assigning an ID and timestamps.++ Returns:+ The assigned ``artifact_id``.+ """+ now = _now_iso()+ artifact_id = artifact.id or _new_artifact_id()+ stored = replace(+ artifact,+ id=artifact_id,+ created_at=artifact.created_at or now,+ updated_at=now,+ )+ self._artifacts[artifact_id] = stored+ return artifact_id++ @_synchronized+ def get_artifact(self, artifact_id: str) -> Artifact | None:+ """Return a single artifact by ID, or ``None``."""+ return self._artifacts.get(artifact_id)++ @_synchronized+ def list_artifacts(+ self,+ *,+ type: ArtifactType | None = None,+ status: ArtifactStatus | None = None,+ universe: str | None = None,+ limit: int = 100,+ ) -> Sequence[Artifact]:+ """List artifacts with composable filters, newest first."""+ results: list[Artifact] = []+ for art in self._artifacts.values():+ if type is not None and art.type != type:+ continue+ if status is not None and art.status != status:+ continue+ if universe is not None and art.universe != universe:+ continue+ results.append(art)++ # Sort by created_at descending (newest first).+ results.sort(key=lambda a: a.created_at or "", reverse=True)+ return results[:limit]++ @_synchronized+ def update_status(+ self,+ artifact_id: str,+ status: ArtifactStatus,+ *,+ reason: str | None = None,+ ) -> Artifact | None:+ """Transition an artifact to a new status.++ Sets ``disabled_at`` and ``disabled_reason`` when transitioning to+ ``DISABLED``. Returns the updated artifact, or ``None`` if not found.+ """+ existing = self._artifacts.get(artifact_id)+ if existing is None:+ return None++ now = _now_iso()+ updates: dict = {+ "status": status,+ "updated_at": now,+ }++ if status is ArtifactStatus.DISABLED:+ updates["disabled_at"] = now+ if reason is not None:+ updates["disabled_reason"] = reason+ else:+ # Clear disabled fields when moving out of DISABLED.+ if existing.status is ArtifactStatus.DISABLED:+ updates["disabled_at"] = None+ updates["disabled_reason"] = None++ updated = replace(existing, **updates)+ self._artifacts[artifact_id] = updated+ return updated++ @_synchronized+ def update_artifact(self, artifact: Artifact) -> Artifact | None:+ """Replace an artifact record.++ Returns the updated artifact, or ``None`` if the ID is not found.+ """+ if artifact.id not in self._artifacts:+ return None++ now = _now_iso()+ stored = replace(artifact, updated_at=now)+ self._artifacts[artifact.id] = stored+ return stored++ # -- Bench history -------------------------------------------------------++ @_synchronized+ def record_bench(self, result: BenchResult) -> int:+ """Record a bench result, assigning an auto-increment ID.++ Returns:+ The assigned result ID.+ """+ self._bench_counter += 1+ now = _now_iso()+ stored = replace(+ result,+ id=self._bench_counter,+ created_at=result.created_at or now,+ )+ self._bench_results.append(stored)+ return stored.id++ @_synchronized+ def get_bench_history(+ self, artifact_id: str, *, limit: int = 50+ ) -> Sequence[BenchResult]:+ """Return bench results for an artifact, newest first."""+ matched = [r for r in self._bench_results if r.artifact_id == artifact_id]+ matched.sort(key=lambda r: r.created_at or "", reverse=True)+ return matched[:limit]++ # -- Decay snapshots -----------------------------------------------------++ @_synchronized+ def record_decay_snapshot(self, snapshot: DecaySnapshot) -> int:+ """Record a decay monitoring snapshot, assigning an auto-increment ID.++ Returns:+ The assigned snapshot ID.+ """+ self._decay_counter += 1+ now = _now_iso()+ stored = replace(+ snapshot,+ id=self._decay_counter,+ created_at=snapshot.created_at or now,+ )+ self._decay_snapshots.append(stored)+ return stored.id++ @_synchronized+ def get_decay_history(+ self, artifact_id: str, *, limit: int = 20+ ) -> Sequence[DecaySnapshot]:+ """Return decay snapshots for an artifact, newest first."""+ matched = [s for s in self._decay_snapshots if s.artifact_id == artifact_id]+ matched.sort(key=lambda s: s.created_at or "", reverse=True)+ return matched[:limit]diff --git a/agent/src/tools/sdm_decay_scan_tool.py b/agent/src/tools/sdm_decay_scan_tool.pynew file mode 100644index 000000000..f8f824277--- /dev/null+++ b/agent/src/tools/sdm_decay_scan_tool.py@@ -0,0 +1,245 @@+"""BaseTool wrapper for batch decay monitoring scan across active artifacts."""++from __future__ import annotations++import json+from dataclasses import asdict+from typing import Any++from src.agent.tools import BaseTool+from src.strategy_store.decay import DecayEvaluator+from src.strategy_store.models import (+ ArtifactStatus,+ ArtifactType,+ DecaySignal,+ DecaySnapshot,+)+from src.strategy_store._shared import get_store as _get_store+++def _ok(payload: dict[str, Any]) -> str:+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False)+++def _error(exc: Exception) -> str:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+++def _compute_scan_metrics(+ bench_history: list[Any],+) -> dict[str, float | None]:+ """Compute baseline and rolling IC metrics from bench history.++ Uses last 20 bench results: baseline from first 5, rolling from last 5.+ Returns dict with baseline_ic_mean, rolling_ic_mean, ic_ratio,+ rolling_ir, ic_positive_ratio.+ """+ result: dict[str, float | None] = {+ "baseline_ic_mean": None,+ "rolling_ic_mean": None,+ "ic_ratio": None,+ "rolling_ir": None,+ "ic_positive_ratio": None,+ }++ # bench_history is newest-first; reverse for chronological order+ chronological = list(reversed(bench_history))++ ic_values = [+ r.ic_mean for r in chronological if r.ic_mean is not None+ ]++ if len(ic_values) < 3:+ return result++ baseline_ics = ic_values[:5]+ rolling_ics = ic_values[-5:]++ baseline_mean = sum(baseline_ics) / len(baseline_ics)+ rolling_mean = sum(rolling_ics) / len(rolling_ics)++ result["baseline_ic_mean"] = round(baseline_mean, 6)+ result["rolling_ic_mean"] = round(rolling_mean, 6)++ if baseline_mean != 0:+ result["ic_ratio"] = round(rolling_mean / baseline_mean, 4)++ # IR from rolling window+ if len(rolling_ics) > 1:+ mean_r = sum(rolling_ics) / len(rolling_ics)+ var_r = sum((x - mean_r) ** 2 for x in rolling_ics) / (len(rolling_ics) - 1)+ std_r = var_r**0.5+ if std_r > 0:+ result["rolling_ir"] = round(mean_r / std_r, 4)++ # IC positive ratio across all available values+ positive_count = sum(1 for v in ic_values if v > 0)+ result["ic_positive_ratio"] = round(positive_count / len(ic_values), 4)++ return result+++class SdmDecayScanTool(BaseTool):+ """Run decay monitoring scan on active factors/strategies."""++ name = "sdm_decay_scan"+ description = (+ "Run decay monitoring scan on active factors/strategies. "+ "Evaluates rolling IC vs baseline for each active artifact and "+ "reports decay signals."+ )+ is_readonly = True+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "universe": {+ "type": "string",+ "description": "Filter by universe",+ },+ "artifact_type": {+ "type": "string",+ "enum": ["factor", "strategy"],+ "description": "Filter by type",+ },+ "dry_run": {+ "type": "boolean",+ "description": "Report without applying transitions",+ "default": False,+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Scan active artifacts for decay and return a summary."""+ try:+ store = _get_store()+ evaluator = DecayEvaluator()++ universe = kwargs.get("universe")+ type_filter = None+ if kwargs.get("artifact_type"):+ type_filter = ArtifactType(kwargs["artifact_type"])+ dry_run = bool(kwargs.get("dry_run", False))++ # Collect ACTIVE and MONITORING artifacts+ active = store.list_artifacts(+ type=type_filter,+ status=ArtifactStatus.ACTIVE,+ universe=universe,+ )+ monitoring = store.list_artifacts(+ type=type_filter,+ status=ArtifactStatus.MONITORING,+ universe=universe,+ )++ targets = list(active) + list(monitoring)++ counts = {+ "total_scanned": 0,+ "healthy": 0,+ "warning": 0,+ "decayed": 0,+ "critical": 0,+ "insufficient_data": 0,+ }+ transitions_applied: list[dict[str, Any]] = []+ per_artifact: list[dict[str, Any]] = []++ for artifact in targets:+ counts["total_scanned"] += 1+ bench_history = list(+ store.get_bench_history(artifact.id, limit=20)+ )++ if len(bench_history) < 3:+ counts["insufficient_data"] += 1+ per_artifact.append({+ "artifact_id": artifact.id,+ "name": artifact.name,+ "signal": "insufficient_data",+ "bench_count": len(bench_history),+ })+ continue++ metrics = _compute_scan_metrics(bench_history)++ signal = evaluator.evaluate_decay(+ ic_ratio=metrics["ic_ratio"],+ ir=metrics["rolling_ir"],+ ic_positive_ratio=metrics["ic_positive_ratio"],+ )++ # Count by signal+ signal_key = signal.value+ if signal_key in counts:+ counts[signal_key] += 1++ # Determine transition+ decay_history = list(+ store.get_decay_history(artifact.id, limit=10)+ )+ prior_signals = [+ s.decay_signal for s in reversed(decay_history)+ if s.decay_signal is not None+ ]+ recommended = evaluator.should_transition(+ artifact.status, prior_signals + [signal]+ )++ # Apply transition if not dry_run+ transition_info: dict[str, Any] | None = None+ if recommended and not dry_run:+ updated = store.update_status(+ artifact.id,+ recommended,+ reason=f"Decay scan: {signal.value} signal triggered transition",+ )+ if updated is not None:+ transition_info = {+ "from": artifact.status.value,+ "to": recommended.value,+ }+ transitions_applied.append({+ "artifact_id": artifact.id,+ "name": artifact.name,+ **transition_info,+ })++ # Record decay snapshot+ if not dry_run:+ snapshot = DecaySnapshot(+ artifact_id=artifact.id,+ rolling_ic_mean=metrics["rolling_ic_mean"],+ rolling_ir=metrics["rolling_ir"],+ baseline_ic_mean=metrics["baseline_ic_mean"],+ ic_ratio=metrics["ic_ratio"],+ decay_signal=signal,+ detail=json.dumps(metrics, ensure_ascii=False),+ )+ store.record_decay_snapshot(snapshot)++ entry: dict[str, Any] = {+ "artifact_id": artifact.id,+ "name": artifact.name,+ "current_status": artifact.status.value,+ "signal": signal.value,+ "metrics": metrics,+ }+ if transition_info:+ entry["transition"] = transition_info+ elif recommended and dry_run:+ entry["recommended_transition"] = recommended.value++ per_artifact.append(entry)++ return _ok({+ "summary": counts,+ "transitions_applied": len(transitions_applied),+ "dry_run": dry_run,+ "artifacts": per_artifact,+ })+ except Exception as exc:+ return _error(exc)diff --git a/agent/src/tools/sdm_register_tool.py b/agent/src/tools/sdm_register_tool.pynew file mode 100644index 000000000..3ea1ab8b6--- /dev/null+++ b/agent/src/tools/sdm_register_tool.py@@ -0,0 +1,123 @@+"""BaseTool wrapper for registering factors/strategies into the strategy store."""++from __future__ import annotations++import json+from dataclasses import asdict+from typing import Any++from src.agent.tools import BaseTool+from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+)+from src.strategy_store._shared import get_store as _get_store+++def _ok(payload: dict[str, Any]) -> str:+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False)+++def _error(exc: Exception) -> str:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+++class SdmRegisterTool(BaseTool):+ """Register a new factor or strategy into the strategy store."""++ name = "sdm_register"+ description = (+ "Register a new factor or strategy extracted from a paper into the "+ "strategy store. Research-only: does not place trades."+ )+ is_readonly = False+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "artifact_type": {+ "type": "string",+ "enum": ["factor", "strategy"],+ "description": "Type of artifact",+ },+ "name": {+ "type": "string",+ "description": "Unique name for the factor or strategy",+ },+ "universe": {+ "type": "string",+ "description": "Target market universe (e.g. CSI300, SP500, BTC)",+ },+ "source_paper": {+ "type": "string",+ "description": "Source paper title or DOI",+ },+ "source_url": {+ "type": "string",+ "description": "Source paper URL",+ },+ "formula_latex": {+ "type": "string",+ "description": "Factor formula in LaTeX (factor only)",+ },+ "theme": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Factor themes (factor only)",+ },+ "columns_required": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Required data columns (factor only)",+ },+ "signal_definition": {+ "type": "string",+ "description": "Signal logic description (strategy only)",+ },+ "signal_engine_path": {+ "type": "string",+ "description": "Path to signal_engine.py",+ },+ "hypothesis_id": {+ "type": "string",+ "description": "Linked hypothesis ID",+ },+ },+ "required": ["artifact_type", "name", "universe"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Build an Artifact from kwargs, register it, and return the record."""+ try:+ store = _get_store()++ artifact_type = ArtifactType(kwargs["artifact_type"])++ theme_raw = kwargs.get("theme")+ theme = tuple(theme_raw) if theme_raw else ()++ columns_raw = kwargs.get("columns_required")+ columns_required = tuple(columns_raw) if columns_raw else ()++ artifact = Artifact(+ id="",+ type=artifact_type,+ name=str(kwargs["name"]),+ universe=str(kwargs["universe"]),+ source_paper=kwargs.get("source_paper"),+ source_url=kwargs.get("source_url"),+ formula_latex=kwargs.get("formula_latex"),+ theme=theme,+ columns_required=columns_required,+ signal_definition=kwargs.get("signal_definition"),+ signal_engine_path=kwargs.get("signal_engine_path"),+ hypothesis_id=kwargs.get("hypothesis_id"),+ status=ArtifactStatus.CREATED,+ )++ artifact_id = store.register_artifact(artifact)+ stored = store.get_artifact(artifact_id)+ return _ok({"artifact": asdict(stored)}) # type: ignore[arg-type]+ except Exception as exc:+ return _error(exc)diff --git a/agent/src/tools/sdm_status_tool.py b/agent/src/tools/sdm_status_tool.pynew file mode 100644index 000000000..f7def2516--- /dev/null+++ b/agent/src/tools/sdm_status_tool.py@@ -0,0 +1,287 @@+"""BaseTool wrapper for querying and updating strategy store artifact status."""++from __future__ import annotations++import json+from dataclasses import asdict+from typing import Any++from src.agent.tools import BaseTool+from src.strategy_store.decay import DecayEvaluator+from src.strategy_store.models import (+ ArtifactStatus,+ ArtifactType,+ DecaySignal,+)+from src.strategy_store._shared import get_store as _get_store+++def _ok(payload: dict[str, Any]) -> str:+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False)+++def _error(exc: Exception) -> str:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+++def _artifact_to_dict(artifact: Any) -> dict[str, Any]:+ """Convert a frozen dataclass artifact to a JSON-safe dict."""+ d = asdict(artifact)+ # Enum values → strings for JSON serialization+ if "type" in d:+ d["type"] = d["type"].value if hasattr(d["type"], "value") else d["type"]+ if "status" in d:+ d["status"] = (+ d["status"].value if hasattr(d["status"], "value") else d["status"]+ )+ if "category" in d and d["category"] is not None:+ d["category"] = (+ d["category"].value+ if hasattr(d["category"], "value")+ else d["category"]+ )+ return d+++def _compute_ic_metrics(+ bench_history: list[Any],+) -> dict[str, float | None]:+ """Compute baseline and rolling IC metrics from bench history.++ Returns dict with baseline_ic_mean, rolling_ic_mean, ic_ratio,+ rolling_ir, ic_positive_ratio.+ """+ result: dict[str, float | None] = {+ "baseline_ic_mean": None,+ "rolling_ic_mean": None,+ "ic_ratio": None,+ "rolling_ir": None,+ "ic_positive_ratio": None,+ }++ # bench_history is newest-first; reverse for chronological order+ chronological = list(reversed(bench_history))++ ic_values = [+ r.ic_mean for r in chronological if r.ic_mean is not None+ ]++ if len(ic_values) < 3:+ return result++ # Baseline from first 5 entries, rolling from last 5+ baseline_ics = ic_values[:5]+ rolling_ics = ic_values[-5:]++ baseline_mean = sum(baseline_ics) / len(baseline_ics)+ rolling_mean = sum(rolling_ics) / len(rolling_ics)++ result["baseline_ic_mean"] = round(baseline_mean, 6)+ result["rolling_ic_mean"] = round(rolling_mean, 6)++ if baseline_mean != 0:+ result["ic_ratio"] = round(rolling_mean / baseline_mean, 4)++ # IR from rolling window+ if len(rolling_ics) > 1:+ mean_r = sum(rolling_ics) / len(rolling_ics)+ var_r = sum((x - mean_r) ** 2 for x in rolling_ics) / (len(rolling_ics) - 1)+ std_r = var_r**0.5+ if std_r > 0:+ result["rolling_ir"] = round(mean_r / std_r, 4)++ # IC positive ratio+ positive_count = sum(1 for v in ic_values if v > 0)+ result["ic_positive_ratio"] = round(positive_count / len(ic_values), 4)++ return result+++class SdmStatusTool(BaseTool):+ """Query or update factor/strategy status in the strategy store."""++ name = "sdm_status"+ description = (+ "Query or update factor/strategy status in the strategy store. "+ "Actions: list, detail, disable, enable, decay_check."+ )+ is_readonly = True+ repeatable = True+ parameters = {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": ["list", "detail", "disable", "enable", "decay_check"],+ "description": "Action to perform",+ },+ "artifact_id": {+ "type": "string",+ "description": "Artifact ID (required for detail/disable/enable/decay_check)",+ },+ "artifact_type": {+ "type": "string",+ "enum": ["factor", "strategy"],+ "description": "Filter by type (list only)",+ },+ "status_filter": {+ "type": "string",+ "description": "Filter by status (list only)",+ },+ "universe_filter": {+ "type": "string",+ "description": "Filter by universe (list only)",+ },+ "reason": {+ "type": "string",+ "description": "Reason for disable",+ },+ },+ "required": ["action"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Route by action and return the result as JSON."""+ try:+ store = _get_store()+ action = str(kwargs["action"])++ if action == "list":+ return self._handle_list(store, kwargs)+ if action == "detail":+ return self._handle_detail(store, kwargs)+ if action == "disable":+ return self._handle_disable(store, kwargs)+ if action == "enable":+ return self._handle_enable(store, kwargs)+ if action == "decay_check":+ return self._handle_decay_check(store, kwargs)++ return _error(ValueError(f"Unknown action: {action}"))+ except Exception as exc:+ return _error(exc)++ def _handle_list(+ self, store: Any, kwargs: dict[str, Any]+ ) -> str:+ """List artifacts with optional filters."""+ type_filter = None+ if kwargs.get("artifact_type"):+ type_filter = ArtifactType(kwargs["artifact_type"])++ status_filter = None+ if kwargs.get("status_filter"):+ status_filter = ArtifactStatus(kwargs["status_filter"])++ artifacts = store.list_artifacts(+ type=type_filter,+ status=status_filter,+ universe=kwargs.get("universe_filter"),+ )+ return _ok({+ "count": len(artifacts),+ "artifacts": [_artifact_to_dict(a) for a in artifacts],+ })++ def _handle_detail(+ self, store: Any, kwargs: dict[str, Any]+ ) -> str:+ """Get full detail for a single artifact."""+ artifact_id = str(kwargs.get("artifact_id", ""))+ if not artifact_id:+ return _error(ValueError("artifact_id is required for detail"))++ artifact = store.get_artifact(artifact_id)+ if artifact is None:+ return _error(ValueError(f"Artifact not found: {artifact_id}"))++ bench_history = store.get_bench_history(artifact_id, limit=50)+ decay_history = store.get_decay_history(artifact_id, limit=20)++ return _ok({+ "artifact": _artifact_to_dict(artifact),+ "bench_history": [asdict(r) for r in bench_history],+ "decay_history": [asdict(s) for s in decay_history],+ })++ def _handle_disable(+ self, store: Any, kwargs: dict[str, Any]+ ) -> str:+ """Disable an artifact."""+ artifact_id = str(kwargs.get("artifact_id", ""))+ if not artifact_id:+ return _error(ValueError("artifact_id is required for disable"))++ updated = store.update_status(+ artifact_id,+ ArtifactStatus.DISABLED,+ reason=kwargs.get("reason"),+ )+ if updated is None:+ return _error(ValueError(f"Artifact not found: {artifact_id}"))++ return _ok({"artifact": _artifact_to_dict(updated)})++ def _handle_enable(+ self, store: Any, kwargs: dict[str, Any]+ ) -> str:+ """Re-enable a disabled artifact."""+ artifact_id = str(kwargs.get("artifact_id", ""))+ if not artifact_id:+ return _error(ValueError("artifact_id is required for enable"))++ updated = store.update_status(artifact_id, ArtifactStatus.ACTIVE)+ if updated is None:+ return _error(ValueError(f"Artifact not found: {artifact_id}"))++ return _ok({"artifact": _artifact_to_dict(updated)})++ def _handle_decay_check(+ self, store: Any, kwargs: dict[str, Any]+ ) -> str:+ """Evaluate decay state for an artifact."""+ artifact_id = str(kwargs.get("artifact_id", ""))+ if not artifact_id:+ return _error(ValueError("artifact_id is required for decay_check"))++ artifact = store.get_artifact(artifact_id)+ if artifact is None:+ return _error(ValueError(f"Artifact not found: {artifact_id}"))++ bench_history = list(store.get_bench_history(artifact_id, limit=10))+ if len(bench_history) < 3:+ return _ok({+ "artifact_id": artifact_id,+ "signal": "insufficient_data",+ "message": f"Need at least 3 bench results, have {len(bench_history)}",+ })++ metrics = _compute_ic_metrics(bench_history)+ evaluator = DecayEvaluator()++ signal = evaluator.evaluate_decay(+ ic_ratio=metrics["ic_ratio"],+ ir=metrics["rolling_ir"],+ ic_positive_ratio=metrics["ic_positive_ratio"],+ )++ # Get prior decay signals from history+ decay_history = list(store.get_decay_history(artifact_id, limit=10))+ prior_signals = [+ s.decay_signal for s in reversed(decay_history)+ if s.decay_signal is not None+ ]++ recommended_transition = evaluator.should_transition(+ artifact.status, prior_signals + [signal]+ )++ return _ok({+ "artifact_id": artifact_id,+ "current_status": artifact.status.value,+ "signal": signal.value,+ "recommended_transition": (+ recommended_transition.value if recommended_transition else None+ ),+ "metrics": metrics,+ })diff --git a/agent/tests/test_strategy_store.py b/agent/tests/test_strategy_store.pynew file mode 100644index 000000000..a1a2a062b--- /dev/null+++ b/agent/tests/test_strategy_store.py@@ -0,0 +1,753 @@+"""Unit tests for the Strategy Development Manager store and tools."""++from __future__ import annotations++import json+import pytest++from src.strategy_store.models import (+ Artifact,+ ArtifactStatus,+ ArtifactType,+ BenchResult,+ BenchCategory,+ DecaySnapshot,+ DecaySignal,+)+from src.strategy_store.store import InMemoryStrategyStore+from src.strategy_store.decay import DecayEvaluator, DecayThresholds+++# ---------------------------------------------------------------------------+# Fixture: reset the shared singleton before each test+# ---------------------------------------------------------------------------++[email protected](autouse=True)+def _reset_store(tmp_path):+ """Reset the shared store singleton before each test."""+ import src.strategy_store._shared as shared+ from src.strategy_store.sqlite_store import SqliteStrategyStore++ shared._store = SqliteStrategyStore(db_path=tmp_path / "test.db")+ yield+ shared._store = None+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_artifact(+ *,+ name: str = "test_factor",+ universe: str = "CSI300",+ artifact_type: ArtifactType = ArtifactType.FACTOR,+ status: ArtifactStatus = ArtifactStatus.CREATED,+) -> Artifact:+ return Artifact(+ id="",+ type=artifact_type,+ name=name,+ universe=universe,+ status=status,+ )+++def _register_active_artifact(+ store: InMemoryStrategyStore,+ *,+ name: str = "test_factor",+ universe: str = "CSI300",+ artifact_type: ArtifactType = ArtifactType.FACTOR,+) -> str:+ """Register an artifact and transition it to ACTIVE."""+ aid = store.register_artifact(_make_artifact(name=name, universe=universe, artifact_type=artifact_type))+ store.update_status(aid, ArtifactStatus.ACTIVE)+ return aid+++# ===========================================================================+# TestModels+# ===========================================================================+++class TestModels:+ """Tests for data-model dataclasses and enums."""++ def test_artifact_creation(self):+ art = Artifact(+ id="art_001",+ type=ArtifactType.FACTOR,+ name="momentum_20d",+ universe="CSI300",+ )+ assert art.id == "art_001"+ assert art.type == ArtifactType.FACTOR+ assert art.name == "momentum_20d"+ assert art.status == ArtifactStatus.CREATED # default+ assert art.theme == ()+ assert art.columns_required == ()+ assert art.decay_horizon == 20+ assert art.disabled_at is None++ def test_artifact_frozen(self):+ art = Artifact(+ id="art_001",+ type=ArtifactType.FACTOR,+ name="momentum_20d",+ universe="CSI300",+ )+ with pytest.raises(AttributeError):+ art.name = "changed" # type: ignore[misc]++ def test_artifact_type_enum(self):+ assert ArtifactType.FACTOR.value == "factor"+ assert ArtifactType.STRATEGY.value == "strategy"++ def test_artifact_status_enum(self):+ expected = {"created", "benching", "active", "monitoring", "decayed", "disabled"}+ actual = {s.value for s in ArtifactStatus}+ assert actual == expected++ def test_bench_result_creation(self):+ br = BenchResult(+ artifact_id="art_001",+ bench_type="initial",+ ic_mean=0.05,+ ic_std=0.02,+ ir=2.5,+ ic_positive_ratio=0.7,+ t_stat=3.1,+ )+ assert br.artifact_id == "art_001"+ assert br.ic_mean == 0.05+ assert br.ir == 2.5+ assert br.id is None # not yet persisted++ def test_decay_snapshot_creation(self):+ snap = DecaySnapshot(+ artifact_id="art_001",+ rolling_ic_mean=0.04,+ rolling_ir=1.5,+ baseline_ic_mean=0.05,+ ic_ratio=0.8,+ decay_signal=DecaySignal.HEALTHY,+ consecutive_warnings=0,+ )+ assert snap.artifact_id == "art_001"+ assert snap.decay_signal == DecaySignal.HEALTHY+ assert snap.ic_ratio == 0.8+++# ===========================================================================+# TestInMemoryStore+# ===========================================================================+++class TestInMemoryStore:+ """Tests for the InMemoryStrategyStore reference implementation."""++ def test_register_artifact(self):+ store = InMemoryStrategyStore()+ art = _make_artifact()+ aid = store.register_artifact(art)+ assert aid.startswith("art_")+ fetched = store.get_artifact(aid)+ assert fetched is not None+ assert fetched.name == "test_factor"++ def test_register_auto_id(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ assert aid.startswith("art_")+ assert len(aid) > 4++ def test_register_auto_timestamp(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ art = store.get_artifact(aid)+ assert art is not None+ assert art.created_at != ""+ assert art.updated_at != ""++ def test_list_artifacts_empty(self):+ store = InMemoryStrategyStore()+ assert store.list_artifacts() == []++ def test_list_artifacts_filter_type(self):+ store = InMemoryStrategyStore()+ store.register_artifact(_make_artifact(name="f1", artifact_type=ArtifactType.FACTOR))+ store.register_artifact(_make_artifact(name="s1", artifact_type=ArtifactType.STRATEGY))+ factors = store.list_artifacts(type=ArtifactType.FACTOR)+ assert len(factors) == 1+ assert factors[0].name == "f1"++ def test_list_artifacts_filter_status(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact(name="f1"))+ store.register_artifact(_make_artifact(name="f2"))+ store.update_status(aid, ArtifactStatus.ACTIVE)+ active = store.list_artifacts(status=ArtifactStatus.ACTIVE)+ assert len(active) == 1+ assert active[0].name == "f1"++ def test_list_artifacts_filter_universe(self):+ store = InMemoryStrategyStore()+ store.register_artifact(_make_artifact(name="f1", universe="CSI300"))+ store.register_artifact(_make_artifact(name="f2", universe="SP500"))+ result = store.list_artifacts(universe="CSI300")+ assert len(result) == 1+ assert result[0].universe == "CSI300"++ def test_update_status(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ original = store.get_artifact(aid)+ assert original is not None+ updated = store.update_status(aid, ArtifactStatus.ACTIVE)+ assert updated is not None+ assert updated.status == ArtifactStatus.ACTIVE+ assert updated.updated_at >= original.updated_at++ def test_update_status_disable(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ store.update_status(aid, ArtifactStatus.ACTIVE)+ updated = store.update_status(aid, ArtifactStatus.DISABLED, reason="decay")+ assert updated is not None+ assert updated.status == ArtifactStatus.DISABLED+ assert updated.disabled_at is not None+ assert updated.disabled_reason == "decay"++ def test_update_status_not_found(self):+ store = InMemoryStrategyStore()+ result = store.update_status("nonexistent", ArtifactStatus.ACTIVE)+ assert result is None++ def test_record_bench(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ br = BenchResult(artifact_id=aid, ic_mean=0.05, ir=2.0)+ bid = store.record_bench(br)+ assert bid == 1 # auto-increment starts at 1++ def test_get_bench_history(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ for i in range(3):+ store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.01 * (i + 1)))+ history = store.get_bench_history(aid)+ assert len(history) == 3+ # Newest first+ assert history[0].id == 3+ assert history[2].id == 1++ def test_record_decay_snapshot(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ snap = DecaySnapshot(+ artifact_id=aid,+ ic_ratio=0.8,+ decay_signal=DecaySignal.HEALTHY,+ )+ sid = store.record_decay_snapshot(snap)+ assert sid == 1++ def test_get_decay_history(self):+ store = InMemoryStrategyStore()+ aid = store.register_artifact(_make_artifact())+ for i in range(3):+ store.record_decay_snapshot(+ DecaySnapshot(artifact_id=aid, ic_ratio=0.9 - i * 0.1)+ )+ history = store.get_decay_history(aid)+ assert len(history) == 3+ assert history[0].id == 3 # newest first+ assert history[2].id == 1+++# ===========================================================================+# TestDecayEvaluator+# ===========================================================================+++class TestDecayEvaluator:+ """Tests for the pure-logic DecayEvaluator state machine."""++ def test_healthy_signal(self):+ ev = DecayEvaluator()+ sig = ev.evaluate_decay(ic_ratio=0.8, ir=1.2)+ assert sig == DecaySignal.HEALTHY++ def test_warning_signal(self):+ ev = DecayEvaluator()+ sig = ev.evaluate_decay(ic_ratio=0.6)+ assert sig == DecaySignal.WARNING++ def test_decayed_signal(self):+ ev = DecayEvaluator()+ sig = ev.evaluate_decay(ic_ratio=0.4)+ assert sig == DecaySignal.DECAYED++ def test_critical_signal(self):+ ev = DecayEvaluator()+ sig = ev.evaluate_decay(ic_ratio=0.2, ir=0.05)+ assert sig == DecaySignal.CRITICAL++ def test_no_metrics_healthy(self):+ ev = DecayEvaluator()+ sig = ev.evaluate_decay()+ assert sig == DecaySignal.HEALTHY++ def test_worst_signal_wins(self):+ ev = DecayEvaluator()+ # ic_ratio=0.8 → HEALTHY, ir=0.3 → DECAYED (ir thresholds: 1.0/0.5/0.1)+ sig = ev.evaluate_decay(ic_ratio=0.8, ir=0.3)+ assert sig == DecaySignal.DECAYED++ def test_transition_active_to_monitoring(self):+ ev = DecayEvaluator()+ signals = [DecaySignal.WARNING, DecaySignal.WARNING, DecaySignal.WARNING]+ new_status = ev.should_transition(ArtifactStatus.ACTIVE, signals)+ assert new_status == ArtifactStatus.MONITORING++ def test_transition_monitoring_to_decayed(self):+ ev = DecayEvaluator()+ signals = [DecaySignal.DECAYED, DecaySignal.DECAYED]+ new_status = ev.should_transition(ArtifactStatus.MONITORING, signals)+ assert new_status == ArtifactStatus.DECAYED++ def test_transition_monitoring_to_active_recovery(self):+ ev = DecayEvaluator()+ signals = [DecaySignal.HEALTHY]+ new_status = ev.should_transition(ArtifactStatus.MONITORING, signals)+ assert new_status == ArtifactStatus.ACTIVE++ def test_transition_decayed_to_disabled(self):+ ev = DecayEvaluator()+ signals = [DecaySignal.CRITICAL, DecaySignal.CRITICAL, DecaySignal.CRITICAL]+ new_status = ev.should_transition(ArtifactStatus.DECAYED, signals)+ assert new_status == ArtifactStatus.DISABLED++ def test_no_transition_insufficient_signals(self):+ ev = DecayEvaluator()+ # Only 1 WARNING from ACTIVE needs 3 consecutive+ signals = [DecaySignal.WARNING]+ new_status = ev.should_transition(ArtifactStatus.ACTIVE, signals)+ assert new_status is None++ def test_custom_thresholds(self):+ thresholds = DecayThresholds(ic_ratio_healthy=0.9)+ ev = DecayEvaluator(thresholds)+ # ic_ratio=0.85 is below custom healthy=0.9 → WARNING+ sig = ev.evaluate_decay(ic_ratio=0.85)+ assert sig == DecaySignal.WARNING+++# ===========================================================================+# TestSdmTools+# ===========================================================================+++class TestSdmTools:+ """Integration tests for the three SDM BaseTool wrappers."""++ def test_register_tool_factor(self):+ from src.tools.sdm_register_tool import SdmRegisterTool++ tool = SdmRegisterTool()+ result = json.loads(+ tool.execute(+ artifact_type="factor",+ name="momentum_20d",+ universe="CSI300",+ formula_latex=r"\\frac{P_{t}}{P_{t-20}}-1",+ theme=["momentum"],+ columns_required=["close"],+ )+ )+ assert result["status"] == "ok"+ assert result["artifact"]["name"] == "momentum_20d"+ assert result["artifact"]["type"] == "factor"++ def test_register_tool_strategy(self):+ from src.tools.sdm_register_tool import SdmRegisterTool++ tool = SdmRegisterTool()+ result = json.loads(+ tool.execute(+ artifact_type="strategy",+ name="ma_crossover",+ universe="SP500",+ signal_definition="Buy when MA20 > MA50",+ )+ )+ assert result["status"] == "ok"+ assert result["artifact"]["type"] == "strategy"++ def test_register_tool_missing_required(self):+ from src.tools.sdm_register_tool import SdmRegisterTool++ tool = SdmRegisterTool()+ result = json.loads(tool.execute(artifact_type="factor"))+ assert result["status"] == "error"++ def test_status_tool_list(self):+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_status_tool import SdmStatusTool++ SdmRegisterTool().execute(+ artifact_type="factor", name="f1", universe="CSI300"+ )+ result = json.loads(SdmStatusTool().execute(action="list"))+ assert result["status"] == "ok"+ assert result["count"] == 1++ def test_status_tool_detail(self):+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_status_tool import SdmStatusTool++ reg_result = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="f1", universe="CSI300"+ )+ )+ aid = reg_result["artifact"]["id"]+ result = json.loads(SdmStatusTool().execute(action="detail", artifact_id=aid))+ assert result["status"] == "ok"+ assert result["artifact"]["name"] == "f1"+ assert "bench_history" in result+ assert "decay_history" in result++ def test_status_tool_disable_enable(self):+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_status_tool import SdmStatusTool++ reg = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="f1", universe="CSI300"+ )+ )+ aid = reg["artifact"]["id"]++ # Disable+ dis = json.loads(+ SdmStatusTool().execute(+ action="disable", artifact_id=aid, reason="testing"+ )+ )+ assert dis["status"] == "ok"+ assert dis["artifact"]["status"] == "disabled"++ # Enable+ en = json.loads(+ SdmStatusTool().execute(action="enable", artifact_id=aid)+ )+ assert en["status"] == "ok"+ assert en["artifact"]["status"] == "active"++ def test_status_tool_decay_check_insufficient(self):+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_status_tool import SdmStatusTool++ reg = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="f1", universe="CSI300"+ )+ )+ aid = reg["artifact"]["id"]+ result = json.loads(+ SdmStatusTool().execute(action="decay_check", artifact_id=aid)+ )+ assert result["status"] == "ok"+ assert result["signal"] == "insufficient_data"++ def test_decay_scan_tool_empty(self):+ from src.tools.sdm_decay_scan_tool import SdmDecayScanTool++ result = json.loads(SdmDecayScanTool().execute())+ assert result["status"] == "ok"+ assert result["summary"]["total_scanned"] == 0++ def test_decay_scan_tool_dry_run(self):+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_decay_scan_tool import SdmDecayScanTool++ # Register an ACTIVE factor with bench history+ reg = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="f1", universe="CSI300"+ )+ )+ aid = reg["artifact"]["id"]++ import src.strategy_store._shared as shared++ store = shared._store+ assert store is not None+ store.update_status(aid, ArtifactStatus.ACTIVE)++ # Add 3+ bench results so it's not insufficient_data+ for i in range(5):+ store.record_bench(+ BenchResult(artifact_id=aid, ic_mean=0.05 - i * 0.01)+ )++ result = json.loads(SdmDecayScanTool().execute(dry_run=True))+ assert result["status"] == "ok"+ assert result["dry_run"] is True+ assert result["transitions_applied"] == 0+ assert result["summary"]["total_scanned"] == 1+++# ===========================================================================+# TestSqliteStore+# ===========================================================================+++class TestSqliteStore:+ """Tests specific to the SQLite store implementation."""++ @pytest.fixture(autouse=True)+ def _setup(self, tmp_path):+ """Create a temporary SQLite store for each test."""+ from src.strategy_store.sqlite_store import SqliteStrategyStore++ self.store = SqliteStrategyStore(db_path=tmp_path / "sqlite_test.db")++ def test_register_and_get(self):+ """Register an artifact and retrieve it."""+ art = _make_artifact(name="sqlite_factor")+ aid = self.store.register_artifact(art)+ assert aid.startswith("art_")++ fetched = self.store.get_artifact(aid)+ assert fetched is not None+ assert fetched.name == "sqlite_factor"+ assert fetched.type == ArtifactType.FACTOR+ assert fetched.universe == "CSI300"+ assert fetched.status == ArtifactStatus.CREATED++ def test_register_auto_id(self):+ """Empty ID gets auto-generated."""+ art = _make_artifact(name="auto_id_factor")+ aid = self.store.register_artifact(art)+ assert aid.startswith("art_")+ assert len(aid) > 4++ def test_register_auto_timestamp(self):+ """Timestamps auto-set when not provided."""+ art = _make_artifact(name="ts_factor")+ aid = self.store.register_artifact(art)+ fetched = self.store.get_artifact(aid)+ assert fetched is not None+ assert fetched.created_at != ""+ assert fetched.updated_at != ""++ def test_list_with_filters(self):+ """List with type/status/universe filters."""+ self.store.register_artifact(+ _make_artifact(name="f1", artifact_type=ArtifactType.FACTOR, universe="CSI300")+ )+ self.store.register_artifact(+ _make_artifact(name="s1", artifact_type=ArtifactType.STRATEGY, universe="SP500")+ )+ self.store.register_artifact(+ _make_artifact(name="f2", artifact_type=ArtifactType.FACTOR, universe="SP500")+ )++ # Filter by type+ factors = self.store.list_artifacts(type=ArtifactType.FACTOR)+ assert len(factors) == 2++ # Filter by universe+ csi = self.store.list_artifacts(universe="CSI300")+ assert len(csi) == 1+ assert csi[0].name == "f1"++ # Filter by status+ active = self.store.list_artifacts(status=ArtifactStatus.ACTIVE)+ assert len(active) == 0++ def test_list_artifacts_limit(self):+ """List respects the limit parameter."""+ for i in range(5):+ self.store.register_artifact(_make_artifact(name=f"factor_{i}"))+ result = self.store.list_artifacts(limit=3)+ assert len(result) == 3++ def test_list_artifacts_ordering(self):+ """List returns newest first."""+ for i in range(3):+ self.store.register_artifact(_make_artifact(name=f"factor_{i}"))+ result = self.store.list_artifacts()+ assert result[0].name == "factor_2"+ assert result[2].name == "factor_0"++ def test_update_status_disable_enable(self):+ """Disable sets disabled_at, enable clears it."""+ aid = self.store.register_artifact(_make_artifact(name="toggle_factor"))+ self.store.update_status(aid, ArtifactStatus.ACTIVE)++ # Disable+ disabled = self.store.update_status(+ aid, ArtifactStatus.DISABLED, reason="testing"+ )+ assert disabled is not None+ assert disabled.status == ArtifactStatus.DISABLED+ assert disabled.disabled_at is not None+ assert disabled.disabled_reason == "testing"++ # Re-enable+ enabled = self.store.update_status(aid, ArtifactStatus.ACTIVE)+ assert enabled is not None+ assert enabled.status == ArtifactStatus.ACTIVE+ assert enabled.disabled_at is None+ assert enabled.disabled_reason is None++ def test_update_status_not_found(self):+ """update_status returns None for unknown artifact."""+ result = self.store.update_status("nonexistent", ArtifactStatus.ACTIVE)+ assert result is None++ def test_update_artifact(self):+ """update_artifact replaces the record."""+ aid = self.store.register_artifact(_make_artifact(name="orig_name"))+ fetched = self.store.get_artifact(aid)+ assert fetched is not None++ from dataclasses import replace++ updated_art = replace(fetched, name="new_name", decay_horizon=30)+ result = self.store.update_artifact(updated_art)+ assert result is not None+ assert result.name == "new_name"+ assert result.decay_horizon == 30++ def test_update_artifact_not_found(self):+ """update_artifact returns None for unknown artifact."""+ art = Artifact(+ id="nonexistent",+ type=ArtifactType.FACTOR,+ name="ghost",+ universe="CSI300",+ )+ result = self.store.update_artifact(art)+ assert result is None++ def test_bench_history_ordering(self):+ """Bench history returned newest-first."""+ aid = self.store.register_artifact(_make_artifact(name="bench_factor"))+ for i in range(3):+ self.store.record_bench(+ BenchResult(artifact_id=aid, ic_mean=0.01 * (i + 1))+ )+ history = self.store.get_bench_history(aid)+ assert len(history) == 3+ # Newest first — last inserted has highest id+ assert history[0].id > history[1].id > history[2].id++ def test_bench_history_limit(self):+ """Bench history respects limit."""+ aid = self.store.register_artifact(_make_artifact(name="bench_limit"))+ for i in range(5):+ self.store.record_bench(+ BenchResult(artifact_id=aid, ic_mean=0.01 * (i + 1))+ )+ history = self.store.get_bench_history(aid, limit=2)+ assert len(history) == 2++ def test_bench_result_with_category(self):+ """Bench result with BenchCategory enum round-trips."""+ aid = self.store.register_artifact(_make_artifact(name="cat_factor"))+ bid = self.store.record_bench(+ BenchResult(+ artifact_id=aid,+ ic_mean=0.05,+ ir=2.5,+ category=BenchCategory.ALIVE,+ )+ )+ history = self.store.get_bench_history(aid)+ assert len(history) == 1+ assert history[0].category == BenchCategory.ALIVE++ def test_decay_snapshot_crud(self):+ """Record and retrieve decay snapshots."""+ aid = self.store.register_artifact(_make_artifact(name="decay_factor"))+ for i in range(3):+ self.store.record_decay_snapshot(+ DecaySnapshot(+ artifact_id=aid,+ ic_ratio=0.9 - i * 0.1,+ decay_signal=DecaySignal.HEALTHY,+ consecutive_warnings=i,+ )+ )+ history = self.store.get_decay_history(aid)+ assert len(history) == 3+ # Newest first+ assert history[0].id > history[1].id > history[2].id+ assert history[0].decay_signal == DecaySignal.HEALTHY++ def test_decay_history_limit(self):+ """Decay history respects limit."""+ aid = self.store.register_artifact(_make_artifact(name="decay_limit"))+ for i in range(5):+ self.store.record_decay_snapshot(+ DecaySnapshot(artifact_id=aid, ic_ratio=0.9 - i * 0.1)+ )+ history = self.store.get_decay_history(aid, limit=2)+ assert len(history) == 2++ def test_persistence_across_instances(self):+ """Data persists when creating a new store instance with same db_path."""+ from src.strategy_store.sqlite_store import SqliteStrategyStore++ db_path = self.store.db_path+ aid = self.store.register_artifact(_make_artifact(name="persist_factor"))++ # Create a new store instance pointing to the same DB+ store2 = SqliteStrategyStore(db_path=db_path)+ fetched = store2.get_artifact(aid)+ assert fetched is not None+ assert fetched.name == "persist_factor"++ def test_json_roundtrip(self):+ """Tuple fields round-trip through JSON serialization."""+ art = Artifact(+ id="",+ type=ArtifactType.FACTOR,+ name="json_factor",+ universe="CSI300",+ theme=("momentum", "reversal"),+ columns_required=("close", "volume", "high"),+ )+ aid = self.store.register_artifact(art)+ fetched = self.store.get_artifact(aid)+ assert fetched is not None+ assert fetched.theme == ("momentum", "reversal")+ assert fetched.columns_required == ("close", "volume", "high")++ def test_protocol_satisfied(self):+ """SqliteStrategyStore satisfies StrategyStoreProtocol."""+ from src.strategy_store.store import StrategyStoreProtocol++ assert isinstance(self.store, StrategyStoreProtocol)++ def test_cascade_delete_bench_history(self):+ """Deleting an artifact cascades to bench_history."""+ aid = self.store.register_artifact(_make_artifact(name="cascade_factor"))+ self.store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.05))+ self.store.record_decay_snapshot(+ DecaySnapshot(artifact_id=aid, ic_ratio=0.8)+ )++ # Delete the artifact directly via SQL+ with self.store._write_transaction():+ self.store._conn.execute("DELETE FROM artifacts WHERE id = ?", (aid,))++ assert self.store.get_bench_history(aid) == []+ assert self.store.get_decay_history(aid) == []