Fase 0 — Preparazione #85
No files matched your search
@@ -0,0 +1,11 @@
|
||||
**/bin/
|
||||
**/obj/
|
||||
.git/
|
||||
.claude/
|
||||
.vs/
|
||||
artifacts/
|
||||
TestResults/
|
||||
docs/
|
||||
**/*.md
|
||||
.env
|
||||
.env.*
|
||||
@@ -0,0 +1,26 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.{json,yml,yaml,xml,props,targets,csproj,slnx}]
|
||||
indent_size = 2
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.cs]
|
||||
csharp_style_namespace_declarations = file_scoped:warning
|
||||
csharp_style_var_for_built_in_types = true:silent
|
||||
csharp_style_var_when_type_is_apparent = true:silent
|
||||
csharp_style_var_elsewhere = true:silent
|
||||
csharp_prefer_braces = when_multiline:silent
|
||||
dotnet_sort_system_directives_first = true
|
||||
csharp_using_directive_placement = outside_namespace:warning
|
||||
dotnet_style_qualification_for_field = false:warning
|
||||
dotnet_style_qualification_for_property = false:warning
|
||||
dotnet_style_qualification_for_method = false:warning
|
||||
@@ -0,0 +1,8 @@
|
||||
# Example only: every value here is fake. Copy to .env and fill in locally; .env is never committed (SPEC 2.2).
|
||||
ANUBIS_DB_ENGINE=sqlite
|
||||
ANUBIS_DB_PASSWORD=change-me
|
||||
ANUBIS_SECRET_KEY=replace-with-random-bytes
|
||||
ANUBIS_ADMIN_PASSWORD=change-me-at-first-login
|
||||
# Real money stays off during development: never set it to 1.
|
||||
ANUBIS_ALLOW_LIVE=0
|
||||
TZ=Europe/Rome
|
||||
@@ -0,0 +1,7 @@
|
||||
# Line endings: LF in the repository; shell scripts and the Dockerfile stay LF everywhere.
|
||||
* text=auto
|
||||
*.sh text eol=lf
|
||||
.githooks/* text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
@@ -0,0 +1,64 @@
|
||||
# CI (SPEC 15.5, ADR 0003/0004): only run steps with git, dotnet and docker, no external actions.
|
||||
# Publishing to the registry on v* tags arrives in phase 9 (issue #70).
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
db: [sqlite, postgres]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_DB: anubis
|
||||
POSTGRES_USER: anubis
|
||||
POSTGRES_PASSWORD: anubis-ci
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U anubis -d anubis"
|
||||
--health-interval 3s
|
||||
--health-timeout 3s
|
||||
--health-retries 20
|
||||
env:
|
||||
ANUBIS_TEST_DB: ${{ matrix.db }}
|
||||
ANUBIS_TEST_PG_HOST: postgres
|
||||
ANUBIS_TEST_PG_PORT: "5432"
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
||||
DOTNET_NOLOGO: "1"
|
||||
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git init -q .
|
||||
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git checkout -q FETCH_HEAD
|
||||
- name: Check
|
||||
run: sh ./tasks.sh check
|
||||
|
||||
image:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
# Registry settings for phase 9 (issue #70): declared here, not used before then.
|
||||
env:
|
||||
REGISTRY: gitea.encke-hake.ts.net
|
||||
REGISTRY_USER: ${{ github.repository_owner }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git init -q .
|
||||
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git checkout -q FETCH_HEAD
|
||||
- name: Build image (no publish)
|
||||
run: docker build -f deploy/docker/Dockerfile -t anubis:ci .
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
# Project pre-commit hook (ADR 0006), in place of the pre-commit tool of SPEC 17.
|
||||
# Enable once per clone with: tasks hooks. Skip only in an emergency with: git commit --no-verify
|
||||
exec sh ./tasks.sh check
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/Anubis.Desktop/Anubis.Desktop.csproj" />
|
||||
<Project Path="src/Anubis.Guard/Anubis.Guard.csproj" />
|
||||
<Project Path="src/Anubis.Server/Anubis.Server.csproj" />
|
||||
<Project Path="src/Anubis.Setup/Anubis.Setup.csproj" />
|
||||
<Project Path="src/Anubis/Anubis.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Anubis.Tests/Anubis.Tests.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tools/">
|
||||
<Project Path="tools/Anubis.Tasks/Anubis.Tasks.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -11,7 +11,17 @@ Bot di trading personale: azioni USA su Alpaca, crypto spot su OKX Europe, senza
|
||||
|
||||
## Comandi
|
||||
|
||||
Nessuno ancora: nascono nella Fase 0 (issue #3). Previsti, tutti da `tools/Anubis.Tasks` tramite `./tasks.ps1` (Windows) o `./tasks.sh` (Linux): `tasks check` (analizzatori, test, controllo dei pacchetti), `tasks dev`, `tasks test`, `tasks build` (immagine Docker), `tasks ci`, `tasks seed-demo`, `tasks desktop-win`. Niente `make`. Aggiorna questa sezione appena esistono.
|
||||
Da `tools/Anubis.Tasks`, tramite `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh <comando>` (Linux). Niente `make`.
|
||||
- `check`: ripristino con `--locked-mode`, `dotnet format --verify-no-changes`, build Release con gli analizzatori, test. Va verde prima di ogni commit.
|
||||
- `test`: solo i test; il motore viene da `ANUBIS_TEST_DB` (`sqlite` o `postgres`). Esclude la categoria `LiveDemo`.
|
||||
- `dev`: il server con `dotnet watch` su http://localhost:5000 (o `--urls`).
|
||||
- `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`.
|
||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||
- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`.
|
||||
|
||||
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006).
|
||||
|
||||
## Regole che, se dimenticate, fanno sbagliare
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project>
|
||||
<!-- Shared build rules (ADR 0003): .NET 10, nullable on, analyzer warnings are errors. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<AnalysisLevel>latest</AnalysisLevel>
|
||||
<AnalysisMode>Recommended</AnalysisMode>
|
||||
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
|
||||
<Deterministic>true</Deterministic>
|
||||
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||
<Company>BalboSoft</Company>
|
||||
<Product>Anubis</Product>
|
||||
<Version>0.0.1</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project>
|
||||
<!--
|
||||
The only NuGet packages Anubis may use (ADR 0004). Adding a line here needs the user's
|
||||
permission first and a new ADR. DependencyPolicyTests fails on anything not allowed.
|
||||
-->
|
||||
<ItemGroup>
|
||||
<!-- MSTest through its base packages, without the coverage extension (ADR 0006). -->
|
||||
<PackageVersion Include="MSTest.TestFramework" Version="4.5.2" />
|
||||
<PackageVersion Include="MSTest.TestAdapter" Version="4.5.2" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
# Anubis image (ADR 0003). Phase 0: minimal server with /health.
|
||||
# Phase 1 adds the entrypoint (PUID/PGID, data folder) and the HEALTHCHECK (issue #16).
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY global.json Directory.Build.props Directory.Packages.props ./
|
||||
COPY src/Anubis/Anubis.csproj src/Anubis/packages.lock.json src/Anubis/
|
||||
COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json src/Anubis.Server/
|
||||
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode
|
||||
COPY src/Anubis/ src/Anubis/
|
||||
COPY src/Anubis.Server/ src/Anubis.Server/
|
||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||
WORKDIR /app
|
||||
COPY --from=build /app ./
|
||||
ENV ASPNETCORE_HTTP_PORTS=8787 \
|
||||
TZ=Europe/Rome
|
||||
EXPOSE 8787
|
||||
VOLUME /data
|
||||
USER $APP_UID
|
||||
ENTRYPOINT ["dotnet", "Anubis.Server.dll"]
|
||||
@@ -0,0 +1,44 @@
|
||||
# Development only (SPEC 3): the app plus a local PostgreSQL. Never used in production.
|
||||
# Start: docker compose up --build Health: curl http://localhost:8787/health
|
||||
services:
|
||||
anubis:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: deploy/docker/Dockerfile
|
||||
image: gitea.encke-hake.ts.net/balbosoft/anubis:dev
|
||||
ports:
|
||||
- "8787:8787"
|
||||
environment:
|
||||
ANUBIS_DB_ENGINE: postgres
|
||||
ANUBIS_DB_HOST: postgres
|
||||
ANUBIS_DB_PORT: "5432"
|
||||
ANUBIS_DB_NAME: anubis
|
||||
ANUBIS_DB_USER: anubis
|
||||
ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}
|
||||
ANUBIS_ALLOW_LIVE: "0"
|
||||
TZ: Europe/Rome
|
||||
volumes:
|
||||
- anubis-data:/data
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
postgres:
|
||||
image: postgres:18
|
||||
environment:
|
||||
POSTGRES_DB: anubis
|
||||
POSTGRES_USER: anubis
|
||||
POSTGRES_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}
|
||||
ports:
|
||||
- "127.0.0.1:55432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U anubis -d anubis"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql
|
||||
|
||||
volumes:
|
||||
anubis-data:
|
||||
postgres-data:
|
||||
@@ -0,0 +1,215 @@
|
||||
# Note sulle API
|
||||
|
||||
Controllo del 10 novembre 2026 dei fatti della sezione 4 di `docs/SPEC.md` (verificati il 9 ottobre 2026). Sono state lette solo pagine pubbliche e fatte solo chiamate pubbliche senza chiave. Nessuna registrazione, nessuna chiave usata.
|
||||
|
||||
Ogni fatto ha uno di questi esiti:
|
||||
- **confermato**: vale ancora come scritto nella specifica;
|
||||
- **cambiato**: vale in parte o non vale più; la colonna Dettaglio dice cosa è diverso;
|
||||
- **non verificabile**: le pagine pubbliche non bastano per verificarlo. Il fatto resta dietro una protezione, elencata in fondo alla pagina.
|
||||
|
||||
Sono segnati **non più rilevante**, senza essere ricontrollati, i fatti che non toccano più il progetto:
|
||||
- gli strumenti abbandonati con l'ADR 0003 (`alpaca-py`, `ccxt`, `ib_async`);
|
||||
- le fonti che la specifica esclude e Anubis non usa.
|
||||
|
||||
Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggiorna questa pagina (SPEC 4).
|
||||
|
||||
## 4.1 Alpaca
|
||||
|
||||
| # | Fatto (SPEC 4.1) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| A1 | Conto paper per tutti, 100.000 $ finti, solo dati IEX | confermato | Chiunque nel mondo lo apre con un'email. Il saldo si può azzerare con un importo a scelta. | https://docs.alpaca.markets/docs/paper-trading |
|
||||
| A2 | Conto reale per residenti italiani: "più di 195 paesi", nessun elenco | non verificabile | Nessuna pagina ufficiale dà più né il numero né l'elenco. L'Italia compare tra i paesi del bonifico in valuta locale e del passaporto UE di Alpaca Europe (luglio 2026). Nessuna fonte dice però che un privato italiano può aprire un conto Trading API. | https://alpaca.markets/support/countries-alpaca-is-available · https://alpaca.markets/blog/alpaca-completes-eea-passporting-to-29-countries-expanding-access-to-regulated-investment-services-across-europe/ |
|
||||
| A3 | Crypto su Alpaca non disponibile ai residenti UE | non verificabile | La documentazione parla solo di "alcune giurisdizioni internazionali". La pagina delle regioni ammesse risponde 404. Non cambia nulla: la crypto resta su OKX. | https://docs.alpaca.markets/docs/crypto-trading |
|
||||
| A4 | Piano Basic: tempo reale solo IEX, 30 simboli via WebSocket, storico dal 2016, SIP solo se vecchio di almeno 15 minuti, 200 chiamate al minuto; piano a pagamento 99 $ al mese | confermato | Il flusso `delayed_sip` esiste come WebSocket. Attenzione: nelle API dei dati il parametro `feed` vale `sip` se non lo si indica. | https://docs.alpaca.markets/docs/about-market-data-api · https://docs.alpaca.markets/docs/market-data-faq |
|
||||
| A4b | I volumi IEX sono una piccola parte del mercato: i filtri di liquidità usano le barre giornaliere consolidate | confermato | Discende da A4: le barre SIP si chiedono con un `end` vecchio di almeno 15 minuti. | come A4 |
|
||||
| A5 | Notizie: Benzinga, REST e WebSocket `v1beta1/news`, storico dal 2015, campi headline, summary, symbols, created_at, source; gratuite? | cambiato | URL e campi confermati. In più ci sono `id`, `author`, `updated_at`, `content`, `url` e `images`. La fonte non è più solo Benzinga: gli esempi mostrano anche "fiscal.ai". Lo storico dal 2015 e la presenza nel piano gratuito non sono più scritti. Senza tempo reale, le notizie via REST arrivano con 15 minuti di ritardo. | https://docs.alpaca.markets/us/reference/news-3 · https://docs.alpaca.markets/us/docs/streaming-real-time-news |
|
||||
| A6 | Tipi d'ordine e validità; `opg` rifiutati 09:28–19:00 ET, `cls` 15:50–19:00 ET | confermato | Dopo le 19:00 ET questi ordini vanno in coda per l'asta del giorno dopo. | https://docs.alpaca.markets/docs/orders-at-alpaca |
|
||||
| A7 | Frazioni da 1 $; solo market, limit, stop e stop-limit con `day`; niente `opg`/`cls`, niente vendite allo scoperto | confermato | In più: gli importi hanno al massimo 2 decimali, e gli ordini in importo non si modificano (si annullano e si rimandano). Le frazioni ora sono ammesse anche fuori orario, solo con ordini limit. | https://docs.alpaca.markets/docs/fractional-trading |
|
||||
| A8 | Fuori orario: solo limit con `extended_hours=true` | confermato | Validità solo `day` o `gtc`, niente bracket. Anubis opera solo in orario regolare. | https://docs.alpaca.markets/docs/orders-at-alpaca |
|
||||
| A9 | PDT: soglia dei 25.000 $ tolta il 4 giugno 2026; campi PDT facoltativi; usare `buying_power` | cambiato | Data confermata. I campi `pattern_day_trader`, `daytrade_count`, `last_daytrade_count`, `daytrading_buying_power` e `last_daytrading_buying_power` sono stati tolti dall'API entro il 6 luglio 2026: possono mancare del tutto. | https://alpaca.markets/blog/finra-retires-the-pdt-rule-introducing-alpacas-new-intraday-margin-framework/ |
|
||||
| A10 | Nessuna commissione, solo tasse regolamentari sulle vendite; conto in dollari; cambio sui versamenti circa 1,5% | cambiato | La tassa FINRA TAF è solo sulle vendite, ma la tassa CAT si paga anche sugli acquisti. L'1,5% vale per il bonifico in valuta locale (Italia compresa), con un massimo di 40 $. | https://docs.alpaca.markets/docs/regulatory-fees · https://alpaca.markets/support/currencycloud-transfer-questions |
|
||||
| A11 | Calendario e orologio: `/v2/calendar` e `/v2/clock` | cambiato | Funzionano ancora, ma la documentazione li chiama "legacy". I nuovi sono `GET /v3/calendar/{market}` e `GET /v3/clock?markets=…`, che indicano anche la fase della seduta. Nessuna data di chiusura per i `/v2`. | https://docs.alpaca.markets/us/reference/calendar-2.md · https://docs.alpaca.markets/us/reference/legacyclock.md |
|
||||
| A12 | Azioni societarie: `GET https://data.alpaca.markets/v1/corporate-actions` con symbols, types, start, end; nel piano gratuito? | confermato | Il sito le mette nel piano gratuito. Senza `start` e `end` restituisce solo il giorno corrente; la paginazione usa `page_token`, con `limit` da 1 a 1000. | https://docs.alpaca.markets/us/reference/corporateactions-1 · https://alpaca.markets/data |
|
||||
| A13 | Ordini di segno opposto rifiutati con 403, con le eccezioni bracket, OCO e trailing stop | confermato | Vale anche per paper e crypto. Uno stop-limit conta come stop se accoppiato a un ordine market o stop. | https://docs.alpaca.markets/docs/user-protection |
|
||||
| A14 | Su un conto senza margine il ricavato di una vendita può non essere spendibile fino al regolamento | cambiato | Alpaca non offre conti senza margine: tutti i conti sono a margine. Sotto i 2.000 $ il conto è "limited margin", con potere d'acquisto 1x. Il ricavato si reinveste subito in azioni, ma non si usa per la crypto né si preleva prima del regolamento (T+1). | https://alpaca.markets/support/alpaca-cash-accounts · https://docs.alpaca.markets/docs/account-plans |
|
||||
| A15 | Nessun indicatore ETF negli asset Alpaca; `nasdaqtraded.txt` ha la colonna ETF Y/N | confermato | La colonna `ETF` è la sesta. | https://docs.alpaca.markets/us/reference/get-v2-assets-1.md · https://www.nasdaqtrader.com/dynamic/SymDir/nasdaqtraded.txt |
|
||||
| A16 | Indirizzi e autenticazione da scrivere in casa | confermato | Paper `https://paper-api.alpaca.markets`, dati `https://data.alpaca.markets`, intestazioni `APCA-API-KEY-ID` e `APCA-API-SECRET-KEY`. WebSocket IEX `wss://stream.data.alpaca.markets/v2/iex`, autenticazione `{"action":"auth",…}` con risposta `authenticated`. | https://docs.alpaca.markets/docs/real-time-stock-pricing-data |
|
||||
| A17 | SDK `alpaca-py` 0.44.0 | non più rilevante | Client scritto in casa (ADR 0003, 0004). | — |
|
||||
|
||||
**Cosa cambia per il codice**
|
||||
- **A4**: passare sempre `feed=iex` per i dati recenti. Il `sip` solo con un `end` vecchio di almeno 15 minuti.
|
||||
- **A5**: `source` è un testo libero, non un valore fisso.
|
||||
- **A9**: non leggere i campi PDT. Il potere d'acquisto viene da `buying_power` (e `non_marginable_buying_power` per frazioni e crypto).
|
||||
- **A10**: la tassa CAT entra nel calcolo dei costi anche sugli acquisti.
|
||||
- **A11**: il calendario sta dietro un'interfaccia, così si passa ai `/v3` senza toccare il resto. Si parte con i `/v2`.
|
||||
- **A14**: il conto sarà a margine, quindi il divieto di leva (SPEC 9.1) lo impone Anubis. Compra solo fino alla liquidità propria, mai allo scoperto, anche se sopra i 2.000 $ Alpaca lo permetterebbe.
|
||||
|
||||
## 4.2 OKX Europe
|
||||
|
||||
| # | Fatto (SPEC 4.2) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| O1 | OKX Europe Ltd, autorizzata MiCA (Malta) dal 27/01/2025, opera in Italia | confermato | Autorizzazione dell'autorità maltese (MFSA) del 27/01/2025, con passaporto nello Spazio economico europeo. | https://www.casptracker.eu/casp/OKX-Europe-Limited |
|
||||
| O2 | REST `https://eea.okx.com`; WebSocket `wss://wseea.okx.com/ws/v5/public`, `/private`, `/business` | confermato | Con un conto europeo, `www.okx.com` risponde con l'errore 50119. | https://my.okx.com/docs-v5/en/ |
|
||||
| O3 | Demo: stessa REST con `x-simulated-trading: 1`; WebSocket `wss://wseeapap.okx.com/ws/v5/...`; chiavi a parte che non scadono | cambiato | Tutto confermato, ma la porta 8443 è chiusa dal 31/10/2026. I WebSocket vanno sulla 443, quindi senza porta nell'URL. | https://my.okx.com/docs-v5/log_en |
|
||||
| O3b | Il demo europeo elenca 27 coppie in EUR e 29 in USDC | non verificabile | Senza chiave l'elenco demo mostra 28 EUR e 30 USDC, ma non è filtrato per l'Europa. Il 30/09/2026 sono state tolte alcune coppie (ICX, STORJ, ELF). | `GET https://eea.okx.com/api/v5/public/instruments?instType=SPOT` |
|
||||
| O4 | Chiave, segreto e passphrase; fino a 20 IP; una chiave di trading senza IP scade dopo 14 giorni di inattività | confermato | La firma è Base64(HMAC-SHA256(timestamp + metodo + percorso + corpo)). Il timestamp REST è in formato ISO UTC con millisecondi; oltre 30 secondi di scarto arriva l'errore 50102. Il login WebSocket firma invece i **secondi** Unix + `GET` + `/users/self/verify`. | https://my.okx.com/docs-v5/en/ |
|
||||
| O5 | Commissioni spot dal 25/09/2026: 0,10% maker, 0,20% taker | confermato | Sulle coppie di stablecoin 0% maker e 0,05% taker. La pagina generale delle commissioni mostra ancora la tariffa vecchia. | https://www.okx.com/en-eu/help/important-notice-upcoming-spot-fee-adjustment-eea |
|
||||
| O6 | Quotazioni in EUR e USDC; USDT non negoziabile | confermato | L'USDT depositato resta congelato. Anche USDG è ammesso. | https://www.okx.com/en-eu/learn/usdt-not-tradeable-okx-europe-stablecoin-guide |
|
||||
| O7 | Liquidità buona su BTC, ETH e SOL in EUR, scarsa sulle altre coppie in EUR (spread 7–17 punti base) | non verificabile | La documentazione non ne parla. Volumi a 24 ore del 10/11/2026: BTC-EUR circa 5,1 M€, ETH-EUR circa 2,0 M€, SOL-EUR circa 0,45 M€ (meno di HYPE-EUR e XRP-EUR). La mediana delle 272 coppie EUR è circa 400 €. | `GET https://eea.okx.com/api/v5/market/tickers?instType=SPOT` |
|
||||
| O8 | Ultime 1.440 candele da `candles`, le precedenti da `history-candles`; BTC-EUR da novembre 2023; `1D` apre alle 16:00 UTC, `1Dutc` alle 00:00 UTC | confermato | Prima candela giornaliera di BTC-EUR: 21/11/2023. Gli orari di apertura sono stati controllati sui dati. Massimo 300 candele per chiamata. | chiamate pubbliche a eea.okx.com |
|
||||
| O9 | `public/instruments` dà `minSz`, `lotSz`, `tickSz` | confermato | Per lo spot sono espressi nella moneta base. Esempio BTC-EUR: minSz 0,0001, lotSz 0,00000001, tickSz 0,1. | `GET https://eea.okx.com/api/v5/public/instruments?instType=SPOT` |
|
||||
| O10 | Ordini market, limit, post-only, FOK, IOC; ordini algoritmici con stop, OCO, trigger, trailing stop | confermato | Gli algoritmici vanno su `POST /api/v5/trade/order-algo`. Esistono anche `optimal_limit_ioc` (solo derivati) e `rpi`; `elp` è dismesso. | https://my.okx.com/docs-v5/en/ |
|
||||
| O11 | `clOrdId`: solo lettere e cifre, massimo 32 caratteri | confermato | Distingue maiuscole e minuscole, niente trattini, unico tra gli ordini aperti. Il formato `ANU` + lettere e cifre (ADR 0001) va bene. | https://my.okx.com/docs-v5/en/ |
|
||||
| O12 | Dati dei derivati senza chiave: finanziamento, open interest, rapporto long/short | confermato | Finanziamento e open interest sono nella documentazione europea. Gli endpoint `rubik` del rapporto long/short non ci sono, ma rispondono su eea.okx.com (provato il 10/11/2026). | https://my.okx.com/docs-v5/en/ · `GET https://eea.okx.com/api/v5/rubik/stat/contracts/long-short-account-ratio?ccy=BTC&period=1D` |
|
||||
| O13 | ccxt `myokx` 4.5.85 e le sue commissioni predefinite | non più rilevante | Client scritto in casa (ADR 0003). | — |
|
||||
| O14 | La commissione può essere trattenuta nella moneta comprata | confermato | Ogni esecuzione ha `fee`, negativa quando è un costo, e `feeCcy`. Con l'impostazione di conto `feeType` = 1 si paga nella valuta di quotazione. | https://my.okx.com/docs-v5/en/ · https://www.okx.com/en-eu/help/okx-to-introduce-spot-fee-payment-option-in-quote-currency |
|
||||
| O15 | Limiti di frequenza (dato in più, utile all'adapter) | confermato | `candles` 40 ogni 2 s per IP; `history-candles` 20 ogni 2 s; invio ordine 60 ogni 2 s; `instruments` 20 ogni 2 s; `fills` 60 ogni 2 s. | https://my.okx.com/docs-v5/en/ |
|
||||
| O16 | Alternative, commissioni: Bitvavo 0,15%/0,25%; Kraken 0,40%/0,80% al livello base | confermato | Kraken applica questa tariffa dal 9/7/2026. | https://www.bitvavo.com/en/fees · https://blog.kraken.com/product/pro/new-kraken-pro-fee-tiers |
|
||||
| O16b | Kraken: candele solo le ultime 720 | confermato | — | https://docs.kraken.com/api/docs/rest-api/get-ohlc-data |
|
||||
| O16c | Bitvavo: libri in EUR più profondi, nessun ambiente di prova; Kraken: nessun ambiente di prova, solo `validate=true` | non più rilevante | Conta solo se l'utente cambia exchange: si ricontrolla in quel momento. | — |
|
||||
| O18 | Per le monete minori le coppie in USDC sono più profonde di quelle in EUR | confermato | Libri degli ordini pubblici del 10/11/2026, controvalore entro lo 0,5% dal prezzo medio. Su 12 monete su 12 (ADA, AVAX, DOGE, DOT, LINK, LTC, NEAR, ONDO, PEPE, SUI, XRP, ZEC) la coppia in USDC è più profonda; per esempio XRP circa 749.000 contro 195.000, DOT circa 11.600 contro 0. Lo spread in USDC è quasi sempre più stretto. | `GET https://eea.okx.com/api/v5/market/books?instId=XRP-USDC&sz=400` |
|
||||
| O17 | Binance non serve più i residenti italiani dal 1/7/2026; archivi pubblici con candele a 1 minuto dal 2017 | confermato | La chiusura risulta solo dalla stampa, non da una nota ufficiale di Binance. L'archivio BTCUSDT a 1 minuto va da agosto 2017 a ottobre 2026. | https://data.binance.vision/?prefix=data/spot/monthly/klines/BTCUSDT/1m/ |
|
||||
|
||||
**Cosa cambia per il codice**
|
||||
- **O3**: gli URL WebSocket sono scritti senza porta, sia in produzione sia in demo.
|
||||
- **O3b, O6**: chiamato senza chiave, `public/instruments` restituisce anche le coppie in USDT, TRY, BRL e altre valute. Ciò che si può davvero negoziare lo dice `GET /api/v5/account/instruments`, con la chiave. Fino ad allora vale un elenco fisso di coppie in EUR e USDC.
|
||||
- **O4**: si controlla lo scarto con `GET /api/v5/public/time`, usando l'orologio iniettabile. Formati del timestamp diversi tra REST e WebSocket.
|
||||
- **O8**: per le giornaliere si usa `1Dutc`, mai `1D`. Lo storico si scarica con un ritmo prudente (`history-candles` ha il limite più basso).
|
||||
- **O12**: i dati `rubik` sono facoltativi; se smettono di rispondere, il bot va avanti senza.
|
||||
- **O14**: la contabilità legge `fee` e `feeCcy` da ogni esecuzione e non ne deduce la valuta.
|
||||
|
||||
## 4.3 Altri broker (fasi opzionali)
|
||||
|
||||
| # | Fatto (SPEC 4.3) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| B1 | eToro: chiavi distinte demo e reale | confermato | Cambia solo il percorso: `trading/execution/demo` contro `trading/execution`. | https://builders.etoro.com/learn/authentication-and-api-keys.md |
|
||||
| B1b | eToro: REST `https://public-api.etoro.com` e WebSocket | confermato | Il WebSocket è documentato; il suo indirizzo `wss://` non compare nella pagina letta. | https://api-portal.etoro.com/core/websocket/overview.md |
|
||||
| B1c | eToro: circa 60 letture e 20 scritture al minuto | confermato | Le pagine dei dati di mercato indicano invece 120 richieste al minuto: le due pagine non coincidono. Si progetta su 60. | https://api-portal.etoro.com/getting-started/rate-limits.md |
|
||||
| B1d | eToro: candele da 1 minuto a 1 settimana, 1.000 per richiesta | confermato | — | https://api-portal.etoro.com/api-reference/market-data/get-instrument-candle-history.md |
|
||||
| B1e | eToro: nessun ordine limite in attesa | confermato | Gli ordini nuovi (v2 da maggio, v3 da agosto 2026) accettano solo `mkt`, `mit` e `limitIOC`, e solo in apertura. | https://api-portal.etoro.com/api-reference/trading--real/create-an-order.md |
|
||||
| B1f | eToro: crypto 1% per lato | confermato | Sconti solo dai livelli Platinum in su. | https://www.etoro.com/trading/fees/ |
|
||||
| B2 | Interactive Brokers: serve IB Gateway; secondo fattore manuale ogni settimana; dati a pagamento | confermato | Il flusso consolidato USA si paga; esiste un flusso gratuito non consolidato (Cboe One e IEX). Il sito risponde 403 ai programmi: letto dai risultati di ricerca. | https://www.interactivebrokers.com/docs/tws-api/doc/tws-settings/daily-weekly-reauthentication |
|
||||
| B2b | Libreria `ib_async` | non più rilevante | Esiste un client C# ufficiale (`CSharpAPI.dll`), con una licenza non commerciale e fuori da NuGet. Sarebbe un componente esterno da chiedere all'utente (ADR 0004). | https://interactivebrokers.github.io/ |
|
||||
| B3 | cTrader (IC Markets EU, Pepperstone EU): solo forex e CFD → escluso | confermato | Azioni e crypto ci sono solo come CFD con leva. | https://www.icmarkets.eu/en/range-of-markets · https://pepperstone.com/en-eu/platforms/ |
|
||||
| B4 | OANDA: v20 non disponibile per l'entità europea → escluso | confermato | Esclusa l'entità polacca che serve l'Europa. | https://developer.oanda.com/rest-live-v20/introduction/ |
|
||||
| B5 | MetaTrader 5: su Linux solo con Wine → escluso | confermato | Nessuna versione nativa. | https://www.metatrader5.com/en/terminal/help/start_advanced/install_linux.md |
|
||||
|
||||
## 4.4 Fonti gratuite
|
||||
|
||||
| # | Fatto (SPEC 4.4) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| F1 | `data.binance.vision`: archivi giornalieri e mensili senza chiave | confermato | Esiste anche l'intervallo da 1 secondo. Dal 1° gennaio 2025 i timestamp dei file spot sono in **microsecondi**, prima in millisecondi. | https://github.com/binance/binance-public-data |
|
||||
| F2a | Cambio BCE, file XML giornaliero, nel pomeriggio | confermato | Di solito verso le 16:00 ora dell'Europa centrale. Ultimo valore letto: 9/11/2026, 1,1193. | https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml |
|
||||
| F2b | Frankfurter come alternativa | cambiato | La versione principale è la v2, che mescola più banche centrali (il 10/11 dava 1,1194 contro 1,1193 della BCE). La v1 è deprecata dal 18/05/2026, ma resta attiva. Il dato della sola BCE è su `/v2/providers/ecb/rates`. | https://frankfurter.dev/ |
|
||||
| F3a | Calendario economico `ff_calendar_thisweek.json`: settimana corrente, senza dato effettivo | confermato | Campi title, country (la valuta), date, impact, forecast, previous. | https://nfs.faireconomy.media/ff_calendar_thisweek.json |
|
||||
| F3b | Calendario economico: al massimo una richiesta ogni 5 minuti | non verificabile | Nessuna documentazione ufficiale; un post di forum parla di 2 richieste ogni 5 minuti. | https://www.forexfactory.com/thread/post/15159093 (risponde 403) |
|
||||
| F4 | FRED `release/dates`: chiave gratuita e **facoltativa**, 120 richieste al minuto | cambiato | Il parametro e il limite sono confermati, ma la chiave è **obbligatoria**: senza chiave l'API risponde 400. Resta facoltativa per Anubis: senza chiave la funzione si spegne, come la specifica già prevede. | https://fred.stlouisfed.org/docs/api/fred/release_dates.html |
|
||||
| F5 | Storico VIX da `cdn.cboe.com` senza chiave | cambiato | Funziona, dati dal 1990, ma risponde con un rinvio 307 a `https://cdn-api.cboe.com/api/global/us_indices/daily_prices/VIX_History.csv`. | https://cdn.cboe.com/api/global/us_indices/daily_prices/VIX_History.csv |
|
||||
| F6 | Finnhub gratuito: 60 chiamate al minuto; `hour` vale `bmo` o `amc` | cambiato | In più c'è un tetto di 30 al secondo. `hour` può valere anche `dmh` (durante la seduta) o essere vuoto. Il piano gratuito dà solo 1 mese di storico delle trimestrali. | https://finnhub.io/static/swagger.json |
|
||||
| F7 | Fear & Greed crypto: giornaliero, con attribuzione | confermato | La fonte va citata in modo evidente accanto al dato. | https://alternative.me/crypto/fear-and-greed-index/ |
|
||||
| F8 | SEC EDGAR: 10 richieste al secondo, User-Agent con nome e contatto | confermato | — | https://www.sec.gov/search-filings/edgar-search-assistance/accessing-edgar-data |
|
||||
| F9 | I 14 feed RSS rispondono | confermato | Tutti e 14 rispondono con RSS valido. CoinDesk rinvia all'indirizzo senza la barra finale: si usa `https://www.coindesk.com/arc/outboundfeeds/rss`. | elenco in SPEC 4.4 |
|
||||
| F10a | CryptoPanic non ha più un piano gratuito | confermato | Piano gratuito chiuso dal 1° aprile 2026; il più economico costa 199 $ al mese. Dato da fonti secondarie: la pagina ufficiale non si legge senza JavaScript. | https://cryptopanic.com/developers/api/plans/ |
|
||||
| F10b | `yfinance`, Stooq, GDELT, API di X e Reddit da non usare | non più rilevante | Fonti escluse dalla specifica: Anubis non le usa, quindi non sono state ricontrollate. | — |
|
||||
| F11 | Date FRED: orario predefinito 08:30 di New York, impatto alto | confermato | Le uscite principali del BLS escono alle 8:30 di New York: il CPI il 10/11 e il 10/12/2026, l'Employment Situation il 6/11 e il 4/12/2026. | https://www.bls.gov/schedule/news_release/cpi.htm · https://www.bls.gov/schedule/news_release/empsit.htm |
|
||||
| F12 | Fed alle 14:00 di New York | confermato | Comunicato del 28/10/2026 "for release at 2:00 p.m.". Prossima riunione 8–9 dicembre 2026. | https://www.federalreserve.gov/newsevents/pressreleases/monetary20261028a.htm · https://www.federalreserve.gov/monetarypolicy/fomccalendars.htm |
|
||||
| F13 | BCE alle 14:15, ora dell'Europa centrale | confermato | Comunicato alle 14:15, conferenza stampa alle 14:45. La BCE scrive "CET" anche con l'ora legale: in pratica è l'ora di Francoforte, quindi si usa il fuso `Europe/Berlin`. Prossima riunione 16–17 dicembre 2026. | https://www.ecb.europa.eu/press/govcdec/mopo/html/index.en.html · https://www.ecb.europa.eu/press/press_conference/html/index.en.html |
|
||||
|
||||
**Cosa cambia per il codice**
|
||||
- **F1**: l'importatore riconosce millisecondi e microsecondi.
|
||||
- **F2b**: se si usa Frankfurter, solo `/v2/providers/ecb/rates`. La fonte principale resta il file BCE.
|
||||
- **F3b**: una richiesta all'ora, come già scritto nella specifica. La pagina "Request Denied" si riconosce come errore.
|
||||
- **F5**: il client HTTP segue i rinvii, oppure usa direttamente `cdn-api.cboe.com`.
|
||||
- **F6**: `dmh` e il campo vuoto sono gestiti; con `dmh` la trimestrale cade in seduta.
|
||||
|
||||
## 4.5 Modelli per le notizie
|
||||
|
||||
| # | Fatto (SPEC 4.5) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| M1 | `mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis`, licenza Apache-2.0 | confermato | — | https://huggingface.co/mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis |
|
||||
| M2 | Esportazione ONNX pronta nei repository `Xenova/...` | confermato | `Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`: `onnx/model.onnx` (circa 329 MB), `onnx/model_quantized.onnx` (circa 83 MB) e `tokenizer.json`. Revisione da fissare: `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`. Il repository **non dichiara una licenza**: vale quella del modello originale (Apache-2.0), da annotare nell'ADR della Fase 7. | https://huggingface.co/Xenova/distilroberta-finetuned-financial-news-sentiment-analysis |
|
||||
| M3 | 10–20 ms per titolo su CPU | non verificabile | Si misura nella Fase 7, con ONNX Runtime per .NET. | — |
|
||||
| M4 | Claude Haiku 5.5: 0,10 $ in ingresso e 0,50 $ in uscita per milione di token (fino a 100.000 token); batch a metà prezzo; non ancora nella panoramica dei modelli | cambiato | Ora **è** nella panoramica, con identificativo `claude-haiku-5-5`. Prezzi confermati. Oltre i 100.000 token costa 0,50 $ e 2,50 $. | https://platform.claude.com/docs/en/about-claude/models/overview · https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
| M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
|
||||
L'identificativo del modello resta una voce di configurazione, mai una costante nel codice (SPEC 4.5).
|
||||
|
||||
## 4.6 Vincoli per un residente italiano
|
||||
|
||||
| # | Fatto (SPEC 4.6) | Esito | Dettaglio | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| V1 | ETF domiciliati negli USA di norma non acquistabili dai privati europei (PRIIPs) | confermato | Senza il documento KID i broker europei ne bloccano l'acquisto; si possono tenere o vendere. Il filtro di Anubis resta attivo di base. | https://www.justetf.com/en/news/etf/us-domiciled-etfs.html |
|
||||
| V2 | Non è verificato se Alpaca applichi il blocco ai residenti europei | non verificabile | Nessuna pagina pubblica ne parla. Il filtro di Anubis non dipende da questo. | — |
|
||||
| V3 | Broker esteri, nessun sostituto d'imposta: serve l'esportazione delle operazioni in euro al cambio BCE | non verificabile | Non è consulenza fiscale e non si verifica su pagine tecniche. Il requisito dell'esportazione resta (SPEC 13.3). | — |
|
||||
|
||||
## Fatti non verificabili e protezioni
|
||||
|
||||
Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazioni sono provvisori: si fissano nella fase indicata.
|
||||
|
||||
| Fatto | Protezione | Fase |
|
||||
|---|---|---|
|
||||
| A2 conto reale italiano | Anubis funziona tutto in paper. L'apertura del conto reale è una voce di `GO-LIVE.md`. | 2, 9 |
|
||||
| A3 crypto su Alpaca | L'adapter Alpaca non espone la crypto. | 2 |
|
||||
| A5 notizie Alpaca nel piano gratuito | Fonte facoltativa (`news.alpaca.enabled`): si spegne da sola se risponde 401/403; restano le fonti della sezione 4.4. | 7 |
|
||||
| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo. | 3 |
|
||||
| O7 liquidità | Elenco fisso di coppie ammesse e filtro sullo spread prima di ogni ordine. | 3, 5 |
|
||||
| F3b limite del calendario | Una richiesta all'ora, al massimo una ogni 5 minuti anche ai riavvii; la pagina di blocco conta come errore. | 2 |
|
||||
| M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 |
|
||||
| V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 |
|
||||
| V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 |
|
||||
|
||||
## Versioni di .NET e dei pacchetti ammessi
|
||||
|
||||
Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già in uso sono fissate in `Directory.Packages.props`. Gli altri pacchetti si aggiungono nella fase in cui servono, dopo un nuovo controllo della versione.
|
||||
|
||||
| Pacchetto | Versione | Licenza | In uso da | Fonte |
|
||||
|---|---|---|---|---|
|
||||
| .NET 10 runtime | 10.0.14 (LTS, supporto fino al 14/11/2028) | MIT | Fase 0 | https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/10.0/releases.json |
|
||||
| .NET 10 SDK | 10.0.403 (`global.json` chiede almeno 10.0.100) | MIT | Fase 0 | come sopra |
|
||||
| `MSTest.TestFramework`, `MSTest.TestAdapter` | 4.5.2 | MIT | Fase 0 | https://www.nuget.org/packages/MSTest/4.5.2 |
|
||||
| `Microsoft.NET.Test.Sdk` | 18.11.0 | MIT | Fase 0 | https://www.nuget.org/packages/Microsoft.NET.Test.Sdk |
|
||||
| `Microsoft.Data.Sqlite` | 10.0.14 | MIT | Fase 1 | https://www.nuget.org/packages/Microsoft.Data.Sqlite/10.0.14 |
|
||||
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
||||
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 10 | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
||||
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
||||
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Fase 8 | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
||||
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
||||
| `Microsoft.ML.Tokenizers` | 2.0.1 | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.Tokenizers/2.0.1 |
|
||||
|
||||
Il metapacchetto `MSTest` porterebbe con sé l'estensione di copertura `Microsoft.Testing.Extensions.CodeCoverage`. Quell'estensione ha una licenza Microsoft separata da accettare e dipende da `Mono.Cecil`, di terze parti. Per questo si usano i suoi pacchetti di base (ADR 0006).
|
||||
|
||||
## Dipendenze indirette
|
||||
|
||||
**Oggi (Fase 0).** I file di blocco contengono solo pacchetti Microsoft e MSTest. Oltre ai tre diretti (`MSTest.TestFramework`, `MSTest.TestAdapter`, `Microsoft.NET.Test.Sdk`), il progetto dei test si porta dietro:
|
||||
|
||||
| Pacchetto | Versione | Arriva con | Nota |
|
||||
|---|---|---|---|
|
||||
| `MSTest.Analyzers` | 4.5.2 | MSTest.TestFramework | Analizzatori del codice dei test |
|
||||
| `Microsoft.Testing.Platform`, `Microsoft.Testing.Platform.MSBuild` | 2.5.2 | MSTest.TestAdapter | Piattaforma che esegue i test |
|
||||
| `Microsoft.Testing.Extensions.TrxReport.Abstractions` | 2.5.2 | MSTest.TestAdapter | Solo le interfacce del rapporto TRX |
|
||||
| `Microsoft.Testing.Extensions.Telemetry` | 2.5.2 | MSTest.TestAdapter | Telemetria della piattaforma: spenta con `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in `tasks` e nella CI |
|
||||
| `Microsoft.ApplicationInsights` | 2.23.0 | Microsoft.Testing.Extensions.Telemetry | Libreria di telemetria (MIT), non usata con la telemetria spenta |
|
||||
| `Microsoft.TestPlatform.ObjectModel`, `Microsoft.TestPlatform.TestHost` | 18.11.0 | Microsoft.NET.Test.Sdk | Esecutore `dotnet test` |
|
||||
| `Microsoft.CodeCoverage` | 18.11.0 | Microsoft.NET.Test.Sdk | Raccoglitore di copertura classico (MIT, senza dipendenze di terze parti). Arriva sempre con `Microsoft.NET.Test.Sdk`; Anubis non lo attiva |
|
||||
|
||||
Tutti sono di Microsoft, con licenza MIT. Sono solo strumenti di sviluppo e non finiscono nell'immagine né nell'applicazione.
|
||||
|
||||
**Di terze parti, in arrivo con le prossime fasi.** I pacchetti autorizzati se ne portano dietro alcuni non pubblicati da Microsoft; l'ADR 0004 li accetta insieme al pacchetto che li richiede. Il test `DependencyPolicyTests` blocca:
|
||||
- ogni pacchetto diretto fuori dall'elenco dell'ADR 0004, anche con un nome Microsoft;
|
||||
- ogni pacchetto indiretto di terze parti che non sia nel suo elenco.
|
||||
|
||||
Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del test. Un altro test controlla che ogni nome di quell'elenco compaia in questa tabella.
|
||||
|
||||
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
||||
|---|---|---|---|---|
|
||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 | Contiene la libreria nativa di SQLite. |
|
||||
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | 8 | — |
|
||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 | — |
|
||||
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||
|
||||
## Immagini Docker
|
||||
|
||||
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
||||
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Si aggiunge nella Fase 8, insieme a LightGBM.
|
||||
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
||||
+11
-11
@@ -9,7 +9,7 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
|
||||
|
||||
| Fase | Titolo | Stato |
|
||||
|---|---|---|
|
||||
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Da fare |
|
||||
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Completata |
|
||||
| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Da fare |
|
||||
| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Da fare |
|
||||
| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Da fare |
|
||||
@@ -31,19 +31,19 @@ Un progetto vuoto ma completo di toolchain, con i fatti sulle API ricontrollati.
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#1](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/1) Ricontrollare i fatti sulle API e scrivere API-NOTES.md
|
||||
- [ ] [#2](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/2) Struttura del repository e file di memoria del progetto
|
||||
- [ ] [#3](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/3) Toolchain .NET: analizzatori, MSTest, controllo dei pacchetti, comandi `tasks`
|
||||
- [ ] [#4](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/4) Applicazione minima con /health, Dockerfile minimo e docker-compose con PostgreSQL
|
||||
- [ ] [#5](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/5) Scheletro della CI su Gitea Actions (backend su SQLite e PostgreSQL)
|
||||
- [ ] [#6](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/6) Chiusura della fase, revisione indipendente e tag `fase-0`
|
||||
- [x] [#1](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/1) Ricontrollare i fatti sulle API e scrivere API-NOTES.md
|
||||
- [x] [#2](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/2) Struttura del repository e file di memoria del progetto
|
||||
- [x] [#3](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/3) Toolchain .NET: analizzatori, MSTest, controllo dei pacchetti, comandi `tasks`
|
||||
- [x] [#4](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/4) Applicazione minima con /health, Dockerfile minimo e docker-compose con PostgreSQL
|
||||
- [x] [#5](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/5) Scheletro della CI su Gitea Actions (backend su SQLite e PostgreSQL)
|
||||
- [x] [#6](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/6) Chiusura della fase, revisione indipendente e tag `fase-0`
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] `tasks check` passa su una soluzione vuota ma completa di toolchain
|
||||
- [ ] `docker compose up` avvia l'applicazione minima, che risponde su `/health`
|
||||
- [ ] `docs/API-NOTES.md` elenca per ogni fatto della sezione 4 "confermato", "cambiato" o "non verificabile"
|
||||
- [ ] `docs/STATE.md` dice quali chiavi serviranno e da quale fase (paper Alpaca dalla Fase 2, demo OKX dalla Fase 3)
|
||||
- [x] `tasks check` passa su una soluzione vuota ma completa di toolchain
|
||||
- [x] `docker compose up` avvia l'applicazione minima, che risponde su `/health`
|
||||
- [x] `docs/API-NOTES.md` elenca per ogni fatto della sezione 4 "confermato", "cambiato" o "non verificabile"
|
||||
- [x] `docs/STATE.md` dice quali chiavi serviranno e da quale fase (paper Alpaca dalla Fase 2, demo OKX dalla Fase 3)
|
||||
|
||||
## Fase 1 — Fondamenta
|
||||
|
||||
|
||||
+39
-14
@@ -1,21 +1,39 @@
|
||||
# Stato del progetto
|
||||
|
||||
Aggiornato: 2026-11-09
|
||||
Aggiornato: 2026-11-10
|
||||
|
||||
## Fase corrente
|
||||
|
||||
**Fase 0 — Preparazione: non iniziata.** Lo sviluppo parte solo con il via dell'utente.
|
||||
**Fase 0 — Preparazione: completata.** La prossima è la Fase 1 (Fondamenta), da iniziare con il via dell'utente.
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica caricata in `docs/SPEC.md`, con il nome Anubis al posto di Giano (ADR 0001).
|
||||
- Linguaggio: C# su .NET 10 con interfaccia Blazor, al posto di Python (ADR 0003).
|
||||
- Componenti esterni: ammessi solo quelli autorizzati dall'utente, il resto si scrive in casa (ADR 0004).
|
||||
- Logo: la bilancia della pesatura del cuore, con il motivo del nome (ADR 0005); screen e icona Unraid aggiornati.
|
||||
- Screen di riferimento in `docs/design/`, aggiornati al nuovo nome e al nuovo logo.
|
||||
- Bozza del template Unraid in `deploy/unraid/anubis.xml`, già con il registry di Gitea.
|
||||
- Lavori creati su Gitea: una milestone per fase, una issue per lavoro, una issue di chiusura per fase (ADR 0002), riscritti per lo stack C#. Elenco in `docs/ROADMAP.md`.
|
||||
- Regole di lavoro in `docs/SVILUPPO.md` e `CLAUDE.md`.
|
||||
- Specifica in `docs/SPEC.md`, con il nome Anubis (ADR 0001).
|
||||
- Stack:
|
||||
- C# su .NET 10 con interfaccia Blazor (ADR 0003);
|
||||
- solo i componenti autorizzati dall'utente (ADR 0004);
|
||||
- precisazioni della Fase 0 nell'ADR 0006.
|
||||
- Logo: la bilancia della pesatura del cuore (ADR 0005).
|
||||
- Lavori su Gitea, una milestone per fase (ADR 0002), elencati in `docs/ROADMAP.md`.
|
||||
- **Fase 0:**
|
||||
- Fatti della sezione 4 ricontrollati il 10/11/2026 in `docs/API-NOTES.md`, insieme alle versioni dei pacchetti e alle dipendenze indirette.
|
||||
- Soluzione `Anubis.slnx` con sette progetti:
|
||||
- `src/`: Anubis, Server, Guard, Desktop, Setup;
|
||||
- `tests/`: Anubis.Tests;
|
||||
- `tools/`: Anubis.Tasks.
|
||||
- Toolchain:
|
||||
- analizzatori con avvisi trattati come errori;
|
||||
- formattazione controllata;
|
||||
- versioni centralizzate, file di blocco.
|
||||
- Comandi `tasks` (vedi `CLAUDE.md`) e hook pre-commit, attivo in questa copia.
|
||||
- Test sempre attivi:
|
||||
- generatore casuale a seme fisso per i test di proprietà;
|
||||
- pacchetti ammessi;
|
||||
- nessun `ANUBIS_ALLOW_LIVE=1`;
|
||||
- nessun segreto nei file;
|
||||
- `/health`.
|
||||
- Applicazione minima con `GET /health`, `Dockerfile` e `docker-compose.yml` con PostgreSQL 18.
|
||||
- CI in `.gitea/workflows/ci.yml`: test su SQLite e PostgreSQL, poi l'immagine. Solo passi `run:`.
|
||||
|
||||
## In corso
|
||||
|
||||
@@ -23,16 +41,23 @@ Nulla.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
Fase 0, a partire dalla issue #1 (verifica dei fatti sulle API), poi #2–#5 e la chiusura #6.
|
||||
Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, accesso, guscio dell'interfaccia.
|
||||
|
||||
## Da sapere
|
||||
|
||||
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
||||
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
|
||||
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
|
||||
- Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale.
|
||||
- Su questo PC Docker Desktop non partiva: erano rimasti due file di comunicazione di una sessione di ottobre, che Windows non riusciva a cancellare. Le cartelle che li contengono sono state rinominate, non cancellate: `%LOCALAPPDATA%\Docker\run.stale*` e `%LOCALAPPDATA%\docker-secrets-engine.stale*`. Si possono eliminare dopo un riavvio.
|
||||
|
||||
## Serve dall'utente
|
||||
|
||||
| Cosa | Da quando serve | Senza |
|
||||
|---|---|---|
|
||||
| Via libera per iniziare lo sviluppo | Subito | Non si parte |
|
||||
| Via libera per la Fase 1 | Subito | Non si parte |
|
||||
| Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa |
|
||||
| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa |
|
||||
| Un esecutore di Gitea Actions (runner), se si vuole la CI remota | Fase 0 | `tasks ci` in locale |
|
||||
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
|
||||
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
|
||||
| Chiavi FRED e Finnhub (facoltative, gratuite) | Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
|
||||
@@ -40,4 +65,4 @@ Fase 0, a partire dalla issue #1 (verifica dei fatti sulle API), poi #2–#5 e l
|
||||
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
|
||||
| Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa |
|
||||
|
||||
Le chiavi non vanno mai scritte nel repository: si mettono nel file `.env` locale (Fase 0 crea `.env.example`) oppure, più avanti, dall'interfaccia.
|
||||
Le chiavi non vanno mai scritte nel repository: si mettono nel file `.env` locale (modello in `.env.example`) oppure, più avanti, dall'interfaccia.
|
||||
@@ -1,6 +1,6 @@
|
||||
# 0004 — Nessun SDK o componente esterno senza il permesso dell'utente
|
||||
|
||||
Data: 2026-11-09 · Stato: accettata
|
||||
Data: 2026-11-09 · Stato: accettata · Precisata dall'ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8)
|
||||
|
||||
## Contesto
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 0006 — Precisazioni della Fase 0 su test, immagini Docker e API
|
||||
|
||||
Data: 2026-11-10 · Stato: accettata · Precisa gli ADR 0003 e 0004, senza cambiare i componenti autorizzati
|
||||
|
||||
## Contesto
|
||||
|
||||
La Fase 0 ha preparato il progetto e ricontrollato i fatti della sezione 4 (`docs/API-NOTES.md`). Sono emersi alcuni punti in cui gli ADR 0003 e 0004 vanno precisati. Nessuno aggiunge componenti esterni: due ne tolgono.
|
||||
|
||||
## Decisione
|
||||
|
||||
**1. MSTest tramite i suoi pacchetti di base.** L'ADR 0004 autorizza `MSTest`. Il metapacchetto con quel nome si porta dietro l'estensione di copertura `Microsoft.Testing.Extensions.CodeCoverage`. Quell'estensione ha una licenza Microsoft separata da accettare e dipende da `Mono.Cecil`, di terze parti. Al suo posto si usano i tre pacchetti che il metapacchetto già contiene, tutti Microsoft con licenza MIT:
|
||||
- `MSTest.TestFramework`;
|
||||
- `MSTest.TestAdapter`;
|
||||
- `Microsoft.NET.Test.Sdk`.
|
||||
|
||||
Niente copertura del codice per ora. `Microsoft.NET.Test.Sdk` porta sempre con sé il raccoglitore classico `Microsoft.CodeCoverage` (Microsoft, MIT, nessuna dipendenza di terze parti): resta nel file di blocco ma non si attiva. Se servirà la copertura, si chiede all'utente (ADR 0004).
|
||||
|
||||
La piattaforma di test porta con sé la telemetria (`Microsoft.Testing.Extensions.Telemetry`, che usa `Microsoft.ApplicationInsights`). È spenta con `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in `tasks` e nella CI. L'elenco completo delle dipendenze indirette di oggi è in `docs/API-NOTES.md`.
|
||||
|
||||
**2. Test dell'applicazione senza host di prova.** `Microsoft.AspNetCore.Mvc.Testing` non è autorizzato. I test avviano il server vero su una porta locale libera (`--urls http://127.0.0.1:0`) e lo interrogano con `HttpClient`.
|
||||
|
||||
**3. Immagini Docker su Ubuntu.** Dal .NET 10 i tag `sdk:10.0` e `aspnet:10.0` usano Ubuntu 24.04 "noble", non Debian. Si resta su questi tag ufficiali. `libgomp1` si installa con `apt-get` nella Fase 8, quando arriva LightGBM. L'ADR 0004 la datava alla Fase 5, ma i modelli si addestrano nella Fase 8.
|
||||
|
||||
**4. Dipendenze indirette sotto controllo.**
|
||||
- I file di blocco (`packages.lock.json`) sono nel repository, e `tasks check` ripristina con `--locked-mode`.
|
||||
- `DependencyPolicyTests` fallisce se:
|
||||
- `Directory.Packages.props` elenca un pacchetto fuori dall'elenco dell'ADR 0004, anche come `GlobalPackageReference`;
|
||||
- un `.csproj`, `.props` o `.targets` usa un pacchetto non autorizzato, o fissa una versione propria (come attributo o come elemento);
|
||||
- nei file di blocco c'è un pacchetto diretto non autorizzato. Vale anche con un nome Microsoft: EF Core e Identity, per esempio, sono esclusi;
|
||||
- nei file di blocco c'è un pacchetto indiretto di terze parti che non è nell'elenco del test;
|
||||
- un nome dell'elenco del test non compare in `docs/API-NOTES.md`.
|
||||
- I pacchetti indiretti con nome `Microsoft.*`, `System.*` o `MSTest.*` sono riservati a Microsoft su nuget.org e passano senza elenco. Restano comunque riportati in `docs/API-NOTES.md`.
|
||||
- Le dipendenze di terze parti già note (SQLitePCLRaw, Newtonsoft.Json, LightGBM, Google.Protobuf) entrano nell'elenco del test nella fase che aggiunge il pacchetto che le richiede.
|
||||
- I test sui file del repository (pacchetti, segreti, soldi veri) leggono i file che git considera: quelli tracciati e quelli nuovi non esclusi da `.gitignore`. Il `.env` locale con le chiavi dell'utente e la cartella `/data` restano fuori.
|
||||
|
||||
**5. Cartelle dei moduli.** Le cartelle di `src/Anubis` nascono con il primo codice che le riempie, così git non deve tenere cartelle vuote. La tabella in `src/Anubis/README.md` dice per ogni modulo la cartella, il namespace e la fase.
|
||||
|
||||
**6. Hook pre-commit al posto dello strumento `pre-commit`.** La Fase 0 della SPEC 17 nomina `pre-commit`, uno strumento Python. Al suo posto c'è `.githooks/pre-commit`, uno script che esegue `tasks check`. Si attiva una volta per copia del repository con `tasks hooks` (`git config core.hooksPath .githooks`). In emergenza si salta con `git commit --no-verify`, ma la CI ripete lo stesso controllo.
|
||||
|
||||
**7. Cambi delle API che toccano il progetto** (dettagli in `docs/API-NOTES.md`):
|
||||
- **OKX, WebSocket sulla porta 443.** La 8443 è chiusa dal 31/10/2026. Gli URL si scrivono senza porta, in produzione e in demo.
|
||||
- **Alpaca, calendario e orologio.** Si parte con i `/v2` ancora attivi, dietro un'interfaccia. I `/v3` vanno usati appena i `/v2` vengono dismessi.
|
||||
- **Alpaca, conti a margine.** Alpaca non offre più conti senza margine. Il divieto di leva (SPEC 9.1) lo fa rispettare Anubis: compra solo con la liquidità propria e non va mai allo scoperto.
|
||||
- **Alpaca, dati.** Il parametro `feed=iex` si passa sempre, perché senza di esso Alpaca usa `sip`.
|
||||
- **FRED, chiave obbligatoria.** Per l'API la chiave è obbligatoria. Per Anubis resta facoltativa: senza chiave la funzione si spegne, come la specifica prevede.
|
||||
|
||||
## Alternative scartate
|
||||
|
||||
- **Tenere il metapacchetto `MSTest` e accettare l'estensione di copertura.** Porta una licenza in più e un pacchetto di terze parti che non serve.
|
||||
- **Lo strumento `pre-commit` di Python.** Richiederebbe Python e pacchetti esterni; uno script git fa lo stesso.
|
||||
- **Chiedere a parte il pacchetto `Microsoft.AspNetCore.Mvc.Testing`.** Il server vero su una porta libera fa la stessa prova senza componenti in più.
|
||||
- **Un'immagine Debian fatta in casa.** Bisognerebbe mantenere un'immagine propria e perdere gli aggiornamenti di sicurezza di Microsoft.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- `Directory.Packages.props` elenca `MSTest.TestFramework`, `MSTest.TestAdapter` e `Microsoft.NET.Test.Sdk` al posto di `MSTest`. L'elenco dell'ADR 0004 si legge con questa precisazione.
|
||||
- Ogni fase che aggiunge un pacchetto aggiorna i file di blocco, l'elenco del test e `docs/API-NOTES.md`.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<RootNamespace>Anubis.Desktop</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
// Placeholder: the desktop window and tray icon arrives in phase 10 (ADR 0003).
|
||||
await Console.Error.WriteLineAsync("Anubis.Desktop non è ancora disponibile: arriva nella Fase 10.").ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>Anubis.Guard</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
// Placeholder: the guard process (SPEC 9.3) arrives in phase 6 (ADR 0003).
|
||||
await Console.Error.WriteLineAsync("Anubis.Guard non è ancora disponibile: arriva nella Fase 6.").ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis.Server</RootNamespace>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
using Anubis.Server;
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>Builds the web application. Kept apart from Program so tests can host it.</summary>
|
||||
internal static class ServerApp
|
||||
{
|
||||
public static WebApplication Build(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok", AnubisInfo.Name, AnubisInfo.Version)));
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Answer of <c>GET /health</c>.</summary>
|
||||
internal sealed record HealthResponse(string Status, string Name, string Version);
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<RootNamespace>Anubis.Setup</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
// Placeholder: the Windows installer arrives in phase 10 (ADR 0003).
|
||||
await Console.Error.WriteLineAsync("Anubis.Setup non è ancora disponibile: arriva nella Fase 10.").ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Anubis;
|
||||
|
||||
/// <summary>Names fixed by ADR 0001, shared by every part of the bot.</summary>
|
||||
public static class AnubisInfo
|
||||
{
|
||||
/// <summary>Name shown to the user.</summary>
|
||||
public const string Name = "Anubis";
|
||||
|
||||
/// <summary>Three-letter prefix of every client order id (SPEC 7.2).</summary>
|
||||
public const string OrderPrefix = "ANU";
|
||||
|
||||
/// <summary>Prefix of every environment variable read at start-up.</summary>
|
||||
public const string EnvironmentPrefix = "ANUBIS_";
|
||||
|
||||
/// <summary>Version of the running build, for example "0.0.1".</summary>
|
||||
public static string Version { get; } =
|
||||
typeof(AnubisInfo).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Anubis (libreria)
|
||||
|
||||
Tutta la logica del bot, una cartella e un namespace per ogni modulo della SPEC 5.1 (ADR 0003).
|
||||
Le cartelle nascono con il primo codice che le riempie:
|
||||
|
||||
| Cartella | Namespace | Contenuto | Fase |
|
||||
|---|---|---|---|
|
||||
| `Core/` | `Anubis.Core` | orologio, bus degli eventi, pianificatore, impostazioni, segreti, registri, identificativi, guardia, formati | 1 |
|
||||
| `Platform/` | `Anubis.Platform` | configurazione d'avvio Docker e desktop, cartella dei dati, custodia dei segreti | 1 |
|
||||
| `Db/` | `Anubis.Db` | accesso ADO.NET, repository, migrazioni SQL | 1 |
|
||||
| `Brokers/` | `Anubis.Brokers` | interfaccia, Alpaca, OKX, simulatore, batteria di conformità | 2–3 |
|
||||
| `Data/` | `Anubis.Data` | strumenti, barre, raccolta, qualità, importatori, cambi, calendari | 2 |
|
||||
| `News/` | `Anubis.News` | fonti, pipeline, classificatore, analista, impatto | 7 |
|
||||
| `Strategies/` | `Anubis.Strategies` | strategie e candidate | 4–5 |
|
||||
| `Portfolio/` | `Anubis.Portfolio` | allocazione, dimensionamento, ribilanciamento | 5 |
|
||||
| `Risk/` | `Anubis.Risk` | regole, motore, interruttore, riconciliazione | 3–6 |
|
||||
| `Execution/` | `Anubis.Execution` | OMS, algoritmi d'ordine, scostamento | 3 |
|
||||
| `Accounting/` | `Anubis.Accounting` | registro, lotti, patrimonio, rendimenti, esportazioni | 3 |
|
||||
| `Ml/` | `Anubis.Ml` | feature, etichette, addestramento, registro modelli, deriva | 8 |
|
||||
| `Backtest/` | `Anubis.Backtest` | motore, costi, validazione, rapporti | 4 |
|
||||
| `Journal/` | `Anubis.Journal` | codici motivo e frasi in italiano | 3 |
|
||||
| `Notify/` | `Anubis.Notify` | Telegram | 6 |
|
||||
| `Demo/` | `Anubis.Demo` | modalità dimostrativa (appendice F) | 1 |
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Project commands (ADR 0003). Usage: ./tasks.ps1 check
|
||||
# The tool is built into artifacts/tasks so the solution build never overwrites a running copy.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Push-Location $PSScriptRoot
|
||||
try {
|
||||
dotnet build tools/Anubis.Tasks -c Release -o artifacts/tasks --nologo -v quiet | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { dotnet build tools/Anubis.Tasks -c Release -o artifacts/tasks --nologo; exit $LASTEXITCODE }
|
||||
dotnet artifacts/tasks/Anubis.Tasks.dll @args
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
finally { Pop-Location }
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env sh
|
||||
# Project commands (ADR 0003). Usage: ./tasks.sh check
|
||||
# The tool is built into artifacts/tasks so the solution build never overwrites a running copy.
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
dotnet build tools/Anubis.Tasks -c Release -o artifacts/tasks --nologo -v quiet >/dev/null \
|
||||
|| dotnet build tools/Anubis.Tasks -c Release -o artifacts/tasks --nologo
|
||||
exec dotnet artifacts/tasks/Anubis.Tasks.dll "$@"
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis.Tests</RootNamespace>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest.TestFramework" />
|
||||
<PackageReference Include="MSTest.TestAdapter" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Anubis\Anubis.csproj" />
|
||||
<ProjectReference Include="..\..\src\Anubis.Server\Anubis.Server.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Text.Json;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>ADR 0004 and 0006: only the packages the user authorised, and nothing else sneaking in.</summary>
|
||||
[TestClass]
|
||||
public sealed class DependencyPolicyTests
|
||||
{
|
||||
/// <summary>The list of ADR 0004 as precised by ADR 0006. Changing it needs the user's permission and a new ADR.</summary>
|
||||
private static readonly HashSet<string> _authorised = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Microsoft.Data.Sqlite",
|
||||
"System.Security.Cryptography.ProtectedData",
|
||||
"Microsoft.Web.WebView2",
|
||||
"MSTest.TestFramework",
|
||||
"MSTest.TestAdapter",
|
||||
"Microsoft.NET.Test.Sdk",
|
||||
"Npgsql",
|
||||
"Microsoft.ML",
|
||||
"Microsoft.ML.LightGbm",
|
||||
"Microsoft.ML.FastTree",
|
||||
"Microsoft.ML.OnnxRuntime",
|
||||
"Microsoft.ML.Tokenizers",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Third-party packages pulled in by an authorised one. Each must also be listed in docs/API-NOTES.md
|
||||
/// and reported to the user (checked below). Microsoft.* and System.* ids are reserved to Microsoft on nuget.org.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> _knownThirdPartyTransitive = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static readonly string[] _packageElements = ["PackageReference", "GlobalPackageReference", "PackageDownload"];
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CentralVersionsListOnlyAuthorisedPackages()
|
||||
{
|
||||
var props = XDocument.Load(Path.Combine(Repo.Root.FullName, "Directory.Packages.props"));
|
||||
var listed = props.Descendants()
|
||||
.Where(e => e.Name.LocalName is "PackageVersion" or "GlobalPackageReference")
|
||||
.Select(e => (string?)e.Attribute("Include") ?? "?")
|
||||
.ToList();
|
||||
|
||||
var notAllowed = listed.Where(id => !_authorised.Contains(id)).ToList();
|
||||
Assert.IsEmpty(notAllowed, "Pacchetti non autorizzati (ADR 0004): " + string.Join(", ", notAllowed));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ProjectsDoNotPinVersionsOrBypassTheCentralList()
|
||||
{
|
||||
string[] msbuildExtensions = [".csproj", ".props", ".targets"];
|
||||
var problems = new List<string>();
|
||||
foreach (var file in Repo.Files().Where(f => msbuildExtensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)))
|
||||
{
|
||||
var isCentralList = file.Name.Equals("Directory.Packages.props", StringComparison.OrdinalIgnoreCase);
|
||||
var doc = XDocument.Load(file.FullName);
|
||||
foreach (var reference in doc.Descendants().Where(e => _packageElements.Contains(e.Name.LocalName)))
|
||||
{
|
||||
var id = (string?)reference.Attribute("Include") ?? (string?)reference.Attribute("Update") ?? "?";
|
||||
if (!_authorised.Contains(id))
|
||||
{
|
||||
problems.Add($"{Repo.Relative(file)}: {id} non è autorizzato");
|
||||
}
|
||||
|
||||
var ownVersion = reference.Attribute("Version") is not null
|
||||
|| reference.Attribute("VersionOverride") is not null
|
||||
|| reference.Elements().Any(e => e.Name.LocalName is "Version" or "VersionOverride");
|
||||
if (ownVersion && !isCentralList)
|
||||
{
|
||||
problems.Add($"{Repo.Relative(file)}: {id} ha una versione propria");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void LockFilesContainOnlyAuthorisedDirectPackagesAndKnownIndirectOnes()
|
||||
{
|
||||
var lockFiles = Repo.Files().Where(f => f.Name.Equals("packages.lock.json", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
Assert.IsNotEmpty(lockFiles, "Nessun packages.lock.json: i file di blocco devono essere nel repository.");
|
||||
|
||||
var problems = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in lockFiles)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file.FullName));
|
||||
foreach (var framework in doc.RootElement.GetProperty("dependencies").EnumerateObject())
|
||||
{
|
||||
foreach (var package in framework.Value.EnumerateObject())
|
||||
{
|
||||
var type = package.Value.TryGetProperty("type", out var t) ? t.GetString() : null;
|
||||
var id = package.Name;
|
||||
switch (type)
|
||||
{
|
||||
case "Project":
|
||||
break;
|
||||
case "Direct" or "CentralTransitive":
|
||||
// Whatever a project asks for directly must be on the list, Microsoft or not.
|
||||
if (!_authorised.Contains(id))
|
||||
{
|
||||
problems.Add($"{id} diretto non autorizzato (in {Repo.Relative(file)})");
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
if (!_authorised.Contains(id) && !IsMicrosoftId(id) && !_knownThirdPartyTransitive.Contains(id))
|
||||
{
|
||||
problems.Add($"{id} indiretto di terze parti non dichiarato (in {Repo.Relative(file)})");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join(", ", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void KnownThirdPartyPackagesAreDocumentedInApiNotes()
|
||||
{
|
||||
var notes = File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "API-NOTES.md"));
|
||||
var missing = _knownThirdPartyTransitive.Where(id => !notes.Contains($"`{id}`", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
Assert.IsEmpty(missing, "Dipendenze di terze parti non elencate in docs/API-NOTES.md: " + string.Join(", ", missing));
|
||||
}
|
||||
|
||||
private static bool IsMicrosoftId(string id) =>
|
||||
id.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase)
|
||||
|| id.StartsWith("System.", StringComparison.OrdinalIgnoreCase)
|
||||
|| id.StartsWith("MSTest.", StringComparison.OrdinalIgnoreCase)
|
||||
|| id.Equals("NETStandard.Library", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class HealthEndpointTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task HealthAnswersOkWithNameAndVersion()
|
||||
{
|
||||
// The real server on a free local port: no test host package needed (ADR 0004).
|
||||
var app = ServerApp.Build(["--urls", "http://127.0.0.1:0"]);
|
||||
await app.StartAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var address = app.Urls.Single();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(address) };
|
||||
|
||||
using var response = await http.GetAsync(new Uri("/health", UriKind.Relative)).ConfigureAwait(false);
|
||||
var body = await response.Content.ReadFromJsonAsync<HealthResponse>().ConfigureAwait(false);
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.IsNotNull(body);
|
||||
Assert.AreEqual("ok", body.Status);
|
||||
Assert.AreEqual(AnubisInfo.Name, body.Name);
|
||||
Assert.AreEqual(AnubisInfo.Version, body.Version);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await app.StopAsync().ConfigureAwait(false);
|
||||
await app.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>SPEC 2.2: real money must never be enabled during development.</summary>
|
||||
[TestClass]
|
||||
public sealed partial class LiveSafetyTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AllowLiveIsNotSetInTheEnvironment()
|
||||
{
|
||||
var value = Environment.GetEnvironmentVariable("ANUBIS_ALLOW_LIVE");
|
||||
Assert.IsFalse(value?.Trim() == "1", "ANUBIS_ALLOW_LIVE=1 è attivo: durante lo sviluppo non si attiva mai (SPEC 2.2).");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void NoConfigurationFileEnablesRealMoney()
|
||||
{
|
||||
// Configuration-like files only: the documentation quotes the switches to forbid them.
|
||||
string[] extensions =
|
||||
[
|
||||
".toml", ".env", ".yml", ".yaml", ".json", ".xml", ".ps1", ".sh", ".props", ".targets", ".csproj",
|
||||
".runsettings", ".config", ".ini", ".conf",
|
||||
];
|
||||
var offenders = Repo.Files()
|
||||
.Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)
|
||||
|| f.Name.StartsWith(".env", StringComparison.OrdinalIgnoreCase)
|
||||
|| f.Name.StartsWith("Dockerfile", StringComparison.OrdinalIgnoreCase))
|
||||
.Where(f => LiveSwitch().IsMatch(File.ReadAllText(f.FullName)))
|
||||
.Select(Repo.Relative)
|
||||
.ToList();
|
||||
|
||||
Assert.IsEmpty(offenders, "Soldi veri attivi in: " + string.Join(", ", offenders));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void PatternRecognisesBothSwitchesInEveryFormat()
|
||||
{
|
||||
string[] active =
|
||||
[
|
||||
"ANUBIS_ALLOW_LIVE=1",
|
||||
" ANUBIS_ALLOW_LIVE: \"1\"",
|
||||
"\"ANUBIS_ALLOW_LIVE\": \"1\"",
|
||||
"\"ANUBIS_ALLOW_LIVE\": 1",
|
||||
"ENV ANUBIS_ALLOW_LIVE 1",
|
||||
"$env:ANUBIS_ALLOW_LIVE = '1'",
|
||||
"<Config Name=\"Soldi veri\" Target=\"ANUBIS_ALLOW_LIVE\" Default=\"0|1\" Type=\"Variable\">1</Config>",
|
||||
"<Config Target=\"ANUBIS_ALLOW_LIVE\" Default=\"1|0\" Type=\"Variable\">0</Config>",
|
||||
"allow_live = true",
|
||||
"\"allow_live\": true",
|
||||
];
|
||||
string[] inactive =
|
||||
[
|
||||
"ANUBIS_ALLOW_LIVE=0",
|
||||
"ANUBIS_ALLOW_LIVE: \"0\"",
|
||||
"ENV ANUBIS_ALLOW_LIVE 10",
|
||||
"<Config Name=\"Soldi veri\" Target=\"ANUBIS_ALLOW_LIVE\" Default=\"0|1\" Description=\"1: abilita\" Type=\"Variable\">0</Config>",
|
||||
"allow_live = false",
|
||||
];
|
||||
|
||||
foreach (var line in active)
|
||||
{
|
||||
Assert.IsTrue(LiveSwitch().IsMatch(line), "Non riconosciuto: " + line);
|
||||
}
|
||||
|
||||
foreach (var line in inactive)
|
||||
{
|
||||
Assert.IsFalse(LiveSwitch().IsMatch(line), "Falso allarme: " + line);
|
||||
}
|
||||
}
|
||||
|
||||
// Assignments (=, :, JSON, ENV with a space, PowerShell) and the Unraid template's value or default.
|
||||
[GeneratedRegex(
|
||||
"""ANUBIS_ALLOW_LIVE["']?\s*(?:[:=]|\s)\s*["']?1\b"""
|
||||
+ """|Target=["']ANUBIS_ALLOW_LIVE["'][^>]*>\s*1\s*<"""
|
||||
+ """|Target=["']ANUBIS_ALLOW_LIVE["'][^>]*\bDefault=["']1\b"""
|
||||
+ """|allow_live["']?\s*[:=]\s*["']?true\b""",
|
||||
RegexOptions.IgnoreCase)]
|
||||
private static partial Regex LiveSwitch();
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Property tests without external packages (ADR 0003, 0004): many generated cases from a fixed
|
||||
/// seed, so a failure always repeats, and a message that names the seed and the failing case.
|
||||
/// </summary>
|
||||
internal static class Property
|
||||
{
|
||||
public const int DefaultSeed = 20261110;
|
||||
public const int DefaultCases = 200;
|
||||
|
||||
public static void ForAll<T>(Func<Gen, T> generate, Action<T> property, int cases = DefaultCases, int seed = DefaultSeed)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
for (var i = 0; i < cases; i++)
|
||||
{
|
||||
var value = generate(gen);
|
||||
try
|
||||
{
|
||||
property(value);
|
||||
}
|
||||
catch (Exception ex) when (ex is not AssertInconclusiveException)
|
||||
{
|
||||
throw new AssertFailedException(
|
||||
string.Create(CultureInfo.InvariantCulture, $"Proprietà violata al caso {i} (seme {seed}): {value}"), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fixed-seed generator based on SplitMix64. Unlike a seeded <see cref="Random"/>, its sequence is
|
||||
/// fixed by this code, so it stays the same on every platform and .NET version.
|
||||
/// </summary>
|
||||
internal sealed class Gen(int seed)
|
||||
{
|
||||
private ulong _state = unchecked((ulong)(long)seed);
|
||||
|
||||
public ulong NextUInt64()
|
||||
{
|
||||
var z = _state += 0x9E3779B97F4A7C15UL;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
|
||||
public long Long(long minInclusive, long maxExclusive)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
|
||||
var range = unchecked((ulong)(maxExclusive - minInclusive));
|
||||
var limit = ulong.MaxValue - (ulong.MaxValue % range);
|
||||
ulong x;
|
||||
do
|
||||
{
|
||||
x = NextUInt64();
|
||||
}
|
||||
while (x >= limit);
|
||||
|
||||
return unchecked(minInclusive + (long)(x % range));
|
||||
}
|
||||
|
||||
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
|
||||
|
||||
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
|
||||
|
||||
/// <summary>Uniform value in [0, 1).</summary>
|
||||
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
|
||||
|
||||
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
|
||||
public decimal Decimal(decimal min, decimal max, int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
|
||||
|
||||
var unit = 1m;
|
||||
for (var i = 0; i < scale; i++)
|
||||
{
|
||||
unit /= 10m;
|
||||
}
|
||||
|
||||
var low = decimal.Ceiling(min / unit);
|
||||
var high = decimal.Floor(max / unit);
|
||||
if (low > high)
|
||||
{
|
||||
throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale));
|
||||
}
|
||||
|
||||
var steps = high - low;
|
||||
if (steps >= long.MaxValue)
|
||||
{
|
||||
throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale));
|
||||
}
|
||||
|
||||
var k = Long(0, (long)steps + 1);
|
||||
return (low + k) * unit;
|
||||
}
|
||||
|
||||
public T Pick<T>(IReadOnlyList<T> items)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
|
||||
return items[Int(0, items.Count)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace Anubis.Tests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class PropertyTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public void SplitMix64MatchesTheReferenceSequence()
|
||||
{
|
||||
// First output of the published SplitMix64 reference for seed 0.
|
||||
Assert.AreEqual(0xE220A8397B1DCDAFUL, new Gen(0).NextUInt64());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void SameSeedGivesTheSameSequence()
|
||||
{
|
||||
var a = new Gen(42);
|
||||
var b = new Gen(42);
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
Assert.AreEqual(a.NextUInt64(), b.NextUInt64());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void IntegersStayInRange()
|
||||
{
|
||||
Property.ForAll(g => (Value: g.Int(-3, 4), Wide: g.Long(long.MinValue, long.MaxValue)), x =>
|
||||
{
|
||||
Assert.IsTrue(x.Value is >= -3 and < 4, x.ToString());
|
||||
Assert.AreNotEqual(long.MaxValue, x.Wide);
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DecimalsRespectBoundsAndScale()
|
||||
{
|
||||
Property.ForAll(g => g.Decimal(0.00000001m, 70000m, 8), value =>
|
||||
{
|
||||
Assert.IsTrue(value is >= 0.00000001m and <= 70000m);
|
||||
Assert.AreEqual(value, decimal.Round(value, 8));
|
||||
}, cases: 1000);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DoublesAreInTheUnitInterval()
|
||||
{
|
||||
Property.ForAll(g => g.Double(), value => Assert.IsTrue(value is >= 0.0 and < 1.0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void FailureNamesSeedAndCase()
|
||||
{
|
||||
var error = Assert.ThrowsExactly<AssertFailedException>(() =>
|
||||
Property.ForAll(g => g.Int(0, 10), value => Assert.IsTrue(value < 5), seed: 7));
|
||||
|
||||
Assert.Contains("seme 7", error.Message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>SPEC 2.2: no secret in the repository. Only .env.example with fake values.</summary>
|
||||
[TestClass]
|
||||
public sealed partial class SecretScanTests
|
||||
{
|
||||
private static readonly HashSet<string> _binaryExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".png", ".jpg", ".jpeg", ".ico", ".gif", ".webp", ".ttf", ".woff", ".woff2", ".onnx", ".dll", ".exe", ".pdb", ".zip", ".gz",
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void RepositoryContainsNoSecrets()
|
||||
{
|
||||
var findings = new List<string>();
|
||||
foreach (var file in Repo.Files().Where(f => !_binaryExtensions.Contains(f.Extension)))
|
||||
{
|
||||
var lineNumber = 0;
|
||||
foreach (var line in File.ReadLines(file.FullName))
|
||||
{
|
||||
lineNumber++;
|
||||
if (LooksLikeSecret(line))
|
||||
{
|
||||
findings.Add($"{Repo.Relative(file)}:{lineNumber}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(findings, "Possibili segreti: " + string.Join(", ", findings));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DetectorFindsTypicalSecretsAndIgnoresPlaceholders()
|
||||
{
|
||||
Assert.IsTrue(LooksLikeSecret("-----BEGIN " + "PRIVATE KEY-----"));
|
||||
Assert.IsTrue(LooksLikeSecret("APCA-API-SECRET-KEY: " + new string('a', 40)));
|
||||
Assert.IsTrue(LooksLikeSecret("OK-ACCESS-PASSPHRASE=" + "Sup3rS3cretPass"));
|
||||
Assert.IsTrue(LooksLikeSecret("TELEGRAM_BOT_TOKEN=123456789:" + new string('A', 35)));
|
||||
Assert.IsTrue(LooksLikeSecret("api_key = \"" + "AKZXCVBNMASDFGHJKLQWERTY12" + "\""));
|
||||
Assert.IsTrue(LooksLikeSecret("ANUBIS_SECRET_KEY=" + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822c"));
|
||||
Assert.IsTrue(LooksLikeSecret("OKX_API_PASSPHRASE=" + "MyOkx2026Pass"));
|
||||
Assert.IsTrue(LooksLikeSecret("FINNHUB_API_KEY: " + "c1a2b3c4d5e6f7g8h9i0"));
|
||||
Assert.IsTrue(LooksLikeSecret("\"AlpacaSecret\": \"" + "Zx9Kq2Lm7Np4Rs8T" + "\""));
|
||||
|
||||
Assert.IsFalse(LooksLikeSecret("ANUBIS_SECRET_KEY=replace-with-random"));
|
||||
Assert.IsFalse(LooksLikeSecret("APCA-API-SECRET-KEY: <your-secret>"));
|
||||
Assert.IsFalse(LooksLikeSecret("POSTGRES_PASSWORD: anubis-dev"));
|
||||
Assert.IsFalse(LooksLikeSecret("ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}"));
|
||||
Assert.IsFalse(LooksLikeSecret("REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}"));
|
||||
Assert.IsFalse(LooksLikeSecret("private const string SecretKeyVariable = \"ANUBIS_SECRET_KEY\";"));
|
||||
Assert.IsFalse(LooksLikeSecret("OKX_API_PASSPHRASE=<passphrase-123>"));
|
||||
}
|
||||
|
||||
private static bool LooksLikeSecret(string line) =>
|
||||
PrivateKey().IsMatch(line) || BrokerHeader().IsMatch(line) || TelegramToken().IsMatch(line) || GenericSecret().IsMatch(line)
|
||||
|| NamedSecret().Matches(line).Any(m => !IsPlaceholder(m.Groups["value"].Value));
|
||||
|
||||
// Example values in .env.example, compose files and the CI are clearly fake.
|
||||
private static bool IsPlaceholder(string value) =>
|
||||
value.StartsWith('$') || value.StartsWith('<')
|
||||
|| _placeholderWords.Any(word => value.Contains(word, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static readonly string[] _placeholderWords = ["replace", "change-me", "example", "your-", "dummy", "fake", "xxxx"];
|
||||
|
||||
[GeneratedRegex("-----BEGIN (RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----")]
|
||||
private static partial Regex PrivateKey();
|
||||
|
||||
[GeneratedRegex("""(APCA-API-(KEY-ID|SECRET-KEY)|OK-ACCESS-(KEY|SIGN|PASSPHRASE))\s*[:=]\s*["']?[A-Za-z0-9/+=_\-]{12,}""")]
|
||||
private static partial Regex BrokerHeader();
|
||||
|
||||
[GeneratedRegex(@"\b\d{8,10}:[A-Za-z0-9_\-]{35}\b")]
|
||||
private static partial Regex TelegramToken();
|
||||
|
||||
[GeneratedRegex("""(?i)(api[_-]?key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?=[A-Za-z0-9/+=_\-]*\d)(?=[A-Za-z0-9/+=_\-]*[A-Za-z])[A-Za-z0-9/+=_\-]{24,}""")]
|
||||
private static partial Regex GenericSecret();
|
||||
|
||||
// Variables named like the project's secrets (…KEY, …SECRET, …TOKEN, …PASSPHRASE, …PASSWORD) with a value
|
||||
// of at least 8 characters that mixes letters and digits, as real keys and passwords do.
|
||||
[GeneratedRegex("""(?i)[A-Za-z0-9_\-]*(key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?<value>(?=[^\s"',;#]*\d)(?=[^\s"',;#]*[A-Za-z])[^\s"',;#]{8,})""")]
|
||||
private static partial Regex NamedSecret();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The suite runs on SQLite and on PostgreSQL (SPEC 16): the engine comes from ANUBIS_TEST_DB.</summary>
|
||||
[TestClass]
|
||||
public sealed class TestDatabaseTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void EngineIsSqliteOrPostgres()
|
||||
{
|
||||
Assert.IsTrue(TestDatabase.Engine is "sqlite" or "postgres", $"ANUBIS_TEST_DB non valido: {TestDatabase.Engine}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task PostgresIsReachableWhenSelected()
|
||||
{
|
||||
if (TestDatabase.Engine != "postgres")
|
||||
{
|
||||
Assert.Inconclusive("Giro su SQLite: PostgreSQL non richiesto.");
|
||||
}
|
||||
|
||||
var (host, port) = TestDatabase.Postgres;
|
||||
Assert.IsTrue(
|
||||
await TestDatabase.PostgresReachableAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false),
|
||||
$"PostgreSQL non raggiungibile su {host}:{port}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.Sockets;
|
||||
|
||||
[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>Test categories (ADR 0003). <see cref="LiveDemo"/> never runs in the normal suite.</summary>
|
||||
internal static class Category
|
||||
{
|
||||
public const string Unit = "Unit";
|
||||
public const string Integration = "Integration";
|
||||
public const string Simulation = "Simulation";
|
||||
public const string LiveDemo = "LiveDemo";
|
||||
public const string Golden = "Golden";
|
||||
}
|
||||
|
||||
/// <summary>Locates the repository so policy tests can read its files.</summary>
|
||||
internal static class Repo
|
||||
{
|
||||
public static DirectoryInfo Root { get; } = FindRoot();
|
||||
|
||||
private static DirectoryInfo FindRoot()
|
||||
{
|
||||
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "Anubis.slnx")))
|
||||
{
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Repository root (Anubis.slnx) not found above " + AppContext.BaseDirectory);
|
||||
}
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<FileInfo>> _files = new(ListFiles);
|
||||
|
||||
/// <summary>
|
||||
/// The files git would commit: tracked ones plus new ones that .gitignore does not exclude.
|
||||
/// The local .env, /data and build output stay out, so a key the user puts there never fails the suite.
|
||||
/// </summary>
|
||||
public static IEnumerable<FileInfo> Files() => _files.Value;
|
||||
|
||||
private static List<FileInfo> ListFiles()
|
||||
{
|
||||
var info = new ProcessStartInfo("git")
|
||||
{
|
||||
WorkingDirectory = Root.FullName,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
};
|
||||
foreach (var argument in new[] { "ls-files", "-z", "--cached", "--others", "--exclude-standard" })
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = Process.Start(info) ?? throw new InvalidOperationException("git could not be started.");
|
||||
var errors = process.StandardError.ReadToEndAsync();
|
||||
var output = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
throw new InvalidOperationException("git ls-files failed: " + errors.Result);
|
||||
}
|
||||
|
||||
return output.Split('\0', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(path => new FileInfo(Path.Combine(Root.FullName, path)))
|
||||
.Where(file => file.Exists)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public static string Relative(FileInfo file) =>
|
||||
Path.GetRelativePath(Root.FullName, file.FullName).Replace('\\', '/');
|
||||
}
|
||||
|
||||
/// <summary>Database engine the suite runs against: <c>ANUBIS_TEST_DB</c> = sqlite (default) or postgres.</summary>
|
||||
internal static class TestDatabase
|
||||
{
|
||||
public static string Engine { get; } =
|
||||
(Environment.GetEnvironmentVariable("ANUBIS_TEST_DB") ?? "sqlite").Trim().ToLowerInvariant();
|
||||
|
||||
/// <summary>Host and port of the PostgreSQL used by the tests, from <c>ANUBIS_TEST_PG_HOST</c> and <c>ANUBIS_TEST_PG_PORT</c>.</summary>
|
||||
public static (string Host, int Port) Postgres { get; } = (
|
||||
Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_HOST") ?? "localhost",
|
||||
int.TryParse(Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_PORT"), out var port) ? port : 55432);
|
||||
|
||||
public static async Task<bool> PostgresReachableAsync(TimeSpan timeout)
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
using var cts = new CancellationTokenSource(timeout);
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(Postgres.Host, Postgres.Port, cts.Token).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is SocketException or OperationCanceledException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.NET.Test.Sdk": {
|
||||
"type": "Direct",
|
||||
"requested": "[18.11.0, )",
|
||||
"resolved": "18.11.0",
|
||||
"contentHash": "xf/bR0LNkhK0SnadDRlZIQmC4sac5Wk0e1WAdiQjRN3MSo6gQ9M2c4c1XRNnVGjfOvckh704W5CJ19AL0/Xsdg==",
|
||||
"dependencies": {
|
||||
"Microsoft.CodeCoverage": "18.11.0",
|
||||
"Microsoft.TestPlatform.TestHost": "18.11.0"
|
||||
}
|
||||
},
|
||||
"MSTest.TestAdapter": {
|
||||
"type": "Direct",
|
||||
"requested": "[4.5.2, )",
|
||||
"resolved": "4.5.2",
|
||||
"contentHash": "3ZM4AiMnHHI58VKcn4DUlz9HMtPk+ucN/WNYiB0k29gaihTPiK5vcXX49iisgbLd8aFlSoaEIRBPekKs/wDYfA==",
|
||||
"dependencies": {
|
||||
"MSTest.TestFramework": "4.5.2",
|
||||
"Microsoft.TestPlatform.ObjectModel": "18.10.1",
|
||||
"Microsoft.Testing.Extensions.Telemetry": "2.5.2",
|
||||
"Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2",
|
||||
"Microsoft.Testing.Platform.MSBuild": "2.5.2"
|
||||
}
|
||||
},
|
||||
"MSTest.TestFramework": {
|
||||
"type": "Direct",
|
||||
"requested": "[4.5.2, )",
|
||||
"resolved": "4.5.2",
|
||||
"contentHash": "9U+a6ZcsIEXnC2Q8D2RRBpvo3ro83RfGLfeCJC+NomPhiCD6gi9ehpk00A1TC0Za+nB7j5sn6V1VbDanqoohsA==",
|
||||
"dependencies": {
|
||||
"MSTest.Analyzers": "4.5.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.ApplicationInsights": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw=="
|
||||
},
|
||||
"Microsoft.CodeCoverage": {
|
||||
"type": "Transitive",
|
||||
"resolved": "18.11.0",
|
||||
"contentHash": "MhN9wpvL1Es4hfIYslrsVgIsUdDFxuOBTbAl9mGIMvFo8PP5CLf4DrGdNrfwWSyn0lqi6sssm+I/qkkLL3MU+g=="
|
||||
},
|
||||
"Microsoft.Testing.Extensions.Telemetry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.5.2",
|
||||
"contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==",
|
||||
"dependencies": {
|
||||
"Microsoft.ApplicationInsights": "2.23.0",
|
||||
"Microsoft.Testing.Platform": "[2.5.2, 3.0.0)"
|
||||
}
|
||||
},
|
||||
"Microsoft.Testing.Extensions.TrxReport.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.5.2",
|
||||
"contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Testing.Platform": "[2.5.2, 3.0.0)"
|
||||
}
|
||||
},
|
||||
"Microsoft.Testing.Platform": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.5.2",
|
||||
"contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw=="
|
||||
},
|
||||
"Microsoft.Testing.Platform.MSBuild": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.5.2",
|
||||
"contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Testing.Platform": "[2.5.2, 3.0.0)"
|
||||
}
|
||||
},
|
||||
"Microsoft.TestPlatform.ObjectModel": {
|
||||
"type": "Transitive",
|
||||
"resolved": "18.11.0",
|
||||
"contentHash": "BXBHYnwSOljKute8UYCMXOLAdB7awxEMppPSpqOF1ZxLD/W/OH+vTBgFaXA7q0aditJTVXSMVenel+wOkEIyNg=="
|
||||
},
|
||||
"Microsoft.TestPlatform.TestHost": {
|
||||
"type": "Transitive",
|
||||
"resolved": "18.11.0",
|
||||
"contentHash": "AKjwKpyRBwoQFQmpcchtoYlfJEBlaY/40uxBRi+qXP4NR7xT8t+XTJtOyEyumfvfJcH5pASs75LwNdXYRr4XNA==",
|
||||
"dependencies": {
|
||||
"Microsoft.TestPlatform.ObjectModel": "18.11.0"
|
||||
}
|
||||
},
|
||||
"MSTest.Analyzers": {
|
||||
"type": "Transitive",
|
||||
"resolved": "4.5.2",
|
||||
"contentHash": "t6Dj9AmWO9IfkMBi3yYTf7bfgSTAetsi4LFA3xGdKbJ+gBbSDqbo41U5vYiW9puD8UGl2elsizNeJVYtwNim0Q=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
},
|
||||
"anubis.server": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Anubis": "[0.0.1, )"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>Anubis.Tasks</RootNamespace>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,153 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
// Project commands (ADR 0003): the same steps on Windows and Linux, without make.
|
||||
// Run through tasks.ps1 / tasks.sh, which build this tool apart from the solution.
|
||||
|
||||
var root = FindRoot();
|
||||
var command = args.Length > 0 ? args[0].ToLowerInvariant() : "help";
|
||||
var rest = args.Skip(1).ToArray();
|
||||
|
||||
return command switch
|
||||
{
|
||||
"check" => Check(),
|
||||
"test" => Test(Environment.GetEnvironmentVariable("ANUBIS_TEST_DB") ?? "sqlite", rest),
|
||||
"dev" => Run("dotnet", ["watch", "--project", "src/Anubis.Server", "run", .. rest]),
|
||||
"build" => BuildImage("dev"),
|
||||
"ci" => Ci(),
|
||||
"hooks" => Step("Attivazione dell'hook pre-commit (.githooks)", "git", ["config", "core.hooksPath", ".githooks"]) ?? 0,
|
||||
"seed-demo" => NotYet("seed-demo", 1),
|
||||
"desktop-win" => NotYet("desktop-win", 10),
|
||||
_ => Help(),
|
||||
};
|
||||
|
||||
// Locked restore, formatting, build with analyzers as errors, tests on the engine in ANUBIS_TEST_DB.
|
||||
int Check()
|
||||
{
|
||||
var engine = Environment.GetEnvironmentVariable("ANUBIS_TEST_DB") ?? "sqlite";
|
||||
return Step("Ripristino dei pacchetti dai file di blocco", "dotnet", ["restore", "Anubis.slnx", "--locked-mode"])
|
||||
?? Step("Controllo della formattazione", "dotnet", ["format", "Anubis.slnx", "--verify-no-changes", "--no-restore"])
|
||||
?? Step("Compilazione con gli analizzatori", "dotnet", ["build", "Anubis.slnx", "--no-restore", "-c", "Release"])
|
||||
?? Test(engine, ["--no-build", "-c", "Release"]);
|
||||
}
|
||||
|
||||
int Test(string engine, string[] extra)
|
||||
{
|
||||
var env = new Dictionary<string, string> { ["ANUBIS_TEST_DB"] = engine, ["TESTINGPLATFORM_TELEMETRY_OPTOUT"] = "1" };
|
||||
return Step($"Test su {engine}", "dotnet",
|
||||
["test", "Anubis.slnx", "--filter", "TestCategory!=LiveDemo", "--logger", "console;verbosity=normal", .. extra], env) ?? 0;
|
||||
}
|
||||
|
||||
// What the remote CI does, run locally: check on SQLite, tests on PostgreSQL, image build.
|
||||
int Ci()
|
||||
{
|
||||
var failed = Check();
|
||||
if (failed != 0)
|
||||
{
|
||||
return failed;
|
||||
}
|
||||
|
||||
var ownPostgres = Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_HOST") is null;
|
||||
if (ownPostgres)
|
||||
{
|
||||
failed = Step("Avvio di PostgreSQL per i test", "docker", ["compose", "up", "-d", "--wait", "postgres"]) ?? 0;
|
||||
if (failed != 0)
|
||||
{
|
||||
return failed;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
failed = Test("postgres", ["--no-build", "-c", "Release"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ownPostgres)
|
||||
{
|
||||
Step("Arresto di PostgreSQL", "docker", ["compose", "stop", "postgres"]);
|
||||
}
|
||||
}
|
||||
|
||||
return failed != 0 ? failed : BuildImage("ci");
|
||||
}
|
||||
|
||||
int BuildImage(string tag) =>
|
||||
Step("Costruzione dell'immagine Docker", "docker",
|
||||
["build", "-f", "deploy/docker/Dockerfile", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0;
|
||||
|
||||
int NotYet(string name, int phase)
|
||||
{
|
||||
Console.Error.WriteLine($"'tasks {name}' arriva nella Fase {phase.ToString(CultureInfo.InvariantCulture)}.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
int Help()
|
||||
{
|
||||
Console.WriteLine("""
|
||||
Comandi di Anubis (ADR 0003):
|
||||
tasks check ripristino bloccato, formattazione, compilazione, test
|
||||
tasks test solo i test (motore da ANUBIS_TEST_DB, predefinito sqlite)
|
||||
tasks dev avvia il server e lo riavvia a ogni modifica
|
||||
tasks build costruisce l'immagine Docker
|
||||
tasks ci come la CI: check, test su PostgreSQL, immagine
|
||||
tasks hooks attiva l'hook che esegue check prima di ogni commit
|
||||
tasks seed-demo dati dimostrativi (Fase 1)
|
||||
tasks desktop-win installatore Windows (Fase 10)
|
||||
""");
|
||||
return command == "help" ? 0 : 1;
|
||||
}
|
||||
|
||||
// Runs one step and returns its exit code only when it failed, so steps chain with ??.
|
||||
int? Step(string title, string file, string[] arguments, Dictionary<string, string>? env = null)
|
||||
{
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"== {title}");
|
||||
var code = Run(file, arguments, env);
|
||||
if (code != 0)
|
||||
{
|
||||
Console.Error.WriteLine($"!! {title}: non riuscito (codice {code.ToString(CultureInfo.InvariantCulture)})");
|
||||
return code;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
int Run(string file, string[] arguments, Dictionary<string, string>? env = null)
|
||||
{
|
||||
var info = new ProcessStartInfo(file) { WorkingDirectory = root, UseShellExecute = false };
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
foreach (var (key, value) in env ?? [])
|
||||
{
|
||||
info.Environment[key] = value;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var process = Process.Start(info)!;
|
||||
process.WaitForExit();
|
||||
return process.ExitCode;
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"Impossibile avviare '{file}': {ex.Message}");
|
||||
return 127;
|
||||
}
|
||||
}
|
||||
|
||||
static string FindRoot()
|
||||
{
|
||||
for (var dir = new DirectoryInfo(Environment.CurrentDirectory); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "Anubis.slnx")))
|
||||
{
|
||||
return dir.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Anubis.slnx non trovato: lancia i comandi dalla cartella del repository.");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user