agl 43.8.0 → 43.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/changelog.md +16 -0
  2. package/dist_serve/bundle.js +317 -304
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +824 -6
  6. package/dist_ts/aglapi/interfaces.d.ts +8 -0
  7. package/dist_ts/aglapi/interfaces.js +3 -1
  8. package/dist_ts/classes.mcpclient.js +3 -3
  9. package/dist_ts/classes.mcpcontrollerhost.js +3 -2
  10. package/dist_ts/classes.mcptools.d.ts +1 -1
  11. package/dist_ts/classes.mcptools.js +2 -1
  12. package/dist_ts/classes.ticketstore.d.ts +3 -3
  13. package/dist_ts/classes.ticketstore.js +23 -4
  14. package/dist_ts/functions.deviceapi.js +3 -1
  15. package/dist_ts/functions.mcptickettools.d.ts +60 -0
  16. package/dist_ts/functions.mcptickettools.js +4 -3
  17. package/dist_ts/functions.ticketcli.d.ts +4 -2
  18. package/dist_ts/functions.ticketcli.js +70 -4
  19. package/dist_ts/functions.ticketlisting.d.ts +38 -0
  20. package/dist_ts/functions.ticketlisting.js +211 -0
  21. package/dist_ts/functions.ticketvalidation.d.ts +62 -0
  22. package/dist_ts/functions.ticketvalidation.js +41 -3
  23. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  24. package/dist_ts_interfaces/requests.tickets.d.ts +31 -3
  25. package/dist_ts_interfaces/requests.tickets.js +2 -2
  26. package/dist_ts_interfaces/tickets.d.ts +174 -2
  27. package/dist_ts_interfaces/tickets.js +20 -2
  28. package/package.json +2 -2
  29. package/readme.md +31 -3
  30. package/ts/00_commitinfo_data.ts +1 -1
  31. package/ts/aglapi/aglapisurface.document.ts +823 -5
  32. package/ts/aglapi/interfaces.ts +2 -0
  33. package/ts/classes.mcpclient.ts +2 -2
  34. package/ts/classes.mcpcontrollerhost.ts +2 -1
  35. package/ts/classes.mcptools.ts +1 -0
  36. package/ts/classes.ticketstore.ts +21 -3
  37. package/ts/functions.deviceapi.ts +2 -0
  38. package/ts/functions.mcptickettools.ts +3 -2
  39. package/ts/functions.ticketcli.ts +70 -5
  40. package/ts/functions.ticketlisting.ts +214 -0
  41. package/ts/functions.ticketvalidation.ts +41 -2
  42. package/ts_interfaces/requests.tickets.ts +32 -2
  43. package/ts_interfaces/tickets.ts +136 -3
  44. package/ts_web/00_commitinfo_data.ts +1 -1
  45. package/ts_web/elements.inbox.ts +50 -9
@@ -111,6 +111,8 @@ export const aglApiMethods = {
111
111
  'agl.mcp.configuration.operation.recover': { use: 'excluded', exclusion: 'person', reason: ownerToken },
112
112
  'agl.mcp.configuration.operation.abandon': { use: 'excluded', exclusion: 'person', reason: ownerToken },
113
113
  'agl.mcp.ticket.list': { use: 'read', roles: tickets },
114
+ 'agl.mcp.ticket.page': { use: 'read', roles: tickets },
115
+ 'agl.mcp.ticket.overview': { use: 'read', roles: tickets },
114
116
  'agl.mcp.ticket.board': { use: 'read', roles: tickets },
115
117
  'agl.mcp.ticket.search': { use: 'read', roles: tickets },
116
118
  'agl.mcp.ticket.get': { use: 'read', roles: tickets },
@@ -6,7 +6,7 @@ import type { TWorkerCallerEnrollment, IWorkerCallerEnrollmentResponse } from '.
6
6
  import type { IControllerMcpWireCaller } from '../ts_interfaces/mcprequests.js';
7
7
  import type { TFleetOperation, TFleetRequest, TFleetResult, IFleetOperation } from '../ts_interfaces/fleet.js';
8
8
  import { assertFleetOperation, assertFleetWireRequest } from './fleet/functions.validation.js';
9
- import { readTicketRevisionConflict, ticketErrorMessages, type TTicketClientErrorCode, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
9
+ import { readTicketRevisionConflict, ticketErrorMessages, ticketPageErrorMessages, type TTicketClientErrorCode, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
10
10
  import { assertMcpTicketRequest, assertTicketResponse } from './functions.ticketvalidation.js';
11
11
  import { assertSessionFeedWireRequest, assertSessionFeedWireResponse } from './functions.sessionfeedvalidation.js';
12
12
  import { assertFleetDeployResponse, assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
@@ -1022,7 +1022,7 @@ export class ControllerMcpClient {
1022
1022
  const conflict = readTicketRevisionConflict(decoded.error.data);
1023
1023
  if (serverCode === 'ticket_revision_conflict' && !conflict) throw new Error('Invalid conflict metadata.');
1024
1024
  currentRevision = conflict?.currentRevision;
1025
- if (typeof serverCode === 'string' && Object.hasOwn(ticketErrorMessages, serverCode)) code = serverCode.toUpperCase() as TTicketClientErrorCode;
1025
+ if (typeof serverCode === 'string' && (Object.hasOwn(ticketErrorMessages, serverCode) || Object.hasOwn(ticketPageErrorMessages, serverCode))) code = serverCode.toUpperCase() as TTicketClientErrorCode;
1026
1026
  if (serverCode === 'controller_unavailable') code = 'CONTROLLER_UNAVAILABLE';
1027
1027
  if (serverCode === 'authentication_failed') code = 'AUTHENTICATION_FAILED';
1028
1028
  if (serverCode === 'response_limit') code = 'RESPONSE_LIMIT';
@@ -34,7 +34,7 @@ import { controllerMcpDeployMethods, type TControllerMcpDeployMethod, type TCont
34
34
  import { controllerMcpPushMethods, pushErrorCodes, type TControllerMcpPushMethod, type TControllerMcpPushTypedRequest } from '../ts_interfaces/push.js';
35
35
  import { redactPushRequest } from './functions.pushwire.js';
36
36
  import { deployErrorCodes } from './fleet/classes.deploymonitor.js';
37
- import { readTicketRevisionConflict, ticketErrorMessages, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
37
+ import { readTicketRevisionConflict, ticketErrorMessages, ticketPageErrorMessages, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
38
38
  import { ticketOperation } from './functions.ticketvalidation.js';
39
39
  import { controllerFailureJournal } from './classes.failurejournal.js';
40
40
  import { configurationErrorCodes } from './configuration/classes.configurationerror.js';
@@ -323,6 +323,7 @@ const safeTypedResponseError = (
323
323
  if (typeof code === 'string' && /^[a-z0-9_]{1,64}$/.test(code)) {
324
324
  const messages: Record<string, string> = {
325
325
  ...ticketErrorMessages,
326
+ ...ticketPageErrorMessages,
326
327
  controller_unavailable: 'The controller is not ready to accept this operation.',
327
328
  operation_limit: 'The controller is busy. Try again after current operations settle.',
328
329
  rate_limited: 'The authenticated operation rate limit was reached.',
@@ -65,6 +65,7 @@ export const aglMcpToolNames = [
65
65
  'job_wait',
66
66
  'job_stop',
67
67
  'jobs_list',
68
+ 'board_overview',
68
69
  'tickets_list',
69
70
  'ticket_get',
70
71
  'ticket_create',
@@ -5,7 +5,9 @@ import {
5
5
  type TTicketLink, type TTicketOperation, type TTicketRequest, type TTicketResponse,
6
6
  type TTicketFleetEvent, type ITicketFleetEventResult, type ITicketComment, type TTicketData, type ITicketOpenQuestion, type TTicketAutoLabel,
7
7
  type ITicketDetail, type ITicketGet, type ITicketAsk, type ITicketMaintenanceWindow, ticketHistoryPage,
8
+ type ITicketOverviewRequest, type ITicketPageRequest, ticketPageErrorMessages,
8
9
  } from '../ts_interfaces/tickets.js';
10
+ import { TicketCursorError, ticketOverview, ticketPage } from './functions.ticketlisting.js';
9
11
  import {
10
12
  TicketModel, TicketBoardModel, TicketCommentModel, TicketActivityModel, TicketQuestionModel, TicketFleetEventModel,
11
13
  } from './classes.ticketmodels.js';
@@ -62,7 +64,7 @@ interface ITicketTrack {
62
64
  * lost (`concurrent_change`, nothing written), a transaction whose commit outcome is unknown (`outcome_unknown`), a
63
65
  * fleet event key that names another request, and an owner capability the controller could not verify.
64
66
  */
65
- export type TTicketErrorCode = keyof typeof ticketErrorMessages | 'concurrent_change' | 'outcome_unknown'
67
+ export type TTicketErrorCode = keyof typeof ticketErrorMessages | keyof typeof ticketPageErrorMessages | 'concurrent_change' | 'outcome_unknown'
66
68
  | 'ticket_fleet_event_conflict' | 'unauthorized';
67
69
 
68
70
  export class TicketError extends Error {
@@ -449,7 +451,7 @@ export class TicketStore {
449
451
  public async execute<TMethod extends TTicketOperation>(
450
452
  methodArg: TMethod, requestArg: TTicketRequest<TMethod>, actorArg: ITicketActor | undefined, signalArg?: AbortSignal,
451
453
  ): Promise<TTicketResponse<TMethod>> {
452
- if (actorArg === undefined && methodArg !== 'list' && methodArg !== 'get') {
454
+ if (actorArg === undefined && methodArg !== 'list' && methodArg !== 'get' && methodArg !== 'page' && methodArg !== 'overview') {
453
455
  throw new TicketError('ticket_identity_required', ticketErrorMessages.ticket_identity_required);
454
456
  }
455
457
  const actor = actorArg === undefined ? undefined : ticketActorSchema.parse(actorArg);
@@ -792,7 +794,7 @@ export class TicketStore {
792
794
  }
793
795
 
794
796
  /**
795
- * Each operation reads what it decides on and nothing more: the listing operations read the whole board and every
797
+ * Each operation reads what it decides on and nothing more: the listing operations (list, board, search, page, overview) read the whole board and every
796
798
  * open question; create the parent and the destination column's count; move the source and destination columns;
797
799
  * update the ticket, its parent and, when the project changes, its children; every other operation one ticket, and
798
800
  * get one page of its history or, with `commentId`, that one comment. The board document's revision transition in the caller orders every mutation.
@@ -800,6 +802,22 @@ export class TicketStore {
800
802
  private async perform(methodArg: TTicketOperation, requestArg: TTicketRequest<TTicketOperation>, actorArg: ITicketActor | undefined,
801
803
  sessionArg: TSession, nowArg: string, sequenceArg: number,
802
804
  revisionArg: number, trackArg: ITicketTrack): Promise<unknown> {
805
+ if (methodArg === 'page' || methodArg === 'overview') {
806
+ // Reads what `list` reads; `functions.ticketlisting.ts` pages or summarizes it without another read.
807
+ const request = requestArg as ITicketPageRequest & ITicketOverviewRequest;
808
+ const all = await this.allTickets(sessionArg);
809
+ await this.countOpenQuestions(trackArg, sessionArg);
810
+ const matches = ticketFilter(methodArg === 'page' ? request : { mine: request.mine, project: request.project }, actorArg);
811
+ const tickets = all.map((recordArg) => this.visible(recordArg.ticket, actorArg, trackArg)).filter(matches);
812
+ const openQuestions = (ticketIdArg: string): number => trackArg.openQuestions.get(ticketIdArg) ?? 0;
813
+ try {
814
+ return methodArg === 'page' ? ticketPage(tickets, request, revisionArg, openQuestions, actorArg?.sessionId ?? actorArg?.id)
815
+ : ticketOverview(tickets, request, revisionArg, nowArg, openQuestions);
816
+ } catch (errorArg) {
817
+ if (errorArg instanceof TicketCursorError) throw new TicketError(errorArg.code, ticketPageErrorMessages[errorArg.code]);
818
+ throw errorArg;
819
+ }
820
+ }
803
821
  if (methodArg === 'list' || methodArg === 'board' || methodArg === 'search') {
804
822
  const filters: ITicketFilters = methodArg === 'search'
805
823
  ? { text: (requestArg as TTicketRequest<'search'>).query, label: (requestArg as TTicketRequest<'search'>).label }
@@ -455,6 +455,8 @@ const deviceTicketStoreRefusals: Readonly<Record<Exclude<TTicketErrorCode, keyof
455
455
  outcome_unknown: 'outcome_unknown',
456
456
  ticket_fleet_event_conflict: 'invalid_request',
457
457
  unauthorized: 'invalid_request',
458
+ ticket_cursor_invalid: 'invalid_request',
459
+ ticket_cursor_mismatch: 'invalid_request',
458
460
  };
459
461
 
460
462
  const deviceTicketCodes: ReadonlySet<string> = new Set(deviceTicketRefusalCodes);
@@ -3,7 +3,8 @@ import type { TTicketOperation } from '../ts_interfaces/tickets.js';
3
3
 
4
4
  const workflow = ' Caller identity comes from AGL, never a supplied name. Unidentified callers may list/get tickets with empty mine; every mutation requires a verified caller. Workers create in backlog and may update/move only their assigned tickets within ready, in_progress, needs_input and review. Link a branch with a full sha before Review. Only the driver or owner assigns, lands, releases or closes tickets.';
5
5
  export const ticketToolDefinitions = [
6
- { name: 'tickets_list', operation: 'list', description: 'Read the shared board across all projects. Filter by mine, project, status, label or text. mine uses your verified session. label also matches AutoLabels, which AGL computes and nobody sets: openQuestion marks a ticket with an unanswered question, planned a ticket that is not done and plans a release, a deploy or a maintenance window, undeployed a ticket released in a version some deploy target of its repository does not run yet.' },
6
+ { name: 'board_overview', operation: 'overview', description: 'Read the whole board at a glance in one bounded answer, without any ticket\'s texts; start here. Counts by column, by priority (open tickets), by AutoLabel, by project and by assignee, each open epic\'s progress over its direct children (children, done, columns), and under attention the tickets that need someone: urgent, needsInput, openQuestions, review, unassignedReady and stale (in_progress, needs_input or review work without a change for staleDays, default 3, oldest first). recent holds the tickets changed last. Every list holds at most limit tickets (default 5, at most 50) as summaries and its total counts all of them; projects, assignees and epics list at most 50 beside projectsTotal, assigneesTotal and epicsTotal. project narrows to one project, mine to your verified session. Continue with tickets_list for a whole list and ticket_get for one ticket.' },
7
+ { name: 'tickets_list', operation: 'page', description: 'List the shared board across all projects in pages of limit tickets (1-200, default 50; a page also ends at 256 KiB). Tickets are summaries: key, revision, project, kind, title, columnId, priority, updatedAt, and where present assignee, parentId, labels, autoLabels, links (a count per kind), releasePlan, deployPlan, maintenanceWindow and openQuestions; view full returns whole tickets with description and source words, ticket_get one ticket with its history. total and columns (a count per column) describe everything the filters match, on every page, so a page never hides how much there is. Filter by mine (your verified session), project, status or statuses (several columns), open (true leaves out released and closed, false keeps only those), kind, priorities, parent (a ticket\'s direct children, such as an epic\'s tasks), assignee (a person id or a session id as a ticket shows it, never a name), unassigned, keys (up to 200 tickets by key in one call), updatedSince (an ISO 8601 instant), label or text (in key, title, description or source words). label also matches AutoLabels, which AGL computes and nobody sets: openQuestion marks a ticket with an unanswered question, planned a ticket that is not done and plans a release, a deploy or a maintenance window, undeployed a ticket released in a version some deploy target of its repository does not run yet. sort is board (default: by column, then position), updated or created (newest first) or priority (urgent first). Continue with nextCursor and the same filters, sort and view; a cursor of other ones is refused. moved tells that the board changed since the first page: a ticket that changed its place meanwhile may be missing or shown twice, so list again when the reading must be exact.' },
7
8
  { name: 'ticket_get', operation: 'get', description: 'Read a ticket by its AGL-<n> key: source, links, all its questions and their answers, and the newest page of its history, oldest first: up to limit entries (default 50, at most 500), fewer when the entries and their comments would pass 256 KiB. activity is the page; comments are the markdown comments it names, and a commented entry names its comment by id. historyBefore is present while older history exists: pass it as before for the next older page. commentId instead reads the one comment an activity entry or fleet event names (without before or limit).' },
8
9
  { name: 'ticket_create', operation: 'create', description: 'Capture discussed work as a ticket. Include project, title, description and sourceText (the original words); optional attachments are named URLs. Worker-created tickets start in backlog for driver triage. The driver or owner may give it a releasePlan (repo as org/name of a fleet repository, optional version such as 41.0.0; without a version it means the next release), a deployPlan (a deploy target and the release version it should run: AGL asks the owner on the ticket whether to deploy it now, in the next maintenance window, or to hold) or a maintenanceWindow (from and to as ISO 8601 instants, at most 7 days, and the deploy targets it is for); one the driver plans asks the owner and counts once the owner approves it, the owner\'s own counts at once.' },
9
10
  { name: 'ticket_update', operation: 'update', description: 'Update the title, markdown description, priority, labels, project or parent of your assigned ticket. Supply expectedRevision from the ticket you read; stale edits return TICKET_REVISION_CONFLICT with currentRevision. Reload before editing again. Status is changed only with ticket_move; assignment is driver/owner-only. releasePlan (driver/owner only) plans a release: repo as org/name of a fleet repository and an optional version; null clears it. A hotfix is a release plan on an urgent ticket, without a version. fleet_release for the ticket refuses another repository and stops when gitzone plans another version. deployPlan (driver/owner only) plans a deploy and asks the owner its question; once asked it keeps its target and version (setting the same plan again asks anew once the owner answered; closing the ticket drops it; a deploy ticket holds no code or release: a ticket that does, or that is done, plans none, and one with a plan takes no branch, commit or release link), and AGL closes the ticket once the target runs the release. maintenanceWindow (driver/owner only) plans or moves a window; null removes it, and closing the ticket cancels it. A window the driver plans or moves asks the owner and counts once approved; while that question is open it does not change.' },
@@ -14,4 +15,4 @@ export const ticketToolDefinitions = [
14
15
  { name: 'ticket_question_ask', operation: 'ask', description: 'Ask the owner a question on your assigned ticket. question is markdown; options are up to 20 choices (label, optional description), multiSelect allows several, allowCustom (default true) allows a free-text answer. The ticket shows the openQuestion AutoLabel until the owner or driver answers; the answer arrives in your session as a ticket notice. Keep working on what the question does not block.' },
15
16
  ].map((definitionArg) => ({ ...definitionArg, operation: definitionArg.operation as TTicketOperation,
16
17
  description: definitionArg.description + workflow, inputSchema: ticketInputSchemas[definitionArg.operation as TTicketOperation],
17
- readOnly: definitionArg.operation === 'list' || definitionArg.operation === 'get' }));
18
+ readOnly: definitionArg.operation === 'page' || definitionArg.operation === 'overview' || definitionArg.operation === 'get' }));
@@ -4,11 +4,27 @@ import { withLocalConfigurationOwner } from './functions.configurationowner.js';
4
4
  import { assertTicketRequest } from './functions.ticketvalidation.js';
5
5
  import { defaultControllerPort } from './classes.config.js';
6
6
  import type {
7
- ITicketChanges, ITicketDeployPlanInput, ITicketMaintenanceWindow, ITicketPerson, TTicketOperation, TTicketRequest, TTicketLink,
7
+ ITicketChanges, ITicketDeployPlanInput, ITicketMaintenanceWindow, ITicketOverview, ITicketPerson, ITicketSummary, TTicketOperation,
8
+ TTicketRequest, TTicketLink,
8
9
  } from '../ts_interfaces/tickets.js';
9
10
 
10
- export const ticketCliHelp = `Usage: agl ticket <list|get|create|update|move|comment|link|unlink|assign|ask|answer> [AGL-<n>] [options]
11
+ export const ticketCliHelp = `Usage: agl ticket <overview|page|list|get|create|update|move|comment|link|unlink|assign|ask|answer> [AGL-<n>] [options]
12
+ overview [--project ID] [--mine] [--limit N] [--stale-days N]
13
+ The board at a glance: counts by column, priority, AutoLabel, project and assignee, each open epic's
14
+ progress, the tickets that need someone (urgent, needs input, open questions, review, ready without an
15
+ assignee, stale after N days without a change, default 3) and the tickets changed last. Lists hold at
16
+ most --limit tickets (default 5, at most 50) and name how many there are in all.
17
+ page [--mine] [--project ID] [--status COLUMN] [--statuses COLUMN,…] [--open|--done] [--kind epic|task|subtask]
18
+ [--priorities PRIORITY,…] [--parent AGL-<n>] [--assignee ID] [--unassigned] [--keys AGL-<n>,…]
19
+ [--since INSTANT] [--label LABEL] [--text TEXT] [--sort board|updated|created|priority] [--full]
20
+ [--limit N] [--cursor CURSOR]
21
+ One page of the board (default 50 tickets, at most 200, within 256 KiB) as summaries without description
22
+ and source words; --full returns whole tickets. total and columns count everything the filters match.
23
+ --open leaves out released and closed tickets, --done keeps only those; --parent lists a ticket's direct
24
+ children; --assignee is a person id or a session id; --since an ISO 8601 instant of the last change.
25
+ nextCursor names the next page: pass it as --cursor with the same filters, sort and view.
11
26
  list [--mine] [--project ID] [--status COLUMN] [--label LABEL] [--text TEXT]
27
+ Every matching ticket whole and unpaged; prefer page on a large board.
12
28
  --label also matches AutoLabels, which AGL computes: openQuestion (an unanswered question),
13
29
  planned (a release plan on a ticket not yet released)
14
30
  get AGL-<n> [--limit N] [--before HISTORY-ID] [--comment COMMENT-ID]
@@ -73,6 +89,9 @@ export interface ITicketCliArguments {
73
89
  const common = ['port', 'json'];
74
90
  const actionOptions: Record<string, string[]> = {
75
91
  list: ['mine', 'project', 'status', 'label', 'text'], get: ['limit', 'before', 'comment'],
92
+ page: ['mine', 'project', 'status', 'statuses', 'open', 'done', 'kind', 'priorities', 'parent', 'assignee', 'unassigned', 'keys',
93
+ 'since', 'label', 'text', 'sort', 'full', 'limit', 'cursor'],
94
+ overview: ['project', 'mine', 'limit', 'stale-days'],
76
95
  create: ['project', 'title', 'description', 'kind', 'parent', 'priority', 'labels', 'source', 'attachments', 'column', 'release-plan',
77
96
  'deploy-plan', 'window', 'window-targets'],
78
97
  update: ['expected-revision', 'changes', 'title', 'description', 'priority', 'project', 'labels', 'parent', 'clear-parent',
@@ -82,7 +101,7 @@ const actionOptions: Record<string, string[]> = {
82
101
  assign: ['expected-revision', 'session-id', 'assignee', 'name', 'kind', 'clear'],
83
102
  ask: ['text', 'options', 'multi', 'no-custom'], answer: ['question', 'choice', 'text'],
84
103
  };
85
- const booleanOptions = new Set(['json', 'mine', 'clear', 'clear-parent', 'clear-release-plan', 'clear-window', 'multi', 'no-custom']);
104
+ const booleanOptions = new Set(['json', 'mine', 'open', 'done', 'unassigned', 'full', 'clear', 'clear-parent', 'clear-release-plan', 'clear-window', 'multi', 'no-custom']);
86
105
 
87
106
  /** `REPO[@VERSION]`: the repository a release plan names and, after the last `@`, the version it should reach. */
88
107
  export const parseReleasePlanOption = (valueArg: string): { repo: string; version?: string } => {
@@ -112,7 +131,7 @@ export const parseTicketCliArguments = (argumentsArg: string[]): ITicketCliArgum
112
131
  const [action, ...argumentsRest] = argumentsArg;
113
132
  if (!action || !Object.hasOwn(actionOptions, action)) throw new Error(ticketCliHelp);
114
133
  const rest = [...argumentsRest];
115
- const ticketId = action === 'list' || action === 'create' ? undefined : rest.shift();
134
+ const ticketId = ['list', 'page', 'overview', 'create'].includes(action) ? undefined : rest.shift();
116
135
  const allowed = new Set([...common, ...actionOptions[action]!]);
117
136
  const options = new Map<string, string>();
118
137
  for (let index = 0; index < rest.length; index++) {
@@ -159,6 +178,19 @@ export const parseTicketCliArguments = (argumentsArg: string[]): ITicketCliArgum
159
178
  };
160
179
  if (action === 'list') request = { ...(options.has('mine') ? { mine: true } : {}), ...optional('project'),
161
180
  ...optional('status'), ...optional('label'), ...optional('text') };
181
+ else if (action === 'page') {
182
+ if (options.has('open') && options.has('done')) throw new Error('--open and --done conflict.');
183
+ const list = (keyArg: string, fieldArg = keyArg) => options.has(keyArg)
184
+ ? { [fieldArg]: options.get(keyArg)!.split(',').map((valueArg) => valueArg.trim()).filter(Boolean) } : {};
185
+ request = { ...(options.has('mine') ? { mine: true } : {}), ...optional('project'), ...optional('status'), ...list('statuses'),
186
+ ...(options.has('open') ? { open: true } : {}), ...(options.has('done') ? { open: false } : {}), ...optional('kind'),
187
+ ...list('priorities'), ...optional('parent'), ...optional('assignee'), ...(options.has('unassigned') ? { unassigned: true } : {}),
188
+ ...list('keys'), ...optional('since', 'updatedSince'), ...optional('label'), ...optional('text'), ...optional('sort'),
189
+ ...(options.has('full') ? { view: 'full' } : {}), ...(options.has('limit') ? { limit: Number(required('limit')) } : {}),
190
+ ...optional('cursor') };
191
+ } else if (action === 'overview') request = { ...optional('project'), ...(options.has('mine') ? { mine: true } : {}),
192
+ ...(options.has('limit') ? { limit: Number(required('limit')) } : {}),
193
+ ...(options.has('stale-days') ? { staleDays: Number(required('stale-days')) } : {}) };
162
194
  else if (action === 'get') request = { ticketId, ...optional('before'), ...optional('comment', 'commentId'),
163
195
  ...(options.has('limit') ? { limit: Number(required('limit')) } : {}) };
164
196
  else if (action === 'create') request = { project: required('project'), title: required('title'), ...optional('description'),
@@ -210,11 +242,44 @@ export const parseTicketCliArguments = (argumentsArg: string[]): ITicketCliArgum
210
242
  return { operation, request: assertTicketRequest(operation, request), port, json: options.has('json') };
211
243
  };
212
244
 
245
+ const counts = (countsArg: Record<string, number>): string => Object.entries(countsArg).filter(([, countArg]) => countArg > 0)
246
+ .map(([nameArg, countArg]) => `${nameArg} ${countArg}`).join(', ') || 'none';
247
+ const summaryLine = (ticketArg: Pick<ITicketSummary, 'key' | 'project' | 'columnId' | 'priority' | 'title' | 'assignee'>): string => (
248
+ `${ticketArg.key}\t${ticketArg.project}\t${ticketArg.columnId}\t${ticketArg.priority}\t${ticketArg.assignee?.name ?? '-'}\t${ticketArg.title}\n`);
249
+ /** The overview as text: the counts, then each list with what it stands for. */
250
+ export const formatTicketOverview = (overviewArg: ITicketOverview): string => {
251
+ const lines = [`Board revision ${overviewArg.revision}: ${overviewArg.total} tickets, ${overviewArg.open} open, ${overviewArg.unassignedOpen} open without an assignee\n`,
252
+ `Columns: ${counts(overviewArg.columns)}\n`, `Open by priority: ${counts(overviewArg.priorities)}\n`, `AutoLabels: ${counts(overviewArg.autoLabels)}\n`,
253
+ `\nProjects (${overviewArg.projects.length} of ${overviewArg.projectsTotal}):\n`,
254
+ ...overviewArg.projects.map((projectArg) => ` ${projectArg.project}\t${projectArg.open} open of ${projectArg.total}\t${counts(projectArg.columns)}\n`),
255
+ `\nAssignees (${overviewArg.assignees.length} of ${overviewArg.assigneesTotal}):\n`,
256
+ ...overviewArg.assignees.map((assigneeArg) => ` ${assigneeArg.name}\t${assigneeArg.open} open\t${counts(assigneeArg.columns)}\t${assigneeArg.sessionId ?? assigneeArg.id}\n`),
257
+ `\nOpen epics (${overviewArg.epics.length} of ${overviewArg.epicsTotal}):\n`,
258
+ ...overviewArg.epics.map((epicArg) => ` ${epicArg.key}\t${epicArg.project}\t${epicArg.done}/${epicArg.children} done\t${epicArg.title}\n`)];
259
+ const groups: [string, ITicketOverview['attention'][keyof ITicketOverview['attention']]][] = [
260
+ ['Urgent', overviewArg.attention.urgent], ['Needs input', overviewArg.attention.needsInput],
261
+ ['Open questions', overviewArg.attention.openQuestions], ['Review', overviewArg.attention.review],
262
+ ['Ready without an assignee', overviewArg.attention.unassignedReady], ['Stale', overviewArg.attention.stale]];
263
+ for (const [titleArg, groupArg] of groups) {
264
+ lines.push(`\n${titleArg} (${groupArg.tickets.length} of ${groupArg.total}):\n`, ...groupArg.tickets.map((ticketArg) => ` ${summaryLine(ticketArg)}`));
265
+ }
266
+ lines.push('\nChanged last:\n', ...overviewArg.recent.map((ticketArg) => ` ${ticketArg.updatedAt}\t${summaryLine(ticketArg)}`));
267
+ return lines.join('');
268
+ };
269
+
213
270
  export const formatTicketCliResult = (resultArg: unknown, jsonArg: boolean): string => {
214
271
  if (jsonArg) return JSON.stringify(resultArg) + '\n';
215
272
  const result = resultArg as { tickets?: { key: string; columnId: string; title: string; project: string }[];
216
- ticket?: { key: string; columnId: string; title: string; project: string } };
273
+ ticket?: { key: string; columnId: string; title: string; project: string };
274
+ view?: string; total?: number; columns?: Record<string, number>; nextCursor?: string; moved?: true; attention?: unknown };
275
+ if (result.attention !== undefined) return formatTicketOverview(resultArg as ITicketOverview);
217
276
  const tickets = result.tickets;
277
+ if (tickets && result.view !== undefined) {
278
+ return (tickets as ITicketSummary[]).map(summaryLine).join('')
279
+ + `${tickets.length} of ${result.total} (${counts(result.columns ?? {})})\n`
280
+ + (result.moved ? 'The board changed since the first page: a ticket that changed its place may be missing or shown twice.\n' : '')
281
+ + (result.nextCursor ? `Next page: --cursor ${result.nextCursor}\n` : '');
282
+ }
218
283
  return tickets ? tickets.map((ticketArg) => `${ticketArg.key}\t${ticketArg.project}\t${ticketArg.columnId}\t${ticketArg.title}\n`).join('')
219
284
  : JSON.stringify(resultArg, null, 2) + '\n';
220
285
  };
@@ -0,0 +1,214 @@
1
+ import * as plugins from './plugins.js';
2
+ import {
3
+ ticketAutoLabels, ticketColumns, ticketDoneColumns, ticketListPage, ticketOverviewDefaults, ticketPriorities,
4
+ type ITicket, type ITicketOverview, type ITicketOverviewGroup, type ITicketOverviewRequest, type ITicketPageRequest,
5
+ type ITicketSummary, type TTicketColumn, type TTicketPage, type TTicketPageSort, type TTicketPriority,
6
+ } from '../ts_interfaces/tickets.js';
7
+
8
+ /**
9
+ * Paged listings and the board overview, as pure functions over the tickets a listing shows (`TicketStore.visible`,
10
+ * already narrowed by `ticketFilter`). Nothing here reads the store: `TicketStore.perform` hands in the tickets, the
11
+ * board revision and the open-question counts one transaction read.
12
+ */
13
+
14
+ /** A cursor the store refuses: `invalid` is no `nextCursor` of a page, `mismatch` pages another filter, sort or view. */
15
+ export class TicketCursorError extends Error {
16
+ constructor(public readonly code: 'ticket_cursor_invalid' | 'ticket_cursor_mismatch') { super(code); }
17
+ }
18
+
19
+ const priorityRank: Record<TTicketPriority, number> = { urgent: 0, high: 1, normal: 2, low: 3, none: 4 };
20
+ const ticketNumber = (ticketArg: Pick<ITicket, 'key'>): number => Number(ticketArg.key.slice(4));
21
+ const isDone = (ticketArg: Pick<ITicket, 'columnId'>): boolean => ticketDoneColumns.includes(ticketArg.columnId);
22
+
23
+ /**
24
+ * Where a ticket stands in a sort, as numbers compared left to right; the ticket's number ends every key, so no two
25
+ * tickets share one. `board` is the board's own order (column, then position), `updated` and `created` newest first,
26
+ * `priority` urgent first and then the board's order.
27
+ */
28
+ export const ticketSortKey = (ticketArg: ITicket, sortArg: TTicketPageSort): number[] => {
29
+ const column = ticketColumns.indexOf(ticketArg.columnId), number = ticketNumber(ticketArg);
30
+ switch (sortArg) {
31
+ case 'board': return [column, ticketArg.order, number];
32
+ case 'updated': return [-Date.parse(ticketArg.updatedAt), number];
33
+ case 'created': return [-number];
34
+ case 'priority': return [priorityRank[ticketArg.priority], column, ticketArg.order, number];
35
+ }
36
+ };
37
+ const compareKeys = (leftArg: readonly number[], rightArg: readonly number[]): number => {
38
+ for (let index = 0; index < Math.max(leftArg.length, rightArg.length); index += 1) {
39
+ const difference = (leftArg[index] ?? 0) - (rightArg[index] ?? 0);
40
+ if (difference !== 0) return difference;
41
+ }
42
+ return 0;
43
+ };
44
+
45
+ /** What a page narrows by beyond `ticketFilter`'s own filters (mine, project, status, label, text). */
46
+ export const ticketPageNarrows = (requestArg: ITicketPageRequest): (ticketArg: ITicket) => boolean => {
47
+ const statuses = requestArg.statuses && new Set<TTicketColumn>(requestArg.statuses);
48
+ const priorities = requestArg.priorities && new Set<TTicketPriority>(requestArg.priorities);
49
+ const keys = requestArg.keys && new Set(requestArg.keys);
50
+ const since = requestArg.updatedSince === undefined ? undefined : Date.parse(requestArg.updatedSince);
51
+ return (ticketArg) => (
52
+ (!statuses || statuses.has(ticketArg.columnId))
53
+ && (requestArg.open === undefined || requestArg.open !== isDone(ticketArg))
54
+ && (!requestArg.kind || ticketArg.kind === requestArg.kind)
55
+ && (!priorities || priorities.has(ticketArg.priority))
56
+ && (!requestArg.parent || ticketArg.parentId === requestArg.parent)
57
+ && (!requestArg.assignee || ticketArg.assignee?.id === requestArg.assignee || ticketArg.assignee?.sessionId === requestArg.assignee)
58
+ && (!requestArg.unassigned || ticketArg.assignee === undefined)
59
+ && (!keys || keys.has(ticketArg.key))
60
+ && (since === undefined || Date.parse(ticketArg.updatedAt) >= since)
61
+ );
62
+ };
63
+
64
+ /** A ticket without its texts: what a listing or the overview shows of it. Empty fields are left out. */
65
+ export const ticketSummary = (ticketArg: ITicket, openQuestionsArg: number): ITicketSummary => {
66
+ const links: NonNullable<ITicketSummary['links']> = {};
67
+ for (const link of ticketArg.links) links[link.kind] = (links[link.kind] ?? 0) + 1;
68
+ return {
69
+ key: ticketArg.key, revision: ticketArg.revision, project: ticketArg.project, kind: ticketArg.kind, title: ticketArg.title,
70
+ columnId: ticketArg.columnId, priority: ticketArg.priority, updatedAt: ticketArg.updatedAt,
71
+ ...(ticketArg.assignee === undefined ? {} : { assignee: { id: ticketArg.assignee.id, name: ticketArg.assignee.name,
72
+ ...(ticketArg.assignee.sessionId === undefined ? {} : { sessionId: ticketArg.assignee.sessionId }) } }),
73
+ ...(ticketArg.parentId === undefined ? {} : { parentId: ticketArg.parentId }),
74
+ ...(ticketArg.labels.length ? { labels: [...ticketArg.labels] } : {}),
75
+ ...(ticketArg.autoLabels?.length ? { autoLabels: [...ticketArg.autoLabels] } : {}),
76
+ ...(ticketArg.links.length ? { links } : {}),
77
+ ...(ticketArg.releasePlan === undefined ? {} : { releasePlan: { ...ticketArg.releasePlan } }),
78
+ ...(ticketArg.deployPlan === undefined ? {} : { deployPlan: { target: ticketArg.deployPlan.target, version: ticketArg.deployPlan.version } }),
79
+ ...(ticketArg.maintenanceWindow === undefined ? {} : { maintenanceWindow: { from: ticketArg.maintenanceWindow.from,
80
+ to: ticketArg.maintenanceWindow.to, targets: [...ticketArg.maintenanceWindow.targets] } }),
81
+ ...(openQuestionsArg > 0 ? { openQuestions: openQuestionsArg } : {}),
82
+ };
83
+ };
84
+
85
+ interface ITicketPageCursor { filter: string; key: number[]; revision: number }
86
+ const cursorSchema = plugins.z.object({ filter: plugins.z.string().regex(/^[A-Za-z0-9_-]{22}$/u),
87
+ key: plugins.z.array(plugins.z.number().finite()).min(1).max(4), revision: plugins.z.number().int().nonnegative() }).strict();
88
+ /** The digest a cursor carries of what it pages: every filter, the sort and the view, never `limit`. */
89
+ const pageDigest = (requestArg: ITicketPageRequest, viewerArg: string | undefined): string => plugins.crypto.createHash('sha256')
90
+ .update(JSON.stringify([requestArg.mine === true ? viewerArg ?? '' : null, requestArg.project ?? null, requestArg.status ?? null,
91
+ requestArg.label ?? null, requestArg.text ?? null, requestArg.statuses ? [...requestArg.statuses].sort() : null, requestArg.open ?? null,
92
+ requestArg.kind ?? null, requestArg.priorities ? [...requestArg.priorities].sort() : null, requestArg.parent ?? null,
93
+ requestArg.assignee ?? null, requestArg.unassigned === true, requestArg.keys ? [...requestArg.keys].sort() : null,
94
+ requestArg.updatedSince ?? null, requestArg.sort ?? 'board', requestArg.view ?? 'summary'])).digest('base64url').slice(0, 22);
95
+ const encodeCursor = (cursorArg: ITicketPageCursor): string => Buffer.from(JSON.stringify(cursorArg)).toString('base64url');
96
+ const decodeCursor = (cursorArg: string): ITicketPageCursor => {
97
+ try { return cursorSchema.parse(JSON.parse(Buffer.from(cursorArg, 'base64url').toString('utf8'))); }
98
+ catch { throw new TicketCursorError('ticket_cursor_invalid'); }
99
+ };
100
+
101
+ /**
102
+ * One page of the tickets `ticketsArg` holds (those `ticketFilter` kept), narrowed by the request's further filters
103
+ * and sorted: at most `limit` tickets (`ticketListPage`) and no more than `ticketListPage.bytes` of them serialized,
104
+ * which wins over `limit`; a page holds at least one ticket. `total` and `columns` count the whole filtered set, so a
105
+ * page never hides how much there is. A cursor is a position in the sort, not a snapshot: the next page holds the
106
+ * tickets that sort after the last one shown, as the board stands now, and `moved` tells that the board changed since
107
+ * the first page, so a ticket that changed its place meanwhile may be missing or shown twice.
108
+ */
109
+ export const ticketPage = (ticketsArg: ITicket[], requestArg: ITicketPageRequest, revisionArg: number,
110
+ openQuestionsArg: (ticketIdArg: string) => number, viewerArg?: string): TTicketPage => {
111
+ const sort = requestArg.sort ?? 'board', view = requestArg.view ?? 'summary';
112
+ const filter = pageDigest(requestArg, viewerArg);
113
+ const keyed = ticketsArg.filter(ticketPageNarrows(requestArg)).map((ticketArg) => ({ ticket: ticketArg, key: ticketSortKey(ticketArg, sort) }))
114
+ .sort((leftArg, rightArg) => compareKeys(leftArg.key, rightArg.key));
115
+ const columns: TTicketPage['columns'] = {};
116
+ for (const { ticket } of keyed) columns[ticket.columnId] = (columns[ticket.columnId] ?? 0) + 1;
117
+ let start = 0, firstRevision = revisionArg;
118
+ if (requestArg.cursor !== undefined) {
119
+ const cursor = decodeCursor(requestArg.cursor);
120
+ if (cursor.filter !== filter) throw new TicketCursorError('ticket_cursor_mismatch');
121
+ firstRevision = cursor.revision;
122
+ start = keyed.findIndex((entryArg) => compareKeys(entryArg.key, cursor.key) > 0);
123
+ if (start < 0) start = keyed.length;
124
+ }
125
+ const limit = requestArg.limit ?? ticketListPage.default;
126
+ const rows: (ITicket | ITicketSummary)[] = [];
127
+ let bytes = 0, end = start;
128
+ while (end < keyed.length && rows.length < limit) {
129
+ const { ticket } = keyed[end]!;
130
+ const row = view === 'full' ? ticket : ticketSummary(ticket, openQuestionsArg(ticket.id));
131
+ const size = Buffer.byteLength(JSON.stringify(row));
132
+ if (rows.length && bytes + size > ticketListPage.bytes) break;
133
+ rows.push(row); bytes += size; end += 1;
134
+ }
135
+ return {
136
+ view, tickets: rows, total: keyed.length, columns, revision: revisionArg,
137
+ ...(end < keyed.length ? { nextCursor: encodeCursor({ filter, key: keyed[end - 1]!.key, revision: firstRevision }) } : {}),
138
+ ...(firstRevision !== revisionArg ? { moved: true } : {}),
139
+ } as TTicketPage;
140
+ };
141
+
142
+ const group = (ticketsArg: ITicket[], limitArg: number, openQuestionsArg: (ticketIdArg: string) => number): ITicketOverviewGroup => ({
143
+ total: ticketsArg.length, tickets: ticketsArg.slice(0, limitArg).map((ticketArg) => ticketSummary(ticketArg, openQuestionsArg(ticketArg.id))),
144
+ });
145
+ const byBoard = (leftArg: ITicket, rightArg: ITicket): number => compareKeys(ticketSortKey(leftArg, 'board'), ticketSortKey(rightArg, 'board'));
146
+ const byPriority = (leftArg: ITicket, rightArg: ITicket): number => compareKeys(ticketSortKey(leftArg, 'priority'), ticketSortKey(rightArg, 'priority'));
147
+ const columnCounts = (ticketsArg: ITicket[]): Partial<Record<TTicketColumn, number>> => {
148
+ const counts: Partial<Record<TTicketColumn, number>> = {};
149
+ for (const column of ticketColumns) {
150
+ const count = ticketsArg.filter((ticketArg) => ticketArg.columnId === column).length;
151
+ if (count) counts[column] = count;
152
+ }
153
+ return counts;
154
+ };
155
+
156
+ /**
157
+ * The board in one bounded answer, without any ticket's texts: counts by column, priority, AutoLabel, project and
158
+ * assignee, each open epic's progress over its direct children, the tickets that need someone (urgent, needs input,
159
+ * open questions, review, ready without an assignee, stale work) and the newest changes. Every list is cut to
160
+ * `limit` tickets (projects, assignees and epics to `ticketOverviewDefaults.groups`) and carries the count of all it
161
+ * stands for. Stale is in_progress, needs_input or review work nobody changed for `staleDays`, oldest first.
162
+ */
163
+ export const ticketOverview = (ticketsArg: ITicket[], requestArg: ITicketOverviewRequest, revisionArg: number, nowArg: string,
164
+ openQuestionsArg: (ticketIdArg: string) => number): ITicketOverview => {
165
+ const limit = requestArg.limit ?? ticketOverviewDefaults.limit;
166
+ const staleBefore = Date.parse(nowArg) - (requestArg.staleDays ?? ticketOverviewDefaults.staleDays) * 86_400_000;
167
+ const open = ticketsArg.filter((ticketArg) => !isDone(ticketArg));
168
+ const count = <TKey extends string>(keysArg: readonly TKey[], ofArg: (keyArg: TKey) => number): Record<TKey, number> => (
169
+ Object.fromEntries(keysArg.map((keyArg) => [keyArg, ofArg(keyArg)])) as Record<TKey, number>);
170
+ const projects = [...new Set(ticketsArg.map((ticketArg) => ticketArg.project))].map((projectArg) => {
171
+ const own = ticketsArg.filter((ticketArg) => ticketArg.project === projectArg);
172
+ return { project: projectArg, total: own.length, open: own.filter((ticketArg) => !isDone(ticketArg)).length, columns: columnCounts(own) };
173
+ }).sort((leftArg, rightArg) => rightArg.open - leftArg.open || rightArg.total - leftArg.total || leftArg.project.localeCompare(rightArg.project));
174
+ const assigned = new Map<string, ITicket[]>();
175
+ for (const ticket of open) {
176
+ if (!ticket.assignee) continue;
177
+ const id = ticket.assignee.sessionId ?? ticket.assignee.id;
178
+ assigned.set(id, [...(assigned.get(id) ?? []), ticket]);
179
+ }
180
+ const assignees = [...assigned.values()].map((ownArg) => {
181
+ const { id, name, sessionId } = ownArg[0]!.assignee!;
182
+ return { id, name, ...(sessionId === undefined ? {} : { sessionId }), open: ownArg.length, columns: columnCounts(ownArg) };
183
+ }).sort((leftArg, rightArg) => rightArg.open - leftArg.open || leftArg.name.localeCompare(rightArg.name));
184
+ const epics = open.filter((ticketArg) => ticketArg.kind === 'epic').sort(byBoard).map((epicArg) => {
185
+ const children = ticketsArg.filter((ticketArg) => ticketArg.parentId === epicArg.key);
186
+ return { key: epicArg.key, title: epicArg.title, project: epicArg.project, columnId: epicArg.columnId, children: children.length,
187
+ done: children.filter(isDone).length, columns: columnCounts(children) };
188
+ });
189
+ const active = new Set<TTicketColumn>(['in_progress', 'needs_input', 'review']);
190
+ const groups = ticketOverviewDefaults.groups;
191
+ return {
192
+ revision: revisionArg, total: ticketsArg.length, open: open.length,
193
+ columns: count(ticketColumns, (columnArg) => ticketsArg.filter((ticketArg) => ticketArg.columnId === columnArg).length),
194
+ priorities: count(ticketPriorities, (priorityArg) => open.filter((ticketArg) => ticketArg.priority === priorityArg).length),
195
+ autoLabels: count(ticketAutoLabels, (labelArg) => ticketsArg.filter((ticketArg) => ticketArg.autoLabels?.includes(labelArg)).length),
196
+ projects: projects.slice(0, groups), projectsTotal: projects.length,
197
+ assignees: assignees.slice(0, groups), assigneesTotal: assignees.length,
198
+ unassignedOpen: open.filter((ticketArg) => ticketArg.assignee === undefined).length,
199
+ epics: epics.slice(0, groups), epicsTotal: epics.length,
200
+ attention: {
201
+ urgent: group(open.filter((ticketArg) => ticketArg.priority === 'urgent').sort(byBoard), limit, openQuestionsArg),
202
+ needsInput: group(open.filter((ticketArg) => ticketArg.columnId === 'needs_input').sort(byPriority), limit, openQuestionsArg),
203
+ openQuestions: group(open.filter((ticketArg) => openQuestionsArg(ticketArg.id) > 0).sort(byPriority), limit, openQuestionsArg),
204
+ review: group(open.filter((ticketArg) => ticketArg.columnId === 'review').sort(byPriority), limit, openQuestionsArg),
205
+ unassignedReady: group(open.filter((ticketArg) => ticketArg.columnId === 'ready' && ticketArg.assignee === undefined).sort(byPriority),
206
+ limit, openQuestionsArg),
207
+ stale: group(open.filter((ticketArg) => active.has(ticketArg.columnId) && Date.parse(ticketArg.updatedAt) < staleBefore)
208
+ .sort((leftArg, rightArg) => Date.parse(leftArg.updatedAt) - Date.parse(rightArg.updatedAt) || ticketNumber(leftArg) - ticketNumber(rightArg)),
209
+ limit, openQuestionsArg),
210
+ },
211
+ recent: [...ticketsArg].sort((leftArg, rightArg) => compareKeys(ticketSortKey(leftArg, 'updated'), ticketSortKey(rightArg, 'updated')))
212
+ .slice(0, limit).map((ticketArg) => ticketSummary(ticketArg, openQuestionsArg(ticketArg.id))),
213
+ };
214
+ };
@@ -1,6 +1,7 @@
1
1
  import * as plugins from './plugins.js';
2
2
  import {
3
- ticketAutoLabels, ticketColumns, ticketHistoryPage, type TTicketFleetEvent, type TTicketLink, type TTicketOperation, type TTicketRequest,
3
+ ticketAutoLabels, ticketColumns, ticketHistoryPage, ticketListPage, ticketOverviewDefaults, ticketPageSorts, ticketPriorities,
4
+ type TTicketFleetEvent, type TTicketLink, type TTicketOperation, type TTicketRequest,
4
5
  } from '../ts_interfaces/tickets.js';
5
6
  import { fleetDeployTargetIdPattern } from '../ts_interfaces/deployments.js';
6
7
 
@@ -82,6 +83,15 @@ const optionId = plugins.z.string().regex(/^[1-9][0-9]*$/u);
82
83
  const questionOption = plugins.z.object({ label: text(200).trim().min(1), description: text(1000).optional() }).strict();
83
84
  const filters = plugins.z.object({ mine: plugins.z.boolean().optional(), project: identifier.optional(),
84
85
  status: plugins.z.enum(ticketColumns).optional(), label: text(100).min(1).optional(), text: text(1024).optional() }).strict();
86
+ const pageRequest = plugins.z.object({ ...filters.shape,
87
+ statuses: plugins.z.array(plugins.z.enum(ticketColumns)).min(1).max(ticketColumns.length).optional(), open: plugins.z.boolean().optional(),
88
+ kind: kind.optional(), priorities: plugins.z.array(priority).min(1).max(ticketPriorities.length).optional(), parent: ticketId.optional(),
89
+ assignee: identifier.optional(), unassigned: plugins.z.boolean().optional(), keys: plugins.z.array(ticketId).min(1).max(200).optional(),
90
+ updatedSince: instantInput.optional(), sort: plugins.z.enum(ticketPageSorts).optional(), view: plugins.z.enum(['summary', 'full']).optional(),
91
+ limit: plugins.z.number().int().min(1).max(ticketListPage.maximum).optional(), cursor: text(2048).min(1).optional() }).strict();
92
+ const overviewRequest = plugins.z.object({ project: identifier.optional(), mine: plugins.z.boolean().optional(),
93
+ limit: plugins.z.number().int().min(1).max(ticketOverviewDefaults.maximumLimit).optional(),
94
+ staleDays: plugins.z.number().int().min(1).max(365).optional() }).strict();
85
95
  const changes = plugins.z.object({
86
96
  title: text(200).trim().min(1).optional(), description: text(64 * 1024).optional(),
87
97
  priority: priority.optional(), assignee: person.nullable().optional(), parentId: ticketId.nullable().optional(),
@@ -89,7 +99,7 @@ const changes = plugins.z.object({
89
99
  maintenanceWindow: maintenanceWindowInput.nullable().optional(), deployPlan: deployPlanInput.optional(),
90
100
  }).strict().refine((valueArg) => Object.keys(valueArg).length > 0, 'At least one change is required.');
91
101
  export const ticketInputSchemas = {
92
- list: filters, board: filters,
102
+ list: filters, board: filters, page: pageRequest, overview: overviewRequest,
93
103
  search: plugins.z.object({ query: text(1024), label: text(100).min(1).optional() }).strict(),
94
104
  get: plugins.z.object({ ticketId, before: identifier.optional(),
95
105
  limit: plugins.z.number().int().min(1).max(ticketHistoryPage.maximum).optional(), commentId: identifier.optional() }).strict()
@@ -177,8 +187,37 @@ export const assertTicketResponse = (methodArg: string, valueArg: unknown): void
177
187
  permissions: plugins.z.object({ edit: plugins.z.boolean(), move: plugins.z.boolean(),
178
188
  comment: plugins.z.boolean(), createChild: plugins.z.boolean(), ask: plugins.z.boolean(), answer: plugins.z.boolean() }).strict(),
179
189
  autoLabels: plugins.z.array(plugins.z.enum(ticketAutoLabels)) });
190
+ const count = plugins.z.number().int().nonnegative();
191
+ const columnCounts = plugins.z.partialRecord(storedColumn, count);
192
+ const summaryPerson = plugins.z.object({ id: identifier, name: text(200).min(1), sessionId: identifier.optional() }).strict();
193
+ const summary = plugins.z.object({ key: ticketId, revision: count, project: identifier, kind, title: text(200).min(1),
194
+ columnId: storedColumn, priority, updatedAt: plugins.z.iso.datetime(), assignee: summaryPerson.optional(), parentId: ticketId.optional(),
195
+ labels: labels.optional(), autoLabels: plugins.z.array(plugins.z.enum(ticketAutoLabels)).optional(),
196
+ links: plugins.z.partialRecord(plugins.z.enum(['branch', 'commit', 'release', 'affects']), count).optional(),
197
+ releasePlan: releasePlan.optional(), deployPlan: plugins.z.object({ target: deployTargetId, version: identifier }).strict().optional(),
198
+ maintenanceWindow: plugins.z.object({ from: plugins.z.iso.datetime(), to: plugins.z.iso.datetime(),
199
+ targets: plugins.z.array(deployTargetId) }).strict().optional(), openQuestions: count.optional() }).strict();
200
+ const pageBase = { total: count, columns: columnCounts, revision: count, nextCursor: text(2048).min(1).optional(),
201
+ moved: plugins.z.literal(true).optional() };
202
+ const group = plugins.z.object({ total: count, tickets: plugins.z.array(summary) }).strict();
180
203
  const schemas = {
181
204
  list: plugins.z.object({ tickets: plugins.z.array(ticket) }).strict(),
205
+ page: plugins.z.discriminatedUnion('view', [
206
+ plugins.z.object({ view: plugins.z.literal('summary'), tickets: plugins.z.array(summary), ...pageBase }).strict(),
207
+ plugins.z.object({ view: plugins.z.literal('full'), tickets: plugins.z.array(ticket), ...pageBase }).strict(),
208
+ ]),
209
+ overview: plugins.z.object({ revision: count, total: count, open: count,
210
+ columns: plugins.z.record(storedColumn, count), priorities: plugins.z.record(priority, count),
211
+ autoLabels: plugins.z.record(plugins.z.enum(ticketAutoLabels), count),
212
+ projects: plugins.z.array(plugins.z.object({ project: identifier, total: count, open: count, columns: columnCounts }).strict()),
213
+ projectsTotal: count,
214
+ assignees: plugins.z.array(summaryPerson.extend({ open: count, columns: columnCounts }).strict()), assigneesTotal: count,
215
+ unassignedOpen: count,
216
+ epics: plugins.z.array(plugins.z.object({ key: ticketId, title: text(200).min(1), project: identifier, columnId: storedColumn,
217
+ children: count, done: count, columns: columnCounts }).strict()), epicsTotal: count,
218
+ attention: plugins.z.object({ urgent: group, needsInput: group, openQuestions: group, review: group, unassignedReady: group,
219
+ stale: group }).strict(),
220
+ recent: plugins.z.array(summary) }).strict(),
182
221
  search: plugins.z.object({ tickets: plugins.z.array(ticket) }).strict(),
183
222
  board: plugins.z.object({ revision: plugins.z.number().int().nonnegative(), columns: plugins.z.array(plugins.z.object({
184
223
  id: storedColumn, title: plugins.z.string(), done: plugins.z.boolean().optional() }).strict()), tickets: plugins.z.array(ticket),