R8: Accounting- + Supervisor-Modul + Core-Datenfundament (S-0)
Portierung der beiden fehlenden Grundbausteine aus PolytraderSharp (voller Ausbau). Core S-0 (Datenfundament fuer Analyse/Forensik): - core_decision_journal + core_order_events (+ ReasonCode/Decision/OrderEvent-Enums), IDecisionJournal/IOrderEventLog mit fehlertoleranten EF-Impls (Handel bricht nie). - SignalId-Durchreichung TradeSignal -> ExecutionService -> core_trade_history; ExecutionService schreibt an jeder Verzweigung Journal/Order-Events. - JSONL-Log-Sink (LogJson + Dual-Sink), pure Analytik: RealizedPnlEngine (FIFO), TradeAnalytics, DossierBuilder. Migration AddAnalysisFoundation. Accounting-Modul (acc_): unabhaengiger IBKR-Kontoauszug (Activity Flex Query) hinter Interfaces mit Offline-Null-Stubs -> append-only Ledger + Periodenabrechnung/BWA + FX (USD/EUR) + CSV/PDF (PDFsharp/MigraDoc). Steuerschicht bewusst offen (Platzhalter-Tab). Kein Handel. Migration InitialAccounting. Supervisor-Modul (sup_): read-only OpenRouter-Agent (Function-Calling-Loop) + read-only Tool-Registry (8 Tools) + Profile + Dossier-Browser + Counterfactual-Job (Stub) + Tagesbericht/MCP-Light (opt-in). Migration InitialSupervisor. Verdrahtung: Program.cs (beide Module + Icons), slnx/App/Tests-Referenzen, provision-db.ps1, AppSettings-Sektionen, docs/konzepte, README. Tests: 79 -> 117 gruen (FIFO/KPIs/Dossier/JSONL, Classifier/Engine/FX/Idempotenz, OpenRouter/Registry/Agent/MCP, STA-Konstruktion beider neuen Fenster). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
cbbedb2e0e
commit
2a312ca035
@@ -0,0 +1,59 @@
|
||||
using FluentAssertions;
|
||||
using IBKRTrader.Modules.Supervisor.Agent;
|
||||
using IBKRTrader.Modules.Supervisor.Mcp;
|
||||
|
||||
namespace IBKRTrader.Tests.Modules.Supervisor;
|
||||
|
||||
[Trait("cat", "unit")]
|
||||
public class McpJsonRpcTests
|
||||
{
|
||||
private static SupervisorToolRegistry Registry()
|
||||
{
|
||||
var reg = new SupervisorToolRegistry();
|
||||
reg.Register(new SupervisorTool("echo", "Echo", """{"type":"object","properties":{"x":{"type":"string"}}}""",
|
||||
args => SupervisorToolRegistry.GetString(args, "x") ?? ""));
|
||||
return reg;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Initialize_ReturnsServerInfo()
|
||||
{
|
||||
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":1,"method":"initialize"}""", Registry());
|
||||
res.Should().Contain("ibkrtrader-supervisor").And.Contain("protocolVersion");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolsList_ListsTools()
|
||||
{
|
||||
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":2,"method":"tools/list"}""", Registry());
|
||||
res.Should().Contain("echo").And.Contain("inputSchema");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolsCall_ExecutesAndWrapsResult()
|
||||
{
|
||||
var res = McpJsonRpc.Handle(
|
||||
"""{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"x":"hi"}}}""",
|
||||
Registry());
|
||||
res.Should().Contain("\"text\":\"hi\"").And.Contain("\"isError\":false");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownMethod_ReturnsMethodNotFound()
|
||||
{
|
||||
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":4,"method":"nope"}""", Registry());
|
||||
res.Should().Contain("-32601");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseError_ReturnsMinus32700()
|
||||
{
|
||||
McpJsonRpc.Handle("{ kaputt", Registry()).Should().Contain("-32700");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Notification_WithoutId_ReturnsNull()
|
||||
{
|
||||
McpJsonRpc.Handle("""{"jsonrpc":"2.0","method":"ping"}""", Registry()).Should().BeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using FluentAssertions;
|
||||
using IBKRTrader.Modules.Supervisor.Agent;
|
||||
|
||||
namespace IBKRTrader.Tests.Modules.Supervisor;
|
||||
|
||||
[Trait("cat", "unit")]
|
||||
public class OpenRouterClientTests
|
||||
{
|
||||
private static SupervisorTool Tool() => new(
|
||||
"get_kpis", "KPIs", """{"type":"object","properties":{"module":{"type":"string"}}}""", _ => "{}");
|
||||
|
||||
[Fact]
|
||||
public void BuildRequestBody_IncludesModelMessagesAndTools()
|
||||
{
|
||||
var messages = new[] { ChatMessage.System("sys"), ChatMessage.User("frage?") };
|
||||
var body = OpenRouterClient.BuildRequestBody("openrouter/auto", messages, new[] { Tool() });
|
||||
|
||||
body.Should().Contain("\"model\":\"openrouter/auto\"");
|
||||
body.Should().Contain("\"role\":\"system\"");
|
||||
body.Should().Contain("frage?");
|
||||
body.Should().Contain("\"name\":\"get_kpis\"");
|
||||
body.Should().Contain("\"parameters\"");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseResponse_ExtractsContentAndUsage()
|
||||
{
|
||||
const string json = """
|
||||
{"choices":[{"message":{"content":"Antwort","role":"assistant"}}],
|
||||
"usage":{"prompt_tokens":12,"completion_tokens":3}}
|
||||
""";
|
||||
|
||||
var r = OpenRouterClient.ParseResponse(json);
|
||||
|
||||
r.Content.Should().Be("Antwort");
|
||||
r.ToolCalls.Should().BeEmpty();
|
||||
r.PromptTokens.Should().Be(12);
|
||||
r.CompletionTokens.Should().Be(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseResponse_ExtractsToolCalls()
|
||||
{
|
||||
const string json = """
|
||||
{"choices":[{"message":{"role":"assistant","content":null,
|
||||
"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_kpis","arguments":"{\"module\":\"CT\"}"}}]}}]}
|
||||
""";
|
||||
|
||||
var r = OpenRouterClient.ParseResponse(json);
|
||||
|
||||
r.ToolCalls.Should().HaveCount(1);
|
||||
r.ToolCalls[0].Name.Should().Be("get_kpis");
|
||||
r.ToolCalls[0].ArgumentsJson.Should().Contain("CT");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using FluentAssertions;
|
||||
using IBKRTrader.Modules.Supervisor.Agent;
|
||||
|
||||
namespace IBKRTrader.Tests.Modules.Supervisor;
|
||||
|
||||
[Trait("cat", "unit")]
|
||||
public class SupervisorAgentTests
|
||||
{
|
||||
/// <summary>Fake-Client: gibt vorab definierte Antworten der Reihe nach zurück.</summary>
|
||||
private sealed class FakeChat : IChatCompletionClient
|
||||
{
|
||||
private readonly Queue<ChatResponse> _responses;
|
||||
public List<string> SeenToolResults { get; } = new();
|
||||
public FakeChat(params ChatResponse[] responses) => _responses = new(responses);
|
||||
|
||||
public Task<ChatResponse> CompleteAsync(string model, IReadOnlyList<ChatMessage> messages,
|
||||
IReadOnlyList<SupervisorTool> tools, CancellationToken ct)
|
||||
{
|
||||
foreach (var m in messages)
|
||||
if (m.Role == "tool" && m.Content != null) SeenToolResults.Add(m.Content);
|
||||
return Task.FromResult(_responses.Dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
private static SupervisorToolRegistry EchoRegistry()
|
||||
{
|
||||
var reg = new SupervisorToolRegistry();
|
||||
reg.Register(new SupervisorTool("get_kpis", "KPIs", """{"type":"object"}""", _ => "{\"NetPnl\":42}"));
|
||||
return reg;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunsToolThenReturnsFinalAnswer()
|
||||
{
|
||||
var chat = new FakeChat(
|
||||
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
|
||||
new ChatResponse { Content = "Netto-PnL ist 42." });
|
||||
var agent = new SupervisorAgent(chat, EchoRegistry());
|
||||
|
||||
var result = await agent.AskAsync("Wie ist die Performance?");
|
||||
|
||||
result.Answer.Should().Be("Netto-PnL ist 42.");
|
||||
result.ToolInvocations.Should().ContainSingle();
|
||||
result.ToolInvocations[0].Tool.Should().Be("get_kpis");
|
||||
chat.SeenToolResults.Should().Contain(s => s.Contains("42")); // Tool-Ergebnis ging ans Modell zurück
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProfileFilter_DeniesUnlistedTool()
|
||||
{
|
||||
var chat = new FakeChat(
|
||||
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
|
||||
new ChatResponse { Content = "fertig" });
|
||||
// Technik-Profil listet get_kpis NICHT → Ausführung verweigert.
|
||||
var agent = new SupervisorAgent(chat, EchoRegistry());
|
||||
|
||||
var result = await agent.AskAsync("test", profile: SupervisorProfiles.Technik);
|
||||
|
||||
result.ToolInvocations[0].Result.Should().Contain("nicht freigegeben");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopsAfterMaxIterations()
|
||||
{
|
||||
// Modell fordert IMMER ein Tool an → harte Iterationsgrenze greift.
|
||||
var always = Enumerable.Range(0, SupervisorAgent.MaxIterations + 2)
|
||||
.Select(_ => new ChatResponse { ToolCalls = { new ToolCall("c", "get_kpis", "{}") } })
|
||||
.ToArray();
|
||||
var agent = new SupervisorAgent(new FakeChat(always), EchoRegistry());
|
||||
|
||||
var result = await agent.AskAsync("Endlosschleife?");
|
||||
|
||||
result.Answer.Should().Contain("maximale Tool-Iterationen");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using FluentAssertions;
|
||||
using IBKRTrader.Modules.Supervisor.Agent;
|
||||
|
||||
namespace IBKRTrader.Tests.Modules.Supervisor;
|
||||
|
||||
[Trait("cat", "unit")]
|
||||
public class SupervisorToolRegistryTests
|
||||
{
|
||||
private static SupervisorToolRegistry WithEcho()
|
||||
{
|
||||
var reg = new SupervisorToolRegistry();
|
||||
reg.Register(new SupervisorTool("echo", "Echo", """{"type":"object","properties":{"x":{"type":"string"}}}""",
|
||||
args => SupervisorToolRegistry.GetString(args, "x") ?? "(leer)"));
|
||||
return reg;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownTool_ReturnsErrorText_DoesNotThrow()
|
||||
{
|
||||
var reg = WithEcho();
|
||||
reg.Execute("nope", "{}").Should().StartWith("FEHLER: Unbekanntes Tool");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidJsonArgs_ReturnsErrorText()
|
||||
{
|
||||
var reg = WithEcho();
|
||||
reg.Execute("echo", "{ kaputt").Should().StartWith("FEHLER: Ungültige Tool-Argumente");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecutesRegisteredTool()
|
||||
{
|
||||
var reg = WithEcho();
|
||||
reg.Execute("echo", """{"x":"hallo"}""").Should().Be("hallo");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolException_IsCaught_AsErrorText()
|
||||
{
|
||||
var reg = new SupervisorToolRegistry();
|
||||
reg.Register(new SupervisorTool("boom", "Boom", """{"type":"object"}""",
|
||||
_ => throw new InvalidOperationException("geplatzt")));
|
||||
|
||||
reg.Execute("boom", "{}").Should().Contain("geplatzt");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user