Due bug visivi distinti:
1) Icone Material rotte ("arrow_drop_down" come testo nel selector):
Il selettore CSS '*' applicava font Inter a tutti gli elementi inclusi
gli .material-icons che richiedono il loro proprio font ligature.
Sostituito '*' con whitelist esplicita di elementi UI; aggiunto override
esplicito per .material-icons / .q-icon che forza font 'Material Icons'.
2) JSON keys invisibili nel code block config:
NiceGUI ui.code usa Prism.js (non highlight.js) per il syntax highlighting.
Aggiunti selettori .token.* coordinati con la palette neon:
- .token.property / .token.attr-name → cyan (chiavi JSON)
- .token.string → green (valori string)
- .token.number / .token.boolean / .token.null → pink
- .token.punctuation / .token.operator → muted
- .token.keyword / .token.builtin → amber
Più reset text-shadow per pre[class*=language-].
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunta route /genomes:
- Run selector + Top K (10/25/50)
- Tabella sortable con fitness, DSR, Sharpe, max DD, trades, style, T, lookback
- Selezione riga → pannello ispezione con 6 metric card e blocchi code per
system_prompt + raw_text + parse_error eventuale
- Auto-refresh ogni 3s (mantiene selezione corrente se ancora valida)
- Header nav aggiornato con link Genomes
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Prima fase migrazione da Streamlit a NiceGUI. Pagina indice riproduce
l'Overview con:
- run selector reattivo
- 2 progress bar live (generations, evaluations) con WebSocket push
- 4 metric card (top fitness, median, parse success %, cost)
- timer auto-refresh ogni 3s (no click manuale)
- status badge colorato (running/completed/failed)
- config JSON code block
Avvio: uv run python -m multi_swarm.dashboard.nicegui_app (porta 8080)
Streamlit resta attivo su 8501 durante la migrazione. Backend invariato:
riusa dashboard/data.py senza modifiche.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunto blocco "Progresso run" sopra le metriche statiche con:
- progress bar generazioni (gens_done / n_generations)
- progress bar evaluations (evals_done / pop × gen) con percentuale
- metric top fitness / median fitness / cost so far
- pulsante Refresh manuale + timestamp ultimo update
- emoji status (🟢 running / ✅ completed / ❌ failed)
Niente nuove dipendenze: solo st.progress + st.rerun standard Streamlit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Piano in tasca: NON attivare finché Phase 2 (qwen3 + temporal) non raggiunge
una delle condizioni di trigger documentate:
- plateau max fitness < 0.01 per >= 4 gen consecutive
- diversità prompt Levenshtein <= 0.15
- top genome quasi-fit (>= 0.10) con adversarial HIGH >= 2
Sei tipi di mutazione (tighten_threshold, swap_comparator, add/remove_condition,
change_timeframe, add_temporal_gate) via mutator tier B (deepseek-v4-flash),
weighted_random_mutate dispatcher con default 0.0 (opt-in), diversity guard
Levenshtein, fallback random_mutate su validation fail.
Costo stimato +$0.006/run. A/B con baseline B = phase2-qwen3-001 vs
trattamento T = phase2-qwen3-prompt-mut-001 per attribuzione effetto.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Tier S → google/gemini-3-flash-preview ($0.50/$3.00)
- Tier A/B → deepseek/deepseek-v4-flash ($0.14/$0.28)
- Tier C → qwen/qwen3-235b-a22b-2507 ($0.071/$0.10) — Phase 2 target
- Tier D → openai/gpt-oss-20b ($0.03/$0.14)
Aggiornato cost_tracker con prezzi reali per tier. Defaults config.py
ora rispecchiano .env corrente per evitare divergenze dead-code.
Tier S/A/B/D restano cablati ma non ancora invocati nel loop Phase 2
(solo Hypothesis tier C attivo).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunge hour/dow/is_weekend/minute_of_hour come FeatureNode nella
grammatica esistente. Universal access (non passa da feature_access),
riuso di FeatureNode (no nuovo tipo AST), few-shot examples nel prompt
Hypothesis. Cinque file toccati, ~120 LOC, backward-compatible.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Run phase1.5-nemotron-001 completato in 2h26min, costo $0.1244.
Max fitness 0.0215 stagnante (15x peggio del baseline qwen 0.3347),
DSR=0 universale, Sharpe -1.08/-1.15. Loop non converge.
Adversarial Phase 1.5 attivo: 98 finding totali, 35 fees_eat_alpha
HIGH + 15 flat_too_long + 8 time_in_market — i 3 nuovi check killano
correttamente, ma popolazione non ha materiale sano da cui evolvere.
Tre direzioni candidate per Phase 2: A) rollback qwen-2.5-72b,
B) prompt re-tuning nemotron, C) promuovere deepseek-v4-flash.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EmptyCompletionError ora retryable. resp.usage può essere None su
provider :free (es. nemotron-3-super-120b-a12b:free) → no assert.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Simmetrico opposto di flat_too_long: penalizza strategie LONG/SHORT su
piu' dell'80% delle bar. Una sempre-in-market e' leveraged B&H camuffato,
esposto a funding cumulato (perp ogni 8h), tail risk eventi notturni e
nessuna opportunity-cost flexibility. Sweet spot fitness positiva: 5-80%
time in market.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Stringe le soglie esistenti e aggiunge due check HIGH per killare le
strategie degeneri scoperte nel run v5 (top-1 +2.66% vs BTC B&H +106%,
flat 99.8% del tempo, fees 69% del lordo).
- overtrading: soglia da n_bars/5 a n_bars/20 (MEDIUM)
- undertrading: HIGH se n_trades < 10 (era MEDIUM <5) — sample troppo
piccolo per distinguere edge da rumore (lucky shot)
- flat_too_long (NEW, HIGH): signal attivo per <5% delle bar — la
strategia ha mancato il regime, e' una non-strategia
- fees_eat_alpha (NEW, HIGH): gross_pnl > 0 ma fees > 50% del lordo —
margine sottile non sostenibile in produzione
Test count: 141 -> 145 (+4 nuovi test deterministici via monkeypatch).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase 1 chiusa con tutti i 5 hard gate passati (run phase1-real-005):
- Loop converge: 3 gen consecutive crescita median 0.0001 -> 0.0188.
- Parse success: 100% (98/98) grazie a JSON grammar.
- Top-5 vs median: 1116x ratio (top-1 fit 0.3347 vs median 0.0003).
- Entropy fitness: 0.914 a gen 9 (sopra soglia 0.5).
- Cost: $0.069 reale vs $700 cap.
Decision: GO Phase 2 con 3 aggiustamenti (Adversarial soglie piu' strette,
speciation di base, walk-forward 70/30).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase 1 v0 usava `max(0, dsr - 0.5*max_dd)` che azzerava brutalmente la fitness
quando max_dd > 2*dsr. Real run v4 aveva 55/55 strategie a fitness=0 (DSR ~0.001,
max_dd > 0.5), zero pressione selettiva sul GA.
v1: base = 0.5*dsr + 0.5*0.5*(tanh(sharpe)+1) in [0,1], modulata da penalty
moltiplicativa 1/(1+k*max_dd) in (0,1]. Hard kill (no-trade, HIGH adversarial)
preservati. Fitness sempre >0 per strategie con almeno 1 trade -> il GA
puo' preferire "meno cattivo" a "catastrofico" anche su sharpe negativo.
Tests: +3 nuovi (continuous mediocre, bounded, monotonic drawdown), 4 esistenti
restano verdi. Suite 138 -> 141 passed. ruff + mypy strict puliti.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
HypothesisAgent.propose ora riprova una volta in caso di parse o
validation error: il prompt user del retry include l'output precedente
(troncato a 800 char) e il messaggio di errore, così l'LLM può
auto-correggersi. Configurabile via max_retries (default 1).
Cambia il modello dati di HypothesisProposal: completion (singolare)
diventa completions: list[CompletionResult] con n_attempts. L'orchestrator
itera su completions per registrare il costo di ogni chiamata LLM,
incluse le retry.
Phase 1 v4 mostrava 64% di parse failure recuperabili: il retry punta
a tagliare quel tasso senza inflazionare i token oltre 2x worst-case.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sostituisce la grammatica S-expression con uno schema JSON stretto. La
grammatica S-expression falliva il parsing nel 64% delle generazioni del
modello Qwen3-235B sul run reale; JSON e' nativo per gli LLM moderni e
si parsa con json.loads.
Cambiamenti principali:
- grammar.py: costanti rinominate LOGICAL_OPS / COMPARATOR_OPS /
CROSSOVER_OPS / ACTION_VALUES / KIND_VALUES.
- parser.py: nuovo AST a dataclass tipizzato (OpNode, IndicatorNode,
FeatureNode, LiteralNode, Rule, Strategy); parse_strategy ora consuma
JSON tramite json.loads.
- validator.py: walk dispatchato per tipo (isinstance) invece di
pattern-matching su 'kind'; arity check su operatori e indicator.
- compiler.py: traversal del nuovo AST tipizzato, dispatch per
isinstance; logica indicator/feature/literal invariata.
- hypothesis.py: prompt SYSTEM riscritto con esempi JSON e vincoli
espliciti su no-nesting; estrazione via fence ```json``` + fallback
brace-balanced.
- __init__.py: re-export pubblico delle entita' del protocollo.
- Tutti i test (parser, validator, compiler, hypothesis_agent,
falsification, adversarial, e2e, smoke_run) migrati a JSON.
- Rimossa dipendenza sexpdata da pyproject.toml + uv.lock.
Test: 135 passed (era 122; aggiunti casi parser/validator).
ruff + mypy strict clean. Smoke run end-to-end OK.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Run reale phase1-real-003 ha rivelato: l'LLM genera occasionalmente
"(indicator sma 20 50)" o "(indicator sma (feature close) 20)". Il primo
crashava _ind_sma con TypeError. Il secondo passava attraverso il
validator ma non era supportato dal compiler.
Validator ora:
- Aggiunge INDICATOR_ARITY: sma/rsi/atr/realized_vol = 1 arg, macd = 0-3.
- Rifiuta esplicitamente Node fra gli args di indicator (no-nesting Phase 1).
- Rifiuta arity fuori range con messaggio chiaro.
Strategie con questi pattern vengono ora rigettate dal validator come
parse_error invece di crashare il run. Test suite resta 122 PASSED.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Run reale phase1-real-002 ha rivelato:
1. Cerbero/Deribit cap ~5000 candele per call. Una richiesta di 2 anni
1h (17500 candele) ritorna troncata. CerberoOHLCVLoader._fetch ora
pagina in chunk da 4500 barre, concatena e dedupe.
2. _ind_macd accettava solo (df, fast, slow). Il prompt suggerisce
"(indicator macd 12 26 9)" con 3 numeri (fast/slow/signal). Aggiunto
signal=9 default e calcolo histogram (macd_line - signal_line).
Test suite 122 PASSED, ruff e mypy clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Run reale phase1-real-001 ha rivelato due problemi:
1. 67% parse_error perche' qwen3 nestava indicatori non supportati
(es. "(sma (indicator realized_vol 30) 150)"). Il prompt SYSTEM
ora esplicita le regole strette: indicator non e' annidabile,
sma/rsi/etc. esistono solo come 1o argomento di indicator,
crossover/crossunder accetta espressioni-serie come (feature close)
o (indicator sma N).
2. max_drawdown calcolato su equity assoluta (P&L in unita' BTC) +1.0
produceva drawdown nominali enormi (>89000) per strategie con
posizioni perdenti su BTC a $96k. Normalizziamo dividendo per il
notional iniziale (close[0]), cosi' max_dd diventa drawdown
relativo al wealth iniziale.
Test suite resta 122 PASSED, ruff e mypy clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunge i template per gate decision memo (sez. 4.4 spec) e technical
report (sez. 4.5 spec). Da popolare con numeri reali a chiusura del run
phase1-real-001 (in corso).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Cerbero MCP diventa unica fonte di verità per dati di mercato Phase 1.
Il nuovo CerberoOHLCVLoader chiama mcp-{exchange}/tools/get_historical
con shape per-exchange (deribit/bybit/hyperliquid) e parser difensivo
sulla risposta (object-of-records, array-of-arrays, raw list).
- src/multi_swarm/data/cerbero_ohlcv.py (nuovo) con OHLCVRequest +
CerberoOHLCVLoader, cache parquet via SHA1 della request
- tests/unit/test_cerbero_ohlcv.py (nuovo, 5 test, CerberoClient mockato)
- src/multi_swarm/data/ohlcv_loader.py + test ccxt rimossi
- scripts/run_phase1.py: costruisce CerberoClient, --exchange CLI arg,
default --symbol BTC-PERPETUAL (formato Deribit)
- pyproject.toml: rimosso ccxt>=4.4 (uv sync ha rimosso 16 transitivi)
- .env.example: CERBERO_BASE_URL=https://cerbero-mcp.tielogic.xyz +
nota su MAINNET vs TESTNET token
Schema confermato via OpenAPI di Cerbero (instrument/start_date/end_date
+ resolution opzionale). Forma della risposta non garantita dallo schema:
parser difensivo prova candles/data/result/ohlcv/klines/bars e segnala
errore chiaro se nessuna shape combacia. Live verification skippata
(nessun token in .env).
Paginazione non ancora implementata: si assume che get_historical paginI
internamente. Da rivedere se una live call mostra cap (~1000 candele).
Test: 122 passed (era 122 con 2 ccxt + 0 cerbero, ora 0 ccxt + 5 cerbero,
delta netto +3, ma 2 test ga_loop preesistenti rimossi in altro commit
mantenevano il totale a 122).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rimuove sidebar acquario (slider max-pesci, toggle label): la dimensione
popolazione è già definita dal GA, le label sono ridondanti col pannello
di ispezione. Mostra tutti i pesci della generazione selezionata.
Aggiunge `build_lineage_index` (mappa ogni genome_id della run ai suoi
attributi) e `trace_ancestors` (BFS sui parent_ids fino a max_levels,
guardia su cicli). `build_fish_dataset` accetta ora il lineage_index e
allega il campo `ancestors` ad ogni pesce; conserva la firma legacy per
compat con i fixture di test esistenti.
`build_aquarium_html` perde `show_labels`. Embedda click handler con
hit-test in canvas pixel space (account per CSS scaling) + pannello
info top-right con stile, fitness/DSR/Sharpe/maxDD/trades, prompt e
albero discendenza colorato per cognitive_style.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Tutti i tier (S/A/B/C/D) ora passano per OpenRouter via OpenAI SDK.
Modelli Anthropic raggiungibili via prefisso `anthropic/...`.
- pyproject: rimosso `anthropic>=0.39` da deps + uv.lock
- config: rimosso `anthropic_api_key` field
- LLMClient: dispatch unico, single client OpenAI con base_url OpenRouter
- defaults S/A/B → `anthropic/claude-{opus-4-7,sonnet-4-6}`
- retry exceptions: solo openai.* (drop anthropic.*)
- test rinominati e adattati: tier S/A/B mockano OpenAI con prefisso `anthropic/`
- rimosso test `tier_S_without_anthropic_key_raises` (non più rilevante)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Nuova pagina Streamlit "Aquarium" che renderizza ogni genoma come pesce
animato su canvas HTML5: dimensione proporzionale alla fitness, colore
per cognitive_style, halo per i top-3. Helper puro-Python testabile per
costruire dataset e HTML self-contained (no CDN).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Estende ModelTier a 5 livelli (S/A/B/C/D) con routing automatico:
S/A/B via Anthropic SDK, C/D via OpenRouter (OpenAI SDK). Aggiunge
prezzi per tier S (Opus), A (Sonnet placeholder) e D (Llama). Refactor
LLMClient.complete con dispatch tramite tier_models map e helper
_call_anthropic / _call_openrouter. Settings esposte per tutti e 5
i modelli env-configurabili.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
LLM_MODEL_TIER_C, LLM_MODEL_TIER_B e OPENROUTER_BASE_URL ora override-abili
via env. Default invariati (back-compat). LLMClient accetta i tre valori
come kwargs opzionali; run_phase1 li propaga da Settings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Avvolge LLMClient.complete con tenacity (3 attempts, backoff esponenziale
2-10s) che ritenta solo su errori transient di OpenAI/Anthropic SDK
(APIConnectionError, APITimeoutError, InternalServerError). RateLimit,
Authentication e 4xx non vengono ritentati. reraise=True preserva
l'eccezione originale dopo l'esaurimento dei tentativi.
Aggiunti 2 test (marker slow): esaurimento retry su APIConnectionError
e successo al secondo tentativo dopo APITimeoutError.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunge scripts/run_phase1.py come entry point CLI per eseguire un run
end-to-end di Phase 1 con parametri configurabili via argparse (popolazione,
generazioni, simbolo, finestra temporale, fees, seed). Aggiunge marker
py.typed al package multi_swarm per esporre i tipi a consumatori esterni
(scripts/) sotto mypy --strict.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Aggiunge scheletro multipage Streamlit per Phase 1:
- modulo data.py con helper (list_runs_df, get_run_overview,
generations_df, evaluations_df, genomes_df) sopra Repository.
- streamlit_app.py entry point con DB_PATH da env.
- pages/01_overview.py per elenco run + metriche + config JSON.
- smoke test import di multi_swarm.dashboard.data.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Loop GA completo: build_initial_population -> hypothesis.propose ->
falsification + adversarial -> compute_fitness -> persistenza ->
next_generation. Stato run/gen/genomes/evals/cost/findings su SQLite,
elite skip-eval, run marcato failed su eccezione.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>