agl 43.9.0 → 43.10.1

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 (147) hide show
  1. package/changelog.md +20 -0
  2. package/dist_serve/bundle.js +997 -975
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +2 -2
  5. package/dist_ts/aglapi/aglapisurface.document.js +3 -3
  6. package/dist_ts/classes.accountsactions.d.ts +3 -1
  7. package/dist_ts/classes.accountsactions.js +17 -1
  8. package/dist_ts/classes.authstore.d.ts +6 -0
  9. package/dist_ts/classes.authstore.js +8 -1
  10. package/dist_ts/classes.controller.d.ts +7 -1
  11. package/dist_ts/classes.controller.js +39 -7
  12. package/dist_ts/classes.inferencegateway.js +7 -5
  13. package/dist_ts/classes.inferenceplacement.d.ts +1 -1
  14. package/dist_ts/classes.inferencerouter.d.ts +20 -3
  15. package/dist_ts/classes.inferencerouter.js +37 -10
  16. package/dist_ts/classes.inferenceservice.js +2 -2
  17. package/dist_ts/classes.mcpcallerregistry.d.ts +19 -1
  18. package/dist_ts/classes.mcpcallerregistry.js +33 -7
  19. package/dist_ts/classes.terminalcallers.d.ts +40 -0
  20. package/dist_ts/classes.terminalcallers.js +90 -0
  21. package/dist_ts/classes.terminalmanager.d.ts +20 -1
  22. package/dist_ts/classes.terminalmanager.js +36 -2
  23. package/dist_ts/classes.ticketnotifier.d.ts +2 -2
  24. package/dist_ts/classes.ticketnotifier.js +6 -4
  25. package/dist_ts/classes.ticketorderspread.d.ts +25 -0
  26. package/dist_ts/classes.ticketorderspread.js +52 -0
  27. package/dist_ts/classes.ticketstore.d.ts +60 -5
  28. package/dist_ts/classes.ticketstore.js +176 -40
  29. package/dist_ts/classes.workercallers.d.ts +40 -2
  30. package/dist_ts/classes.workercallers.js +156 -30
  31. package/dist_ts/fleet/classes.boardpump.d.ts +1 -1
  32. package/dist_ts/fleet/classes.boardpump.js +4 -2
  33. package/dist_ts/fleet/classes.claudeworkers.d.ts +18 -5
  34. package/dist_ts/fleet/classes.claudeworkers.js +105 -31
  35. package/dist_ts/fleet/classes.ticketeffects.d.ts +11 -0
  36. package/dist_ts/fleet/classes.ticketeffects.js +28 -1
  37. package/dist_ts/fleet/classes.workers.d.ts +23 -4
  38. package/dist_ts/fleet/classes.workers.js +65 -18
  39. package/dist_ts/fleet/functions.workervalidation.js +7 -4
  40. package/dist_ts/fleet/interfaces.workers.d.ts +16 -2
  41. package/dist_ts/fleet/interfaces.workers.js +8 -1
  42. package/dist_ts/functions.fleetworkercli.d.ts +3 -1
  43. package/dist_ts/functions.fleetworkercli.js +6 -2
  44. package/dist_ts/functions.inferencecli.js +4 -1
  45. package/dist_ts/functions.mcpfleetworkertools.js +3 -3
  46. package/dist_ts/functions.proxycapacity.d.ts +2 -1
  47. package/dist_ts/functions.proxycapacity.js +6 -3
  48. package/dist_ts/functions.proxycapacitycli.js +2 -2
  49. package/dist_ts/functions.workerprocessproof.d.ts +6 -0
  50. package/dist_ts/functions.workerprocessproof.js +8 -3
  51. package/dist_ts/interfaces.auth.d.ts +1 -1
  52. package/dist_ts/interfaces.auth.js +2 -1
  53. package/dist_ts/interfaces.flexipc.d.ts +3 -1
  54. package/dist_ts/interfaces.flexipc.js +1 -1
  55. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  56. package/dist_ts_authswitch/authority-contract.js +1 -1
  57. package/dist_ts_authswitch/authority-overview.d.ts +7 -0
  58. package/dist_ts_authswitch/authority-overview.js +10 -6
  59. package/dist_ts_authswitch/authority-placement.d.ts +5 -2
  60. package/dist_ts_authswitch/authority-placement.js +6 -3
  61. package/dist_ts_authswitch/classes.authoritybroker.d.ts +6 -0
  62. package/dist_ts_authswitch/classes.authoritybroker.js +26 -1
  63. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  64. package/dist_ts_authswitch/classes.authoritycli.js +50 -4
  65. package/dist_ts_authswitch/classes.authorityclient.d.ts +3 -1
  66. package/dist_ts_authswitch/classes.authorityclient.js +9 -4
  67. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  68. package/dist_ts_authswitch/classes.authoritydatabase.js +5 -1
  69. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  70. package/dist_ts_authswitch/classes.authoritymodels.js +13 -6
  71. package/dist_ts_interfaces/fleetworkers.d.ts +26 -1
  72. package/dist_ts_interfaces/fleetworkers.js +1 -1
  73. package/dist_ts_interfaces/interfaces.d.ts +4 -2
  74. package/dist_ts_interfaces/interfaces.js +1 -1
  75. package/dist_ts_interfaces/mcprequests.d.ts +2 -1
  76. package/dist_ts_interfaces/mcprequests.js +3 -2
  77. package/dist_ts_interfaces/proxycapacity.d.ts +1 -1
  78. package/dist_ts_interfaces/requests.accounts.d.ts +19 -0
  79. package/dist_ts_interfaces/requests.accounts.js +1 -1
  80. package/dist_ts_interfaces/requests.d.ts +2 -2
  81. package/dist_ts_interfaces/requests.fleetworkers.d.ts +3 -1
  82. package/dist_ts_interfaces/requests.js +1 -1
  83. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +8 -1
  84. package/dist_ts_migration/classes.documentmigrationrunner.js +11 -2
  85. package/dist_ts_migration/index.d.ts +1 -0
  86. package/dist_ts_migration/index.js +2 -1
  87. package/dist_ts_migration/v41_ticketclosedcolumn.js +7 -3
  88. package/dist_ts_migration/v43_ticketorderstride.d.ts +54 -0
  89. package/dist_ts_migration/v43_ticketorderstride.js +161 -0
  90. package/docs/authswitch.md +22 -0
  91. package/package.json +1 -1
  92. package/readme.md +71 -4
  93. package/ts/00_commitinfo_data.ts +1 -1
  94. package/ts/aglapi/aglapisurface.document.ts +2 -2
  95. package/ts/classes.accountsactions.ts +25 -0
  96. package/ts/classes.authstore.ts +9 -0
  97. package/ts/classes.controller.ts +37 -3
  98. package/ts/classes.inferencegateway.ts +6 -4
  99. package/ts/classes.inferenceplacement.ts +1 -1
  100. package/ts/classes.inferencerouter.ts +49 -10
  101. package/ts/classes.inferenceservice.ts +1 -1
  102. package/ts/classes.mcpcallerregistry.ts +49 -7
  103. package/ts/classes.terminalcallers.ts +91 -0
  104. package/ts/classes.terminalmanager.ts +41 -1
  105. package/ts/classes.ticketnotifier.ts +5 -3
  106. package/ts/classes.ticketorderspread.ts +50 -0
  107. package/ts/classes.ticketstore.ts +164 -35
  108. package/ts/classes.workercallers.ts +183 -30
  109. package/ts/fleet/classes.boardpump.ts +3 -2
  110. package/ts/fleet/classes.claudeworkers.ts +101 -29
  111. package/ts/fleet/classes.ticketeffects.ts +25 -0
  112. package/ts/fleet/classes.workers.ts +62 -17
  113. package/ts/fleet/functions.workervalidation.ts +6 -3
  114. package/ts/fleet/interfaces.workers.ts +16 -2
  115. package/ts/functions.fleetworkercli.ts +5 -1
  116. package/ts/functions.inferencecli.ts +2 -0
  117. package/ts/functions.mcpfleetworkertools.ts +2 -2
  118. package/ts/functions.proxycapacity.ts +5 -2
  119. package/ts/functions.proxycapacitycli.ts +1 -1
  120. package/ts/functions.workerprocessproof.ts +10 -2
  121. package/ts/interfaces.auth.ts +1 -0
  122. package/ts/interfaces.flexipc.ts +3 -1
  123. package/ts_authswitch/authority-contract.ts +20 -0
  124. package/ts_authswitch/authority-overview.ts +17 -6
  125. package/ts_authswitch/authority-placement.ts +7 -3
  126. package/ts_authswitch/classes.authoritybroker.ts +24 -0
  127. package/ts_authswitch/classes.authoritycli.ts +58 -4
  128. package/ts_authswitch/classes.authorityclient.ts +11 -4
  129. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  130. package/ts_authswitch/classes.authoritydatabase.ts +3 -0
  131. package/ts_authswitch/classes.authoritymodels.ts +12 -4
  132. package/ts_interfaces/fleetworkers.ts +26 -1
  133. package/ts_interfaces/interfaces.ts +4 -2
  134. package/ts_interfaces/mcprequests.ts +2 -1
  135. package/ts_interfaces/proxycapacity.ts +1 -1
  136. package/ts_interfaces/requests.accounts.ts +17 -0
  137. package/ts_interfaces/requests.fleetworkers.ts +3 -1
  138. package/ts_interfaces/requests.ts +2 -0
  139. package/ts_migration/classes.documentmigrationrunner.ts +12 -1
  140. package/ts_migration/index.ts +1 -0
  141. package/ts_migration/v41_ticketclosedcolumn.ts +6 -2
  142. package/ts_migration/v43_ticketorderstride.ts +156 -0
  143. package/ts_web/00_commitinfo_data.ts +1 -1
  144. package/ts_web/accounts.templates.ts +12 -2
  145. package/ts_web/classes.accountsreadmodel.ts +42 -6
  146. package/ts_web/elements.accounts.ts +45 -3
  147. package/ts_web/elements.harnesscontrollerapp.ts +6 -1
@@ -15,6 +15,7 @@ import { assertTicketRequest, ticketActorSchema, ticketFleetEventSchema, ticketR
15
15
  import { ticketAutoLabelsFor } from './functions.ticketautolabels.js';
16
16
 
17
17
  type TTicketStored = NonNullable<Awaited<ReturnType<typeof TicketModel.exact.findStoredOne>>>;
18
+ type TBoardStored = NonNullable<Awaited<ReturnType<typeof TicketBoardModel.exact.findStoredOne>>>;
18
19
  type TSession = plugins.nosqldb.SmartdataSession;
19
20
  const workerColumns = new Set(['ready', 'in_progress', 'needs_input', 'review']);
20
21
  const mutableOperations = new Set<TTicketOperation>(['create', 'update', 'move', 'comment', 'link', 'unlink', 'ask', 'answer']);
@@ -23,6 +24,14 @@ const mutableOperations = new Set<TTicketOperation>(['create', 'update', 'move',
23
24
  * entries it returns, whatever its `limit`, so a page cut by the byte budget does not read `limit` records.
24
25
  */
25
26
  export const ticketHistoryBatch = 16;
27
+ /**
28
+ * The gap a ticket placed at the end of a column leaves after the last one (AGL-1907). A ticket's `order` is a sparse,
29
+ * non-negative integer sort key: only its value relative to the other tickets of its column means anything, never a
30
+ * position or a count. A placement before another ticket takes the integer halfway into the gap before it.
31
+ */
32
+ export const ticketOrderStride = 1024;
33
+ /** The order range the first read of a run of tickets that leave no integer free covers; each further read doubles it, up to `ticketOrderRunSpan.maximum`. */
34
+ const ticketOrderRunSpan = { first: 16, maximum: 512 } as const;
26
35
 
27
36
  /** One change a committed ticket transaction made, or an edit it refused as stale. */
28
37
  export interface ITicketChange {
@@ -333,10 +342,7 @@ export class TicketStore {
333
342
  }
334
343
  const board = await TicketBoardModel.exact.findStoredOne({ id: 'global' }, { session: transactionArg });
335
344
  if (!board) throw new Error('The ticket board has not been initialized.');
336
- const fenced = await TicketBoardModel.exact.transition({ current: board, change: (modelArg) => {
337
- modelArg.revision += 1;
338
- } }, { session: transactionArg });
339
- if (fenced.status !== 'transitioned') throw new TicketError('concurrent_change', 'The board changed concurrently.');
345
+ await this.fence(board, transactionArg);
340
346
  const now = new Date().toISOString();
341
347
  const revision = board.revision + 1;
342
348
  track = this.track(originArg);
@@ -463,13 +469,7 @@ export class TicketStore {
463
469
  committed = await session.withTransaction(async (transactionArg) => {
464
470
  const board = await TicketBoardModel.exact.findStoredOne({ id: 'global' }, { session: transactionArg });
465
471
  if (!board) throw new Error('The ticket board has not been initialized.');
466
- if (mutableOperations.has(methodArg)) {
467
- const fenced = await TicketBoardModel.exact.transition({ current: board, change: (modelArg) => {
468
- modelArg.revision += 1;
469
- if (methodArg === 'create') modelArg.sequence += 1;
470
- } }, { session: transactionArg });
471
- if (fenced.status !== 'transitioned') throw new TicketError('concurrent_change', 'The board changed concurrently.');
472
- }
472
+ if (mutableOperations.has(methodArg)) await this.fence(board, transactionArg, methodArg === 'create');
473
473
  const now = new Date().toISOString();
474
474
  const revision = board.revision + (mutableOperations.has(methodArg) ? 1 : 0);
475
475
  track = this.track();
@@ -496,6 +496,64 @@ export class TicketStore {
496
496
  return committed.response as TTicketResponse<TMethod>;
497
497
  }
498
498
 
499
+ /**
500
+ * One transaction of a ticket migration that runs on a live board (AGL-1907's order spread, after the controller is
501
+ * ready). `stepArg` reads and writes in it through the session it is given, and calls `fenceArg` before its first
502
+ * ticket write (a second call does nothing): the board's revision then moves by one through the fence every mutation
503
+ * takes, so the one board document orders the step with every mutation. Whichever of two transactions that read the
504
+ * board writes it second meets a write conflict, which the driver answers by running that transaction again on the
505
+ * new board within the 20 s deadline: a mutation that loses to a step re-runs and succeeds, and so does a step that
506
+ * loses to a mutation. After the commit `onChanged` tells everyone of the new revision and of the tickets the step
507
+ * answers, as after a mutation; a step writes no history, so no observer hears of it. A step that did not fence changed
508
+ * no ticket and tells nobody. Answers the step's result.
509
+ */
510
+ public async migrate<TResult>(stepArg: (sessionArg: TSession, fenceArg: () => Promise<void>) => Promise<{ ticketIds: string[]; result: TResult }>,
511
+ signalArg?: AbortSignal): Promise<TResult> {
512
+ const session = TicketBoardModel.collection.smartdataDb.createSession();
513
+ let committed: { revision?: number; ticketIds: string[]; result: TResult } | undefined;
514
+ try {
515
+ committed = await session.withTransaction(async (transactionArg) => {
516
+ const board = await TicketBoardModel.exact.findStoredOne({ id: 'global' }, { session: transactionArg });
517
+ if (!board) throw new Error('The ticket board has not been initialized.');
518
+ let revision: number | undefined;
519
+ const fence = async (): Promise<void> => {
520
+ if (revision !== undefined) return;
521
+ await this.fence(board, transactionArg);
522
+ revision = board.revision + 1;
523
+ };
524
+ const { ticketIds, result } = await stepArg(transactionArg, fence);
525
+ if (ticketIds.length && revision === undefined) throw new Error('A ticket migration step changed tickets without the board fence.');
526
+ return { ...(revision === undefined ? {} : { revision }), ticketIds, result };
527
+ }, { timeoutMS: 20_000, ...(signalArg ? { signal: signalArg } : {}) });
528
+ } catch (errorArg) {
529
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) !== 'not_committed') {
530
+ throw new TicketError('outcome_unknown', 'The ticket migration transaction outcome is unknown; read the board before running it again.');
531
+ }
532
+ throw errorArg;
533
+ } finally {
534
+ await session.close();
535
+ }
536
+ if (!committed) throw new Error('The ticket migration transaction returned no result.');
537
+ if (committed.revision !== undefined) this.onChanged?.(committed.revision, committed.ticketIds);
538
+ return committed.result;
539
+ }
540
+
541
+ /**
542
+ * The board fence, the store's one write of the board's revision: it moves by one (and the sequence too for a create)
543
+ * in the transaction of every mutation and of every migration step on a live board (`migrate`), before any ticket
544
+ * write. The versioned ticket migrations that fence on their own are the exception: v38 owner principal, v41 closed
545
+ * column, v41 link repos (after `ready`, on the live board) and v43 actor names move it with their own `transition`.
546
+ * A race with another transaction surfaces as the database's write conflict, which the driver answers by running the
547
+ * transaction again (`migrate` says how).
548
+ */
549
+ private async fence(boardArg: TBoardStored, sessionArg: TSession, createArg = false): Promise<void> {
550
+ const fenced = await TicketBoardModel.exact.transition({ current: boardArg, change: (modelArg) => {
551
+ modelArg.revision += 1;
552
+ if (createArg) modelArg.sequence += 1;
553
+ } }, { session: sessionArg });
554
+ if (fenced.status !== 'transitioned') throw new TicketError('concurrent_change', 'The board changed concurrently.');
555
+ }
556
+
499
557
  private observe(observationArg: ITicketObservation): void {
500
558
  if (!this.observer || !observationArg.changes.length) return;
501
559
  // An observer never turns a committed change into a failed request.
@@ -534,10 +592,65 @@ export class TicketStore {
534
592
  return await TicketModel.exact.findStoredOne({ id: ticketIdArg }, { session: sessionArg });
535
593
  }
536
594
 
537
- /** The tickets of one column, by id; the board's `ticket_column_order` index serves it. */
538
- private async columnTickets(columnIdArg: ITicket['columnId'], sessionArg: TSession): Promise<TTicketStored[]> {
539
- return await this.paged((afterArg) => TicketModel.exact.findStored({ filter: { 'ticket.columnId': columnIdArg,
540
- ...(afterArg ? { id: { $gt: afterArg } } : {}) }, sort: { id: 1 }, limit: 500, session: sessionArg }));
595
+ /**
596
+ * The ticket last in a column, `excludeArg` (the ticket being placed) left out: one document, `ticket_column_order`
597
+ * read backwards. The store keeps the orders of a column distinct, so the last order is the column's end.
598
+ */
599
+ private async lastInColumn(columnIdArg: ITicket['columnId'], excludeArg: string | undefined, sessionArg: TSession): Promise<TTicketStored | undefined> {
600
+ return (await TicketModel.exact.findStored({ filter: { 'ticket.columnId': columnIdArg,
601
+ ...(excludeArg === undefined ? {} : { id: { $ne: excludeArg } }) }, sort: { 'ticket.order': -1 }, limit: 1, session: sessionArg }))[0];
602
+ }
603
+
604
+ /**
605
+ * The order a ticket placed at the end of a column takes: `ticketOrderStride` after the last one's, or
606
+ * `ticketOrderStride` in an empty column.
607
+ */
608
+ private async columnEnd(columnIdArg: ITicket['columnId'], excludeArg: string | undefined, sessionArg: TSession): Promise<{ last?: TTicketStored; order: number }> {
609
+ const last = await this.lastInColumn(columnIdArg, excludeArg, sessionArg);
610
+ return { ...(last ? { last } : {}), order: (last?.ticket.order ?? 0) + ticketOrderStride };
611
+ }
612
+
613
+ /**
614
+ * Where a ticket goes before an anchor at order `anchorArg` when the ticket before it holds `previousArg` (−1 for none)
615
+ * and no integer is free between them: the shorter of two runs moves by one. Either the anchor and the tickets right
616
+ * above it move up to the first integer none of them holds, and the ticket takes the anchor's order (`step` 1), or the
617
+ * ticket before the anchor and those right below it move down to the first free integer from 0 on, and the ticket
618
+ * takes that one's order (`step` −1); with every integer from 0 to `previousArg` held, only the first is possible.
619
+ * `excludeArg`, the ticket being placed, is left out of both, so its own order is free on either side. Both runs are
620
+ * read by order range through `ticket_column_order`, nearest the anchor first, one range of each per round, each round
621
+ * twice the last (at most 512 orders). The rounds stop when the first run ends, which is the shorter, so the longer
622
+ * side is read no further than the shorter run needs, never to the column's end. A range holds every ticket of its orders.
623
+ */
624
+ private async orderShift(columnIdArg: ITicket['columnId'], previousArg: number, anchorArg: number, excludeArg: string,
625
+ sessionArg: TSession): Promise<{ order: number; step: 1 | -1; run: TTicketStored[] }> {
626
+ /** Each run: its tickets nearest the anchor first, the next order it reads, and whether that order is free (`ended`). */
627
+ const up = { run: [] as TTicketStored[], next: anchorArg, ended: false };
628
+ const down = { run: [] as TTicketStored[], next: previousArg, ended: false, blocked: previousArg < 0 };
629
+ const range = (orderArg: Record<string, number>, sortArg: 1 | -1) => TicketModel.exact.findStored({ filter: {
630
+ 'ticket.columnId': columnIdArg, 'ticket.order': orderArg, id: { $ne: excludeArg } }, sort: { 'ticket.order': sortArg }, session: sessionArg });
631
+ for (let span: number = ticketOrderRunSpan.first; ; span = Math.min(span * 2, ticketOrderRunSpan.maximum)) {
632
+ const upEnd = up.next + span;
633
+ for (const record of await range({ $gte: up.next, $lt: upEnd }, 1)) {
634
+ if (record.ticket.order > up.next) break;
635
+ up.run.push(record);
636
+ up.next = record.ticket.order + 1;
637
+ }
638
+ up.ended = up.next < upEnd;
639
+ if (!down.blocked) {
640
+ // Orders below 0 are not free: a run that reaches −1 cannot move down.
641
+ const downEnd = Math.max(down.next - span, -1);
642
+ for (const record of await range({ $lte: down.next, $gt: downEnd }, -1)) {
643
+ if (record.ticket.order < down.next) break;
644
+ down.run.push(record);
645
+ down.next = record.ticket.order - 1;
646
+ }
647
+ down.ended = down.next > downEnd;
648
+ down.blocked = !down.ended && down.next < 0;
649
+ }
650
+ // Both read as many orders this round, so a run still going is at least as long as one that ended.
651
+ if (up.ended && (!down.ended || up.run.length <= down.run.length)) return { order: anchorArg, step: 1, run: up.run };
652
+ if (down.ended) return { order: previousArg, step: -1, run: down.run };
653
+ }
541
654
  }
542
655
 
543
656
  private async paged<TRecord extends { id: string }>(pageArg: (afterArg: string | undefined) => Promise<TRecord[]>): Promise<TRecord[]> {
@@ -795,9 +908,11 @@ export class TicketStore {
795
908
 
796
909
  /**
797
910
  * Each operation reads what it decides on and nothing more: the listing operations (list, board, search, page, overview) read the whole board and every
798
- * open question; create the parent and the destination column's count; move the source and destination columns;
799
- * update the ticket, its parent and, when the project changes, its children; every other operation one ticket, and
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.
911
+ * open question; create the parent and the last ticket of its column; move the ticket and, in the destination, the
912
+ * last ticket or the anchor and the ticket before it, plus, only when no integer is free between them, both sides of
913
+ * them a range at a time until the shorter run ends (never the column it leaves, which it does not write either);
914
+ * update the ticket, its parent and, when the project changes, its children; every other operation one ticket, and get
915
+ * one page of its history or, with `commentId`, that one comment. The board document's revision transition in the caller orders every mutation.
801
916
  */
802
917
  private async perform(methodArg: TTicketOperation, requestArg: TTicketRequest<TTicketOperation>, actorArg: ITicketActor | undefined,
803
918
  sessionArg: TSession, nowArg: string, sequenceArg: number,
@@ -849,7 +964,7 @@ export class TicketStore {
849
964
  const id = `AGL-${sequenceArg}`;
850
965
  const ticket: ITicket = { id, key: id, revision: 1, project: input.project, kind: input.kind ?? 'task', title: input.title,
851
966
  description: input.description ?? '', ...(input.parentId ? { parentId: input.parentId } : {}), columnId,
852
- order: await TicketModel.exact.count({ 'ticket.columnId': columnId }, { session: sessionArg }),
967
+ order: (await this.columnEnd(columnId, undefined, sessionArg)).order,
853
968
  priority: input.priority ?? 'normal', ...(input.assignee ? { assignee: input.assignee } : {}), labels: input.labels ?? [], links: [],
854
969
  ...(input.releasePlan ? { releasePlan: input.releasePlan } : {}),
855
970
  ...(input.maintenanceWindow ? { maintenanceWindow: input.maintenanceWindow } : {}),
@@ -1046,23 +1161,37 @@ export class TicketStore {
1046
1161
  if (ticket.columnId !== input.columnId) this.requireEvidence(ticket, input.columnId);
1047
1162
  // Landed code ships with the tag that holds it: closing its ticket would drop it from release and deploy tracking.
1048
1163
  if (ticket.columnId === 'landed' && input.columnId === 'closed') throw new TicketError('ticket_closed_landed', ticketErrorMessages.ticket_closed_landed);
1049
- const destination = (await this.columnTickets(input.columnId, sessionArg)).filter((recordArg) => recordArg.id !== ticketId)
1050
- .sort((leftArg, rightArg) => leftArg.ticket.order - rightArg.ticket.order);
1051
- const index = input.beforeTicketId === undefined ? destination.length : destination.findIndex((recordArg) => recordArg.id === input.beforeTicketId);
1052
- if (index < 0) throw new TicketError('ticket_move_anchor_invalid', 'The before-ticket must belong to the destination column.');
1053
- destination.splice(index, 0, current);
1054
- const source = ticket.columnId === input.columnId ? [] : (await this.columnTickets(ticket.columnId, sessionArg))
1055
- .filter((recordArg) => recordArg.id !== ticketId)
1056
- .sort((leftArg, rightArg) => leftArg.ticket.order - rightArg.ticket.order);
1057
- const changed: ITicket[] = [];
1058
- for (const group of [destination, source]) {
1059
- for (const [order, record] of group.entries()) {
1060
- const columnId = group === destination ? input.columnId : ticket.columnId;
1061
- if (record.ticket.order === order && record.ticket.columnId === columnId) continue;
1062
- const next = { ...record.ticket, columnId, order };
1063
- changed.push(await this.save(record, next, actorArg, sessionArg,
1064
- record.id === ticketId ? 'moved' : 'reordered', nowArg, trackArg, revisionArg));
1164
+ // Orders are sparse (AGL-1907): the column a ticket leaves is neither read nor written, and a place in the destination
1165
+ // costs the ticket's own write unless no integer is free before its anchor. A ticket already in place writes nothing.
1166
+ const sameColumn = ticket.columnId === input.columnId;
1167
+ // The order the ticket takes and, when no integer is free before its anchor, the run that moves by one to free it.
1168
+ let order: number;
1169
+ let shift: { step: 1 | -1; run: TTicketStored[] } = { step: 1, run: [] };
1170
+ if (input.beforeTicketId === undefined) {
1171
+ const end = await this.columnEnd(input.columnId, ticketId, sessionArg);
1172
+ if (sameColumn && (end.last === undefined || end.last.ticket.order < ticket.order)) return { tickets: [] };
1173
+ order = end.order;
1174
+ } else {
1175
+ const anchor = await this.ticket(input.beforeTicketId, sessionArg);
1176
+ if (anchor?.ticket.columnId !== input.columnId) {
1177
+ throw new TicketError('ticket_move_anchor_invalid', 'The before-ticket must belong to the destination column.');
1065
1178
  }
1179
+ const next = anchor.ticket.order;
1180
+ const previous = (await TicketModel.exact.findStored({ filter: { 'ticket.columnId': input.columnId, 'ticket.order': { $lt: next },
1181
+ id: { $ne: ticketId } }, sort: { 'ticket.order': -1 }, limit: 1, session: sessionArg }))[0]?.ticket.order ?? -1;
1182
+ if (sameColumn && previous < ticket.order && ticket.order < next) return { tickets: [] };
1183
+ if (next - previous >= 2) order = previous + Math.floor((next - previous) / 2);
1184
+ else {
1185
+ // No integer is free before the anchor: the shorter run on either side of it moves by one.
1186
+ const placed = await this.orderShift(input.columnId, previous, next, ticketId, sessionArg);
1187
+ order = placed.order;
1188
+ shift = placed;
1189
+ }
1190
+ }
1191
+ const changed = [await this.save(current, { ...ticket, columnId: input.columnId, order }, actorArg, sessionArg, 'moved', nowArg, trackArg, revisionArg)];
1192
+ for (const record of shift.run) {
1193
+ changed.push(await this.save(record, { ...record.ticket, order: record.ticket.order + shift.step }, actorArg, sessionArg,
1194
+ 'reordered', nowArg, trackArg, revisionArg));
1066
1195
  }
1067
1196
  await this.countOpenQuestions(trackArg, sessionArg, changed.map((ticketArg) => ticketArg.id));
1068
1197
  return { tickets: changed.map((ticketArg) => this.visible(ticketArg, actorArg, trackArg)) };