feat: Bao/Iris-Statusrechte + Bao→Iris-Notifications + Agent-Workflow-Übersicht
- Bao darf jetzt Status ändern (neben Iris), Sub-Agents weiterhin nicht - CanEditContent für Inhaltsbearbeitung durch alle bekannten Caller - Bao-Content-Änderungen triggern task_content_changed-Notification an Iris - Bao-Status-Änderungen triggern task_status_changed-Notification an Iris - Iris-Status-Änderungen triggern task_status_changed-Notification an Bao - Neue WorkTask-Felder: IsAgentTask (bool), ExpectedFrom (string) - Agent-Workflow-API: CreateAgentTask, WaitingTasks, AgentOverview - Frontend: Agent-Task-Badge, Iris-Overview-Panel, isBao-Getter - Login-Rate-Limiter mit strukturiertem JSON-Fehlermeldungs-Body - Volume-Name: nexus-postgres → postgres-data (Standardisierung)
This commit is contained in:
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Nexus.Api.DTOs;
|
||||
using Nexus.Api.Integrations;
|
||||
using Nexus.Api.RateLimiting;
|
||||
using Nexus.Api.Services;
|
||||
|
||||
namespace Nexus.Api.Controllers;
|
||||
@@ -14,7 +15,8 @@ public class AuthController(
|
||||
IAuthService authService,
|
||||
IAntiforgery antiforgery,
|
||||
IConfiguration config,
|
||||
IHostEnvironment env) : ControllerBase
|
||||
IHostEnvironment env,
|
||||
LoginAttemptTracker attemptTracker) : ControllerBase
|
||||
{
|
||||
[HttpGet("csrf")]
|
||||
public IActionResult GetCsrfToken()
|
||||
@@ -30,11 +32,38 @@ public class AuthController(
|
||||
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]> { ["credentials"] = ["Email and password are required."] });
|
||||
|
||||
var session = await authService.LoginAsync(request, ct);
|
||||
if (session is null) return Results.Unauthorized();
|
||||
var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
|
||||
var session = await authService.LoginAsync(request, ct);
|
||||
if (session is null)
|
||||
{
|
||||
var remaining = attemptTracker.RecordFailedAttempt(ip);
|
||||
var retryAfterSeconds = attemptTracker.GetRetryAfterSeconds(ip);
|
||||
|
||||
// Attach remaining info to the 401 response via headers only
|
||||
// (the frontend can also parse the 429 body)
|
||||
HttpContext.Response.Headers["X-RateLimit-Remaining"] = remaining.ToString();
|
||||
HttpContext.Response.Headers["X-RateLimit-Limit"] = "5";
|
||||
if (retryAfterSeconds > 0)
|
||||
HttpContext.Response.Headers["X-RateLimit-Reset"] =
|
||||
DateTimeOffset.UtcNow.AddSeconds(retryAfterSeconds).ToUnixTimeSeconds().ToString();
|
||||
|
||||
// Return a structured body so the frontend can display remaining attempts
|
||||
return Results.Json(new
|
||||
{
|
||||
error = "invalid_credentials",
|
||||
message = "Invalid email or password.",
|
||||
remaining,
|
||||
retryAfterSeconds
|
||||
}, statusCode: 401);
|
||||
}
|
||||
|
||||
// Success — reset attempt counter
|
||||
attemptTracker.Reset(ip);
|
||||
SetRefreshCookie(Response, session.RefreshToken);
|
||||
Response.Headers.CacheControl = "no-store";
|
||||
Response.Headers["X-RateLimit-Remaining"] = "5";
|
||||
Response.Headers["X-RateLimit-Limit"] = "5";
|
||||
return Results.Ok(ToAuthResponse(session));
|
||||
}
|
||||
|
||||
@@ -54,6 +83,8 @@ public class AuthController(
|
||||
|
||||
SetRefreshCookie(Response, session.RefreshToken);
|
||||
Response.Headers.CacheControl = "no-store";
|
||||
Response.Headers["X-RateLimit-Remaining"] = "5";
|
||||
Response.Headers["X-RateLimit-Limit"] = "5";
|
||||
return Results.Ok(ToAuthResponse(session));
|
||||
}
|
||||
|
||||
|
||||
@@ -164,18 +164,18 @@ public class DashboardController(
|
||||
public async Task<ActionResult<DashboardTaskDto>> UpdateTaskStatus(
|
||||
Guid id, [FromBody] UpdateDashboardTaskStatusRequest request, CancellationToken ct)
|
||||
{
|
||||
// Bao review gate: Check if moving OUT of Review
|
||||
// Enforce workflow rules based on caller agent
|
||||
var currentTask = await taskService.GetByIdAsync(id, ct);
|
||||
if (currentTask is not null &&
|
||||
string.Equals(currentTask.State, "Review", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(request.Status, "Review", StringComparison.OrdinalIgnoreCase))
|
||||
if (currentTask is null)
|
||||
return NotFound(new { error = "Task not found." });
|
||||
|
||||
// Resolve caller agent from header or JWT
|
||||
var callerAgent = ResolveCallerAgent();
|
||||
|
||||
// Nur Iris und Bao dürfen Status ändern
|
||||
if (!TaskStateHelper.CanChangeState(callerAgent, currentTask))
|
||||
{
|
||||
var user = httpContextAccessor.HttpContext?.User;
|
||||
var isOwner = user?.IsInRole("Owner") == true ||
|
||||
user?.IsInRole("owner") == true ||
|
||||
user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value == "bao";
|
||||
if (!isOwner)
|
||||
return StatusCode(403, new { error = "Only the owner can move tasks out of Review." });
|
||||
return StatusCode(403, new { error = "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben." });
|
||||
}
|
||||
|
||||
var result = await taskService.UpdateStatusAsync(id, request.Status, ct);
|
||||
@@ -190,7 +190,7 @@ public class DashboardController(
|
||||
// ── Task Board Endpoints ──
|
||||
|
||||
[HttpGet("tasks/board")]
|
||||
public async Task<TaskBoardResponse> GetBoard(CancellationToken ct)
|
||||
public async Task<BoardResponse> GetBoard(CancellationToken ct)
|
||||
=> await taskService.GetBoardAsync(ct);
|
||||
|
||||
[HttpPatch("tasks/{id:guid}/move")]
|
||||
@@ -200,18 +200,18 @@ public class DashboardController(
|
||||
if (string.IsNullOrWhiteSpace(request.State))
|
||||
return BadRequest(new { error = "State is required." });
|
||||
|
||||
// Bao review gate: Check if moving OUT of Review
|
||||
// Enforce workflow rules based on caller agent
|
||||
var currentTask = await taskService.GetByIdAsync(id, ct);
|
||||
if (currentTask is not null &&
|
||||
string.Equals(currentTask.State, "Review", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(request.State, "Review", StringComparison.OrdinalIgnoreCase))
|
||||
if (currentTask is null)
|
||||
return NotFound(new { error = "Task not found." });
|
||||
|
||||
// Resolve caller agent from header or JWT
|
||||
var callerAgent = ResolveCallerAgent();
|
||||
|
||||
// Nur Iris und Bao dürfen Status ändern
|
||||
if (!TaskStateHelper.CanChangeState(callerAgent, currentTask))
|
||||
{
|
||||
var user = httpContextAccessor.HttpContext?.User;
|
||||
var isOwner = user?.IsInRole("Owner") == true ||
|
||||
user?.IsInRole("owner") == true ||
|
||||
user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value == "bao";
|
||||
if (!isOwner)
|
||||
return StatusCode(403, new { error = "Only the owner can move tasks out of Review." });
|
||||
return StatusCode(403, new { error = "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben." });
|
||||
}
|
||||
|
||||
var result = await taskService.MoveTaskAsync(id, request.State, ct);
|
||||
@@ -223,6 +223,24 @@ public class DashboardController(
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the caller identity: checks X-Agent-Id header, then JWT name claim.
|
||||
/// Falls back to empty string (which authorization helpers reject accordingly).
|
||||
/// </summary>
|
||||
private string ResolveCallerAgent()
|
||||
{
|
||||
var httpContext = httpContextAccessor.HttpContext;
|
||||
if (httpContext is null) return "";
|
||||
|
||||
var agentHeader = httpContext.Request.Headers["X-Agent-Id"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(agentHeader))
|
||||
return agentHeader.Trim().ToLowerInvariant();
|
||||
|
||||
var user = httpContext.User;
|
||||
var nameClaim = user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
return nameClaim?.ToLowerInvariant() ?? "";
|
||||
}
|
||||
|
||||
// ── New Endpoints: Reset Stale, Children, Activity ──
|
||||
|
||||
[HttpPost("tasks/reset-stale")]
|
||||
@@ -277,7 +295,59 @@ public class DashboardController(
|
||||
return Created($"/api/dashboard/tasks/{id}/activity/{ev.Id}", ev);
|
||||
}
|
||||
|
||||
// ── Agent Workflow Endpoints (Iris Overview) ──
|
||||
|
||||
/// <summary>
|
||||
/// Returns agent-tasks that are still open and waiting for input.
|
||||
/// Iris uses this to see who she is waiting for.
|
||||
/// </summary>
|
||||
[HttpGet("tasks/agent-waiting")]
|
||||
public async Task<ActionResult<List<DashboardTaskDto>>> GetAgentWaitingTasks(CancellationToken ct)
|
||||
{
|
||||
var waiting = await taskService.GetWaitingTasksAsync(ct);
|
||||
return Ok(waiting.Select(MapToDto).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a complete agent-workflow overview grouped by expected respondent
|
||||
/// + stale detection. This is the main Iris dashboard data.
|
||||
/// </summary>
|
||||
[HttpGet("tasks/agent-overview")]
|
||||
public async Task<ActionResult<AgentWorkflowOverview>> GetAgentOverview(
|
||||
CancellationToken ct, [FromQuery] int staleHours = 2)
|
||||
{
|
||||
var threshold = TimeSpan.FromHours(Math.Max(1, staleHours));
|
||||
return Ok(await taskService.GetAgentWorkflowOverviewAsync(threshold, ct));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an agent-task: a task that is tracked as originating from the agent workflow.
|
||||
/// Sub-agents (programmer, reviewer) can only CREATE, not move state.
|
||||
/// </summary>
|
||||
[HttpPost("tasks/agent")]
|
||||
public async Task<ActionResult<DashboardTaskDto>> CreateAgentTask(
|
||||
[FromBody] CreateAgentTaskRequest request, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Title))
|
||||
return BadRequest(new { error = "Title is required." });
|
||||
|
||||
try
|
||||
{
|
||||
var task = await taskService.CreateAgentTaskAsync(
|
||||
request.Title, request.Detail, request.Source ?? "iris",
|
||||
request.Priority, request.AssignedTo, request.ExpectedFrom,
|
||||
request.ParentTaskId, ct);
|
||||
|
||||
return Created($"/api/dashboard/tasks/{task.Id}", MapToDto(task));
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return BadRequest(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
private static DashboardTaskDto MapToDto(WorkTask t) => new(
|
||||
t.Id, t.Title, t.Detail, t.Source, t.State, t.Priority, t.AssignedTo,
|
||||
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt);
|
||||
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt,
|
||||
t.IsAgentTask, t.ExpectedFrom);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Nexus.Api.Data;
|
||||
using Nexus.Api.DTOs;
|
||||
using Nexus.Api.Models;
|
||||
using Nexus.Api.Services;
|
||||
|
||||
namespace Nexus.Api.Controllers;
|
||||
@@ -70,6 +72,10 @@ public class TasksController(ITaskService taskService) : ControllerBase
|
||||
return result.Outcome switch
|
||||
{
|
||||
TaskOperationOutcome.NotFound => Results.NotFound(),
|
||||
TaskOperationOutcome.InvalidState => Results.Problem(
|
||||
title: "Action denied",
|
||||
detail: "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben.",
|
||||
statusCode: StatusCodes.Status403Forbidden),
|
||||
_ => Results.Ok(result.Task)
|
||||
};
|
||||
}
|
||||
@@ -99,4 +105,27 @@ public class TasksController(ITaskService taskService) : ControllerBase
|
||||
_ => Results.NoContent()
|
||||
};
|
||||
}
|
||||
|
||||
// ── Board & Stale-Reset (für Iris Autonomous Worker) ──
|
||||
|
||||
/// <summary>
|
||||
/// Gibt das Task-Board zurück (gruppiert nach Status, priorisiert sortiert).
|
||||
/// Wird vom Iris Autonomous Worker genutzt.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("board")]
|
||||
public async Task<IResult> GetBoard(CancellationToken ct)
|
||||
=> Results.Ok(await taskService.GetBoardAsync(ct));
|
||||
|
||||
/// <summary>
|
||||
/// Setzt stale Tasks (InProgress/Delegated, älter als N Stunden) zurück auf Backlog.
|
||||
/// Wird vom Iris Autonomous Worker genutzt.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("reset-stale")]
|
||||
public async Task<IResult> ResetStale([FromBody] ResetStaleRequest request, CancellationToken ct)
|
||||
{
|
||||
var count = await taskService.ResetStaleAsync(request.StaleHours, ct);
|
||||
return Results.Ok(new ResetStaleResponse(count));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,3 +12,4 @@ public sealed record IncidentInfoDto(
|
||||
string? Title,
|
||||
DateTimeOffset? Since
|
||||
);
|
||||
|
||||
|
||||
@@ -83,6 +83,43 @@ public static class TaskStateHelper
|
||||
string.Equals(state, "Done", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(state, "Backlog", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the caller is allowed to change this task's state.
|
||||
/// POLICY:
|
||||
/// - **Iris und Bao** dürfen Status ändern / verschieben.
|
||||
/// - Sub-agents (programmer, reviewer, architekt) dürfen NIEMALS Status ändern.
|
||||
/// - 'nexus-system' ist ein technischer Fallback für automatische Cron/Reset-Workflows.
|
||||
/// - Jeder andere (unbekannt, leer) wird abgewiesen.
|
||||
/// </summary>
|
||||
public static bool CanChangeState(string? callerAgent, WorkTask task)
|
||||
{
|
||||
var caller = callerAgent?.Trim().ToLowerInvariant() ?? "";
|
||||
|
||||
// Sub-agents must never move state
|
||||
var subAgents = new HashSet<string> { "programmer", "reviewer", "architekt" };
|
||||
if (subAgents.Contains(caller)) return false;
|
||||
|
||||
// Technischer Fallback: nur für interne System-Operationen (Cron, ResetStale)
|
||||
if (caller == "nexus-system") return true;
|
||||
|
||||
// Iris und Bao dürfen Status ändern
|
||||
return caller == "iris" || caller == "bao";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the caller is allowed to edit a task's content fields
|
||||
/// (title, detail, priority, assignedTo, dueDate).
|
||||
/// POLICY:
|
||||
/// - Alle (iris, bao, sub-agents, nexus-system) dürfen inhaltlich bearbeiten.
|
||||
/// - Nur unbekannte/leere Caller werden abgewiesen.
|
||||
/// </summary>
|
||||
public static bool CanEditContent(string? callerAgent)
|
||||
{
|
||||
var caller = callerAgent?.Trim().ToLowerInvariant() ?? "";
|
||||
if (string.IsNullOrWhiteSpace(caller)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Group key for board responses (lowercased English state).</summary>
|
||||
public static string BoardGroupKey(string? state)
|
||||
{
|
||||
@@ -137,6 +174,19 @@ public sealed class WorkTask
|
||||
public string Priority { get; set; } = "Normal";
|
||||
public string Source { get; set; } = "bao";
|
||||
public string? AssignedTo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if this task was created programmatically by an agent (not manually by Bao).
|
||||
/// Agent-tasks in the board are subject to stricter workflow rules.
|
||||
/// </summary>
|
||||
public bool IsAgentTask { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Which agent/user is expected to respond next.
|
||||
/// Helps Iris see who she is waiting for.
|
||||
/// </summary>
|
||||
public string? ExpectedFrom { get; set; }
|
||||
|
||||
public Guid? ParentTaskId { get; set; }
|
||||
public WorkTask? ParentTask { get; set; }
|
||||
public ICollection<WorkTask> ChildTasks { get; set; } = new List<WorkTask>();
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Nexus.Api.Data;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Nexus.Api.Migrations
|
||||
{
|
||||
[DbContext(typeof(NexusDbContext))]
|
||||
[Migration("20260620174200_AddAgentTaskFields")]
|
||||
partial class AddAgentTaskFields
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid?>("TaskId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.HasIndex("TaskId");
|
||||
|
||||
b.ToTable("Activity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastLoginAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.IsRequired()
|
||||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.Notification", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("ForUser")
|
||||
.IsRequired()
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.Property<bool>("IsRead")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid?>("TaskId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(240)
|
||||
.HasColumnType("character varying(240)");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ForUser", "IsRead", "CreatedAt");
|
||||
|
||||
b.ToTable("Notifications");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(160)
|
||||
.HasColumnType("character varying(160)");
|
||||
|
||||
b.Property<int>("Progress")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Projects");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("FamilyId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ReplacedByTokenHash")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserId", "FamilyId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AssignedTo")
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Detail")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<DateTimeOffset?>("DueDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("ExpectedFrom")
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.Property<bool>("IsAgentTask")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("ParentTaskId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Priority")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid?>("ProjectId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(240)
|
||||
.HasColumnType("character varying(240)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AssignedTo");
|
||||
|
||||
b.HasIndex("ExpectedFrom");
|
||||
|
||||
b.HasIndex("IsAgentTask");
|
||||
|
||||
b.HasIndex("ParentTaskId");
|
||||
|
||||
b.HasIndex("Source");
|
||||
|
||||
b.ToTable("Tasks");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("Nexus.Api.Data.NexusUser", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
|
||||
{
|
||||
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
|
||||
.WithMany("ChildTasks")
|
||||
.HasForeignKey("ParentTaskId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("ParentTask");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
|
||||
{
|
||||
b.Navigation("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
|
||||
{
|
||||
b.Navigation("ChildTasks");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Nexus.Api.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddAgentTaskFields : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsAgentTask",
|
||||
table: "Tasks",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "ExpectedFrom",
|
||||
table: "Tasks",
|
||||
type: "character varying(60)",
|
||||
maxLength: 60,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Tasks_IsAgentTask",
|
||||
table: "Tasks",
|
||||
column: "IsAgentTask");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Tasks_ExpectedFrom",
|
||||
table: "Tasks",
|
||||
column: "ExpectedFrom");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Tasks_IsAgentTask",
|
||||
table: "Tasks");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Tasks_ExpectedFrom",
|
||||
table: "Tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ExpectedFrom",
|
||||
table: "Tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsAgentTask",
|
||||
table: "Tasks");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,6 +234,13 @@ namespace Nexus.Api.Migrations
|
||||
b.Property<DateTimeOffset?>("DueDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("ExpectedFrom")
|
||||
.HasMaxLength(60)
|
||||
.HasColumnType("character varying(60)");
|
||||
|
||||
b.Property<bool>("IsAgentTask")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("ParentTaskId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
@@ -265,6 +272,10 @@ namespace Nexus.Api.Migrations
|
||||
|
||||
b.HasIndex("AssignedTo");
|
||||
|
||||
b.HasIndex("ExpectedFrom");
|
||||
|
||||
b.HasIndex("IsAgentTask");
|
||||
|
||||
b.HasIndex("ParentTaskId");
|
||||
|
||||
b.HasIndex("Source");
|
||||
|
||||
@@ -20,8 +20,11 @@ public sealed class NexusDbContext(DbContextOptions<NexusDbContext> options) : D
|
||||
entity.Property(x => x.Detail).HasMaxLength(2000);
|
||||
entity.Property(x => x.Source).HasMaxLength(60);
|
||||
entity.Property(x => x.AssignedTo).HasMaxLength(60);
|
||||
entity.Property(x => x.ExpectedFrom).HasMaxLength(60);
|
||||
entity.HasIndex(x => x.Source);
|
||||
entity.HasIndex(x => x.AssignedTo);
|
||||
entity.HasIndex(x => x.IsAgentTask);
|
||||
entity.HasIndex(x => x.ExpectedFrom);
|
||||
entity.HasOne(x => x.ParentTask)
|
||||
.WithMany(x => x.ChildTasks)
|
||||
.HasForeignKey(x => x.ParentTaskId)
|
||||
|
||||
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Nexus.Api.Data;
|
||||
using Nexus.Api.Integrations;
|
||||
using Nexus.Api.RateLimiting;
|
||||
using Nexus.Api.Repositories;
|
||||
using Nexus.Api.Routing;
|
||||
using Nexus.Api.Services;
|
||||
@@ -71,6 +72,37 @@ public static class ServiceCollectionExtensions
|
||||
services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
|
||||
options.OnRejected = async (context, ct) =>
|
||||
{
|
||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||
context.HttpContext.Response.Headers.ContentType = "application/json";
|
||||
|
||||
var retryAfterSeconds = 60;
|
||||
|
||||
// Try to read retry-after info from the metadata
|
||||
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
|
||||
{
|
||||
retryAfterSeconds = (int)retryAfter.TotalSeconds;
|
||||
}
|
||||
|
||||
// Set standard headers
|
||||
context.HttpContext.Response.Headers.RetryAfter = retryAfterSeconds.ToString();
|
||||
context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
|
||||
context.HttpContext.Response.Headers["X-RateLimit-Reset"] =
|
||||
DateTimeOffset.UtcNow.AddSeconds(retryAfterSeconds).ToUnixTimeSeconds().ToString();
|
||||
|
||||
var body = new
|
||||
{
|
||||
error = "rate_limit_exceeded",
|
||||
message = $"Too many attempts. Try again in {retryAfterSeconds} second(s).",
|
||||
remaining = 0,
|
||||
retryAfterSeconds
|
||||
};
|
||||
|
||||
await context.HttpContext.Response.WriteAsJsonAsync(body, ct);
|
||||
};
|
||||
|
||||
options.AddPolicy("auth", context => RateLimitPartition.GetFixedWindowLimiter(
|
||||
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||
_ => new FixedWindowRateLimiterOptions
|
||||
@@ -171,6 +203,7 @@ public static class ServiceCollectionExtensions
|
||||
public static IServiceCollection AddNexusApplicationServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddSingleton<LoginAttemptTracker>();
|
||||
services.AddTransient<ModelRoutingService>();
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddScoped<IAgentService, AgentService>();
|
||||
|
||||
@@ -89,7 +89,9 @@ public sealed record DashboardTaskDto(
|
||||
Guid? ParentTaskId,
|
||||
DateTimeOffset? DueDate,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset UpdatedAt
|
||||
DateTimeOffset UpdatedAt,
|
||||
bool IsAgentTask = false,
|
||||
string? ExpectedFrom = null
|
||||
);
|
||||
|
||||
public sealed record CreateDashboardTaskRequest(
|
||||
@@ -101,6 +103,16 @@ public sealed record CreateDashboardTaskRequest(
|
||||
Guid? ParentTaskId = null
|
||||
);
|
||||
|
||||
public sealed record CreateAgentTaskRequest(
|
||||
string Title,
|
||||
string? Detail,
|
||||
string? Source,
|
||||
string? Priority,
|
||||
string? AssignedTo,
|
||||
string? ExpectedFrom,
|
||||
Guid? ParentTaskId = null
|
||||
);
|
||||
|
||||
public sealed record UpdateDashboardTaskRequest(
|
||||
string? Title,
|
||||
string? Detail,
|
||||
@@ -121,7 +133,7 @@ public sealed record AgentActivityEntry(
|
||||
|
||||
// ── Task Board DTOs ──
|
||||
|
||||
public sealed record TaskBoardResponse(
|
||||
public sealed record BoardResponse(
|
||||
List<DashboardTaskDto> Offen,
|
||||
List<DashboardTaskDto> InProgress,
|
||||
List<DashboardTaskDto> Delegated,
|
||||
@@ -147,6 +159,20 @@ public sealed record PostActivityRequest(
|
||||
string? Type = null
|
||||
);
|
||||
|
||||
// ── Agent Workflow DTOs ──
|
||||
|
||||
/// <summary>
|
||||
/// Overview of the agent workflow state, grouping tasks by expected respondent
|
||||
/// and highlighting stale tasks. Used by Iris to see who she is waiting for.
|
||||
/// </summary>
|
||||
public sealed record AgentWorkflowOverview(
|
||||
List<DashboardTaskDto> WaitingForBao,
|
||||
List<DashboardTaskDto> WaitingForIris,
|
||||
List<DashboardTaskDto> WaitingForOthers,
|
||||
List<DashboardTaskDto> StaleTasks,
|
||||
TimeSpan StaleThreshold
|
||||
);
|
||||
|
||||
// ── Notification DTOs ──
|
||||
|
||||
public sealed record NotificationDto(
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Nexus.Api.RateLimiting;
|
||||
|
||||
/// <summary>
|
||||
/// Simple in-memory tracking of login attempts per IP,
|
||||
/// aligned with the fixed-window rate limiter (5 attempts / 1 minute).
|
||||
///
|
||||
/// Provides remaining-attempt count that can be passed back to the frontend.
|
||||
/// </summary>
|
||||
public sealed class LoginAttemptTracker
|
||||
{
|
||||
private const int MaxAttempts = 5;
|
||||
private static readonly TimeSpan Window = TimeSpan.FromMinutes(1);
|
||||
|
||||
// IP → (count, windowStartTicks)
|
||||
private static readonly ConcurrentDictionary<string, (int Count, long WindowStartTicks)> _store = new();
|
||||
|
||||
/// <summary>
|
||||
/// Registers a failed attempt for the given IP.
|
||||
/// Returns remaining attempts (0 = locked out until reset).
|
||||
/// </summary>
|
||||
public int RecordFailedAttempt(string ip)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var windowTicks = (long)Window.TotalMilliseconds;
|
||||
|
||||
var (count, windowStart) = _store.AddOrUpdate(ip,
|
||||
_ => (1, now),
|
||||
(_, entry) =>
|
||||
{
|
||||
if (now - entry.WindowStartTicks >= windowTicks)
|
||||
return (1, now);
|
||||
return (entry.Count + 1, entry.WindowStartTicks);
|
||||
});
|
||||
|
||||
return Math.Max(0, MaxAttempts - count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the remaining attempts for the given IP without recording.
|
||||
/// </summary>
|
||||
public int GetRemaining(string ip)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var windowTicks = (long)Window.TotalMilliseconds;
|
||||
|
||||
if (_store.TryGetValue(ip, out var entry))
|
||||
{
|
||||
if (now - entry.WindowStartTicks >= windowTicks)
|
||||
return MaxAttempts;
|
||||
return Math.Max(0, MaxAttempts - entry.Count);
|
||||
}
|
||||
|
||||
return MaxAttempts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the number of seconds until the rate-limit window resets,
|
||||
/// or 0 if the window has already expired / no attempts recorded.
|
||||
/// </summary>
|
||||
public int GetRetryAfterSeconds(string ip)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var windowTicks = (long)Window.TotalMilliseconds;
|
||||
|
||||
if (!_store.TryGetValue(ip, out var entry))
|
||||
return 0;
|
||||
|
||||
var elapsed = now - entry.WindowStartTicks;
|
||||
if (elapsed >= windowTicks)
|
||||
return 0;
|
||||
|
||||
return (int)Math.Ceiling((windowTicks - elapsed) / 1000.0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets attempt count for the given IP (e.g. on success).
|
||||
/// </summary>
|
||||
public void Reset(string ip)
|
||||
{
|
||||
_store.TryRemove(ip, out _);
|
||||
}
|
||||
}
|
||||
@@ -23,15 +23,21 @@ public interface ITaskService
|
||||
// Dashboard-facing task operations
|
||||
Task<IReadOnlyList<WorkTask>> GetOpenAsync(CancellationToken ct = default);
|
||||
Task<WorkTask> CreateDashboardTaskAsync(string title, string? detail, string? source, string? priority, string? assignedTo, Guid? parentTaskId = null, CancellationToken ct = default);
|
||||
Task<WorkTask> CreateAgentTaskAsync(string title, string? detail, string? source, string? priority, string? assignedTo, string? expectedFrom, Guid? parentTaskId = null, CancellationToken ct = default);
|
||||
Task<TaskOperationResult> UpdateDashboardTaskAsync(Guid id, string? title, string? detail, string? source, string? priority, string? assignedTo, DateTimeOffset? dueDate = null, CancellationToken ct = default);
|
||||
Task<TaskOperationResult> UpdateStatusAsync(Guid id, string status, CancellationToken ct = default);
|
||||
Task<TaskOperationResult> CompleteViaQueueAsync(Guid id, CancellationToken ct = default);
|
||||
Task<TaskOperationResult> CyclePriorityAsync(Guid id, CancellationToken ct = default);
|
||||
|
||||
// Task Board
|
||||
Task<TaskBoardResponse> GetBoardAsync(CancellationToken ct = default);
|
||||
Task<BoardResponse> GetBoardAsync(CancellationToken ct = default);
|
||||
Task<TaskOperationResult> MoveTaskAsync(Guid id, string newState, CancellationToken ct = default);
|
||||
Task<int> ResetStaleAsync(int staleHours, CancellationToken ct = default);
|
||||
Task<int> ResetStaleInProgressTasksAsync(TimeSpan staleThreshold, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<WorkTask>> GetChildTasksAsync(Guid parentId, CancellationToken ct = default);
|
||||
Task<List<ActivityEvent>> GetTaskActivityAsync(Guid taskId, CancellationToken ct = default);
|
||||
|
||||
// Agent Workflow Overview
|
||||
Task<IReadOnlyList<WorkTask>> GetWaitingTasksAsync(CancellationToken ct = default);
|
||||
Task<AgentWorkflowOverview> GetAgentWorkflowOverviewAsync(TimeSpan staleThreshold, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
+246
-18
@@ -8,7 +8,8 @@ namespace Nexus.Api.Services;
|
||||
public sealed class TaskService(
|
||||
ITaskRepository taskRepo,
|
||||
IActivityRepository activityRepo,
|
||||
INotificationService notificationService) : ITaskService
|
||||
INotificationService notificationService,
|
||||
IHttpContextAccessor httpContextAccessor) : ITaskService
|
||||
{
|
||||
private static readonly HashSet<string> ValidAssignees =
|
||||
["bao", "iris", "programmer", "reviewer", "architekt"];
|
||||
@@ -71,6 +72,11 @@ public sealed class TaskService(
|
||||
var task = await taskRepo.GetByIdAsync(id, ct);
|
||||
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
|
||||
|
||||
// Enforce workflow rules
|
||||
var caller = ResolveCaller();
|
||||
if (!TaskStateHelper.CanChangeState(caller, task))
|
||||
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
|
||||
|
||||
task.State = canonical;
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} moved to {task.State}", TaskId = task.Id }, ct);
|
||||
@@ -83,15 +89,27 @@ public sealed class TaskService(
|
||||
var task = await taskRepo.GetByIdAsync(id, ct);
|
||||
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Title))
|
||||
var changes = new List<string>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Title) && !string.Equals(task.Title, request.Title.Trim(), StringComparison.Ordinal))
|
||||
{
|
||||
changes.Add($"Titel: \"{task.Title}\" → \"{request.Title.Trim()}\"");
|
||||
task.Title = request.Title.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Priority))
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(request.Priority) && !string.Equals(task.Priority, request.Priority.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
changes.Add($"Priorität: {task.Priority} → {request.Priority.Trim()}");
|
||||
task.Priority = request.Priority.Trim();
|
||||
}
|
||||
if (request.ProjectId.HasValue)
|
||||
{
|
||||
changes.Add($"Projekt-ID geändert");
|
||||
task.ProjectId = request.ProjectId.Value == Guid.Empty ? null : request.ProjectId;
|
||||
}
|
||||
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} updated", TaskId = task.Id }, ct);
|
||||
var changeSummary = changes.Count > 0 ? string.Join("; ", changes) : "keine sichtbaren Änderungen";
|
||||
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" aktualisiert: {changeSummary}", TaskId = task.Id }, ct);
|
||||
return new TaskOperationResult(TaskOperationOutcome.Success, task);
|
||||
}
|
||||
|
||||
@@ -118,6 +136,66 @@ public sealed class TaskService(
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns agent-tasks that are still open and where an agent is expected to respond.
|
||||
/// Iris Dashboard uses this to see who she is waiting for.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<WorkTask>> GetWaitingTasksAsync(CancellationToken ct = default)
|
||||
{
|
||||
var all = await taskRepo.GetAllAsync(ct);
|
||||
return all
|
||||
.Where(t => t.IsAgentTask && !string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(t => t.ExpectedFrom != null ? 0 : 1)
|
||||
.ThenByDescending(t => t.UpdatedAt)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns agent-tasks grouped by which agent is expected to respond,
|
||||
/// with stale-detection: tasks in InProgress/Delegated that haven't been
|
||||
/// updated within the stale threshold.
|
||||
/// </summary>
|
||||
public async Task<AgentWorkflowOverview> GetAgentWorkflowOverviewAsync(TimeSpan staleThreshold, CancellationToken ct = default)
|
||||
{
|
||||
var all = await taskRepo.GetAllAsync(ct);
|
||||
var threshold = DateTimeOffset.UtcNow - staleThreshold;
|
||||
|
||||
var agentTasks = all.Where(t => t.IsAgentTask).ToList();
|
||||
|
||||
var waitingForBao = agentTasks
|
||||
.Where(t => string.Equals(t.ExpectedFrom, "bao", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(MapToDto)
|
||||
.ToList();
|
||||
|
||||
var waitingForIris = agentTasks
|
||||
.Where(t => string.Equals(t.ExpectedFrom, "iris", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(MapToDto)
|
||||
.ToList();
|
||||
|
||||
var waitingForOthers = agentTasks
|
||||
.Where(t =>
|
||||
{
|
||||
var expected = (t.ExpectedFrom ?? "").ToLowerInvariant();
|
||||
return expected != "bao" && expected != "iris" && !string.IsNullOrWhiteSpace(expected) &&
|
||||
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase);
|
||||
})
|
||||
.Select(MapToDto)
|
||||
.ToList();
|
||||
|
||||
var staleTasks = agentTasks
|
||||
.Where(t =>
|
||||
(string.Equals(t.State, "In progress", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(t.State, "Delegated", StringComparison.OrdinalIgnoreCase)) &&
|
||||
t.UpdatedAt < threshold)
|
||||
.Select(MapToDto)
|
||||
.ToList();
|
||||
|
||||
return new AgentWorkflowOverview(waitingForBao, waitingForIris, waitingForOthers,
|
||||
staleTasks, staleThreshold);
|
||||
}
|
||||
|
||||
public async Task<WorkTask> CreateDashboardTaskAsync(
|
||||
string title, string? detail, string? source, string? priority,
|
||||
string? assignedTo, Guid? parentTaskId = null, CancellationToken ct = default)
|
||||
@@ -161,22 +239,108 @@ public sealed class TaskService(
|
||||
return task;
|
||||
}
|
||||
|
||||
public async Task<WorkTask> CreateAgentTaskAsync(
|
||||
string title, string? detail, string? source, string? priority,
|
||||
string? assignedTo, string? expectedFrom, Guid? parentTaskId = null, CancellationToken ct = default)
|
||||
{
|
||||
var task = await CreateDashboardTaskAsync(title, detail, source, priority, assignedTo, parentTaskId, ct);
|
||||
|
||||
task.IsAgentTask = true;
|
||||
task.ExpectedFrom = string.IsNullOrWhiteSpace(expectedFrom) ? null : expectedFrom.Trim().ToLowerInvariant();
|
||||
|
||||
// Persist the agent-task-specific fields
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
|
||||
await activityRepo.AddAsync(new ActivityEvent
|
||||
{
|
||||
Type = "agent_task",
|
||||
Message = $"Agent-Task created: \"{task.Title}\" (Source: {task.Source}, Expected: {task.ExpectedFrom ?? "none"})",
|
||||
TaskId = task.Id
|
||||
}, ct);
|
||||
|
||||
// Notify iris about new agent-task
|
||||
await notificationService.CreateAsync(
|
||||
"agent_task_created",
|
||||
$"Neuer Agent-Task: {task.Title}",
|
||||
detail,
|
||||
"iris",
|
||||
task.Id,
|
||||
ct);
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
public async Task<TaskOperationResult> UpdateDashboardTaskAsync(
|
||||
Guid id, string? title, string? detail, string? source,
|
||||
string? priority, string? assignedTo, DateTimeOffset? dueDate = null, CancellationToken ct = default)
|
||||
{
|
||||
var caller = ResolveCaller();
|
||||
var task = await taskRepo.GetByIdAsync(id, ct);
|
||||
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(title)) task.Title = title.Trim();
|
||||
if (detail is not null) task.Detail = string.IsNullOrWhiteSpace(detail) ? null : detail.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(source)) task.Source = source.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(priority)) task.Priority = priority.Trim();
|
||||
if (assignedTo is not null) task.AssignedTo = ValidateAssignedTo(assignedTo);
|
||||
if (dueDate.HasValue) task.DueDate = dueDate;
|
||||
var changes = new List<string>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(title) && !string.Equals(task.Title, title.Trim(), StringComparison.Ordinal))
|
||||
{
|
||||
changes.Add($"Titel: \"{task.Title}\" → \"{title.Trim()}\"");
|
||||
task.Title = title.Trim();
|
||||
}
|
||||
if (detail is not null)
|
||||
{
|
||||
var newDetail = string.IsNullOrWhiteSpace(detail) ? null : detail.Trim();
|
||||
if (!string.Equals(task.Detail ?? "", newDetail ?? "", StringComparison.Ordinal))
|
||||
{
|
||||
changes.Add("Beschreibung aktualisiert");
|
||||
task.Detail = newDetail;
|
||||
}
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(source))
|
||||
task.Source = source.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(priority) && !string.Equals(task.Priority, priority.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
changes.Add($"Priorität: {task.Priority} → {priority.Trim()}");
|
||||
task.Priority = priority.Trim();
|
||||
}
|
||||
if (assignedTo is not null)
|
||||
{
|
||||
var validated = ValidateAssignedTo(assignedTo);
|
||||
if (!string.Equals(task.AssignedTo ?? "", validated ?? "", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
changes.Add($"Zuständig: {task.AssignedTo ?? "niemand"} → {validated ?? "niemand"}");
|
||||
task.AssignedTo = validated;
|
||||
}
|
||||
}
|
||||
if (dueDate.HasValue)
|
||||
{
|
||||
if (task.DueDate?.Date != dueDate.Value.Date)
|
||||
{
|
||||
changes.Add($"Fällig: {task.DueDate?.ToString("yyyy-MM-dd") ?? "kein Datum"} → {dueDate.Value:yyyy-MM-dd}");
|
||||
task.DueDate = dueDate;
|
||||
}
|
||||
}
|
||||
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" updated", TaskId = task.Id }, ct);
|
||||
|
||||
var changeSummary = changes.Count > 0 ? string.Join("; ", changes) : "keine sichtbaren Änderungen";
|
||||
await activityRepo.AddAsync(new ActivityEvent
|
||||
{
|
||||
Type = "task",
|
||||
Message = $"Task \"{task.Title}\" aktualisiert von {caller}: {changeSummary}",
|
||||
TaskId = task.Id
|
||||
}, ct);
|
||||
|
||||
// Notification: wenn Bao die Task geändert hat, Iris benachrichtigen
|
||||
if (changes.Count > 0 && caller == "bao")
|
||||
{
|
||||
await notificationService.CreateAsync(
|
||||
"task_content_changed",
|
||||
$"Bao hat \"{task.Title}\" geändert",
|
||||
$"{changeSummary}",
|
||||
"iris",
|
||||
task.Id,
|
||||
ct);
|
||||
}
|
||||
|
||||
return new TaskOperationResult(TaskOperationOutcome.Success, task);
|
||||
}
|
||||
|
||||
@@ -188,6 +352,11 @@ public sealed class TaskService(
|
||||
var task = await taskRepo.GetByIdAsync(id, ct);
|
||||
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
|
||||
|
||||
// Enforce workflow rules
|
||||
var caller = ResolveCaller();
|
||||
if (!TaskStateHelper.CanChangeState(caller, task))
|
||||
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
|
||||
|
||||
var canonical = TaskStateHelper.AllStates.First(s => s.Equals(status, StringComparison.OrdinalIgnoreCase));
|
||||
task.State = canonical;
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
@@ -227,7 +396,7 @@ public sealed class TaskService(
|
||||
|
||||
// ── Board operations ──
|
||||
|
||||
public async Task<TaskBoardResponse> GetBoardAsync(CancellationToken ct = default)
|
||||
public async Task<BoardResponse> GetBoardAsync(CancellationToken ct = default)
|
||||
{
|
||||
var all = await taskRepo.GetAllAsync(ct);
|
||||
var offen = new List<DashboardTaskDto>();
|
||||
@@ -259,7 +428,6 @@ public sealed class TaskService(
|
||||
}
|
||||
}
|
||||
|
||||
// Priority sort within each group: High > Medium > Low, then by CreatedAt ascending
|
||||
offen.Sort(SortByPriorityThenCreatedAt);
|
||||
inProgress.Sort(SortByPriorityThenCreatedAt);
|
||||
delegated.Sort(SortByPriorityThenCreatedAt);
|
||||
@@ -267,7 +435,7 @@ public sealed class TaskService(
|
||||
blocked.Sort(SortByPriorityThenCreatedAt);
|
||||
done.Sort(SortByPriorityThenCreatedAt);
|
||||
|
||||
return new TaskBoardResponse(offen, inProgress, delegated, review, blocked, done);
|
||||
return new BoardResponse(offen, inProgress, delegated, review, blocked, done);
|
||||
}
|
||||
|
||||
private static int SortByPriorityThenCreatedAt(DashboardTaskDto a, DashboardTaskDto b)
|
||||
@@ -303,6 +471,11 @@ public sealed class TaskService(
|
||||
var task = await taskRepo.GetByIdAsync(id, ct);
|
||||
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
|
||||
|
||||
// Enforce workflow rules
|
||||
var caller = ResolveCaller();
|
||||
if (!TaskStateHelper.CanChangeState(caller, task))
|
||||
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
|
||||
|
||||
task.State = canonical;
|
||||
await taskRepo.UpdateAsync(task, ct);
|
||||
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" moved to {canonical}", TaskId = task.Id }, ct);
|
||||
@@ -310,6 +483,12 @@ public sealed class TaskService(
|
||||
return new TaskOperationResult(TaskOperationOutcome.Success, task);
|
||||
}
|
||||
|
||||
public Task<int> ResetStaleAsync(int staleHours, CancellationToken ct = default)
|
||||
{
|
||||
var normalizedHours = Math.Max(1, staleHours);
|
||||
return ResetStaleInProgressTasksAsync(TimeSpan.FromHours(normalizedHours), ct);
|
||||
}
|
||||
|
||||
public async Task<int> ResetStaleInProgressTasksAsync(TimeSpan staleThreshold, CancellationToken ct = default)
|
||||
{
|
||||
var all = await taskRepo.GetAllAsync(ct);
|
||||
@@ -351,7 +530,8 @@ public sealed class TaskService(
|
||||
|
||||
private static DashboardTaskDto MapToDto(WorkTask t) => new(
|
||||
t.Id, t.Title, t.Detail, t.Source, t.State, t.Priority, t.AssignedTo,
|
||||
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt);
|
||||
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt,
|
||||
t.IsAgentTask, t.ExpectedFrom);
|
||||
|
||||
/// <summary>
|
||||
/// Validates AssignedTo — only recognized agent values are accepted.
|
||||
@@ -365,16 +545,40 @@ public sealed class TaskService(
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates status-change notifications when a task moves to Review or Blocked.
|
||||
/// Resolves the caller identity from the HTTP context.
|
||||
/// Reads the X-Agent-Id header for agent calls, falls back to JWT name.
|
||||
/// Outside HTTP context → "nexus-system" (allowed for internal Cron/ResetStale ops).
|
||||
/// </summary>
|
||||
private string ResolveCaller()
|
||||
{
|
||||
var httpContext = httpContextAccessor.HttpContext;
|
||||
if (httpContext is null) return "nexus-system"; // internal system ops allowed
|
||||
|
||||
var agentHeader = httpContext.Request.Headers["X-Agent-Id"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(agentHeader))
|
||||
return agentHeader.Trim().ToLowerInvariant();
|
||||
|
||||
var user = httpContext.User;
|
||||
var nameClaim = user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
return nameClaim?.ToLowerInvariant() ?? "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates status-change notifications when a task moves to a new state.
|
||||
/// - Wenn Bao ändert → Iris benachrichtigen
|
||||
/// - Wenn Iris ändert → Bao benachrichtigen
|
||||
/// - Review/Blocked bekommen spezifische Töne
|
||||
/// </summary>
|
||||
private async Task CreateStatusChangeNotificationsAsync(WorkTask task, string canonical, CancellationToken ct)
|
||||
{
|
||||
var caller = ResolveCaller();
|
||||
|
||||
if (string.Equals(canonical, "Review", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await notificationService.CreateAsync(
|
||||
"task_review",
|
||||
$"Task zur Überprüfung: {task.Title}",
|
||||
$"Status auf Review geändert von {task.AssignedTo ?? "unbekannt"}",
|
||||
$"Status auf Review geändert von {caller}",
|
||||
"bao",
|
||||
task.Id,
|
||||
ct);
|
||||
@@ -384,10 +588,34 @@ public sealed class TaskService(
|
||||
await notificationService.CreateAsync(
|
||||
"task_blocked",
|
||||
$"Aufgabe blockiert: {task.Title}",
|
||||
"Die Task konnte nicht abgeschlossen werden und wurde blockiert.",
|
||||
$"Die Task wurde von {caller} auf Blockiert gesetzt.",
|
||||
"iris",
|
||||
task.Id,
|
||||
ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Allgemeine Statusänderung: Gegenüber benachrichtigen
|
||||
if (caller == "bao")
|
||||
{
|
||||
await notificationService.CreateAsync(
|
||||
"task_status_changed",
|
||||
$"Bao hat Status geändert: {task.Title}",
|
||||
$"Status → {canonical}",
|
||||
"iris",
|
||||
task.Id,
|
||||
ct);
|
||||
}
|
||||
else if (caller == "iris")
|
||||
{
|
||||
await notificationService.CreateAsync(
|
||||
"task_status_changed",
|
||||
$"Iris hat Status geändert: {task.Title}",
|
||||
$"Status → {canonical}",
|
||||
"bao",
|
||||
task.Id,
|
||||
ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user