diff --git a/services/src/main/java/io/meeds/task/mcp/TaskMcpTool.java b/services/src/main/java/io/meeds/task/mcp/TaskMcpTool.java index d0021b68f..5b992161e 100644 --- a/services/src/main/java/io/meeds/task/mcp/TaskMcpTool.java +++ b/services/src/main/java/io/meeds/task/mcp/TaskMcpTool.java @@ -165,6 +165,15 @@ public class TaskMcpTool implements McpToolPlugin { private static final int MAX_TO_LOAD = 100; + /** + * The most tasks list_project_activity_since returns, both lists together: + * each one carries its change log and comments of the period. + */ + private static final int MAX_ACTIVITY_TASKS = 20; + + /** The page size list_project_activity_since reads the tasks by. */ + private static final int ACTIVITY_PAGE_SIZE = 10; + private static final String MSG_TASK_NOT_EDITABLE = "Task with identifier '%s' is not editable for user '%s'"; @@ -832,7 +841,11 @@ private long countAssignedTasks(TaskQuery taskQuery, String username) { * access, so that one call tells which boards hold such tasks and how many * of those open tasks they are, whatever the number of boards (EXO-94250). * A personal task, on - * no board, is listed but counted on none. + * no board, is listed but counted on none. The grouped answer also counts + * the boards holding open tasks, the boards left out of the list and the + * personal tasks, and states them in a summary naming the filters applied; + * a grouped call with a limit of 1, made for the counts, returns at most + * one task and says no next page remains (EXO-94360). *

* Each task comes as a list item, without its description or coworkers, * which {@link #getTaskById(Long)} returns; with {@code includeDescription}, @@ -926,7 +939,24 @@ public TaskCollectionModel listTasks(Long projectId, // NOSONAR the tool's param } TaskCollectionModel collection = toTaskCollection(taskModels, usedOffset, usedLimit, countTasks(taskQuery)); if (Boolean.TRUE.equals(groupByProject)) { + if (usedLimit == 1) { + // a call for the counts, its one task aside, asks no next page (EXO-94360) + collection.setHasMore(false); + collection.setNextOffset(null); + } setProjectCounts(collection, taskQuery, projectId, zone); + collection.setSummary(getGroupedSummary(collection, + new ListingFilters(Boolean.TRUE.equals(overdueOnly), + Boolean.TRUE.equals(hideCompletedTasks), + Boolean.TRUE.equals(withoutDueDate), + dueFrom, + dueTo, + priority, + assignee, + statusId, + title, + changedSince, + completedSince))); } return collection; } @@ -1742,10 +1772,19 @@ private TaskDto getAccessibleTask(long taskId) throws ObjectNotFoundException, I * number of days ago, in the user's time zone, the server's when they have * none: the day's first instant when a daylight-saving switch skips its * midnight. A task updated at that very instant is in the period. + *

+ * At most {@value #MAX_ACTIVITY_TASKS} tasks in all, each with its change + * log and comments of the period: the updated ones first, the most recently + * active first, then as many other uncompleted ones as there is room for. + * The tasks are read in their last-activity order, in which the updated ones + * come first, and only the tasks returned are read in full. The answer says + * whether more tasks exist than it holds, and how many uncompleted tasks the + * project has. * * @param projectId the project, or null for every project the user sees * @param days the number of days to look back - * @return the tasks updated in the period, then the other uncompleted ones + * @return the tasks updated in the period, then the other uncompleted ones, + * whether more exist and the count of uncompleted tasks * @throws IllegalAccessException when the user can't view the project * @throws ObjectNotFoundException when the project doesn't exist */ @@ -1753,47 +1792,67 @@ public ProjectActivityModel listProjectActivitySince(Long projectId, Integer day ObjectNotFoundException { long count = countTaskModels(projectId, false); if (count == 0) { - return new ProjectActivityModel(Collections.emptyList(), Collections.emptyList()); + return new ProjectActivityModel(Collections.emptyList(), Collections.emptyList(), false, 0L); } else { - List updatedTasks = new ArrayList<>(); - List uncompletedTasks = new ArrayList<>(); ZoneId zone = getCurrentUserZone(); LocalDate today = getToday(zone); // the period starts at midnight of the user's day, in the user's zone Instant sinceInstant = today.minusDays(days).atStartOfDay(zone).toInstant(); + // the updated tasks come first in the last-activity order: stop at the + // first page they don't fill, or once one more than the cap is found + List updatedTasks = new ArrayList<>(); + boolean hasMore = false; int offset = 0; - int limit = 10; + int updatedInPage; do { - List taskModels = getTasks(projectId, offset, limit, false).stream() - .filter(t -> !Instant.ofEpochMilli(getLastUpdateDate(t).getTime()) - .isBefore(sinceInstant)) - .map(t -> toTaskWithChangeLogModel(t, - sinceInstant, - zone, - today)) - .toList(); - updatedTasks.addAll(taskModels); - if (taskModels.size() < limit) { - break; - } else { - offset += limit; + updatedInPage = 0; + for (TaskDto task : getTasks(projectId, offset, ACTIVITY_PAGE_SIZE, false)) { + if (!Instant.ofEpochMilli(getLastUpdateDate(task).getTime()).isBefore(sinceInstant)) { + updatedInPage++; + if (updatedTasks.size() < MAX_ACTIVITY_TASKS) { + updatedTasks.add(task); + } else { + hasMore = true; + break; + } + } } - } while (offset < count); - - count = countTaskModels(projectId, false); + offset += ACTIVITY_PAGE_SIZE; + } while (!hasMore && updatedInPage == ACTIVITY_PAGE_SIZE && offset < count); + + // then the other uncompleted tasks, as many as there is room for, and + // one more to tell whether more exist + long uncompletedCount = countTaskModels(projectId, true); + int room = MAX_ACTIVITY_TASKS - updatedTasks.size(); + List uncompletedTasks = new ArrayList<>(); offset = 0; - limit = 10; - do { - getTasks(projectId, offset, limit, true).stream() - .filter(t -> Instant.ofEpochMilli(getLastUpdateDate(t).getTime()) - .isBefore(sinceInstant)) - .map(t -> toTaskWithChangeLogModel(t, sinceInstant, zone, today)) - .forEach(uncompletedTasks::add); - offset += limit; - } while (offset < count); - return new ProjectActivityModel(updatedTasks, uncompletedTasks); + while (!hasMore && offset < uncompletedCount) { + List page = getTasks(projectId, offset, ACTIVITY_PAGE_SIZE, true); + for (TaskDto task : page) { + if (Instant.ofEpochMilli(getLastUpdateDate(task).getTime()).isBefore(sinceInstant)) { + if (uncompletedTasks.size() < room) { + uncompletedTasks.add(task); + } else { + hasMore = true; + break; + } + } + } + if (page.size() < ACTIVITY_PAGE_SIZE) { + break; + } + offset += ACTIVITY_PAGE_SIZE; + } + return new ProjectActivityModel(updatedTasks.stream() + .map(t -> toTaskWithChangeLogModel(t, sinceInstant, zone, today)) + .toList(), + uncompletedTasks.stream() + .map(t -> toTaskWithChangeLogModel(t, sinceInstant, zone, today)) + .toList(), + hasMore, + uncompletedCount); } } @@ -2363,7 +2422,9 @@ private void checkNotOverdueAndCompleted(Boolean overdueOnly, Date completedSinc * open tasks, the boards with the most selected tasks first, then by name * and identifier, so that two calls list them in the same order, at most * {@value #MAX_PROJECT_COUNTS}. The open tasks are counted with the - * listing's own accessibility, among the boards listed only (EXO-94250). + * listing's own accessibility on every board, which counts the boards that + * hold open tasks too; the boards left out of the list and the personal + * tasks, on no board, are counted (EXO-94360). * * @param collection the listing's answer, to which the counts are added * @param taskQuery the listing's query @@ -2385,23 +2446,136 @@ private void setProjectCounts(TaskCollectionModel collection, .thenComparingLong(ProjectTaskCountDto::getProjectId)) .limit(MAX_PROJECT_COUNTS) .toList(); - Map openCounts = Collections.emptyMap(); - if (!kept.isEmpty()) { - TaskQuery openQuery = getTaskQuery(projectId, true, false, zone); - openQuery.setProjectIds(kept.stream().map(ProjectTaskCountDto::getProjectId).toList()); - openCounts = taskService.countTasksByProject(openQuery) - .stream() - .collect(Collectors.toMap(ProjectTaskCountDto::getProjectId, ProjectTaskCountDto::getCount)); - } - Map open = openCounts; + // the open tasks of every board the user can access: their boards are + // counted, and the listed boards read their open count from them + Map open = taskService.countTasksByProject(getTaskQuery(projectId, true, false, zone)) + .stream() + .collect(Collectors.toMap(ProjectTaskCountDto::getProjectId, + ProjectTaskCountDto::getCount)); List projects = kept.stream() .map(count -> new ProjectTaskCountModel(count.getProjectId(), count.getProjectName(), count.getCount(), open.getOrDefault(count.getProjectId(), 0L))) .toList(); + long onBoards = counts.stream().mapToLong(ProjectTaskCountDto::getCount).sum(); collection.setProjects(projects); collection.setProjectCount(counts.size()); + collection.setOpenProjectCount(open.size()); + collection.setProjectsNotListed(counts.size() - kept.size()); + collection.setPersonalCount(Math.max(0L, collection.getCount() - onBoards)); + } + + /** + * States a grouped listing in one sentence: the count, the filters applied, + * the boards holding the tasks among the boards holding open tasks when only + * open tasks are selected, the personal tasks and the boards left out of the + * list, such as « 260 overdue open tasks in 29 of 86 boards » (EXO-94360). + * + * @param collection the grouped answer, its counts set + * @param filters the filters the listing applied + * @return the sentence + */ + static String getGroupedSummary(TaskCollectionModel collection, ListingFilters filters) { + long count = collection.getCount(); + long personal = collection.getPersonalCount() == null ? 0L : collection.getPersonalCount(); + // hide_completed_tasks keeps the completed tasks when completed_since is + // given (TaskServiceImpl#addChangeFilter): the tasks are open only without it + boolean openOnly = filters.overdueOnly() || filters.hideCompleted() && StringUtils.isBlank(filters.completedSince()); + StringBuilder summary = new StringBuilder().append(count).append(' '); + if (filters.overdueOnly()) { + summary.append("overdue open "); + } else if (openOnly) { + summary.append("open "); + } + summary.append(count == 1 ? "task" : "tasks").append(describeFilters(filters)); + int boards = collection.getProjectCount(); + StringBuilder where = new StringBuilder(" in ").append(boards); + int last = boards; + if (openOnly) { + last = collection.getOpenProjectCount(); + where.append(" of ").append(last); + } + where.append(last == 1 ? " board" : " boards"); + if (personal > 0 && personal == count) { + summary.append(", all personal, on no board"); + } else if (personal > 0) { + summary.append(": ").append(count - personal).append(where).append(", ").append(personal).append(" personal"); + } else { + summary.append(where); + } + if (collection.getProjectsNotListed() != null && collection.getProjectsNotListed() > 0) { + summary.append("; the ").append(collection.getProjects().size()).append(" boards with the most are listed"); + } + return summary.toString(); + } + + /** + * @param filters the filters a listing applied + * @return the filters other than overdue and open, each as the words that + * follow « tasks », in the order of the tool's arguments + */ + private static String describeFilters(ListingFilters filters) { + StringBuilder words = new StringBuilder(); + if (filters.priority() == Priority.NONE) { + words.append(" with no priority"); + } else if (filters.priority() != null) { + words.append(" of priority ").append(filters.priority().name().toLowerCase(Locale.ROOT)); + } + if (StringUtils.isNotBlank(filters.title())) { + words.append(" whose title contains \"").append(filters.title().trim()).append('"'); + } + if (StringUtils.isNotBlank(filters.assignee())) { + words.append(" assigned to ").append(filters.assignee().trim()); + } + if (filters.statusId() != null) { + words.append(" in status ").append(filters.statusId()); + } + if (filters.withoutDueDate()) { + words.append(" with no due date"); + } + if (StringUtils.isNotBlank(filters.dueFrom())) { + words.append(" due from ").append(filters.dueFrom().trim()); + } + if (StringUtils.isNotBlank(filters.dueTo())) { + words.append(StringUtils.isNotBlank(filters.dueFrom()) ? " to " : " due until ").append(filters.dueTo().trim()); + } + if (StringUtils.isNotBlank(filters.changedSince())) { + words.append(" changed since ").append(filters.changedSince().trim()); + } + if (StringUtils.isNotBlank(filters.completedSince())) { + words.append(" completed since ").append(filters.completedSince().trim()); + } + return words.toString(); + } + + /** + * The filters a listing applied, as its tool call gave them, for the + * summary of a grouped answer (EXO-94360). + * + * @param overdueOnly whether only the overdue tasks are listed + * @param hideCompleted whether the completed tasks are left out + * @param withoutDueDate whether only the tasks with no due date are listed + * @param dueFrom the first day or instant of the due range, blank for none + * @param dueTo the last day or instant of the due range, blank for none + * @param priority the priority, null for any + * @param assignee the username of the assignee, blank for any + * @param statusId the status, null for any + * @param title a part of the title, blank for any + * @param changedSince the change date, blank for none + * @param completedSince the completion date, blank for none + */ + record ListingFilters(boolean overdueOnly, // NOSONAR the tool's filters, each one its own + boolean hideCompleted, + boolean withoutDueDate, + String dueFrom, + String dueTo, + Priority priority, + String assignee, + Long statusId, + String title, + String changedSince, + String completedSince) { } /** diff --git a/services/src/main/java/io/meeds/task/mcp/model/ProjectActivityModel.java b/services/src/main/java/io/meeds/task/mcp/model/ProjectActivityModel.java index 9c2c61539..77ebbdacd 100644 --- a/services/src/main/java/io/meeds/task/mcp/model/ProjectActivityModel.java +++ b/services/src/main/java/io/meeds/task/mcp/model/ProjectActivityModel.java @@ -37,4 +37,12 @@ public class ProjectActivityModel { @JsonProperty("other_uncompleted_tasks") private List otherUncompletedTasks; + /** Whether the project has more such tasks than the answer holds. */ + @JsonProperty("has_more") + private boolean hasMore; + + /** The project's uncompleted tasks, whatever their last activity. */ + @JsonProperty("uncompleted_count") + private long uncompletedCount; + } diff --git a/services/src/main/java/io/meeds/task/mcp/model/TaskCollectionModel.java b/services/src/main/java/io/meeds/task/mcp/model/TaskCollectionModel.java index c834aca31..19d0a2210 100644 --- a/services/src/main/java/io/meeds/task/mcp/model/TaskCollectionModel.java +++ b/services/src/main/java/io/meeds/task/mcp/model/TaskCollectionModel.java @@ -90,6 +90,37 @@ public class TaskCollectionModel { @JsonInclude(Include.NON_NULL) private Long coworkerCount; + /** + * With {@code group_by_project}, the number of boards the user can access + * that hold at least one open task (EXO-94360). + */ + @JsonProperty("open_project_count") + @JsonInclude(Include.NON_NULL) + private Integer openProjectCount; + + /** + * With {@code group_by_project}, the boards holding selected tasks that + * {@code projects} leaves out, past its cap (EXO-94360). + */ + @JsonProperty("projects_not_listed") + @JsonInclude(Include.NON_NULL) + private Integer projectsNotListed; + + /** + * With {@code group_by_project}, how many of the tasks counted by + * {@code count} are personal tasks, on no board (EXO-94360). + */ + @JsonProperty("personal_count") + @JsonInclude(Include.NON_NULL) + private Long personalCount; + + /** + * With {@code group_by_project}, one sentence stating the count, the + * filters applied and the boards, built from the fields above (EXO-94360). + */ + @JsonInclude(Include.NON_NULL) + private String summary; + /** * A page of tasks, with no count per board. * @@ -101,7 +132,7 @@ public class TaskCollectionModel { * @param nextOffset the offset of the next page, null when none remains */ public TaskCollectionModel(List tasks, int usedOffset, int usedLimit, long count, boolean hasMore, Integer nextOffset) { - this(tasks, usedOffset, usedLimit, count, hasMore, nextOffset, null, null, null, null); + this(tasks, usedOffset, usedLimit, count, hasMore, nextOffset, null, null, null, null, null, null, null, null); } } diff --git a/services/src/main/resources/ai-tool-definition-upgrades.json b/services/src/main/resources/ai-tool-definition-upgrades.json index 3fb17900d..b82e8a102 100644 --- a/services/src/main/resources/ai-tool-definition-upgrades.json +++ b/services/src/main/resources/ai-tool-definition-upgrades.json @@ -1,5 +1,11 @@ { "tools": [ + { + "name": "list_project_activity_since", + "replaced_definitions": [ + "0648b6b3cc88c4567304a1730b8a9ac39b7f69a62acddd8c2aa2235831c15b04" + ] + }, { "name": "list_assigned_tasks", "replaced_definitions": [ @@ -28,6 +34,7 @@ "10abeb66b8198e0d58c2a6912dd9fa52206b6c2f7fe52580ad35ef6164748fd5", "145e138e197cb987638d1861ae78e2afb5657e21544a30f0a20080bf338b7988", "252681e7e18cb7d368b2b2057465564e5c407751768dccb753233f86b31214f4", + "2b53f023e39465e999c43f9d33f7ae28dc3e78340a9e53d79f9c5f8eee831642", "3762d94cb1d5a4d859a6160b4851d45b04f5167424a9c918b2ef07d93b0a78fb", "391321c06ae52b6c4f483cd44d91168bcb31ede13535969a64069eb2d7b631a8", "444ebb6dcec142ec858fdbd0328f7074d8cbeffb93ac7ea6004a3a2646097159", diff --git a/services/src/main/resources/ai-tool-definitions.json b/services/src/main/resources/ai-tool-definitions.json index 13dc4014e..66cb4e4d3 100644 --- a/services/src/main/resources/ai-tool-definitions.json +++ b/services/src/main/resources/ai-tool-definitions.json @@ -144,7 +144,7 @@ { "name": "list_tasks", "title": "List Tasks", - "description": "List tasks, optionally filtered by project; without project_id, every task the user can access, personal tasks included. With overdue_only, only the open tasks past their due date, the most overdue first; an overdue task carries days_overdue. With title, only the tasks whose title contains it, ignoring case. With changed_since, only the tasks whose status, project, due date, assignee or completion changed since that date, completed tasks included unless hide_completed_tasks; an assignee change of a task created since that date is not counted. With completed_since, only the tasks completed since that date. A task listed with either carries changes: each change since that date, oldest first, with its field (status, project, due_date, assignee or completed), its old_value and new_value when the change log records them, its date and its author; to tell what moved, use them instead of comparing dates. With assignee, only the tasks assigned to that user; with status_id, only the tasks in that status. With without_due_date, only the tasks with no due date; with due_from and due_to, only those due in that range. With priority, only the tasks of that priority: for a question on priority, filter with it and answer from count and the items, never by reading pages for it. With group_by_project, projects counts board by board the tasks selected (count) beside the board's open tasks the user can access (open_count), the most first: to tell which boards have tasks with no due date, or due in a range, call it once without project_id, never once per project; in a run limited to a space, once per project of that space. Compact items (status is the board column); get_task_by_id for details. A commented task carries last_comment_date and last_comment_author, its latest comment or reply; comments_count counts the replies. count is the total. While has_more, call again with offset=next_offset. In a run limited to a space, project_id is required and must be a project of that space, as list_projects returns them; to find a task by its title, list the tasks of each of those projects with title. Elsewhere, to find a task by words of its title or description, call search_tasks instead of listing a whole project.", + "description": "List tasks, optionally filtered by project; without project_id, every task the user can access, personal tasks included. With overdue_only, only the open tasks past their due date, the most overdue first; an overdue task carries days_overdue. With title, only the tasks whose title contains it, ignoring case. With changed_since, only the tasks whose status, project, due date, assignee or completion changed since that date, completed tasks included unless hide_completed_tasks; an assignee change of a task created since that date is not counted. With completed_since, only the tasks completed since that date. A task listed with either carries changes: each change since that date, oldest first, with its field (status, project, due_date, assignee or completed), its old_value and new_value when the change log records them, its date and its author; to tell what moved, use them instead of comparing dates. With assignee, only the tasks assigned to that user; with status_id, only the tasks in that status. With without_due_date, only the tasks with no due date; with due_from and due_to, only those due in that range. With priority, only the tasks of that priority: for a question on priority, filter with it and answer from count and the items, never by reading pages for it. With group_by_project, projects counts board by board the tasks selected (count) beside the board's open tasks the user can access (open_count), the most first: to tell which boards have tasks with no due date, or due in a range, call it once without project_id, never once per project; in a run limited to a space, once per project of that space. The grouped answer also gives project_count, the boards holding the tasks selected; open_project_count, the boards holding open tasks the user can access; projects_not_listed, the boards left out of projects; personal_count, the personal tasks, on no board, among count; and summary, one sentence stating them with the filters of this call: answer from these fields about this call's filters, never reuse a summary for another question. A grouped call with limit 1 returns at most one task beside the counts, and has_more false; a grouped call with a larger limit pages as usual. Compact items (status is the board column); get_task_by_id for details. A commented task carries last_comment_date and last_comment_author, its latest comment or reply; comments_count counts the replies. count is the total. While has_more, call again with offset=next_offset. In a run limited to a space, project_id is required and must be a project of that space, as list_projects returns them; to find a task by its title, list the tasks of each of those projects with title. Elsewhere, to find a task by words of its title or description, call search_tasks instead of listing a whole project.", "input_schema": { "type": "object", "properties": { @@ -163,7 +163,7 @@ "without_due_date": { "type": "boolean", "description": "Only the tasks with no due date; not together with overdue_only, due_from or due_to." }, "due_from": { "type": "string", "description": "Only the tasks due at or after this date: a date such as 2026-11-09, from the start of that day in the user's time zone, or a date and time with its offset." }, "due_to": { "type": "string", "description": "Only the tasks due at or before this date: a date such as 2026-11-15, to the end of that day in the user's time zone, or a date and time with its offset." }, - "group_by_project": { "type": "boolean", "description": "true: also projects, the count of the tasks the filters select on each board (hide_completed_tasks included) and its open_count, the board's open tasks the user can access, and project_count." }, + "group_by_project": { "type": "boolean", "description": "true: also projects, the count of the tasks the filters select on each board (hide_completed_tasks included) and its open_count, the board's open tasks the user can access, project_count, open_project_count, projects_not_listed, personal_count and summary." }, "priority": { "type": "string", "enum": ["HIGH", "NORMAL", "LOW", "NONE"], "description": "Only the tasks of this priority; NONE also selects the tasks with no priority. count then counts those tasks, and with group_by_project so does each board's count." } } }, @@ -178,7 +178,7 @@ { "name": "list_project_activity_since", "title": "Get Project Activity since last days", - "description": "Retrieve a project activity since a designated date and list all other uncompleted tasks.", + "description": "Lists a project's tasks updated in the last days, the most recently active first, each with its changes and comments of the period, then its other uncompleted tasks: at most 20 tasks in all. The period starts at midnight of the user's day, that number of days ago. has_more is true when the project has more such tasks than shown: to list every uncompleted task of the project, page list_tasks with project_id and hide_completed_tasks true. uncompleted_count is the count of the project's uncompleted tasks.", "input_schema": { "type": "object", "properties": { diff --git a/services/src/test/java/io/meeds/task/mcp/TaskMcpToolTest.java b/services/src/test/java/io/meeds/task/mcp/TaskMcpToolTest.java index 6d7bd0326..85aaf9cb7 100644 --- a/services/src/test/java/io/meeds/task/mcp/TaskMcpToolTest.java +++ b/services/src/test/java/io/meeds/task/mcp/TaskMcpToolTest.java @@ -59,6 +59,7 @@ import java.util.ResourceBundle; import java.util.Set; import java.util.TimeZone; +import java.util.stream.LongStream; import org.junit.Before; import org.junit.Test; @@ -1981,6 +1982,8 @@ public void listProjectActivitySinceWhenNoTasksShouldReturnEmptyLists() throws E assertEquals(0, result.getLastUpdatedTasks().size()); assertEquals(0, result.getOtherUncompletedTasks().size()); + assertFalse(result.isHasMore()); + assertEquals(0, result.getUncompletedCount()); } @Test @@ -3458,6 +3461,172 @@ protected LocalDate getToday(ZoneId zone) { assertEquals(Set.of("editTitle", "commented"), Set.copyOf(actions)); } + /** + * list_project_activity_since returns at most 20 tasks: of 25 updated in the + * period, the 20 most recently active, no older one, and has_more; only + * those 20 are read in full. Mutants: the cap at 21; the tasks read in full + * before the cap. + */ + @Test + public void listProjectActivitySinceListsAtMostTwentyUpdatedTasks() throws Exception { // NOSONAR + mockProjectActivity(25, 0, 0); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(LongStream.range(100, 120).boxed().toList(), + result.getLastUpdatedTasks().stream().map(TaskWithChangeLogModel::getId).toList()); + assertEquals(List.of(), result.getOtherUncompletedTasks()); + assertTrue(result.isHasMore()); + verify(commentService, times(20)).countComments(anyLong()); + } + + /** + * Below the cap, the older uncompleted tasks fill the room the updated ones + * leave, the most recently active first, never a completed one: 15 + * updated and 10 older give 15 and 5, and has_more. The read of all tasks + * stops at the first page the updated ones don't fill. Mutants: the older + * tasks past the room; the completed tasks read among the older ones; the + * read of all tasks past that page. + */ + @Test + public void listProjectActivitySinceFillsTheRestWithOlderUncompletedTasks() throws Exception { // NOSONAR + mockProjectActivity(15, 10, 3); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(15, result.getLastUpdatedTasks().size()); + assertEquals(LongStream.range(200, 205).boxed().toList(), + result.getOtherUncompletedTasks().stream().map(TaskWithChangeLogModel::getId).toList()); + assertTrue(result.isHasMore()); + verify(taskService, times(2)).findLastUpdatedTasks(argThat(query -> !isUncompletedOnly(query)), anyInt(), anyInt()); + } + + /** + * A project of exactly 20 such tasks fits: 15 updated and 5 older are all + * returned, without has_more, whatever completed tasks the project holds. + * Mutants: has_more set at the cap rather than past it; the completed tasks + * read among the older ones. + */ + @Test + public void listProjectActivitySinceHasNoMoreWhenTheTasksFitTheCap() throws Exception { // NOSONAR + mockProjectActivity(15, 5, 3); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(15, result.getLastUpdatedTasks().size()); + assertEquals(LongStream.range(200, 205).boxed().toList(), + result.getOtherUncompletedTasks().stream().map(TaskWithChangeLogModel::getId).toList()); + assertFalse(result.isHasMore()); + } + + /** + * Twenty updated tasks fill the cap: one older uncompleted task left out + * sets has_more, which none does not. Mutant: the older tasks not read once + * the updated ones fill the cap. + */ + @Test + public void listProjectActivitySinceHasMoreWhenAnOlderTaskIsLeftOut() throws Exception { // NOSONAR + mockProjectActivity(20, 1, 0); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(20, result.getLastUpdatedTasks().size()); + assertEquals(List.of(), result.getOtherUncompletedTasks()); + assertTrue(result.isHasMore()); + } + + /** + * Twenty updated tasks and no older one: all are returned, without + * has_more. + */ + @Test + public void listProjectActivitySinceHasNoMoreWhenTwentyUpdatedTasksAreAll() throws Exception { // NOSONAR + mockProjectActivity(20, 0, 0); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(20, result.getLastUpdatedTasks().size()); + assertFalse(result.isHasMore()); + } + + /** + * uncompleted_count is the count of the project's uncompleted tasks, not of + * all its tasks. Mutant: the count of all tasks. + */ + @Test + public void listProjectActivitySinceCountsTheUncompletedTasks() throws Exception { // NOSONAR + mockProjectActivity(3, 2, 4); + + ProjectActivityModel result = runWithDateFormatMockResult(() -> tool.listProjectActivitySince(null, 7)); + + assertEquals(5, result.getUncompletedCount()); + assertFalse(result.isHasMore()); + } + + /** + * Stubs a project for list_project_activity_since: uncompleted tasks updated + * yesterday (ids from 100), then completed ones updated 20 days ago (ids + * from 300) and uncompleted ones updated 30 days ago (ids from 200), in the + * last-activity order. The read of all tasks pages through every one, the + * read of the uncompleted ones leaves the completed out, and each count + * counts what its read pages through. + * + * @param updated the uncompleted tasks updated in the period + * @param older the uncompleted tasks updated before it + * @param completed the completed tasks updated before it + */ + @SneakyThrows + private void mockProjectActivity(int updated, int older, int completed) { + List uncompletedTasks = new ArrayList<>(); + List allTasks = new ArrayList<>(); + Date yesterday = Date.from(TODAY.minusDays(1).atTime(12, 0).atZone(USER_ZONE).toInstant()); + Date twentyDaysAgo = Date.from(TODAY.minusDays(20).atTime(12, 0).atZone(USER_ZONE).toInstant()); + Date monthAgo = Date.from(TODAY.minusDays(30).atTime(12, 0).atZone(USER_ZONE).toInstant()); + for (int i = 0; i < updated; i++) { + uncompletedTasks.add(mockTaskWithProject(100L + i, yesterday)); + } + allTasks.addAll(uncompletedTasks); + for (int i = 0; i < completed; i++) { + allTasks.add(mockTaskWithProject(300L + i, twentyDaysAgo)); + } + for (int i = 0; i < older; i++) { + TaskDto task = mockTaskWithProject(200L + i, monthAgo); + uncompletedTasks.add(task); + allTasks.add(task); + } + when(taskService.countTasks(any())).thenAnswer(invocation -> isUncompletedOnly(invocation.getArgument(0)) ? uncompletedTasks.size() + : allTasks.size()); + when(taskService.findLastUpdatedTasks(any(), anyInt(), anyInt())).thenAnswer(invocation -> { + List tasks = isUncompletedOnly(invocation.getArgument(0)) ? uncompletedTasks : allTasks; + int offset = invocation.getArgument(1); + int limit = invocation.getArgument(2); + return tasks.subList(Math.min(offset, tasks.size()), Math.min(offset + limit, tasks.size())); + }); + when(taskService.getTaskLogs(anyLong(), anyInt(), anyInt())).thenReturn(Collections.emptyList()); + when(commentService.getLastComment(anyLong())).thenReturn(null); + when(commentService.countComments(anyLong())).thenReturn(0); + } + + /** + * @param query a task query + * @return true when it leaves the completed tasks out + */ + private static boolean isUncompletedOnly(TaskQuery query) { + return query != null && restrictsField(query.getCondition(), "completed"); + } + + /** + * @param condition a query condition, null for none + * @param field a task field + * @return true when it, or one of its conditions, is on that field + */ + private static boolean restrictsField(Condition condition, String field) { + if (condition instanceof AggregateCondition aggregate) { + return aggregate.getConditions().stream().anyMatch(c -> restrictsField(c, field)); + } + return condition instanceof SingleCondition single && field.equals(single.getField()); + } + /** * @param createdTime when the comment was posted * @return a comment of another user, posted then, with no reply @@ -3768,12 +3937,14 @@ && isSingle(or.getConditions().get(0), SingleCondition.EQ, "priority", Priority. /** * group_by_project counts board by board with the listing's own query, then - * the open tasks of those boards only, with the same accessibility: the - * boards with the most selected tasks first, ties by name ignoring case, - * each with its open count, and project_count counting them all. Mutants: - * the counts read from another query than the listing's, the open count - * taken from the selected count, the open query not restricted to the - * boards or keeping the completed tasks, the order reversed or by id. + * the open tasks of every board the user can access, with the same + * accessibility: the boards with the most selected tasks first, ties by + * name ignoring case, each with its open count, project_count counting them + * all and open_project_count the boards holding open tasks, a board with + * none selected included (EXO-94360). Mutants: the counts read from another + * query than the listing's, the open count taken from the selected count, + * the open query restricted to the listed boards or keeping the completed + * tasks, the order reversed or by id. * * @throws Exception never */ @@ -3787,13 +3958,15 @@ public void listTasksGroupedByProjectCountsEachBoardBesideItsOpenTasks() throws new ProjectTaskCountDto(8L, "Alpha", 3L)), List.of(new ProjectTaskCountDto(7L, "Beta", 5L), new ProjectTaskCountDto(8L, "Alpha", 3L), - new ProjectTaskCountDto(9L, "zeta", 4L))); + new ProjectTaskCountDto(9L, "zeta", 4L), + new ProjectTaskCountDto(10L, "Gamma", 2L))); TaskCollectionModel result = tool.listTasks(null, true, false, null, null, null, null, null, null, null, null, null, true, null, null, true, null); assertSame(listed.getValue(), counted.getAllValues().get(0)); TaskQuery open = counted.getAllValues().get(1); - assertTrue(conjunction(open).stream().anyMatch(c -> isSingle(c, SingleCondition.IN, "status.project.id", List.of(8L, 9L, 7L)))); + assertFalse("the open tasks are counted on every board", + conjunction(open).stream().anyMatch(c -> c instanceof SingleCondition in && "status.project.id".equals(in.getField()))); assertTrue(selectsOpenTasksOnly(open)); assertTrue(scopedToTheUser(open)); assertFalse("the open count is every open task of the board the user can access", hasDueDateCondition(open)); @@ -3802,13 +3975,14 @@ public void listTasksGroupedByProjectCountsEachBoardBesideItsOpenTasks() throws new ProjectTaskCountModel(7L, "Beta", 1L, 5L)), result.getProjects()); assertEquals(Integer.valueOf(3), result.getProjectCount()); + assertEquals(Integer.valueOf(4), result.getOpenProjectCount()); } /** - * Without group_by_project, the answer carries no board counts and no - * grouped count runs; with it and no board holding a selected task, the - * counts are empty and the open tasks are not counted. Mutants: the counts - * always computed, or the open count run on an empty set of boards. + * Without group_by_project, the answer carries no board counts, no summary + * and no grouped count runs; with it and no board holding a selected task, + * the counts are empty and the open tasks are still counted, for + * open_project_count (EXO-94360). Mutant: the counts always computed. * * @throws Exception never */ @@ -3819,21 +3993,26 @@ public void listTasksCountsBoardsOnlyWhenAsked() throws Exception { // NOSONAR TaskCollectionModel plain = tool.listTasks(null, true, false, null, null, null, null, null, null, null, null, null, true, null, null, null, null); assertNull(plain.getProjects()); assertNull(plain.getProjectCount()); + assertNull(plain.getSummary()); + assertNull(plain.getOpenProjectCount()); verify(taskService, never()).countTasksByProject(any()); when(taskService.countTasksByProject(any())).thenReturn(List.of()); TaskCollectionModel none = tool.listTasks(null, true, false, null, null, null, null, null, null, null, null, null, true, null, null, true, null); assertEquals(List.of(), none.getProjects()); assertEquals(Integer.valueOf(0), none.getProjectCount()); - verify(taskService, times(1)).countTasksByProject(any()); + assertEquals(Integer.valueOf(0), none.getOpenProjectCount()); + verify(taskService, times(2)).countTasksByProject(any()); } /** * The board counts list {@value TaskMcpTool#MAX_PROJECT_COUNTS} boards at * most, those with the most selected tasks, while project_count counts - * every board, and the open tasks are counted on the listed boards only. - * Mutants: the cap dropped, or applied before the sort; the open count - * run on every board. + * every board and projects_not_listed the boards left out, and the + * personal tasks are the count less the tasks of every board, the board + * left out included (EXO-94360). Mutants: the cap dropped, or applied + * before the sort; the boards left out not counted; the personal tasks + * counted from the listed boards only. * * @throws Exception never */ @@ -3846,22 +4025,163 @@ public void listTasksGroupedByProjectListsTheBusiestBoardsFirst() throws Excepti } ArgumentCaptor counted = ArgumentCaptor.forClass(TaskQuery.class); when(taskService.countTasksByProject(counted.capture())).thenReturn(counts, List.of()); + long onBoards = counts.stream().mapToLong(ProjectTaskCountDto::getCount).sum(); + when(taskService.countTasks(any())).thenReturn((int) onBoards + 7); TaskCollectionModel result = tool.listTasks(null, true, false, null, null, null, null, null, null, null, null, null, true, null, null, true, null); - List listedBoards = new ArrayList<>(); - for (long id = TaskMcpTool.MAX_PROJECT_COUNTS + 1L; id >= 2; id--) { - listedBoards.add(id); - } - assertTrue(conjunction(counted.getAllValues().get(1)).stream() - .anyMatch(c -> isSingle(c, SingleCondition.IN, "status.project.id", listedBoards))); assertEquals(TaskMcpTool.MAX_PROJECT_COUNTS, result.getProjects().size()); + assertEquals(Integer.valueOf(1), result.getProjectsNotListed()); + assertEquals("the board left out holds 1 task, not a personal one", Long.valueOf(7L), result.getPersonalCount()); assertEquals(TaskMcpTool.MAX_PROJECT_COUNTS + 1L, result.getProjects().get(0).getProjectId()); assertEquals(2L, result.getProjects().get(TaskMcpTool.MAX_PROJECT_COUNTS - 1).getProjectId()); assertEquals(0L, result.getProjects().get(0).getOpenCount()); assertEquals(Integer.valueOf(TaskMcpTool.MAX_PROJECT_COUNTS + 1), result.getProjectCount()); } + /** + * A grouped call with a limit of 1 is made for the counts: it returns at + * most one task and says no next page remains, though more tasks match; a + * grouped call reading a real page, and an ungrouped call with a limit of + * 1, keep has_more and next_offset (EXO-94360). Mutants: has_more left on + * the counting call; has_more dropped on every grouped call; the rule + * applied without group_by_project. + * + * @throws Exception never + */ + @Test + public void listTasksGroupedCountingCallSaysNoNextPage() throws Exception { // NOSONAR + List ten = new ArrayList<>(); + for (long id = 1; id <= 10; id++) { + ten.add(mockTaskWithProject(id, new Date())); + } + when(taskService.findLastUpdatedTasks(any(), eq(0), eq(1))).thenReturn(ten.subList(0, 1)); + when(taskService.findLastUpdatedTasks(any(), eq(0), eq(10))).thenReturn(ten); + when(taskService.countTasks(any())).thenReturn(25); + when(taskService.countTasksByProject(any())).thenReturn(List.of(new ProjectTaskCountDto(8L, "Alpha", 25L))); + + TaskCollectionModel counting = runWithDateFormatMockResult(() -> tool.listTasks(null, true, false, null, 0, 1, null, null, null, null, null, null, null, null, null, true, null)); + assertFalse(counting.isHasMore()); + assertNull(counting.getNextOffset()); + JsonNode json = JSON.readTree(JSON.writeValueAsString(counting)); + assertFalse(json.path("has_more").asBoolean()); + assertFalse(json.has("next_offset")); + assertEquals(25, json.path("count").asInt()); + + TaskCollectionModel page = runWithDateFormatMockResult(() -> tool.listTasks(null, true, false, null, 0, 10, null, null, null, null, null, null, null, null, null, true, null)); + assertTrue(page.isHasMore()); + assertEquals(Integer.valueOf(10), page.getNextOffset()); + + TaskCollectionModel plain = runWithDateFormatMockResult(() -> tool.listTasks(null, true, false, null, 0, 1, null, null, null, null, null, null, null, null, null, null, null)); + assertTrue(plain.isHasMore()); + assertEquals(Integer.valueOf(1), plain.getNextOffset()); + } + + /** + * The grouped answer counts the boards holding open tasks the user can + * access, the boards left out of the list and the selected personal tasks, + * which are on no board: the count less the tasks of every board, those + * left out of the list included; its summary states them, under the JSON + * names the definition gives (EXO-94360). Mutants: the personal tasks not + * subtracted; the open boards counted from the selected ones. + * + * @throws Exception never + */ + @Test + public void listTasksGroupedCountsOpenBoardsAndPersonalTasks() throws Exception { // NOSONAR + when(taskService.findLastUpdatedTasks(any(), eq(0), eq(10))).thenReturn(Collections.emptyList()); + when(taskService.countTasks(any())).thenReturn(60); + when(taskService.countTasksByProject(any())).thenReturn(List.of(new ProjectTaskCountDto(8L, "Alpha", 30L), + new ProjectTaskCountDto(9L, "Beta", 20L)), + List.of(new ProjectTaskCountDto(8L, "Alpha", 50L), + new ProjectTaskCountDto(9L, "Beta", 20L), + new ProjectTaskCountDto(10L, "Gamma", 5L))); + + TaskCollectionModel result = tool.listTasks(null, true, false, null, null, null, null, null, null, null, null, null, null, null, null, true, null); + + assertEquals(Long.valueOf(10L), result.getPersonalCount()); + assertEquals(Integer.valueOf(3), result.getOpenProjectCount()); + assertEquals(Integer.valueOf(0), result.getProjectsNotListed()); + assertEquals(50L, result.getProjects().get(0).getOpenCount()); + assertEquals("60 open tasks: 50 in 2 of 3 boards, 10 personal", result.getSummary()); + JsonNode json = JSON.readTree(JSON.writeValueAsString(result)); + assertEquals(3, json.path("open_project_count").asInt()); + assertEquals(0, json.path("projects_not_listed").asInt()); + assertEquals(10, json.path("personal_count").asInt()); + assertEquals(result.getSummary(), json.path("summary").asText()); + } + + /** + * The summary names the filters the call applied: overdue and open before + * « tasks », the others after it in the tool's order; it counts the boards + * among the boards holding open tasks only when the listing selects open + * tasks only, which hide_completed_tasks with completed_since does not, and + * says when the list leaves boards out (EXO-94360). Mutants: « overdue » + * always written; « open » or « of » the open boards when completed tasks + * are included; a filter left out; the singular lost; « 0 in 0 boards » + * written when every task is personal. + */ + @Test + public void groupedSummaryNamesTheFiltersApplied() { // NOSONAR + assertEquals("260 overdue open tasks in 29 of 86 boards", + TaskMcpTool.getGroupedSummary(grouped(260, 29, 86, 0, 0), + new TaskMcpTool.ListingFilters(true, false, false, null, null, null, null, null, null, null, null))); + assertEquals("41 tasks in 12 boards", + TaskMcpTool.getGroupedSummary(grouped(41, 12, 86, 0, 0), + new TaskMcpTool.ListingFilters(false, false, false, null, null, null, null, null, null, null, null))); + assertEquals("1 task in 1 board", + TaskMcpTool.getGroupedSummary(grouped(1, 1, 5, 0, 0), + new TaskMcpTool.ListingFilters(false, false, false, null, null, null, null, null, null, null, null))); + assertEquals("7 open tasks of priority high whose title contains \"Report\" assigned to john in status 4 due from 2026-11-01 to 2026-11-30" + + " changed since 2026-11-02 in 3 of 9 boards", + TaskMcpTool.getGroupedSummary(grouped(7, 3, 9, 0, 0), + new TaskMcpTool.ListingFilters(false, + true, + false, + "2026-11-01", + "2026-11-30", + Priority.HIGH, + "john", + 4L, + " Report ", + "2026-11-02", + null))); + assertEquals("2 open tasks with no priority with no due date in 1 of 1 board", + TaskMcpTool.getGroupedSummary(grouped(2, 1, 1, 0, 0), + new TaskMcpTool.ListingFilters(false, true, true, null, null, Priority.NONE, null, null, null, null, null))); + assertEquals("3 tasks due until 2026-11-30 completed since 2026-11-01 in 2 boards", + TaskMcpTool.getGroupedSummary(grouped(3, 2, 9, 0, 0), + new TaskMcpTool.ListingFilters(false, true, false, null, "2026-11-30", null, null, null, null, null, "2026-11-01"))); + assertEquals("3 overdue open tasks, all personal, on no board", + TaskMcpTool.getGroupedSummary(grouped(3, 0, 4, 3, 0), + new TaskMcpTool.ListingFilters(true, false, false, null, null, null, null, null, null, null, null))); + assertEquals("150 tasks in 101 boards; the 100 boards with the most are listed", + TaskMcpTool.getGroupedSummary(grouped(150, 101, 120, 0, 1), + new TaskMcpTool.ListingFilters(false, false, false, null, null, null, null, null, null, null, null))); + } + + /** + * @param count the count of the tasks selected + * @param boards the boards holding them + * @param openBoards the boards holding open tasks + * @param personal the personal tasks among them + * @param notListed the boards left out of the list + * @return a grouped answer with those counts, listing every other board + */ + private static TaskCollectionModel grouped(long count, int boards, int openBoards, long personal, int notListed) { + TaskCollectionModel collection = new TaskCollectionModel(Collections.emptyList(), 0, 1, count, false, null); + List listed = new ArrayList<>(); + for (long id = 1; id <= boards - notListed; id++) { + listed.add(new ProjectTaskCountModel(id, "Board " + id, 1L, 1L)); + } + collection.setProjects(listed); + collection.setProjectCount(boards); + collection.setOpenProjectCount(openBoards); + collection.setPersonalCount(personal); + collection.setProjectsNotListed(notListed); + return collection; + } + /** * A due range on list_assigned_tasks narrows the user's open tasks to those * due in it, both whole days in the user's time zone; without one, no diff --git a/services/src/test/java/io/meeds/task/mcp/TaskToolDefinitionUpgradesTest.java b/services/src/test/java/io/meeds/task/mcp/TaskToolDefinitionUpgradesTest.java index 66097b2b1..a76e2d8ca 100644 --- a/services/src/test/java/io/meeds/task/mcp/TaskToolDefinitionUpgradesTest.java +++ b/services/src/test/java/io/meeds/task/mcp/TaskToolDefinitionUpgradesTest.java @@ -54,11 +54,13 @@ public class TaskToolDefinitionUpgradesTest { /** How many earlier definitions of each changed tool the history of every ref holds. */ private static final Map EARLIER_DEFINITIONS = Map.of("list_tasks", - 22, + 23, "list_assigned_tasks", 15, "list_projects", - 5); + 5, + "list_project_activity_since", + 1); /** * The definitions feature/rtd shipped before EXO-94250, which the @@ -96,10 +98,26 @@ public class TaskToolDefinitionUpgradesTest { Map.of("list_assigned_tasks", "b184d4331d207cc11557d2a50596ca5a9f1ee9e178a8ad29a257188bcd309c63"); + /** + * The definition every line shipped before list_project_activity_since was + * capped (EXO-94377), the only one it ever had. + */ + private static final Map DEFINITIONS_BEFORE_94377 = + Map.of("list_project_activity_since", + "0648b6b3cc88c4567304a1730b8a9ac39b7f69a62acddd8c2aa2235831c15b04"); + + /** + * The definition of list_tasks feature/rtd shipped before the grouped + * answer's board counts and summary (EXO-94360). + */ + private static final Map DEFINITIONS_BEFORE_94360 = + Map.of("list_tasks", + "2b53f023e39465e999c43f9d33f7ae28dc3e78340a9e53d79f9c5f8eee831642"); + /** * Each changed tool lists every earlier definition, those shipped before - * EXO-94250, before EXO-94284, before managed_only and before the relation - * included, and not its + * EXO-94250, before EXO-94284, before managed_only, before the relation, + * before EXO-94377 and before EXO-94360 included, and not its * shipped one, which an instance already holding it keeps anyway. Mutants: * a digest removed, the shipped digest added, a tool's entry dropped. * @@ -118,7 +136,9 @@ public void eachChangedToolListsItsEarlierDefinitionsOnly() throws Exception { / for (Map pinned : List.of(DEFINITIONS_BEFORE_94250, DEFINITIONS_BEFORE_94284, DEFINITIONS_BEFORE_MANAGED_ONLY, - DEFINITIONS_BEFORE_RELATION)) { + DEFINITIONS_BEFORE_RELATION, + DEFINITIONS_BEFORE_94377, + DEFINITIONS_BEFORE_94360)) { if (pinned.containsKey(name)) { assertTrue(name, digests.contains(pinned.get(name))); }