CUB-54: implement AgentState entity, repository, and DI registration
- Add AgentState entity mapping to 'agents' table (snake_case columns) - Add IAgentStateRepository interface (GetAllAsync, GetBySessionKeyAsync, UpdateStatusAsync) - Add AgentStateRepository with EF Core implementation - Add ControlCenterDbContext with ApplyConfigurationsFromAssembly - Add AgentStateConfiguration with snake_case column mappings and indexes - Register DbContext (Npgsql) and repository in Program.cs DI - Add ConnectionStrings to appsettings.json - Add EF Core 9.0.7 and Npgsql.EntityFrameworkCore.PostgreSQL 9.0.4 packages
This commit is contained in:
@@ -11,6 +11,8 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.7" />
|
||||||
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
using ControlCenter.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||||
|
|
||||||
|
namespace ControlCenter.Data.Configurations;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EF Core entity configuration for <see cref="AgentState"/>.
|
||||||
|
///
|
||||||
|
/// <para>Maps to the <c>agents</c> table with snake_case column naming,
|
||||||
|
/// consistent with the Extrudex project conventions.</para>
|
||||||
|
///
|
||||||
|
/// <para>CUB-56 will create the migration; this configuration only
|
||||||
|
/// defines the entity-to-table mapping and constraints.</para>
|
||||||
|
/// </summary>
|
||||||
|
public class AgentStateConfiguration : IEntityTypeConfiguration<AgentState>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<AgentState> builder)
|
||||||
|
{
|
||||||
|
// Table name
|
||||||
|
builder.ToTable("agents");
|
||||||
|
|
||||||
|
// Primary key
|
||||||
|
builder.HasKey(a => a.Id);
|
||||||
|
|
||||||
|
// Properties with snake_case column names
|
||||||
|
builder.Property(a => a.Id)
|
||||||
|
.HasColumnName("id")
|
||||||
|
.ValueGeneratedOnAdd();
|
||||||
|
|
||||||
|
builder.Property(a => a.Status)
|
||||||
|
.HasColumnName("status")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasDefaultValue("idle");
|
||||||
|
|
||||||
|
builder.Property(a => a.Task)
|
||||||
|
.HasColumnName("task")
|
||||||
|
.IsRequired(false)
|
||||||
|
.HasMaxLength(500);
|
||||||
|
|
||||||
|
builder.Property(a => a.Progress)
|
||||||
|
.HasColumnName("progress")
|
||||||
|
.IsRequired(false);
|
||||||
|
|
||||||
|
builder.Property(a => a.SessionKey)
|
||||||
|
.HasColumnName("session_key")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(255);
|
||||||
|
|
||||||
|
builder.Property(a => a.Channel)
|
||||||
|
.HasColumnName("channel")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(50);
|
||||||
|
|
||||||
|
builder.Property(a => a.LastActivity)
|
||||||
|
.HasColumnName("last_activity")
|
||||||
|
.IsRequired()
|
||||||
|
.HasDefaultValueSql("NOW()");
|
||||||
|
|
||||||
|
// Indexes
|
||||||
|
builder.HasIndex(a => a.SessionKey)
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("ix_agents_session_key");
|
||||||
|
|
||||||
|
builder.HasIndex(a => a.Status)
|
||||||
|
.HasDatabaseName("ix_agents_status");
|
||||||
|
}
|
||||||
|
}
|
||||||
39
backend/ControlCenter/Data/ControlCenterDbContext.cs
Normal file
39
backend/ControlCenter/Data/ControlCenterDbContext.cs
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
using ControlCenter.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace ControlCenter.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EF Core DbContext for the Control Center database.
|
||||||
|
///
|
||||||
|
/// <para>Provides <see cref="DbSet{T}"/> access to all persistent entities.
|
||||||
|
/// Uses snake_case naming conventions for PostgreSQL columns,
|
||||||
|
/// applied via <see cref="Configurations.AgentStateConfiguration"/>.</para>
|
||||||
|
///
|
||||||
|
/// <para>Connection string is configured in <c>appsettings.json</c>
|
||||||
|
/// under <c>ConnectionStrings:ControlCenterDb</c>.</para>
|
||||||
|
/// </summary>
|
||||||
|
public class ControlCenterDbContext : DbContext
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Agent state records — one row per active or recently active agent.
|
||||||
|
/// Maps to the <c>agents</c> table.
|
||||||
|
/// </summary>
|
||||||
|
public DbSet<AgentState> AgentStates => Set<AgentState>();
|
||||||
|
|
||||||
|
public ControlCenterDbContext(DbContextOptions<ControlCenterDbContext> options)
|
||||||
|
: base(options)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
// Apply all entity configurations from this assembly
|
||||||
|
modelBuilder.ApplyConfigurationsFromAssembly(
|
||||||
|
typeof(Configurations.AgentStateConfiguration).Assembly);
|
||||||
|
|
||||||
|
// Global snake_case naming convention for any unmapped columns
|
||||||
|
// (explicit configurations take precedence)
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
}
|
||||||
|
}
|
||||||
59
backend/ControlCenter/Models/AgentState.cs
Normal file
59
backend/ControlCenter/Models/AgentState.cs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
namespace ControlCenter.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Persistent state for an agent in the Control Center.
|
||||||
|
/// Maps to the <c>agents</c> table in PostgreSQL.
|
||||||
|
///
|
||||||
|
/// <para>Tracks the operational status, current task, progress,
|
||||||
|
/// session identity, and last activity timestamp for each agent
|
||||||
|
/// in the minion fleet.</para>
|
||||||
|
///
|
||||||
|
/// <para>The <see cref="Status"/> property uses string values matching
|
||||||
|
/// the AgentStatus enum: "active", "idle", "thinking", "error".
|
||||||
|
/// Stored as <c>varchar</c> rather than a DB enum for schema flexibility.</para>
|
||||||
|
/// </summary>
|
||||||
|
public class AgentState
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Unique identifier for the agent state record.
|
||||||
|
/// Defaults to a new <see cref="Guid"/> on creation.
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Operational status of the agent.
|
||||||
|
/// Valid values: "active", "idle", "thinking", "error".
|
||||||
|
/// Maps to the AgentStatus enum used by SignalR.
|
||||||
|
/// </summary>
|
||||||
|
public string Status { get; set; } = "idle";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Description of the agent's current task, if any.
|
||||||
|
/// Null when the agent is idle with no active assignment.
|
||||||
|
/// </summary>
|
||||||
|
public string? Task { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Task progress percentage (0–100).
|
||||||
|
/// Null when progress is not trackable for the current task.
|
||||||
|
/// </summary>
|
||||||
|
public int? Progress { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Full session key identifying the agent's active session.
|
||||||
|
/// Format: <c>agent:{agentId}:{channel}:...</c>
|
||||||
|
/// Used to correlate SignalR events with persistent state.
|
||||||
|
/// </summary>
|
||||||
|
public string SessionKey { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The channel the agent is operating on (e.g., "telegram", "discord", "slack").
|
||||||
|
/// </summary>
|
||||||
|
public string Channel { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Timestamp of the agent's last recorded activity.
|
||||||
|
/// Updated on every status change or task progress event.
|
||||||
|
/// </summary>
|
||||||
|
public DateTime LastActivity { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using ControlCenter.Data;
|
||||||
using ControlCenter.Hubs;
|
using ControlCenter.Hubs;
|
||||||
|
using ControlCenter.Repositories;
|
||||||
using ControlCenter.Services;
|
using ControlCenter.Services;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -25,6 +28,19 @@ builder.Services.AddSwaggerGen(c =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Database ────────────────────────────────────────────────
|
||||||
|
// PostgreSQL via EF Core with Npgsql.
|
||||||
|
// Connection string from appsettings.json or environment variable.
|
||||||
|
builder.Services.AddDbContext<ControlCenterDbContext>(options =>
|
||||||
|
options.UseNpgsql(
|
||||||
|
builder.Configuration.GetConnectionString("ControlCenterDb")
|
||||||
|
?? throw new InvalidOperationException(
|
||||||
|
"Connection string 'ControlCenterDb' not found. " +
|
||||||
|
"Add it to appsettings.json or set the environment variable.")));
|
||||||
|
|
||||||
|
// ── Repositories ────────────────────────────────────────────
|
||||||
|
builder.Services.AddScoped<IAgentStateRepository, AgentStateRepository>();
|
||||||
|
|
||||||
// ── CORS (kiosk + remote browser) ─────────────────────────
|
// ── CORS (kiosk + remote browser) ─────────────────────────
|
||||||
// The Control Center frontend runs on a different origin than the backend.
|
// The Control Center frontend runs on a different origin than the backend.
|
||||||
// SignalR requires credentials for WebSocket transport, so we use
|
// SignalR requires credentials for WebSocket transport, so we use
|
||||||
|
|||||||
62
backend/ControlCenter/Repositories/AgentStateRepository.cs
Normal file
62
backend/ControlCenter/Repositories/AgentStateRepository.cs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
using ControlCenter.Data;
|
||||||
|
using ControlCenter.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace ControlCenter.Repositories;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EF Core implementation of <see cref="IAgentStateRepository"/>.
|
||||||
|
///
|
||||||
|
/// <para>Queries the <c>agents</c> table via <see cref="ControlCenterDbContext"/>
|
||||||
|
/// using snake_case column mappings defined in the <see cref="Data.Configurations.AgentStateConfiguration"/>.
|
||||||
|
/// All write operations call <c>SaveChangesAsync</c> immediately.</para>
|
||||||
|
/// </summary>
|
||||||
|
public class AgentStateRepository : IAgentStateRepository
|
||||||
|
{
|
||||||
|
private readonly ControlCenterDbContext _context;
|
||||||
|
private readonly ILogger<AgentStateRepository> _logger;
|
||||||
|
|
||||||
|
public AgentStateRepository(
|
||||||
|
ControlCenterDbContext context,
|
||||||
|
ILogger<AgentStateRepository> logger)
|
||||||
|
{
|
||||||
|
_context = context;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<AgentState>> GetAllAsync()
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Fetching all agent states");
|
||||||
|
return await _context.AgentStates.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<AgentState?> GetBySessionKeyAsync(string sessionKey)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Looking up agent state by session key: {SessionKey}", sessionKey);
|
||||||
|
return await _context.AgentStates
|
||||||
|
.FirstOrDefaultAsync(a => a.SessionKey == sessionKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<AgentState?> UpdateStatusAsync(Guid id, string status)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Updating agent status: {Id} → {Status}", id, status);
|
||||||
|
|
||||||
|
var entity = await _context.AgentStates.FindAsync(id);
|
||||||
|
if (entity is null)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Agent state not found: {Id}", id);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.Status = status;
|
||||||
|
entity.LastActivity = DateTime.UtcNow;
|
||||||
|
|
||||||
|
_context.AgentStates.Update(entity);
|
||||||
|
await _context.SaveChangesAsync();
|
||||||
|
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
}
|
||||||
38
backend/ControlCenter/Repositories/IAgentStateRepository.cs
Normal file
38
backend/ControlCenter/Repositories/IAgentStateRepository.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
using ControlCenter.Models;
|
||||||
|
|
||||||
|
namespace ControlCenter.Repositories;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Repository interface for querying and updating agent state.
|
||||||
|
///
|
||||||
|
/// <para>Provides the data-access contract used by controllers,
|
||||||
|
/// background services, and SignalR hubs to read and mutate
|
||||||
|
/// persistent agent state.</para>
|
||||||
|
///
|
||||||
|
/// <para>Implementation should use <see cref="Data.ControlCenterDbContext"/>
|
||||||
|
/// via EF Core with PostgreSQL (snake_case columns).</para>
|
||||||
|
/// </summary>
|
||||||
|
public interface IAgentStateRepository
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Returns all agent states from the database.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A collection of all <see cref="AgentState"/> records.</returns>
|
||||||
|
Task<IEnumerable<AgentState>> GetAllAsync();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Finds an agent state by its session key.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sessionKey">The full session key, e.g. "agent:dex:telegram:direct:...".</param>
|
||||||
|
/// <returns>The matching <see cref="AgentState"/>, or null if not found.</returns>
|
||||||
|
Task<AgentState?> GetBySessionKeyAsync(string sessionKey);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Updates the status of an agent state record.
|
||||||
|
/// Also updates <c>LastActivity</c> to <see cref="DateTime.UtcNow"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">The unique identifier of the agent state record.</param>
|
||||||
|
/// <param name="status">The new status value ("active", "idle", "thinking", "error").</param>
|
||||||
|
/// <returns>The updated <see cref="AgentState"/>, or null if the record was not found.</returns>
|
||||||
|
Task<AgentState?> UpdateStatusAsync(Guid id, string status);
|
||||||
|
}
|
||||||
@@ -8,6 +8,10 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
|
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"ControlCenterDb": "Host=localhost;Port=5432;Database=control_center;Username=control_center;Password=changeme"
|
||||||
|
},
|
||||||
|
|
||||||
"Gateway": {
|
"Gateway": {
|
||||||
"WebSocketUrl": "ws://localhost:3271/ws",
|
"WebSocketUrl": "ws://localhost:3271/ws",
|
||||||
"AuthToken": ""
|
"AuthToken": ""
|
||||||
|
|||||||
Reference in New Issue
Block a user