|
| 1 | +using System.Text.Json; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Taskdeck.Application.DTOs; |
| 4 | +using Taskdeck.Application.Interfaces; |
| 5 | +using Taskdeck.Domain.Agents; |
| 6 | +using Taskdeck.Domain.Common; |
| 7 | +using Taskdeck.Domain.Entities; |
| 8 | +using Taskdeck.Domain.Enums; |
| 9 | +using Taskdeck.Domain.Exceptions; |
| 10 | + |
| 11 | +namespace Taskdeck.Application.Services; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Bounded agent template that triages inbox items into proposals. |
| 15 | +/// Never directly mutates board state — all changes are routed through |
| 16 | +/// the proposal system and policy evaluator. |
| 17 | +/// </summary> |
| 18 | +public sealed class InboxTriageAssistant |
| 19 | +{ |
| 20 | + /// <summary>Tool key for the inbox triage tool registered in the tool registry.</summary> |
| 21 | + public const string ToolKey = "inbox.triage"; |
| 22 | + |
| 23 | + /// <summary>Maximum number of inbox items to gather in a single triage run.</summary> |
| 24 | + private const int MaxInboxItemsPerRun = 20; |
| 25 | + |
| 26 | + private readonly IUnitOfWork _unitOfWork; |
| 27 | + private readonly IAgentPolicyEvaluator _policyEvaluator; |
| 28 | + private readonly IAutomationProposalService _proposalService; |
| 29 | + private readonly ILogger<InboxTriageAssistant>? _logger; |
| 30 | + |
| 31 | + public InboxTriageAssistant( |
| 32 | + IUnitOfWork unitOfWork, |
| 33 | + IAgentPolicyEvaluator policyEvaluator, |
| 34 | + IAutomationProposalService proposalService, |
| 35 | + ILogger<InboxTriageAssistant>? logger = null) |
| 36 | + { |
| 37 | + _unitOfWork = unitOfWork; |
| 38 | + _policyEvaluator = policyEvaluator; |
| 39 | + _proposalService = proposalService; |
| 40 | + _logger = logger; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Run the inbox triage template for a given agent profile and board. |
| 45 | + /// Gathers pending inbox items, evaluates policy, and creates a proposal |
| 46 | + /// for triage actions. Returns a failure result if policy denies the action |
| 47 | + /// or if no actionable items are found. |
| 48 | + /// </summary> |
| 49 | + public async Task<Result<InboxTriageResultDto>> RunTriageAsync( |
| 50 | + Guid agentProfileId, |
| 51 | + Guid userId, |
| 52 | + Guid boardId, |
| 53 | + CancellationToken cancellationToken = default) |
| 54 | + { |
| 55 | + if (agentProfileId == Guid.Empty) |
| 56 | + return Result.Failure<InboxTriageResultDto>(ErrorCodes.ValidationError, "Agent profile ID is required."); |
| 57 | + |
| 58 | + if (userId == Guid.Empty) |
| 59 | + return Result.Failure<InboxTriageResultDto>(ErrorCodes.ValidationError, "User ID is required."); |
| 60 | + |
| 61 | + if (boardId == Guid.Empty) |
| 62 | + return Result.Failure<InboxTriageResultDto>(ErrorCodes.ValidationError, "Board ID is required."); |
| 63 | + |
| 64 | + // Evaluate policy before proceeding |
| 65 | + var policyDecision = await _policyEvaluator.EvaluateToolUseAsync( |
| 66 | + agentProfileId, |
| 67 | + ToolKey, |
| 68 | + new Dictionary<string, string> { ["boardId"] = boardId.ToString() }, |
| 69 | + cancellationToken); |
| 70 | + |
| 71 | + if (!policyDecision.Allowed) |
| 72 | + { |
| 73 | + _logger?.LogInformation( |
| 74 | + "Inbox triage denied by policy for profile '{ProfileId}': {Reason}", |
| 75 | + agentProfileId, policyDecision.Reason); |
| 76 | + return Result.Failure<InboxTriageResultDto>(ErrorCodes.Forbidden, policyDecision.Reason); |
| 77 | + } |
| 78 | + |
| 79 | + // Gather inbox context: recent pending items for this user |
| 80 | + var pendingItems = (await _unitOfWork.LlmQueue.GetByUserAsync(userId, cancellationToken)) |
| 81 | + .Where(r => r.Status == RequestStatus.Pending) |
| 82 | + .OrderBy(r => r.CreatedAt) |
| 83 | + .Take(MaxInboxItemsPerRun) |
| 84 | + .ToList(); |
| 85 | + |
| 86 | + if (pendingItems.Count == 0) |
| 87 | + { |
| 88 | + _logger?.LogInformation("Inbox triage found no pending items for user '{UserId}'", userId); |
| 89 | + return Result.Failure<InboxTriageResultDto>( |
| 90 | + ErrorCodes.NotFound, "No pending inbox items to triage."); |
| 91 | + } |
| 92 | + |
| 93 | + // Verify board exists |
| 94 | + var board = await _unitOfWork.Boards.GetByIdAsync(boardId, cancellationToken); |
| 95 | + if (board is null) |
| 96 | + { |
| 97 | + return Result.Failure<InboxTriageResultDto>( |
| 98 | + ErrorCodes.NotFound, $"Board '{boardId}' not found."); |
| 99 | + } |
| 100 | + |
| 101 | + // Get the first column to use as the default target |
| 102 | + var columns = (await _unitOfWork.Columns.GetByBoardIdAsync(boardId, cancellationToken)) |
| 103 | + .OrderBy(c => c.Position) |
| 104 | + .ToList(); |
| 105 | + |
| 106 | + if (columns.Count == 0) |
| 107 | + { |
| 108 | + return Result.Failure<InboxTriageResultDto>( |
| 109 | + ErrorCodes.NotFound, "Board has no columns to triage into."); |
| 110 | + } |
| 111 | + |
| 112 | + var defaultColumnId = columns[0].Id; |
| 113 | + |
| 114 | + // Build proposal operations — one create-card per inbox item |
| 115 | + var operations = pendingItems.Select((item, i) => |
| 116 | + { |
| 117 | + var parameters = JsonSerializer.Serialize(new |
| 118 | + { |
| 119 | + title = TruncateTitle(item.Payload), |
| 120 | + description = $"Triaged from inbox item {item.Id}", |
| 121 | + columnId = defaultColumnId, |
| 122 | + boardId |
| 123 | + }); |
| 124 | + |
| 125 | + return new CreateProposalOperationDto( |
| 126 | + Sequence: i, |
| 127 | + ActionType: "create", |
| 128 | + TargetType: "card", |
| 129 | + Parameters: parameters, |
| 130 | + IdempotencyKey: $"inbox-triage:{item.Id:N}:{boardId:N}"); |
| 131 | + }).ToList(); |
| 132 | + |
| 133 | + // Create the proposal — never directly mutating the board |
| 134 | + var summary = pendingItems.Count == 1 |
| 135 | + ? $"Inbox triage: 1 item for board '{board.Name}'" |
| 136 | + : $"Inbox triage: {pendingItems.Count} items for board '{board.Name}'"; |
| 137 | + |
| 138 | + var createResult = await _proposalService.CreateProposalAsync( |
| 139 | + new CreateProposalDto( |
| 140 | + SourceType: ProposalSourceType.Queue, |
| 141 | + RequestedByUserId: userId, |
| 142 | + Summary: summary, |
| 143 | + RiskLevel: RiskLevel.Low, |
| 144 | + CorrelationId: Guid.NewGuid().ToString(), |
| 145 | + BoardId: boardId, |
| 146 | + Operations: operations), |
| 147 | + cancellationToken); |
| 148 | + |
| 149 | + if (!createResult.IsSuccess) |
| 150 | + { |
| 151 | + _logger?.LogWarning( |
| 152 | + "Inbox triage proposal creation failed for profile '{ProfileId}': {Error}", |
| 153 | + agentProfileId, createResult.ErrorMessage); |
| 154 | + return Result.Failure<InboxTriageResultDto>(createResult.ErrorCode, createResult.ErrorMessage); |
| 155 | + } |
| 156 | + |
| 157 | + _logger?.LogInformation( |
| 158 | + "Inbox triage created proposal '{ProposalId}' with {Count} operations (review required: {Review})", |
| 159 | + createResult.Value.Id, operations.Count, policyDecision.RequiresReview); |
| 160 | + |
| 161 | + return Result.Success(new InboxTriageResultDto( |
| 162 | + createResult.Value.Id, |
| 163 | + operations.Count, |
| 164 | + policyDecision.RequiresReview, |
| 165 | + policyDecision.Reason)); |
| 166 | + } |
| 167 | + |
| 168 | + private static string TruncateTitle(string input) |
| 169 | + { |
| 170 | + const int maxLength = 200; |
| 171 | + var firstLine = input.Split('\n', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? input; |
| 172 | + var trimmed = firstLine.Trim(); |
| 173 | + return trimmed.Length > maxLength ? trimmed[..maxLength].TrimEnd() : trimmed; |
| 174 | + } |
| 175 | + |
| 176 | + /// <summary> |
| 177 | + /// Returns the built-in tool definition for registration in the tool registry. |
| 178 | + /// </summary> |
| 179 | + public static ITaskdeckTool GetToolDefinition() |
| 180 | + { |
| 181 | + return new TaskdeckToolDefinition( |
| 182 | + Key: ToolKey, |
| 183 | + DisplayName: "Inbox Triage", |
| 184 | + Description: "Triages pending inbox items into card proposals for a target board.", |
| 185 | + Scope: ToolScope.Inbox, |
| 186 | + RiskLevel: ToolRiskLevel.Medium); |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +/// <summary> |
| 191 | +/// Result DTO for an inbox triage run. |
| 192 | +/// </summary> |
| 193 | +public record InboxTriageResultDto( |
| 194 | + Guid ProposalId, |
| 195 | + int ItemsTriaged, |
| 196 | + bool RequiresReview, |
| 197 | + string PolicyReason); |
0 commit comments