feat: Phase 3 J/K/L (Sell Decision, Trade Execution, Portfolio Reconciliation) + fix pre-existing build/boot breakage

Completes VS-10/VS-12/VS-14 and makes the solution and Host actually
build and boot for the first time on this branch (main did not build
before this commit).

Root-cause fixes required to reach a green build/boot (not scoped to
J/K/L but blocking any verification of it):
- Restore Polly PackageVersion accidentally deleted from
  Directory.Packages.props (broke KArtSell.Host).
- Remove MediatR dependency from Compliance/VS-04 (package was never
  installed; ICommand/ICommandHandler/IMediator never existed) and
  wire Endpoint -> Handler directly per this repo's convention.
- Migrate FastEndpoints v5 API calls (SendOkAsync/SendAsync/
  SendCreatedAtAsync/SendNotFoundAsync, Description().WithName()) to
  the v7 Send.* fluent API across ~10 endpoint files.
- Fix migrations 0036/0038/0039/0040: rewritten from invalid T-SQL
  (`IF NOT EXISTS ... BEGIN ... END`) to idiomatic Postgres
  (`CREATE TABLE/INDEX IF NOT EXISTS`) — these could not apply to any
  fresh database before this fix.
- Collapse 3 duplicate cross-cutting abstractions that shadowed the
  BuildingBlocks versions and caused type-mismatch compile errors:
  IKrxDataService, IOutboxWriter (ReconcileTradeHandler), IClock
  (ApprovalWorkflow/ApprovalPolicy).
- Inject IClock (BuildingBlocks.Time) in place of direct
  DateTime.Now/UtcNow across 19 files to satisfy the architecture
  test AGENTS.md#DateTime-abstraction rule (13/13 architecture tests
  now pass, was 12/13).
- Register all new and previously-unregistered slices in
  Program.cs DI (SellDecision, TradeExecution, PortfolioReconciliation,
  Compliance, Features/ApprovalWorkflow) — the Host had never
  successfully completed a boot with this code present.
- Disable ("[DontRegister]") the older, route-colliding
  ApprovalWorkflow/ (Workstream H) endpoint set in favor of
  Features/ApprovalWorkflow/ (Workstream G, matches the documented
  Features/<Slice>/ convention); kept for its existing test coverage.
  See TECH_DEBT-017 for the follow-up decision needed.

Verified: dotnet build 0 errors/0 warnings; architecture tests 13/13;
unit tests 54/54 + 18/18; integration tests 34/36 (2 failures are a
local test-DB migration-journal/schema mismatch, not a code defect);
Host boots cleanly and registers all 34 endpoints.

New tech debt recorded: DEBT-017 (duplicate VS-03 implementation),
DEBT-018 (outbox write not co-transactional with entity write in
TradeExecution/PortfolioReconciliation), DEBT-019 (duplicate
BuildingBlocks-shadowing abstractions, partially resolved).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-07 19:53:38 +09:00
parent 75f72fbb72
commit b1e38ac374
55 changed files with 5620 additions and 196 deletions
@@ -2,6 +2,8 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Dapper;
using KArtSell.BuildingBlocks.Time;
using KArtSell.Modules.ModelOperations.ShadowRun.Services;
using Microsoft.Extensions.Logging;
using Npgsql;
@@ -18,6 +20,7 @@ public sealed class ImportMarketDataHandler
private readonly IKrxDataService? _krxService;
private readonly IOpenDartDataService? _openDartService;
private readonly IKisDataService? _kisService;
private readonly IClock _clock;
private readonly ILogger<ImportMarketDataHandler> _logger;
public ImportMarketDataHandler(
@@ -25,12 +28,14 @@ public sealed class ImportMarketDataHandler
IKrxDataService? krxService,
IOpenDartDataService? openDartService,
IKisDataService? kisService,
IClock clock,
ILogger<ImportMarketDataHandler> logger)
{
_connectionString = connectionString;
_krxService = krxService;
_openDartService = openDartService;
_kisService = kisService;
_clock = clock;
_logger = logger;
}
@@ -41,7 +46,7 @@ public sealed class ImportMarketDataHandler
ImportMarketDataCommand command,
CancellationToken cancellationToken)
{
var startTime = DateTime.UtcNow;
var startTime = _clock.UtcNow.UtcDateTime;
try
{
@@ -91,7 +96,7 @@ public sealed class ImportMarketDataHandler
errorMessage,
cancellationToken);
var duration = DateTime.UtcNow - startTime;
var duration = _clock.UtcNow.UtcDateTime - startTime;
_logger.LogInformation(
"Market data import completed: API={ApiName}, Status={Status}, Rows={RowCount}, Duration={DurationMs}ms",
command.ApiName, success ? "SUCCESS" : "FAILURE", rowCount, duration.TotalMilliseconds);
@@ -222,12 +227,12 @@ public sealed class ImportMarketDataHandler
await conn.ExecuteAsync(sql, new
{
Id = Guid.NewGuid(),
ImportAt = DateTime.UtcNow,
ImportAt = _clock.UtcNow.UtcDateTime,
RowCount = rowCount,
Checksum = checksum,
Status = status,
ErrorMessage = errorMessage,
PublishedAt = DateTime.UtcNow,
PublishedAt = _clock.UtcNow.UtcDateTime,
command.CorrelationId
});
}
@@ -1,4 +1,5 @@
using Hangfire;
using KArtSell.BuildingBlocks.Time;
using Microsoft.Extensions.Logging;
namespace KArtSell.Modules.ModelOperations.ShadowRun.Features.ImportMarketData;
@@ -12,15 +13,18 @@ public sealed class ScheduleDailyImportsJob
{
private readonly ImportMarketDataHandler _handler;
private readonly IBackgroundJobClient _jobClient;
private readonly IClock _clock;
private readonly ILogger<ScheduleDailyImportsJob> _logger;
public ScheduleDailyImportsJob(
ImportMarketDataHandler handler,
IBackgroundJobClient jobClient,
IClock clock,
ILogger<ScheduleDailyImportsJob> logger)
{
_handler = handler;
_jobClient = jobClient;
_clock = clock;
_logger = logger;
}
@@ -31,7 +35,7 @@ public sealed class ScheduleDailyImportsJob
[Queue("q-evaluation")]
public async Task ExecuteAsync(CancellationToken cancellationToken)
{
var importDate = DateOnly.FromDateTime(DateTime.UtcNow);
var importDate = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
var correlationId = Guid.NewGuid();
_logger.LogInformation("Starting daily market data imports: Date={ImportDate}, CorrelationId={CorrelationId}",
@@ -0,0 +1,28 @@
namespace KArtSell.Modules.ModelOperations.ShadowRun.Services;
public interface IKisDataService
{
/// <summary>
/// Fetch trading orders for an account within date range.
/// </summary>
Task<IReadOnlyList<OrderItem>> GetTradingOrdersAsync(
string accountNumber,
DateOnly startDate,
DateOnly endDate,
CancellationToken cancellationToken);
/// <summary>
/// Fetch current portfolio holdings for position reconciliation.
/// </summary>
Task<IReadOnlyList<PositionItem>> GetPortfolioHoldingsAsync(
string accountNumber,
CancellationToken cancellationToken);
/// <summary>
/// Execute a buy/sell order (production only, not used in shadow run).
/// </summary>
Task<OrderExecutionResult> ExecuteOrderAsync(
string accountNumber,
OrderRequest request,
CancellationToken cancellationToken);
}
@@ -1,21 +0,0 @@
namespace KArtSell.Modules.ModelOperations.ShadowRun.Services;
public interface IKrxDataService
{
/// <summary>
/// Fetch daily OHLCV bars for a ticker within date range.
/// </summary>
Task<IReadOnlyList<DataBackfiller.OhlcvBar>> GetDailyOhlcvAsync(
string ticker,
DateOnly startDate,
DateOnly endDate,
CancellationToken cancellationToken);
/// <summary>
/// Fetch fee schedule (transaction costs) for date range.
/// </summary>
Task<IReadOnlyList<DataBackfiller.FeeScheduleEntry>> GetFeeScheduleAsync(
DateOnly startDate,
DateOnly endDate,
CancellationToken cancellationToken);
}
@@ -1,5 +1,6 @@
using System.Net;
using System.Text.Json;
using KArtSell.BuildingBlocks.Time;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
@@ -13,6 +14,7 @@ public sealed class KisDataService : IKisDataService
{
private readonly HttpClient _httpClient;
private readonly IMemoryCache _cache;
private readonly IClock _clock;
private readonly ILogger<KisDataService> _logger;
private const int CacheDurationMinutes = 60; // 1 hour for positions
@@ -45,10 +47,11 @@ public sealed class KisDataService : IKisDataService
new EventId(23, nameof(LogRetryError)),
"Retryable error: {ErrorMessage}");
public KisDataService(HttpClient httpClient, IMemoryCache cache, ILogger<KisDataService> logger)
public KisDataService(HttpClient httpClient, IMemoryCache cache, IClock clock, ILogger<KisDataService> logger)
{
_httpClient = httpClient;
_cache = cache;
_clock = clock;
_logger = logger;
}
@@ -153,7 +156,7 @@ public sealed class KisDataService : IKisDataService
quantity: 100,
currentPrice: 70000m,
totalValue: 7000000m,
asOfDate: DateOnly.FromDateTime(DateTime.UtcNow))
asOfDate: DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime))
};
var cacheOptions = new MemoryCacheEntryOptions
@@ -329,3 +332,29 @@ public sealed class KisDataService : IKisDataService
|| (ex.InnerException is TimeoutException);
}
}
public record OrderItem(
string orderId,
string ticker,
string side,
int quantity,
decimal price,
DateOnly executedDate,
string status);
public record PositionItem(
string ticker,
int quantity,
decimal currentPrice,
decimal totalValue,
DateOnly asOfDate);
public record OrderRequest(
string ticker,
string side,
int quantity);
public record OrderExecutionResult(
bool success,
string orderId,
string? errorMessage);