@mastra/factory 0.29.0-alpha.0 → 0.29.0-alpha.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 (237) hide show
  1. package/README.md +20 -4
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/semantics.d.ts +1 -3
  8. package/dist/boards/semantics.d.ts.map +1 -1
  9. package/dist/boards/semantics.js +1 -5
  10. package/dist/boards/semantics.js.map +1 -1
  11. package/dist/factory.d.ts +4 -0
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +51 -3
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/base.d.ts +9 -0
  16. package/dist/integrations/base.d.ts.map +1 -1
  17. package/dist/integrations/github/pull-request-source.js +2 -1
  18. package/dist/integrations/github/pull-request-source.js.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +1 -1
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts +5 -2
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +16 -13
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/gitlab/default-rules.js +2 -1
  28. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  29. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  30. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  31. package/dist/integrations/gitlab/discovery.js +107 -0
  32. package/dist/integrations/gitlab/discovery.js.map +1 -0
  33. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/integration.js +1 -2
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  38. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  39. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  40. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  41. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  42. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/reconciler.js +4 -2
  44. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  45. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  46. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  48. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  49. package/dist/integrations/gitlab/routes.d.ts +17 -0
  50. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  51. package/dist/integrations/gitlab/routes.js +28 -22
  52. package/dist/integrations/gitlab/routes.js.map +1 -1
  53. package/dist/integrations/gitlab/rules.d.ts +10 -4
  54. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  55. package/dist/integrations/gitlab/rules.js +32 -8
  56. package/dist/integrations/gitlab/rules.js.map +1 -1
  57. package/dist/integrations/incidentio/integration.d.ts +2 -1
  58. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  59. package/dist/integrations/incidentio/integration.js +7 -7
  60. package/dist/integrations/incidentio/integration.js.map +1 -1
  61. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  62. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  63. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  64. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  65. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  66. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  68. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  69. package/dist/integrations/incidentio/routes.d.ts +24 -8
  70. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/routes.js +33 -35
  72. package/dist/integrations/incidentio/routes.js.map +1 -1
  73. package/dist/integrations/incidentio/rules.d.ts +0 -4
  74. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  75. package/dist/integrations/incidentio/rules.js +17 -14
  76. package/dist/integrations/incidentio/rules.js.map +1 -1
  77. package/dist/integrations/intake-discovery.d.ts +44 -0
  78. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  79. package/dist/integrations/intake-discovery.js +60 -0
  80. package/dist/integrations/intake-discovery.js.map +1 -0
  81. package/dist/integrations/issue-reconcile-worker.js +1 -1
  82. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  83. package/dist/integrations/issue-reconciler.d.ts +7 -0
  84. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  85. package/dist/integrations/issue-reconciler.js +47 -12
  86. package/dist/integrations/issue-reconciler.js.map +1 -1
  87. package/dist/integrations/jira/integration.d.ts +3 -2
  88. package/dist/integrations/jira/integration.d.ts.map +1 -1
  89. package/dist/integrations/jira/integration.js +5 -7
  90. package/dist/integrations/jira/integration.js.map +1 -1
  91. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  92. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/jira/issue-reconciler.js +34 -1
  94. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  96. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  97. package/dist/integrations/jira/reconciliation-config.js +2 -5
  98. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  99. package/dist/integrations/jira/routes.d.ts +0 -7
  100. package/dist/integrations/jira/routes.d.ts.map +1 -1
  101. package/dist/integrations/jira/routes.js +2 -12
  102. package/dist/integrations/jira/routes.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts +0 -4
  104. package/dist/integrations/jira/rules.d.ts.map +1 -1
  105. package/dist/integrations/jira/rules.js +3 -13
  106. package/dist/integrations/jira/rules.js.map +1 -1
  107. package/dist/integrations/kept-cards.d.ts +49 -0
  108. package/dist/integrations/kept-cards.d.ts.map +1 -0
  109. package/dist/integrations/kept-cards.js +97 -0
  110. package/dist/integrations/kept-cards.js.map +1 -0
  111. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  112. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  113. package/dist/integrations/linear/intake-discovery.js +112 -0
  114. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  115. package/dist/integrations/linear/integration.d.ts.map +1 -1
  116. package/dist/integrations/linear/integration.js +1 -4
  117. package/dist/integrations/linear/integration.js.map +1 -1
  118. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  119. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  120. package/dist/integrations/linear/issue-reconciler.js +24 -20
  121. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  122. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  123. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  124. package/dist/integrations/linear/reconciliation-config.js +2 -8
  125. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  126. package/dist/integrations/linear/routes.d.ts +0 -2
  127. package/dist/integrations/linear/routes.d.ts.map +1 -1
  128. package/dist/integrations/linear/routes.js +3 -9
  129. package/dist/integrations/linear/routes.js.map +1 -1
  130. package/dist/integrations/platform/api-client.d.ts +2 -0
  131. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  132. package/dist/integrations/platform/api-client.js +6 -1
  133. package/dist/integrations/platform/api-client.js.map +1 -1
  134. package/dist/integrations/platform/connect/routes.js +4 -1
  135. package/dist/integrations/platform/connect/routes.js.map +1 -1
  136. package/dist/integrations/platform/github/event-worker.d.ts +12 -0
  137. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  138. package/dist/integrations/platform/github/event-worker.js +56 -5
  139. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  140. package/dist/integrations/platform/github/integration.d.ts +1 -0
  141. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  142. package/dist/integrations/platform/github/integration.js +8 -3
  143. package/dist/integrations/platform/github/integration.js.map +1 -1
  144. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  145. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  146. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  147. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  148. package/dist/integrations/platform/incidentio/integration.js +7 -7
  149. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  150. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  151. package/dist/integrations/platform/jira/integration.js +4 -7
  152. package/dist/integrations/platform/jira/integration.js.map +1 -1
  153. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  154. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  155. package/dist/integrations/platform/jira/routes.js +2 -12
  156. package/dist/integrations/platform/jira/routes.js.map +1 -1
  157. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  158. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  159. package/dist/integrations/platform/linear/event-worker.js +1 -1
  160. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  161. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  162. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  163. package/dist/integrations/platform/linear/integration.js +7 -7
  164. package/dist/integrations/platform/linear/integration.js.map +1 -1
  165. package/dist/integrations/platform/vanta/integration.d.ts +7 -2
  166. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  167. package/dist/integrations/platform/vanta/integration.js +22 -6
  168. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  169. package/dist/integrations/reconciliation-config.d.ts +0 -1
  170. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  171. package/dist/integrations/reconciliation-config.js +1 -8
  172. package/dist/integrations/reconciliation-config.js.map +1 -1
  173. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  175. package/dist/integrations/startup-summary.d.ts +8 -0
  176. package/dist/integrations/startup-summary.d.ts.map +1 -0
  177. package/dist/integrations/startup-summary.js +36 -0
  178. package/dist/integrations/startup-summary.js.map +1 -0
  179. package/dist/integrations/vanta/sync.d.ts +9 -5
  180. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  181. package/dist/integrations/vanta/sync.js +16 -8
  182. package/dist/integrations/vanta/sync.js.map +1 -1
  183. package/dist/linked-repositories-changed.d.ts +14 -0
  184. package/dist/linked-repositories-changed.d.ts.map +1 -0
  185. package/dist/linked-repositories-changed.js +48 -0
  186. package/dist/linked-repositories-changed.js.map +1 -0
  187. package/dist/routes/contracts.d.ts +117 -0
  188. package/dist/routes/contracts.d.ts.map +1 -1
  189. package/dist/routes/contracts.js +44 -1
  190. package/dist/routes/contracts.js.map +1 -1
  191. package/dist/routes/run-queue.d.ts +17 -0
  192. package/dist/routes/run-queue.d.ts.map +1 -0
  193. package/dist/routes/run-queue.js +69 -0
  194. package/dist/routes/run-queue.js.map +1 -0
  195. package/dist/routes/surface.d.ts +8 -0
  196. package/dist/routes/surface.d.ts.map +1 -1
  197. package/dist/routes/surface.js +4 -2
  198. package/dist/routes/surface.js.map +1 -1
  199. package/dist/routes/work-item-selection.d.ts +4 -1
  200. package/dist/routes/work-item-selection.d.ts.map +1 -1
  201. package/dist/routes/work-item-selection.js +7 -2
  202. package/dist/routes/work-item-selection.js.map +1 -1
  203. package/dist/routes/work-items.d.ts +5 -0
  204. package/dist/routes/work-items.d.ts.map +1 -1
  205. package/dist/routes/work-items.js +17 -0
  206. package/dist/routes/work-items.js.map +1 -1
  207. package/dist/rules/dispatcher.d.ts +13 -1
  208. package/dist/rules/dispatcher.d.ts.map +1 -1
  209. package/dist/rules/dispatcher.js +9 -2
  210. package/dist/rules/dispatcher.js.map +1 -1
  211. package/dist/rules/review-source-tool.js +2 -1
  212. package/dist/rules/review-source-tool.js.map +1 -1
  213. package/dist/storage/domains/projects/base.d.ts +2 -0
  214. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  215. package/dist/storage/domains/projects/base.js +13 -1
  216. package/dist/storage/domains/projects/base.js.map +1 -1
  217. package/dist/storage/domains/source-control/base.d.ts +32 -0
  218. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  219. package/dist/storage/domains/source-control/base.js +54 -4
  220. package/dist/storage/domains/source-control/base.js.map +1 -1
  221. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  222. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  223. package/dist/storage/domains/source-control/inmemory.js +17 -0
  224. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  225. package/dist/storage/domains/work-items/base.d.ts +1 -0
  226. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  227. package/dist/storage/domains/work-items/base.js +9 -0
  228. package/dist/storage/domains/work-items/base.js.map +1 -1
  229. package/dist/timing.d.ts +8 -1
  230. package/dist/timing.d.ts.map +1 -1
  231. package/dist/timing.js +10 -2
  232. package/dist/timing.js.map +1 -1
  233. package/dist/work-items/source-external-id.d.ts +4 -0
  234. package/dist/work-items/source-external-id.d.ts.map +1 -0
  235. package/dist/work-items/source-external-id.js +9 -0
  236. package/dist/work-items/source-external-id.js.map +1 -0
  237. package/package.json +8 -8
@@ -0,0 +1,107 @@
1
+ import { ingestListedEvents, listedIssueEvent, listedMergeRequestEvents, positiveId, routedGitLabSourceIds } from "./routes.js";
2
+ import { attachGitLabRules } from "./rules.js";
3
+ // src/integrations/gitlab/discovery.ts
4
+ /**
5
+ * First observation of the merge requests and issues GitLab sent no event
6
+ * for. It runs inside the leased reconcile sweep, so a card appears whether or
7
+ * not anyone has the board open, and the list routes stay pure reads.
8
+ *
9
+ * A listed delivery every Factory has settled would only replay, after paying
10
+ * for its rule evaluation and GitLab member lookups. The sweep remembers those
11
+ * per project and skips them, so an unchanged GitLab costs listings only. The
12
+ * memory holds what the last sweep listed and nothing older; a restart or a
13
+ * lease moving to another replica costs one pass that replays.
14
+ */
15
+ function attachGitLabDiscovery(gitlab, context) {
16
+ const ingest = attachGitLabRules(gitlab, context);
17
+ if (!ingest) return void 0;
18
+ const { projects, sourceControl, intake } = context.storage;
19
+ let settled = /* @__PURE__ */ new Set();
20
+ return async () => {
21
+ const listed = /* @__PURE__ */ new Set();
22
+ const summary = {
23
+ projects: 0,
24
+ checked: 0,
25
+ updated: 0,
26
+ closed: 0,
27
+ missing: 0,
28
+ failed: 0,
29
+ errors: []
30
+ };
31
+ for (const project of await projects.listAll()) {
32
+ summary.projects += 1;
33
+ const scope = {
34
+ orgId: project.orgId,
35
+ factoryProjectId: project.id
36
+ };
37
+ const failed = (error) => {
38
+ summary.failed += 1;
39
+ summary.errors.push({
40
+ projectId: project.id,
41
+ error: error instanceof Error ? error.message : String(error)
42
+ });
43
+ };
44
+ const key = (event) => `${project.id}\u0000${event.deliveryId}`;
45
+ const unsettled = (events) => events.filter((event) => {
46
+ if (!event || !settled.has(key(event))) return event !== null;
47
+ listed.add(key(event));
48
+ return false;
49
+ });
50
+ const remembered = async (event) => {
51
+ const result = await ingest(event);
52
+ if (result.settled) listed.add(key(event));
53
+ return result;
54
+ };
55
+ const each = async (list, discover) => {
56
+ for (const entry of await list().catch((error) => (failed(error), []))) await discover(entry).catch(failed);
57
+ };
58
+ await each(() => sourceControl.projectRepositories.listByProject(scope), async (link) => {
59
+ const linked = await gitlab.getLinkedRepository({
60
+ ...scope,
61
+ projectRepositoryId: link.id
62
+ });
63
+ const projectId = linked && positiveId(linked.repository.externalId);
64
+ if (!linked || !projectId) return;
65
+ const target = await gitlab.versionControl.getRepositoryTarget({
66
+ orgId: project.orgId,
67
+ repositoryId: linked.repository.id
68
+ });
69
+ for (let page = 1; page <= 5; page += 1) {
70
+ const result = await gitlab.versionControl.listPullRequests({
71
+ ...target,
72
+ includeDrafts: false,
73
+ cursor: String(page)
74
+ });
75
+ const events = result.pullRequests.flatMap((pr) => listedMergeRequestEvents({
76
+ host: linked.host,
77
+ projectId,
78
+ projectPath: linked.repository.slug
79
+ }, pr));
80
+ (await ingestListedEvents(unsettled(events), remembered)).forEach(failed);
81
+ if (result.nextCursor === null) break;
82
+ }
83
+ });
84
+ await each(async () => await routedGitLabSourceIds(intake, scope) ?? [], async (sourceId) => {
85
+ let cursor;
86
+ for (let page = 1; page <= 5; page += 1) {
87
+ const result = await gitlab.intake.listIssues({
88
+ connection: {
89
+ type: "oauth",
90
+ accessToken: "gitlab-sweep"
91
+ },
92
+ sourceIds: [sourceId],
93
+ cursor
94
+ });
95
+ (await ingestListedEvents(unsettled(result.issues.map(listedIssueEvent)), remembered)).forEach(failed);
96
+ if (result.nextCursor === null) break;
97
+ cursor = result.nextCursor;
98
+ }
99
+ });
100
+ }
101
+ settled = listed;
102
+ return summary;
103
+ };
104
+ }
105
+ export { attachGitLabDiscovery };
106
+
107
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.js","names":[],"sources":["../../../src/integrations/gitlab/discovery.ts"],"sourcesContent":["import type { IntegrationContext } from '../base.js';\nimport type { IssueReconciler, IssueReconcileSummary } from '../issue-reconciler.js';\nimport type { GitLabIntegrationBase } from './integration.js';\nimport {\n ingestListedEvents,\n LINKED_BACKLOG_MAX_PAGES,\n listedIssueEvent,\n listedMergeRequestEvents,\n positiveId,\n routedGitLabSourceIds,\n} from './routes.js';\nimport { attachGitLabRules } from './rules.js';\nimport type { ParsedGitLabWebhook } from './webhook.js';\n\n/**\n * First observation of the merge requests and issues GitLab sent no event\n * for. It runs inside the leased reconcile sweep, so a card appears whether or\n * not anyone has the board open, and the list routes stay pure reads.\n *\n * A listed delivery every Factory has settled would only replay, after paying\n * for its rule evaluation and GitLab member lookups. The sweep remembers those\n * per project and skips them, so an unchanged GitLab costs listings only. The\n * memory holds what the last sweep listed and nothing older; a restart or a\n * lease moving to another replica costs one pass that replays.\n */\nexport function attachGitLabDiscovery(\n gitlab: Pick<\n GitLabIntegrationBase,\n | 'versionControl'\n | 'intake'\n | 'getLinkedRepository'\n | 'rules'\n | 'getProjectMemberAccessLevel'\n | 'getWorkItemAuthorUsername'\n | 'resolveActiveConnectionForHost'\n >,\n context: IntegrationContext,\n): IssueReconciler | undefined {\n const ingest = attachGitLabRules(gitlab, context);\n if (!ingest) return undefined;\n const { projects, sourceControl, intake } = context.storage;\n let settled = new Set<string>();\n\n return async () => {\n const listed = new Set<string>();\n const summary: IssueReconcileSummary = {\n projects: 0,\n checked: 0,\n updated: 0,\n closed: 0,\n missing: 0,\n failed: 0,\n errors: [],\n };\n for (const project of await projects.listAll()) {\n summary.projects += 1;\n const scope = { orgId: project.orgId, factoryProjectId: project.id };\n const failed = (error: unknown) => {\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n };\n const key = (event: ParsedGitLabWebhook) => `${project.id}\\u0000${event.deliveryId}`;\n const unsettled = (events: Array<ParsedGitLabWebhook | null>) =>\n events.filter((event): event is ParsedGitLabWebhook => {\n if (!event || !settled.has(key(event))) return event !== null;\n listed.add(key(event));\n return false;\n });\n const remembered = async (event: ParsedGitLabWebhook) => {\n const result = await ingest(event);\n if (result.settled) listed.add(key(event));\n return result;\n };\n // One unreachable repository or source must not hide the others.\n const each = async <T>(list: () => Promise<T[]>, discover: (entry: T) => Promise<void>) => {\n for (const entry of await list().catch(error => (failed(error), []))) await discover(entry).catch(failed);\n };\n\n await each(\n () => sourceControl.projectRepositories.listByProject(scope),\n async link => {\n const linked = await gitlab.getLinkedRepository({ ...scope, projectRepositoryId: link.id });\n const projectId = linked && positiveId(linked.repository.externalId);\n if (!linked || !projectId) return;\n const target = await gitlab.versionControl.getRepositoryTarget({\n orgId: project.orgId,\n repositoryId: linked.repository.id,\n });\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await gitlab.versionControl.listPullRequests({\n ...target,\n includeDrafts: false,\n cursor: String(page),\n });\n const events = result.pullRequests.flatMap(pr =>\n listedMergeRequestEvents({ host: linked.host, projectId, projectPath: linked.repository.slug }, pr),\n );\n (await ingestListedEvents(unsettled(events), remembered)).forEach(failed);\n if (result.nextCursor === null) break;\n }\n },\n );\n\n await each(\n async () => (await routedGitLabSourceIds(intake, scope)) ?? [],\n async sourceId => {\n let cursor: string | undefined;\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await gitlab.intake.listIssues({\n // GitLab resolves the credential from the source id; no caller identity is read.\n connection: { type: 'oauth', accessToken: 'gitlab-sweep' },\n sourceIds: [sourceId],\n cursor,\n });\n (await ingestListedEvents(unsettled(result.issues.map(listedIssueEvent)), remembered)).forEach(failed);\n if (result.nextCursor === null) break;\n cursor = result.nextCursor;\n }\n },\n );\n }\n settled = listed;\n return summary;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAgB,sBACd,QAUA,SAC6B;CAC7B,MAAM,SAAS,kBAAkB,QAAQ,OAAO;CAChD,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,EAAE,UAAU,eAAe,WAAW,QAAQ;CACpD,IAAI,0BAAU,IAAI,IAAY;CAE9B,OAAO,YAAY;EACjB,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,UAAiC;GACrC,UAAU;GACV,SAAS;GACT,SAAS;GACT,QAAQ;GACR,SAAS;GACT,QAAQ;GACR,QAAQ,CAAC;EACX;EACA,KAAK,MAAM,WAAW,MAAM,SAAS,QAAQ,GAAG;GAC9C,QAAQ,YAAY;GACpB,MAAM,QAAQ;IAAE,OAAO,QAAQ;IAAO,kBAAkB,QAAQ;GAAG;GACnE,MAAM,UAAU,UAAmB;IACjC,QAAQ,UAAU;IAClB,QAAQ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AAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,qBAAqB,GAAG,IAAI,CAE1E;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,oBAAoB,GAAG,MAAM,CAa5E;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,oBAAoB,GAAG,IAAI,CAE/E;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,2BAA2B,GAAG,IAAI,CAE7F;AAED,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,qBAAqB,CAE5E;AAqBD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAExD"}
@@ -3,7 +3,7 @@ import { buildGitLabAgentTools } from "./agent-tools.js";
3
3
  import { GitLabApiClient, GitLabApiError } from "./api.js";
4
4
  import { resolveGitLabRules } from "./default-rules.js";
5
5
  import { attachGitLabReconciler } from "./reconciler.js";
6
- import { gitlabReconciliationEnabled, gitlabReconciliationInterval } from "./reconciliation-config.js";
6
+ import { gitlabReconciliationInterval } from "./reconciliation-config.js";
7
7
  import { buildGitLabRoutes, ingestLinkedGitLabRepositoryBacklog } from "./routes.js";
8
8
  import { attachGitLabRules } from "./rules.js";
9
9
  import { createGitLabSubscriptionTools, parseCreatedMergeRequest, subscribeCurrentSessionToMergeRequest } from "./session-subscriptions.js";
@@ -184,7 +184,6 @@ var GitLabIntegrationBase = class {
184
184
  async verifyStatus() {}
185
185
  get webhookSecret() {}
186
186
  workers(ctx) {
187
- if (!gitlabReconciliationEnabled()) return [];
188
187
  const reconcile = attachGitLabReconciler(this, ctx);
189
188
  if (!reconcile) return [];
190
189
  const intervalMs = gitlabReconciliationInterval();
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/gitlab/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n CreatedIntakeComment,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n IntakeItemPage,\n IntakeSource,\n ListIntakeIssuesInput,\n ListIntakeItemsInput,\n ResolveIntakeDispatchInput,\n ResolvedIntakeDispatch,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildGitLabAgentTools } from './agent-tools.js';\nimport {\n GITLAB_ISSUES_PAGE_SIZE,\n GITLAB_NOTES_PAGE_SIZE,\n GITLAB_PROJECTS_PAGE_SIZE,\n GitLabApiClient,\n GitLabApiError,\n} from './api.js';\nimport type { GitLabIssue, GitLabNote, GitLabProject } from './api.js';\nimport { resolveGitLabRules } from './default-rules.js';\nimport type { GitLabEventRules, GitLabRuleOverrides } from './default-rules.js';\nimport { attachGitLabReconciler } from './reconciler.js';\nimport { gitlabReconciliationEnabled, gitlabReconciliationInterval } from './reconciliation-config.js';\nimport { buildGitLabRoutes, ingestLinkedGitLabRepositoryBacklog } from './routes.js';\nimport { attachGitLabRules } from './rules.js';\nimport {\n createGitLabSubscriptionTools,\n parseCreatedMergeRequest,\n subscribeCurrentSessionToMergeRequest,\n} from './session-subscriptions.js';\nimport type { GitLabSubscriptionStorage } from './subscriptions.js';\nimport { buildGitLabVersionControl } from './version-control.js';\n\ninterface GitLabConnectionContext {\n id: string;\n label: string | null;\n api: GitLabApiClient;\n connection: IntegrationConnection;\n host: string;\n webBaseUrl?: string;\n /** Resolves a fresh provider token for a single brokered git operation. */\n repositoryAccessToken?: () => Promise<string>;\n}\n\ninterface GitLabSourceReference {\n /** Present only on legacy v1 ids; authentication is not resource identity. */\n connectionId?: string;\n /** Canonical v2 ids use the GitLab instance host plus immutable project id. */\n host?: string;\n projectId: string;\n /** Legacy ids carry display metadata; v2 resolves it from GitLab. */\n projectPath?: string;\n}\n\ninterface ResolvedGitLabSourceReference extends GitLabSourceReference {\n connectionId: string;\n host: string;\n projectPath: string;\n}\n\ninterface GitLabIssueReference extends GitLabSourceReference {\n issueIid: number;\n}\n\nexport interface GitLabMergeRequestReference {\n version: 1;\n host: string;\n projectId: number;\n mergeRequestIid: number;\n}\n\ninterface GitLabPageCursor {\n source: number;\n page: number;\n}\n\nexport interface GitLabStatusConnection {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n}\n\nconst DIRECT_CONNECTION_ID = 'direct';\nconst GITLAB_CONNECTION_TOKEN_PREFIX = 'gitlab-connection:';\nconst GITLAB_SOURCE_PREFIX = 'gitlab-project:';\nconst GITLAB_ISSUE_PREFIX = 'gitlab-issue:';\nconst GITLAB_MERGE_REQUEST_PREFIX = 'gitlab-pr:';\nexport const GITLAB_TRUSTED_ACCESS_LEVEL = 30;\n// Bound issue detail reads to 2,000 notes. GitLab does not expose truncation through the Intake contract.\nconst MAX_NOTES_PAGES = 20;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport abstract class GitLabIntegrationBase implements FactoryIntegration {\n readonly id = 'gitlab';\n #projects: FactoryProjectsStorage | undefined;\n #sourceControl: SourceControlStorageHandle | undefined;\n #integrationStorage: GitLabSubscriptionStorage | undefined;\n #auth: RouteAuth | undefined;\n #ingestFactoryEvent: ReturnType<typeof attachGitLabRules>;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n readonly rules: GitLabEventRules;\n\n constructor(rules?: GitLabRuleOverrides) {\n this.rules = resolveGitLabRules(rules);\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: () => this.#listSources(),\n listItems: input => this.#listItems(input),\n listIssues: input => this.#listIssues(input),\n getIssue: input => this.#getIssue(input),\n createComment: input => this.#createComment(input),\n updateIssue: input => this.#updateIssue(input),\n };\n readonly versionControl = buildGitLabVersionControl({\n contextForConnection: connection => this.#versionControlContext(connection),\n contextForStoredInstallation: (connection, host) => this.#versionControlContextForInstallation(connection, host),\n });\n initialize({\n storage,\n projects,\n auth,\n sourceControl,\n }: {\n storage?: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n sourceControl?: SourceControlStorageHandle;\n }): void {\n this.#projects = projects;\n this.#auth = auth;\n this.#sourceControl = sourceControl;\n this.#integrationStorage = storage as GitLabSubscriptionStorage | undefined;\n }\n\n /** Generic integration persistence (merge-request subscriptions). */\n get integrationStorage(): GitLabSubscriptionStorage {\n if (!this.#integrationStorage) {\n throw new Error(`${this.constructor.name} is not initialized — the factory binds storage during prepare().`);\n }\n return this.#integrationStorage;\n }\n\n /** Source-control rows for this integration; absent when the host runs without them. */\n get sourceControlStorage(): SourceControlStorageHandle | undefined {\n return this.#sourceControl;\n }\n\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error(`${this.constructor.name} is not initialized — the factory binds storage during prepare().`);\n }\n return this.#projects;\n }\n\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n const orgId = project?.orgId ?? null;\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n } catch {\n return null;\n }\n }\n\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n abstract hasActiveConnections(): Promise<boolean>;\n abstract authFailureMessage(): string;\n protected abstract activeContexts(): Promise<GitLabConnectionContext[]>;\n protected abstract contextById(connectionId: string): Promise<GitLabConnectionContext>;\n\n /** Resolve only a GitLab repository linked to this Factory in this organization. */\n async getLinkedRepository(input: { orgId: string; factoryProjectId: string; projectRepositoryId: string }) {\n if (!this.#sourceControl) return null;\n const connections = await this.#sourceControl.connections.list({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n for (const connection of connections) {\n if (connection.integrationId !== 'gitlab') continue;\n const links = await this.#sourceControl.projectRepositories.list({\n orgId: input.orgId,\n connectionId: connection.id,\n });\n const link = links.find(candidate => candidate.id === input.projectRepositoryId);\n if (!link) continue;\n const repository = await this.#sourceControl.repositories.get({ orgId: input.orgId, id: link.repositoryId });\n const installation = await this.#sourceControl.installations.get({\n orgId: input.orgId,\n id: connection.installationId,\n });\n if (!repository || !installation) return null;\n const host = installation.providerMetadata.host;\n if (typeof host !== 'string' || !host) return null;\n return { repository, host: normalizeGitLabHost(host) };\n }\n return null;\n }\n\n async getProjectMemberAccessLevel(\n connectionId: string,\n projectId: string,\n username: string,\n ): Promise<number | undefined> {\n const normalized = username.trim().toLowerCase();\n if (!normalized) return undefined;\n const members = await (await this.contextById(connectionId)).api.listProjectMembers(projectId, { query: username });\n const member = members.find(\n candidate => candidate.username.toLowerCase() === normalized && candidate.state !== 'blocked',\n );\n return member?.access_level;\n }\n\n async getWorkItemAuthorUsername(\n connectionId: string,\n projectId: string,\n kind: 'issue' | 'merge_request',\n iid: number,\n ): Promise<string | undefined> {\n const api = (await this.contextById(connectionId)).api;\n const item = kind === 'issue' ? await api.getIssue(projectId, iid) : await api.getMergeRequest(projectId, iid);\n return item.author?.username;\n }\n\n async isProjectMemberTrustedForSource(sourceId: string, username: string): Promise<boolean> {\n const reference = decodeSourceId(sourceId);\n if (!reference) throw new GitLabApiError('GitLab source identity is invalid.', 400);\n const { context, source } = await this.#resolveSourceReference(reference);\n const accessLevel = await this.getProjectMemberAccessLevel(context.id, source.projectId, username);\n return (accessLevel ?? 0) >= GITLAB_TRUSTED_ACCESS_LEVEL;\n }\n\n async getIssueForFactoryProject(input: {\n orgId: string;\n factoryProjectId: string;\n issueId: string;\n }): Promise<IntakeIssueDetail | null> {\n if (!this.#sourceControl) throw new GitLabApiError('GitLab source control is unavailable.', 503);\n const reference = decodeIssueReference(input.issueId);\n const locator = parseIssueLocator(input.issueId);\n if (!reference && !locator) {\n throw new GitLabApiError('GitLab issue must include a project and issue IID.', 400);\n }\n\n const normalizePath = (value: string) => value.replace(/^\\/+|\\/+$/g, '').toLowerCase();\n const matches: Array<{\n connectionId: string;\n projectId: string;\n projectPath: string;\n }> = [];\n const connections = await this.#sourceControl.connections.list({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n for (const connection of connections) {\n const installation = await this.#sourceControl.installations.get({\n orgId: input.orgId,\n id: connection.installationId,\n });\n if (!installation) continue;\n for (const projectRepository of await this.#sourceControl.projectRepositories.list({\n orgId: input.orgId,\n connectionId: connection.id,\n })) {\n const repository = await this.#sourceControl.repositories.get({\n orgId: input.orgId,\n id: projectRepository.repositoryId,\n });\n if (!repository) continue;\n if (reference?.projectId && repository.externalId !== reference.projectId) continue;\n if (reference?.projectPath && normalizePath(repository.slug) !== normalizePath(reference.projectPath)) continue;\n if (locator?.projectPath && normalizePath(repository.slug) !== normalizePath(locator.projectPath)) continue;\n if (reference?.connectionId && installation.externalId !== reference.connectionId) continue;\n const installationHost =\n typeof installation.providerMetadata.host === 'string'\n ? normalizeGitLabHost(installation.providerMetadata.host)\n : null;\n if (reference?.host && installationHost !== normalizeGitLabHost(reference.host)) continue;\n if (locator?.host && installationHost !== normalizeGitLabHost(locator.host)) continue;\n matches.push({\n connectionId: installation.externalId,\n projectId: repository.externalId,\n projectPath: repository.slug,\n });\n }\n }\n const match = matches.sort((left, right) => left.connectionId.localeCompare(right.connectionId))[0];\n if (!match) throw new GitLabApiError('GitLab issue is outside the active Factory project.', 404);\n return this.intake.getIssue({\n connection: gitlabConnection(match.connectionId),\n sourceId: encodeSourceId(match),\n issueId: input.issueId,\n });\n }\n\n /** Platform mode exposes org connections; direct mode returns undefined. */\n async statusConnections(): Promise<GitLabStatusConnection[] | undefined> {\n return undefined;\n }\n\n /** Direct mode verifies its configured credential; Platform mode uses connection status. */\n async verifyStatus(): Promise<void> {\n // Platform connection state is authoritative unless a provider overrides this probe.\n }\n\n protected get webhookSecret(): string | undefined {\n return undefined;\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!gitlabReconciliationEnabled()) return [];\n const reconcile = attachGitLabReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = gitlabReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n routes(ctx: IntegrationContext): ApiRoute[] {\n const ingestFactoryEvent = attachGitLabRules(this, ctx);\n this.#ingestFactoryEvent = ingestFactoryEvent;\n return buildGitLabRoutes({\n gitlab: this,\n auth: ctx.auth,\n intake: ctx.storage?.intake,\n emitAudit: ctx.hooks?.emitAudit,\n sandbox: ctx.sandbox,\n webhookSecret: this.webhookSecret,\n ingestFactoryEvent,\n ...(ctx.controller ? { controller: ctx.controller } : {}),\n });\n }\n\n async ingestLinkedRepositoryBacklog(args: { orgId: string; projectRepositoryId: string }): Promise<void> {\n await ingestLinkedGitLabRepositoryBacklog({ gitlab: this, ...args, ingestFactoryEvent: this.#ingestFactoryEvent });\n }\n\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildGitLabAgentTools({ requestContext: args.requestContext, gitlab: this });\n }\n\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGitLabSubscriptionTools(requestContext, this);\n }\n\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const mergeRequestUrl = parseCreatedMergeRequest(toolContext);\n if (!mergeRequestUrl || !requestContext) return;\n await subscribeCurrentSessionToMergeRequest(requestContext, mergeRequestUrl, 'auto-create-change-request', this);\n }\n\n abstract diagnostics(): Record<string, unknown>;\n\n /** Prefer the configured direct token over an older Platform installation on the same host. */\n async resolveActiveConnectionForHost(storedConnectionId: string, host: string): Promise<string> {\n if (this.diagnostics().mode !== 'direct') return storedConnectionId;\n const [direct] = await this.activeContexts();\n return direct && normalizeGitLabHost(direct.host) === normalizeGitLabHost(host) ? direct.id : storedConnectionId;\n }\n\n async #versionControlContext(connection: IntegrationConnection): Promise<GitLabConnectionContext> {\n const connectionId = connectionIdFromConnection(connection);\n if (connectionId) return this.contextById(connectionId);\n const contexts = await this.activeContexts();\n if (contexts.length !== 1) {\n throw new GitLabApiError(\n 'GitLab version-control requests must identify a connection when multiple GitLab accounts are connected.',\n 400,\n );\n }\n return contexts[0]!;\n }\n async #versionControlContextForInstallation(\n connection: IntegrationConnection,\n host: string | undefined,\n ): Promise<GitLabConnectionContext> {\n // A direct PAT intentionally overrides Platform credentials. Old links can\n // retain their Platform connection id; use the PAT only for the same host.\n if (this.diagnostics().mode === 'direct' && host) {\n const [direct] = await this.activeContexts();\n if (direct && normalizeGitLabHost(host) === normalizeGitLabHost(direct.host)) return direct;\n }\n return this.#versionControlContext(connection);\n }\n async #contextForReference(reference: GitLabSourceReference): Promise<GitLabConnectionContext> {\n if (reference.connectionId) return this.contextById(reference.connectionId);\n const contexts = (await this.activeContexts()).filter(\n context => !reference.host || normalizeGitLabHost(context.host) === normalizeGitLabHost(reference.host),\n );\n if (contexts.length === 0) {\n throw new GitLabApiError('No active GitLab connection can access this source.', 401);\n }\n if (contexts.length === 1) return contexts[0]!;\n\n if (this.#sourceControl) {\n const linkedConnectionIds = new Set(\n (await this.#sourceControl.projectRepositories.listConfiguredExternalKeys())\n .filter(key => key.repositoryExternalId === reference.projectId)\n .map(key => key.installationExternalId),\n );\n const linked = contexts.filter(context => linkedConnectionIds.has(context.id));\n if (linked.length > 0) return linked.sort((left, right) => left.id.localeCompare(right.id))[0]!;\n }\n\n for (const context of contexts.sort((left, right) => left.id.localeCompare(right.id))) {\n try {\n await context.api.getProject(reference.projectId);\n return context;\n } catch (error) {\n if (!(error instanceof GitLabApiError) || ![401, 403, 404].includes(error.status ?? 0)) throw error;\n // This credential cannot access the project; try another active account for the same canonical source.\n }\n }\n throw new GitLabApiError('No active GitLab connection can access this source.', 404);\n }\n\n async #resolveSourceReference(\n reference: GitLabSourceReference,\n ): Promise<{ context: GitLabConnectionContext; source: ResolvedGitLabSourceReference }> {\n const context = await this.#contextForReference(reference);\n const projectPath =\n reference.projectPath ?? (await context.api.getProject(reference.projectId)).path_with_namespace;\n return {\n context,\n source: {\n connectionId: context.id,\n host: normalizeGitLabHost(reference.host ?? context.host),\n projectId: reference.projectId,\n projectPath,\n },\n };\n }\n\n async #resolveIntakeDispatch({ externalSource }: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null> {\n if (externalSource.type !== 'issue') return null;\n const reference = decodeIssueReference(externalSource.externalId);\n if (!reference) return null;\n const { context, source } = await this.#resolveSourceReference(reference);\n return {\n connection: context.connection,\n sourceId: encodeSourceId(source),\n issueId: String(reference.issueIid),\n };\n }\n\n async #listSources(): Promise<IntakeSource[]> {\n const sources = new Map<string, IntakeSource>();\n for (const context of await this.activeContexts()) {\n for (let page = 1; ; page++) {\n const projects = await context.api.listProjects({ page });\n for (const project of projects) {\n const source = this.#toIntakeSource(context, project);\n if (!sources.has(source.id)) sources.set(source.id, source);\n }\n if (projects.length < GITLAB_PROJECTS_PAGE_SIZE) break;\n }\n }\n return [...sources.values()];\n }\n\n async #listItems(input: ListIntakeItemsInput): Promise<IntakeItemPage> {\n const result = await this.#listIssuePage(input.sourceIds, input.cursor);\n return {\n items: result.issues.map(({ issue, source, context }) => ({\n source: {\n type: 'issue',\n externalId: encodeIssueReference({ ...source, issueIid: issue.iid }),\n url: issue.web_url,\n },\n sourceId: encodeSourceId(source),\n title: `${source.projectPath}#${issue.iid}: ${issue.title}`,\n status: issue.state,\n labels: issue.labels ?? [],\n assignee: displayName(issue.assignee),\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n metadata: {\n identifier: `${source.projectPath}#${issue.iid}`,\n projectId: source.projectId,\n projectPath: source.projectPath,\n connectionId: context.id,\n accountLabel: context.label,\n labelColors: Object.fromEntries((issue.labelDetails ?? []).map(label => [label.name, label.color])),\n },\n })),\n nextCursor: result.nextCursor,\n };\n }\n\n async #listIssues(input: ListIntakeIssuesInput) {\n const result = await this.#listIssuePage(input.sourceIds, input.cursor, input.labels);\n return {\n issues: result.issues.map(({ issue, source }) => ({\n ...this.#toIntakeIssue(issue, source.projectPath),\n sourceId: encodeSourceId(source),\n })),\n nextCursor: result.nextCursor,\n };\n }\n\n async #listIssuePage(sourceIds: string[], cursor?: string, labels?: string[]) {\n const sources = sourceIds.map(decodeSourceId).filter((source): source is GitLabSourceReference => source !== null);\n if (sources.length === 0) return { issues: [], nextCursor: null };\n const current = decodePageCursor(cursor);\n if (!current || current.source >= sources.length) return { issues: [], nextCursor: null };\n\n for (let sourceIndex = current.source; sourceIndex < sources.length; sourceIndex++) {\n const { source, context } = await this.#resolveSourceReference(sources[sourceIndex]!);\n const page = sourceIndex === current.source ? current.page : 1;\n const issues = await context.api.listIssues(source.projectId, { page, labels });\n const nextCursor =\n issues.length === GITLAB_ISSUES_PAGE_SIZE\n ? encodePageCursor({ source: sourceIndex, page: page + 1 })\n : sourceIndex + 1 < sources.length\n ? encodePageCursor({ source: sourceIndex + 1, page: 1 })\n : null;\n return { issues: issues.map(issue => ({ issue, source, context })), nextCursor };\n }\n return { issues: [], nextCursor: null };\n }\n\n async #getIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const resolved = await this.#resolveRequest(input);\n let issue: GitLabIssue;\n try {\n issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n const notes = await this.#listAllNotes(resolved.context.api, resolved.projectId, resolved.issueIid);\n return {\n ...this.#toIntakeIssue(issue, resolved.projectPath),\n description: issue.description?.trim() || null,\n comments: notes\n .filter(note => !note.system)\n .map(note => ({ author: displayName(note.author), body: note.body, createdAt: note.created_at })),\n };\n }\n\n async #listAllNotes(api: GitLabApiClient, projectId: string, issueIid: number): Promise<GitLabNote[]> {\n const notes: GitLabNote[] = [];\n for (let page = 1; page <= MAX_NOTES_PAGES; page++) {\n const result = await api.listNotes(projectId, issueIid, { page });\n notes.push(...result);\n if (result.length < GITLAB_NOTES_PAGE_SIZE) break;\n }\n return notes;\n }\n\n async #createComment(input: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null> {\n const resolved = await this.#resolveRequest(input);\n try {\n const issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n const note = await resolved.context.api.createNote(resolved.projectId, resolved.issueIid, input.body);\n return { id: String(note.id), url: `${issue.web_url}#note_${note.id}` };\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n async #updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const resolved = await this.#resolveRequest(input);\n let issue: GitLabIssue;\n try {\n issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n const stateEvent = targetStateEvent(input);\n if (!stateEvent) return null;\n if ((stateEvent === 'close' && issue.state === 'closed') || (stateEvent === 'reopen' && issue.state === 'opened')) {\n return this.#toIntakeIssue(issue, resolved.projectPath);\n }\n const updated = await resolved.context.api.updateIssueState(resolved.projectId, resolved.issueIid, stateEvent);\n return this.#toIntakeIssue(updated, resolved.projectPath);\n }\n\n async #resolveRequest(input: GetIntakeIssueInput): Promise<{\n context: GitLabConnectionContext;\n projectId: string;\n projectPath: string;\n issueIid: number;\n }> {\n const issueReference = decodeIssueReference(input.issueId);\n const source = input.sourceId ? decodeSourceId(input.sourceId) : null;\n const locator = parseIssueLocator(input.issueId);\n const reference = issueReference ?? source;\n let context: GitLabConnectionContext;\n if (reference) {\n context = await this.#contextForReference(reference);\n } else {\n const connectionId = connectionIdFromConnection(input.connection);\n const contexts = connectionId ? [await this.contextById(connectionId)] : await this.activeContexts();\n if (contexts.length !== 1) {\n throw new GitLabApiError('GitLab issue reference must resolve to exactly one active connection.', 400);\n }\n context = contexts[0]!;\n }\n const projectId = issueReference?.projectId ?? source?.projectId ?? locator?.projectPath;\n const issueIid = issueReference?.issueIid ?? locator?.issueIid ?? parsePositiveInteger(input.issueId);\n if (!projectId || !issueIid) {\n throw new GitLabApiError(\n 'GitLab issue must include a project and issue IID (for example, group/project#42).',\n 400,\n );\n }\n const projectPath =\n issueReference?.projectPath ??\n source?.projectPath ??\n locator?.projectPath ??\n (await context.api.getProject(projectId)).path_with_namespace;\n return { context, projectId, projectPath, issueIid };\n }\n\n #toIntakeSource(context: GitLabConnectionContext, project: GitLabProject): IntakeSource {\n const reference: GitLabSourceReference = {\n host: normalizeGitLabHost(context.host),\n projectId: String(project.id),\n projectPath: project.path_with_namespace,\n };\n return {\n id: encodeSourceId(reference),\n name: project.path_with_namespace,\n type: 'project',\n metadata: {\n projectId: String(project.id),\n projectPath: project.path_with_namespace,\n defaultBranch: project.default_branch ?? null,\n connectionId: context.id,\n accountLabel: context.label,\n url: project.web_url,\n },\n };\n }\n\n #toIntakeIssue(issue: GitLabIssue, projectPath: string): IntakeIssue {\n const assignees = issue.assignees?.map(displayName).filter((name): name is string => name !== null) ?? [];\n return {\n id: String(issue.iid),\n identifier: `${projectPath}#${issue.iid}`,\n title: issue.title,\n url: issue.web_url,\n author: displayName(issue.author),\n authorUsername: issue.author?.username ?? null,\n state: issue.state,\n stateType: issue.state === 'closed' ? 'completed' : 'unstarted',\n priority: typeof issue.weight === 'number' ? String(issue.weight) : null,\n assignee: displayName(issue.assignee) ?? assignees[0] ?? null,\n assignees,\n source: projectPath,\n labels: issue.labels ?? [],\n labelColors: Object.fromEntries((issue.labelDetails ?? []).map(label => [label.name, label.color])),\n commentCount: issue.user_notes_count ?? null,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n };\n }\n}\n\nexport type GitLabAccessTokenType = 'personal' | 'group';\n\nexport interface GitLabIntegrationConfig {\n rules?: GitLabRuleOverrides;\n accessToken?: string;\n /** Defaults to `personal`; both token types authenticate identically but have different resource reach. */\n accessTokenType?: GitLabAccessTokenType;\n baseUrl?: string;\n webhookSecret?: string;\n fetchImpl?: typeof fetch;\n}\n\nconst DIRECT_CONNECTION_TOKEN = 'gitlab-direct-access-token';\n\nexport class GitLabIntegration extends GitLabIntegrationBase {\n readonly #accessToken: string;\n readonly #accessTokenType: GitLabAccessTokenType;\n readonly #baseUrl: string;\n readonly #webhookSecret: string | undefined;\n readonly #context: GitLabConnectionContext;\n\n constructor(config: GitLabIntegrationConfig = {}) {\n super(config.rules);\n const accessToken = config.accessToken?.trim() || process.env.GITLAB_ACCESS_TOKEN?.trim();\n if (!accessToken) {\n throw new Error('GitLabIntegration: missing required GITLAB_ACCESS_TOKEN.');\n }\n this.#accessToken = accessToken;\n this.#accessTokenType = parseAccessTokenType(\n config.accessTokenType ?? process.env.GITLAB_ACCESS_TOKEN_TYPE?.trim(),\n );\n this.#baseUrl = (config.baseUrl ?? process.env.GITLAB_BASE_URL?.trim() ?? 'https://gitlab.com').replace(/\\/+$/, '');\n this.#webhookSecret = config.webhookSecret?.trim() || process.env.GITLAB_WEBHOOK_SECRET?.trim() || undefined;\n const api = new GitLabApiClient({\n baseUrl: this.#baseUrl,\n accessToken: this.#accessToken,\n ...(config.fetchImpl ? { fetchImpl: config.fetchImpl } : {}),\n });\n this.#context = {\n id: DIRECT_CONNECTION_ID,\n label: new URL(this.#baseUrl).host,\n api,\n connection: { type: 'oauth', accessToken: DIRECT_CONNECTION_TOKEN },\n host: new URL(this.#baseUrl).host,\n webBaseUrl: this.#baseUrl,\n repositoryAccessToken: async () => this.#accessToken,\n };\n }\n\n protected override get webhookSecret(): string | undefined {\n return this.#webhookSecret;\n }\n\n async hasActiveConnections(): Promise<boolean> {\n return true;\n }\n\n override async verifyStatus(): Promise<void> {\n await this.#context.api.getCurrentUser();\n }\n\n authFailureMessage(): string {\n return `GitLab rejected the configured ${this.#accessTokenType} access token. Check the token and its scopes.`;\n }\n\n protected async activeContexts(): Promise<GitLabConnectionContext[]> {\n return [this.#context];\n }\n\n protected async contextById(connectionId: string): Promise<GitLabConnectionContext> {\n if (connectionId !== DIRECT_CONNECTION_ID) {\n throw new GitLabApiError('GitLab connection is unavailable.', 401);\n }\n return this.#context;\n }\n\n diagnostics(): Record<string, unknown> {\n return {\n configured: true,\n mode: 'direct',\n accessTokenType: this.#accessTokenType,\n endpointHost: new URL(this.#baseUrl).host,\n webhookConfigured: Boolean(this.#webhookSecret),\n };\n }\n}\n\nfunction parseAccessTokenType(value: string | undefined): GitLabAccessTokenType {\n const normalized = value?.trim().toLowerCase() || 'personal';\n if (normalized === 'personal' || normalized === 'group') return normalized;\n throw new Error(\"GitLabIntegration: GITLAB_ACCESS_TOKEN_TYPE must be 'personal' or 'group'.\");\n}\n\nexport function encodeSourceId(reference: GitLabSourceReference): string {\n if (reference.host) {\n return `${GITLAB_SOURCE_PREFIX}${encodeOpaque({\n version: 2,\n host: normalizeGitLabHost(reference.host),\n projectId: reference.projectId,\n })}`;\n }\n if (!reference.connectionId || !reference.projectPath) {\n throw new Error('GitLab source reference is missing its instance host.');\n }\n return `${GITLAB_SOURCE_PREFIX}${encodeOpaque(reference)}`;\n}\n\nexport function decodeSourceId(value: string): GitLabSourceReference | null {\n return decodeOpaque(value, GITLAB_SOURCE_PREFIX, isSourceReference);\n}\n\nexport function encodeIssueReference(reference: GitLabIssueReference): string {\n if (reference.host) {\n return `${GITLAB_ISSUE_PREFIX}${encodeOpaque({\n version: 2,\n host: normalizeGitLabHost(reference.host),\n projectId: reference.projectId,\n issueIid: reference.issueIid,\n })}`;\n }\n if (!reference.connectionId || !reference.projectPath) {\n throw new Error('GitLab issue reference is missing its instance host.');\n }\n return `${GITLAB_ISSUE_PREFIX}${encodeOpaque(reference)}`;\n}\n\nexport function decodeIssueReference(value: string): GitLabIssueReference | null {\n return decodeOpaque(value, GITLAB_ISSUE_PREFIX, isIssueReference);\n}\n\nexport function decodeMergeRequestReference(value: string): GitLabMergeRequestReference | null {\n return decodeOpaque(value, GITLAB_MERGE_REQUEST_PREFIX, isMergeRequestReference);\n}\n\nexport function gitlabConnection(connectionId: string): IntegrationConnection {\n return { type: 'oauth', accessToken: `${GITLAB_CONNECTION_TOKEN_PREFIX}${connectionId}` };\n}\n\nfunction connectionIdFromConnection(connection: IntegrationConnection): string | null {\n if (connection.type !== 'oauth' || !connection.accessToken.startsWith(GITLAB_CONNECTION_TOKEN_PREFIX)) return null;\n return connection.accessToken.slice(GITLAB_CONNECTION_TOKEN_PREFIX.length) || null;\n}\n\nfunction encodeOpaque(value: unknown): string {\n return Buffer.from(JSON.stringify(value)).toString('base64url');\n}\n\nfunction decodeOpaque<T>(value: string, prefix: string, guard: (value: unknown) => value is T): T | null {\n if (!value.startsWith(prefix)) return null;\n try {\n const decoded = JSON.parse(Buffer.from(value.slice(prefix.length), 'base64url').toString('utf8')) as unknown;\n return guard(decoded) ? decoded : null;\n } catch {\n return null;\n }\n}\n\nexport function normalizeGitLabHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction isSourceReference(value: unknown): value is GitLabSourceReference {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const ref = value as Record<string, unknown>;\n if (typeof ref.projectId !== 'string' || ref.projectId.length === 0) return false;\n const canonical = ref.version === 2 && typeof ref.host === 'string' && normalizeGitLabHost(ref.host).length > 0;\n const legacy =\n typeof ref.connectionId === 'string' &&\n ref.connectionId.length > 0 &&\n typeof ref.projectPath === 'string' &&\n ref.projectPath.length > 0;\n return canonical || legacy;\n}\n\nfunction isIssueReference(value: unknown): value is GitLabIssueReference {\n return (\n isSourceReference(value) &&\n Number.isSafeInteger((value as GitLabIssueReference).issueIid) &&\n (value as GitLabIssueReference).issueIid > 0\n );\n}\n\nfunction isMergeRequestReference(value: unknown): value is GitLabMergeRequestReference {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const ref = value as Record<string, unknown>;\n return (\n ref.version === 1 &&\n typeof ref.host === 'string' &&\n normalizeGitLabHost(ref.host).length > 0 &&\n Number.isSafeInteger(ref.projectId) &&\n (ref.projectId as number) > 0 &&\n Number.isSafeInteger(ref.mergeRequestIid) &&\n (ref.mergeRequestIid as number) > 0\n );\n}\n\nfunction encodePageCursor(cursor: GitLabPageCursor): string {\n return encodeOpaque(cursor);\n}\n\nfunction decodePageCursor(value: string | undefined): GitLabPageCursor | null {\n if (!value) return { source: 0, page: 1 };\n try {\n const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as Record<string, unknown>;\n if (!Number.isSafeInteger(decoded.source) || Number(decoded.source) < 0) return null;\n if (!Number.isSafeInteger(decoded.page) || Number(decoded.page) < 1) return null;\n return { source: Number(decoded.source), page: Number(decoded.page) };\n } catch {\n return null;\n }\n}\n\nfunction displayName(user: { name?: string | null; username: string } | null | undefined): string | null {\n return user?.name?.trim() || user?.username || null;\n}\n\nfunction parsePositiveInteger(value: string): number | null {\n if (!/^\\d+$/.test(value)) return null;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction parseIssueLocator(value: string): {\n host?: string;\n projectPath: string;\n issueIid: number;\n} | null {\n const shorthand = value.match(/^(.+?)#(\\d+)$/);\n if (shorthand) {\n const issueIid = parsePositiveInteger(shorthand[2]!);\n const projectPath = shorthand[1]!.replace(/^\\/+|\\/+$/g, '');\n return issueIid && projectPath ? { projectPath, issueIid } : null;\n }\n try {\n const url = new URL(value);\n const match = url.pathname.match(/^\\/(.+)\\/-\\/issues\\/(\\d+)\\/?$/);\n if (!match) return null;\n const issueIid = parsePositiveInteger(match[2]!);\n if (!issueIid) return null;\n const projectPath = decodeURIComponent(match[1]!);\n return { host: url.host, projectPath, issueIid };\n } catch {\n return null;\n }\n}\n\nfunction targetStateEvent(input: UpdateIntakeIssueInput): 'close' | 'reopen' | null {\n if (input.state.kind === 'byType') {\n // GitLab issues have only opened/closed states, so canceled is intentionally mapped to close.\n return input.state.stateType === 'completed' || input.state.stateType === 'canceled' ? 'close' : 'reopen';\n }\n const name = input.state.name.trim().toLowerCase();\n if (name === 'closed' || name === 'close') return 'close';\n if (name === 'opened' || name === 'open' || name === 'reopen') return 'reopen';\n return null;\n}\n"],"mappings":";;;;;;;;;;;AAmGA,MAAM,uBAAuB;AAC7B,MAAM,iCAAiC;AACvC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AAC5B,MAAM,8BAA8B;AACpC,MAAa,8BAA8B;AAE3C,MAAM,kBAAkB;AACxB,MAAM,eAAe;AAErB,IAAsB,wBAAtB,MAA0E;CACxE,KAAc;CACd;CACA;CACA;CACA;CACA;CACA,qCAA8B,IAAI,IAA2B;CAC7D;CAEA,YAAY,OAA6B;EACvC,KAAK,QAAQ,mBAAmB,KAAK;CACvC;CAEA,SAA0B;EACxB,wBAAuB,UAAS,KAAK,uBAAuB,KAAK;EACjE,mBAAmB,KAAK,aAAa;EACrC,YAAW,UAAS,KAAK,WAAW,KAAK;EACzC,aAAY,UAAS,KAAK,YAAY,KAAK;EAC3C,WAAU,UAAS,KAAK,UAAU,KAAK;EACvC,gBAAe,UAAS,KAAK,eAAe,KAAK;EACjD,cAAa,UAAS,KAAK,aAAa,KAAK;CAC/C;CACA,iBAA0B,0BAA0B;EAClD,uBAAsB,eAAc,KAAK,uBAAuB,UAAU;EAC1E,+BAA+B,YAAY,SAAS,KAAK,sCAAsC,YAAY,IAAI;CACjH,CAAC;CACD,WAAW,EACT,SACA,UACA,MACA,iBAMO;EACP,KAAK,YAAY;EACjB,KAAK,QAAQ;EACb,KAAK,iBA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AE,QAAQ,cAAc,EAAE;EAC1D,OAAO,YAAY,cAAc;GAAE;GAAa;EAAS,IAAI;CAC/D;CACA,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,MAAM,QAAQ,IAAI,SAAS,MAAM,+BAA+B;EAChE,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,WAAW,qBAAqB,MAAM,EAAG;EAC/C,IAAI,CAAC,UAAU,OAAO;EACtB,MAAM,cAAc,mBAAmB,MAAM,EAAG;EAChD,OAAO;GAAE,MAAM,IAAI;GAAM;GAAa;EAAS;CACjD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB,OAA0D;CAClF,IAAI,MAAM,MAAM,SAAS,UAEvB,OAAO,MAAM,MAAM,cAAc,eAAe,MAAM,MAAM,cAAc,aAAa,UAAU;CAEnG,MAAM,OAAO,MAAM,MAAM,KAAK,KAAK,CAAC,CAAC,YAAY;CACjD,IAAI,SAAS,YAAY,SAAS,SAAS,OAAO;CAClD,IAAI,SAAS,YAAY,SAAS,UAAU,SAAS,UAAU,OAAO;CACtE,OAAO;AACT"}
1
+ {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/gitlab/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n CreatedIntakeComment,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n IntakeItemPage,\n IntakeSource,\n ListIntakeIssuesInput,\n ListIntakeItemsInput,\n ResolveIntakeDispatchInput,\n ResolvedIntakeDispatch,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildGitLabAgentTools } from './agent-tools.js';\nimport {\n GITLAB_ISSUES_PAGE_SIZE,\n GITLAB_NOTES_PAGE_SIZE,\n GITLAB_PROJECTS_PAGE_SIZE,\n GitLabApiClient,\n GitLabApiError,\n} from './api.js';\nimport type { GitLabIssue, GitLabNote, GitLabProject } from './api.js';\nimport { resolveGitLabRules } from './default-rules.js';\nimport type { GitLabEventRules, GitLabRuleOverrides } from './default-rules.js';\nimport { attachGitLabReconciler } from './reconciler.js';\nimport { gitlabReconciliationInterval } from './reconciliation-config.js';\nimport { buildGitLabRoutes, ingestLinkedGitLabRepositoryBacklog } from './routes.js';\nimport { attachGitLabRules } from './rules.js';\nimport {\n createGitLabSubscriptionTools,\n parseCreatedMergeRequest,\n subscribeCurrentSessionToMergeRequest,\n} from './session-subscriptions.js';\nimport type { GitLabSubscriptionStorage } from './subscriptions.js';\nimport { buildGitLabVersionControl } from './version-control.js';\n\ninterface GitLabConnectionContext {\n id: string;\n label: string | null;\n api: GitLabApiClient;\n connection: IntegrationConnection;\n host: string;\n webBaseUrl?: string;\n /** Resolves a fresh provider token for a single brokered git operation. */\n repositoryAccessToken?: () => Promise<string>;\n}\n\ninterface GitLabSourceReference {\n /** Present only on legacy v1 ids; authentication is not resource identity. */\n connectionId?: string;\n /** Canonical v2 ids use the GitLab instance host plus immutable project id. */\n host?: string;\n projectId: string;\n /** Legacy ids carry display metadata; v2 resolves it from GitLab. */\n projectPath?: string;\n}\n\ninterface ResolvedGitLabSourceReference extends GitLabSourceReference {\n connectionId: string;\n host: string;\n projectPath: string;\n}\n\ninterface GitLabIssueReference extends GitLabSourceReference {\n issueIid: number;\n}\n\nexport interface GitLabMergeRequestReference {\n version: 1;\n host: string;\n projectId: number;\n mergeRequestIid: number;\n}\n\ninterface GitLabPageCursor {\n source: number;\n page: number;\n}\n\nexport interface GitLabStatusConnection {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n}\n\nconst DIRECT_CONNECTION_ID = 'direct';\nconst GITLAB_CONNECTION_TOKEN_PREFIX = 'gitlab-connection:';\nconst GITLAB_SOURCE_PREFIX = 'gitlab-project:';\nconst GITLAB_ISSUE_PREFIX = 'gitlab-issue:';\nconst GITLAB_MERGE_REQUEST_PREFIX = 'gitlab-pr:';\nexport const GITLAB_TRUSTED_ACCESS_LEVEL = 30;\n// Bound issue detail reads to 2,000 notes. GitLab does not expose truncation through the Intake contract.\nconst MAX_NOTES_PAGES = 20;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport abstract class GitLabIntegrationBase implements FactoryIntegration {\n readonly id = 'gitlab';\n #projects: FactoryProjectsStorage | undefined;\n #sourceControl: SourceControlStorageHandle | undefined;\n #integrationStorage: GitLabSubscriptionStorage | undefined;\n #auth: RouteAuth | undefined;\n #ingestFactoryEvent: ReturnType<typeof attachGitLabRules>;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n readonly rules: GitLabEventRules;\n\n constructor(rules?: GitLabRuleOverrides) {\n this.rules = resolveGitLabRules(rules);\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: () => this.#listSources(),\n listItems: input => this.#listItems(input),\n listIssues: input => this.#listIssues(input),\n getIssue: input => this.#getIssue(input),\n createComment: input => this.#createComment(input),\n updateIssue: input => this.#updateIssue(input),\n };\n readonly versionControl = buildGitLabVersionControl({\n contextForConnection: connection => this.#versionControlContext(connection),\n contextForStoredInstallation: (connection, host) => this.#versionControlContextForInstallation(connection, host),\n });\n initialize({\n storage,\n projects,\n auth,\n sourceControl,\n }: {\n storage?: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n sourceControl?: SourceControlStorageHandle;\n }): void {\n this.#projects = projects;\n this.#auth = auth;\n this.#sourceControl = sourceControl;\n this.#integrationStorage = storage as GitLabSubscriptionStorage | undefined;\n }\n\n /** Generic integration persistence (merge-request subscriptions). */\n get integrationStorage(): GitLabSubscriptionStorage {\n if (!this.#integrationStorage) {\n throw new Error(`${this.constructor.name} is not initialized — the factory binds storage during prepare().`);\n }\n return this.#integrationStorage;\n }\n\n /** Source-control rows for this integration; absent when the host runs without them. */\n get sourceControlStorage(): SourceControlStorageHandle | undefined {\n return this.#sourceControl;\n }\n\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error(`${this.constructor.name} is not initialized — the factory binds storage during prepare().`);\n }\n return this.#projects;\n }\n\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n const orgId = project?.orgId ?? null;\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n } catch {\n return null;\n }\n }\n\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n abstract hasActiveConnections(): Promise<boolean>;\n abstract authFailureMessage(): string;\n protected abstract activeContexts(): Promise<GitLabConnectionContext[]>;\n protected abstract contextById(connectionId: string): Promise<GitLabConnectionContext>;\n\n /** Resolve only a GitLab repository linked to this Factory in this organization. */\n async getLinkedRepository(input: { orgId: string; factoryProjectId: string; projectRepositoryId: string }) {\n if (!this.#sourceControl) return null;\n const connections = await this.#sourceControl.connections.list({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n for (const connection of connections) {\n if (connection.integrationId !== 'gitlab') continue;\n const links = await this.#sourceControl.projectRepositories.list({\n orgId: input.orgId,\n connectionId: connection.id,\n });\n const link = links.find(candidate => candidate.id === input.projectRepositoryId);\n if (!link) continue;\n const repository = await this.#sourceControl.repositories.get({ orgId: input.orgId, id: link.repositoryId });\n const installation = await this.#sourceControl.installations.get({\n orgId: input.orgId,\n id: connection.installationId,\n });\n if (!repository || !installation) return null;\n const host = installation.providerMetadata.host;\n if (typeof host !== 'string' || !host) return null;\n return { repository, host: normalizeGitLabHost(host) };\n }\n return null;\n }\n\n async getProjectMemberAccessLevel(\n connectionId: string,\n projectId: string,\n username: string,\n ): Promise<number | undefined> {\n const normalized = username.trim().toLowerCase();\n if (!normalized) return undefined;\n const members = await (await this.contextById(connectionId)).api.listProjectMembers(projectId, { query: username });\n const member = members.find(\n candidate => candidate.username.toLowerCase() === normalized && candidate.state !== 'blocked',\n );\n return member?.access_level;\n }\n\n async getWorkItemAuthorUsername(\n connectionId: string,\n projectId: string,\n kind: 'issue' | 'merge_request',\n iid: number,\n ): Promise<string | undefined> {\n const api = (await this.contextById(connectionId)).api;\n const item = kind === 'issue' ? await api.getIssue(projectId, iid) : await api.getMergeRequest(projectId, iid);\n return item.author?.username;\n }\n\n async isProjectMemberTrustedForSource(sourceId: string, username: string): Promise<boolean> {\n const reference = decodeSourceId(sourceId);\n if (!reference) throw new GitLabApiError('GitLab source identity is invalid.', 400);\n const { context, source } = await this.#resolveSourceReference(reference);\n const accessLevel = await this.getProjectMemberAccessLevel(context.id, source.projectId, username);\n return (accessLevel ?? 0) >= GITLAB_TRUSTED_ACCESS_LEVEL;\n }\n\n async getIssueForFactoryProject(input: {\n orgId: string;\n factoryProjectId: string;\n issueId: string;\n }): Promise<IntakeIssueDetail | null> {\n if (!this.#sourceControl) throw new GitLabApiError('GitLab source control is unavailable.', 503);\n const reference = decodeIssueReference(input.issueId);\n const locator = parseIssueLocator(input.issueId);\n if (!reference && !locator) {\n throw new GitLabApiError('GitLab issue must include a project and issue IID.', 400);\n }\n\n const normalizePath = (value: string) => value.replace(/^\\/+|\\/+$/g, '').toLowerCase();\n const matches: Array<{\n connectionId: string;\n projectId: string;\n projectPath: string;\n }> = [];\n const connections = await this.#sourceControl.connections.list({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n for (const connection of connections) {\n const installation = await this.#sourceControl.installations.get({\n orgId: input.orgId,\n id: connection.installationId,\n });\n if (!installation) continue;\n for (const projectRepository of await this.#sourceControl.projectRepositories.list({\n orgId: input.orgId,\n connectionId: connection.id,\n })) {\n const repository = await this.#sourceControl.repositories.get({\n orgId: input.orgId,\n id: projectRepository.repositoryId,\n });\n if (!repository) continue;\n if (reference?.projectId && repository.externalId !== reference.projectId) continue;\n if (reference?.projectPath && normalizePath(repository.slug) !== normalizePath(reference.projectPath)) continue;\n if (locator?.projectPath && normalizePath(repository.slug) !== normalizePath(locator.projectPath)) continue;\n if (reference?.connectionId && installation.externalId !== reference.connectionId) continue;\n const installationHost =\n typeof installation.providerMetadata.host === 'string'\n ? normalizeGitLabHost(installation.providerMetadata.host)\n : null;\n if (reference?.host && installationHost !== normalizeGitLabHost(reference.host)) continue;\n if (locator?.host && installationHost !== normalizeGitLabHost(locator.host)) continue;\n matches.push({\n connectionId: installation.externalId,\n projectId: repository.externalId,\n projectPath: repository.slug,\n });\n }\n }\n const match = matches.sort((left, right) => left.connectionId.localeCompare(right.connectionId))[0];\n if (!match) throw new GitLabApiError('GitLab issue is outside the active Factory project.', 404);\n return this.intake.getIssue({\n connection: gitlabConnection(match.connectionId),\n sourceId: encodeSourceId(match),\n issueId: input.issueId,\n });\n }\n\n /** Platform mode exposes org connections; direct mode returns undefined. */\n async statusConnections(): Promise<GitLabStatusConnection[] | undefined> {\n return undefined;\n }\n\n /** Direct mode verifies its configured credential; Platform mode uses connection status. */\n async verifyStatus(): Promise<void> {\n // Platform connection state is authoritative unless a provider overrides this probe.\n }\n\n protected get webhookSecret(): string | undefined {\n return undefined;\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const reconcile = attachGitLabReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = gitlabReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n routes(ctx: IntegrationContext): ApiRoute[] {\n const ingestFactoryEvent = attachGitLabRules(this, ctx);\n this.#ingestFactoryEvent = ingestFactoryEvent;\n return buildGitLabRoutes({\n gitlab: this,\n auth: ctx.auth,\n intake: ctx.storage?.intake,\n emitAudit: ctx.hooks?.emitAudit,\n sandbox: ctx.sandbox,\n webhookSecret: this.webhookSecret,\n ingestFactoryEvent,\n ...(ctx.controller ? { controller: ctx.controller } : {}),\n });\n }\n\n async ingestLinkedRepositoryBacklog(args: { orgId: string; projectRepositoryId: string }): Promise<void> {\n await ingestLinkedGitLabRepositoryBacklog({ gitlab: this, ...args, ingestFactoryEvent: this.#ingestFactoryEvent });\n }\n\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildGitLabAgentTools({ requestContext: args.requestContext, gitlab: this });\n }\n\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGitLabSubscriptionTools(requestContext, this);\n }\n\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const mergeRequestUrl = parseCreatedMergeRequest(toolContext);\n if (!mergeRequestUrl || !requestContext) return;\n await subscribeCurrentSessionToMergeRequest(requestContext, mergeRequestUrl, 'auto-create-change-request', this);\n }\n\n abstract diagnostics(): Record<string, unknown>;\n\n /** Prefer the configured direct token over an older Platform installation on the same host. */\n async resolveActiveConnectionForHost(storedConnectionId: string, host: string): Promise<string> {\n if (this.diagnostics().mode !== 'direct') return storedConnectionId;\n const [direct] = await this.activeContexts();\n return direct && normalizeGitLabHost(direct.host) === normalizeGitLabHost(host) ? direct.id : storedConnectionId;\n }\n\n async #versionControlContext(connection: IntegrationConnection): Promise<GitLabConnectionContext> {\n const connectionId = connectionIdFromConnection(connection);\n if (connectionId) return this.contextById(connectionId);\n const contexts = await this.activeContexts();\n if (contexts.length !== 1) {\n throw new GitLabApiError(\n 'GitLab version-control requests must identify a connection when multiple GitLab accounts are connected.',\n 400,\n );\n }\n return contexts[0]!;\n }\n async #versionControlContextForInstallation(\n connection: IntegrationConnection,\n host: string | undefined,\n ): Promise<GitLabConnectionContext> {\n // A direct PAT intentionally overrides Platform credentials. Old links can\n // retain their Platform connection id; use the PAT only for the same host.\n if (this.diagnostics().mode === 'direct' && host) {\n const [direct] = await this.activeContexts();\n if (direct && normalizeGitLabHost(host) === normalizeGitLabHost(direct.host)) return direct;\n }\n return this.#versionControlContext(connection);\n }\n async #contextForReference(reference: GitLabSourceReference): Promise<GitLabConnectionContext> {\n if (reference.connectionId) return this.contextById(reference.connectionId);\n const contexts = (await this.activeContexts()).filter(\n context => !reference.host || normalizeGitLabHost(context.host) === normalizeGitLabHost(reference.host),\n );\n if (contexts.length === 0) {\n throw new GitLabApiError('No active GitLab connection can access this source.', 401);\n }\n if (contexts.length === 1) return contexts[0]!;\n\n if (this.#sourceControl) {\n const linkedConnectionIds = new Set(\n (await this.#sourceControl.projectRepositories.listConfiguredExternalKeys())\n .filter(key => key.repositoryExternalId === reference.projectId)\n .map(key => key.installationExternalId),\n );\n const linked = contexts.filter(context => linkedConnectionIds.has(context.id));\n if (linked.length > 0) return linked.sort((left, right) => left.id.localeCompare(right.id))[0]!;\n }\n\n for (const context of contexts.sort((left, right) => left.id.localeCompare(right.id))) {\n try {\n await context.api.getProject(reference.projectId);\n return context;\n } catch (error) {\n if (!(error instanceof GitLabApiError) || ![401, 403, 404].includes(error.status ?? 0)) throw error;\n // This credential cannot access the project; try another active account for the same canonical source.\n }\n }\n throw new GitLabApiError('No active GitLab connection can access this source.', 404);\n }\n\n async #resolveSourceReference(\n reference: GitLabSourceReference,\n ): Promise<{ context: GitLabConnectionContext; source: ResolvedGitLabSourceReference }> {\n const context = await this.#contextForReference(reference);\n const projectPath =\n reference.projectPath ?? (await context.api.getProject(reference.projectId)).path_with_namespace;\n return {\n context,\n source: {\n connectionId: context.id,\n host: normalizeGitLabHost(reference.host ?? context.host),\n projectId: reference.projectId,\n projectPath,\n },\n };\n }\n\n async #resolveIntakeDispatch({ externalSource }: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null> {\n if (externalSource.type !== 'issue') return null;\n const reference = decodeIssueReference(externalSource.externalId);\n if (!reference) return null;\n const { context, source } = await this.#resolveSourceReference(reference);\n return {\n connection: context.connection,\n sourceId: encodeSourceId(source),\n issueId: String(reference.issueIid),\n };\n }\n\n async #listSources(): Promise<IntakeSource[]> {\n const sources = new Map<string, IntakeSource>();\n for (const context of await this.activeContexts()) {\n for (let page = 1; ; page++) {\n const projects = await context.api.listProjects({ page });\n for (const project of projects) {\n const source = this.#toIntakeSource(context, project);\n if (!sources.has(source.id)) sources.set(source.id, source);\n }\n if (projects.length < GITLAB_PROJECTS_PAGE_SIZE) break;\n }\n }\n return [...sources.values()];\n }\n\n async #listItems(input: ListIntakeItemsInput): Promise<IntakeItemPage> {\n const result = await this.#listIssuePage(input.sourceIds, input.cursor);\n return {\n items: result.issues.map(({ issue, source, context }) => ({\n source: {\n type: 'issue',\n externalId: encodeIssueReference({ ...source, issueIid: issue.iid }),\n url: issue.web_url,\n },\n sourceId: encodeSourceId(source),\n title: `${source.projectPath}#${issue.iid}: ${issue.title}`,\n status: issue.state,\n labels: issue.labels ?? [],\n assignee: displayName(issue.assignee),\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n metadata: {\n identifier: `${source.projectPath}#${issue.iid}`,\n projectId: source.projectId,\n projectPath: source.projectPath,\n connectionId: context.id,\n accountLabel: context.label,\n labelColors: Object.fromEntries((issue.labelDetails ?? []).map(label => [label.name, label.color])),\n },\n })),\n nextCursor: result.nextCursor,\n };\n }\n\n async #listIssues(input: ListIntakeIssuesInput) {\n const result = await this.#listIssuePage(input.sourceIds, input.cursor, input.labels);\n return {\n issues: result.issues.map(({ issue, source }) => ({\n ...this.#toIntakeIssue(issue, source.projectPath),\n sourceId: encodeSourceId(source),\n })),\n nextCursor: result.nextCursor,\n };\n }\n\n async #listIssuePage(sourceIds: string[], cursor?: string, labels?: string[]) {\n const sources = sourceIds.map(decodeSourceId).filter((source): source is GitLabSourceReference => source !== null);\n if (sources.length === 0) return { issues: [], nextCursor: null };\n const current = decodePageCursor(cursor);\n if (!current || current.source >= sources.length) return { issues: [], nextCursor: null };\n\n for (let sourceIndex = current.source; sourceIndex < sources.length; sourceIndex++) {\n const { source, context } = await this.#resolveSourceReference(sources[sourceIndex]!);\n const page = sourceIndex === current.source ? current.page : 1;\n const issues = await context.api.listIssues(source.projectId, { page, labels });\n const nextCursor =\n issues.length === GITLAB_ISSUES_PAGE_SIZE\n ? encodePageCursor({ source: sourceIndex, page: page + 1 })\n : sourceIndex + 1 < sources.length\n ? encodePageCursor({ source: sourceIndex + 1, page: 1 })\n : null;\n return { issues: issues.map(issue => ({ issue, source, context })), nextCursor };\n }\n return { issues: [], nextCursor: null };\n }\n\n async #getIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const resolved = await this.#resolveRequest(input);\n let issue: GitLabIssue;\n try {\n issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n const notes = await this.#listAllNotes(resolved.context.api, resolved.projectId, resolved.issueIid);\n return {\n ...this.#toIntakeIssue(issue, resolved.projectPath),\n description: issue.description?.trim() || null,\n comments: notes\n .filter(note => !note.system)\n .map(note => ({ author: displayName(note.author), body: note.body, createdAt: note.created_at })),\n };\n }\n\n async #listAllNotes(api: GitLabApiClient, projectId: string, issueIid: number): Promise<GitLabNote[]> {\n const notes: GitLabNote[] = [];\n for (let page = 1; page <= MAX_NOTES_PAGES; page++) {\n const result = await api.listNotes(projectId, issueIid, { page });\n notes.push(...result);\n if (result.length < GITLAB_NOTES_PAGE_SIZE) break;\n }\n return notes;\n }\n\n async #createComment(input: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null> {\n const resolved = await this.#resolveRequest(input);\n try {\n const issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n const note = await resolved.context.api.createNote(resolved.projectId, resolved.issueIid, input.body);\n return { id: String(note.id), url: `${issue.web_url}#note_${note.id}` };\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n async #updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const resolved = await this.#resolveRequest(input);\n let issue: GitLabIssue;\n try {\n issue = await resolved.context.api.getIssue(resolved.projectId, resolved.issueIid);\n } catch (error) {\n if (error instanceof GitLabApiError && error.status === 404) return null;\n throw error;\n }\n const stateEvent = targetStateEvent(input);\n if (!stateEvent) return null;\n if ((stateEvent === 'close' && issue.state === 'closed') || (stateEvent === 'reopen' && issue.state === 'opened')) {\n return this.#toIntakeIssue(issue, resolved.projectPath);\n }\n const updated = await resolved.context.api.updateIssueState(resolved.projectId, resolved.issueIid, stateEvent);\n return this.#toIntakeIssue(updated, resolved.projectPath);\n }\n\n async #resolveRequest(input: GetIntakeIssueInput): Promise<{\n context: GitLabConnectionContext;\n projectId: string;\n projectPath: string;\n issueIid: number;\n }> {\n const issueReference = decodeIssueReference(input.issueId);\n const source = input.sourceId ? decodeSourceId(input.sourceId) : null;\n const locator = parseIssueLocator(input.issueId);\n const reference = issueReference ?? source;\n let context: GitLabConnectionContext;\n if (reference) {\n context = await this.#contextForReference(reference);\n } else {\n const connectionId = connectionIdFromConnection(input.connection);\n const contexts = connectionId ? [await this.contextById(connectionId)] : await this.activeContexts();\n if (contexts.length !== 1) {\n throw new GitLabApiError('GitLab issue reference must resolve to exactly one active connection.', 400);\n }\n context = contexts[0]!;\n }\n const projectId = issueReference?.projectId ?? source?.projectId ?? locator?.projectPath;\n const issueIid = issueReference?.issueIid ?? locator?.issueIid ?? parsePositiveInteger(input.issueId);\n if (!projectId || !issueIid) {\n throw new GitLabApiError(\n 'GitLab issue must include a project and issue IID (for example, group/project#42).',\n 400,\n );\n }\n const projectPath =\n issueReference?.projectPath ??\n source?.projectPath ??\n locator?.projectPath ??\n (await context.api.getProject(projectId)).path_with_namespace;\n return { context, projectId, projectPath, issueIid };\n }\n\n #toIntakeSource(context: GitLabConnectionContext, project: GitLabProject): IntakeSource {\n const reference: GitLabSourceReference = {\n host: normalizeGitLabHost(context.host),\n projectId: String(project.id),\n projectPath: project.path_with_namespace,\n };\n return {\n id: encodeSourceId(reference),\n name: project.path_with_namespace,\n type: 'project',\n metadata: {\n projectId: String(project.id),\n projectPath: project.path_with_namespace,\n defaultBranch: project.default_branch ?? null,\n connectionId: context.id,\n accountLabel: context.label,\n url: project.web_url,\n },\n };\n }\n\n #toIntakeIssue(issue: GitLabIssue, projectPath: string): IntakeIssue {\n const assignees = issue.assignees?.map(displayName).filter((name): name is string => name !== null) ?? [];\n return {\n id: String(issue.iid),\n identifier: `${projectPath}#${issue.iid}`,\n title: issue.title,\n url: issue.web_url,\n author: displayName(issue.author),\n authorUsername: issue.author?.username ?? null,\n state: issue.state,\n stateType: issue.state === 'closed' ? 'completed' : 'unstarted',\n priority: typeof issue.weight === 'number' ? String(issue.weight) : null,\n assignee: displayName(issue.assignee) ?? assignees[0] ?? null,\n assignees,\n source: projectPath,\n labels: issue.labels ?? [],\n labelColors: Object.fromEntries((issue.labelDetails ?? []).map(label => [label.name, label.color])),\n commentCount: issue.user_notes_count ?? null,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n };\n }\n}\n\nexport type GitLabAccessTokenType = 'personal' | 'group';\n\nexport interface GitLabIntegrationConfig {\n rules?: GitLabRuleOverrides;\n accessToken?: string;\n /** Defaults to `personal`; both token types authenticate identically but have different resource reach. */\n accessTokenType?: GitLabAccessTokenType;\n baseUrl?: string;\n webhookSecret?: string;\n fetchImpl?: typeof fetch;\n}\n\nconst DIRECT_CONNECTION_TOKEN = 'gitlab-direct-access-token';\n\nexport class GitLabIntegration extends GitLabIntegrationBase {\n readonly #accessToken: string;\n readonly #accessTokenType: GitLabAccessTokenType;\n readonly #baseUrl: string;\n readonly #webhookSecret: string | undefined;\n readonly #context: GitLabConnectionContext;\n\n constructor(config: GitLabIntegrationConfig = {}) {\n super(config.rules);\n const accessToken = config.accessToken?.trim() || process.env.GITLAB_ACCESS_TOKEN?.trim();\n if (!accessToken) {\n throw new Error('GitLabIntegration: missing required GITLAB_ACCESS_TOKEN.');\n }\n this.#accessToken = accessToken;\n this.#accessTokenType = parseAccessTokenType(\n config.accessTokenType ?? process.env.GITLAB_ACCESS_TOKEN_TYPE?.trim(),\n );\n this.#baseUrl = (config.baseUrl ?? process.env.GITLAB_BASE_URL?.trim() ?? 'https://gitlab.com').replace(/\\/+$/, '');\n this.#webhookSecret = config.webhookSecret?.trim() || process.env.GITLAB_WEBHOOK_SECRET?.trim() || undefined;\n const api = new GitLabApiClient({\n baseUrl: this.#baseUrl,\n accessToken: this.#accessToken,\n ...(config.fetchImpl ? { fetchImpl: config.fetchImpl } : {}),\n });\n this.#context = {\n id: DIRECT_CONNECTION_ID,\n label: new URL(this.#baseUrl).host,\n api,\n connection: { type: 'oauth', accessToken: DIRECT_CONNECTION_TOKEN },\n host: new URL(this.#baseUrl).host,\n webBaseUrl: this.#baseUrl,\n repositoryAccessToken: async () => this.#accessToken,\n };\n }\n\n protected override get webhookSecret(): string | undefined {\n return this.#webhookSecret;\n }\n\n async hasActiveConnections(): Promise<boolean> {\n return true;\n }\n\n override async verifyStatus(): Promise<void> {\n await this.#context.api.getCurrentUser();\n }\n\n authFailureMessage(): string {\n return `GitLab rejected the configured ${this.#accessTokenType} access token. Check the token and its scopes.`;\n }\n\n protected async activeContexts(): Promise<GitLabConnectionContext[]> {\n return [this.#context];\n }\n\n protected async contextById(connectionId: string): Promise<GitLabConnectionContext> {\n if (connectionId !== DIRECT_CONNECTION_ID) {\n throw new GitLabApiError('GitLab connection is unavailable.', 401);\n }\n return this.#context;\n }\n\n diagnostics(): Record<string, unknown> {\n return {\n configured: true,\n mode: 'direct',\n accessTokenType: this.#accessTokenType,\n endpointHost: new URL(this.#baseUrl).host,\n webhookConfigured: Boolean(this.#webhookSecret),\n };\n }\n}\n\nfunction parseAccessTokenType(value: string | undefined): GitLabAccessTokenType {\n const normalized = value?.trim().toLowerCase() || 'personal';\n if (normalized === 'personal' || normalized === 'group') return normalized;\n throw new Error(\"GitLabIntegration: GITLAB_ACCESS_TOKEN_TYPE must be 'personal' or 'group'.\");\n}\n\nexport function encodeSourceId(reference: GitLabSourceReference): string {\n if (reference.host) {\n return `${GITLAB_SOURCE_PREFIX}${encodeOpaque({\n version: 2,\n host: normalizeGitLabHost(reference.host),\n projectId: reference.projectId,\n })}`;\n }\n if (!reference.connectionId || !reference.projectPath) {\n throw new Error('GitLab source reference is missing its instance host.');\n }\n return `${GITLAB_SOURCE_PREFIX}${encodeOpaque(reference)}`;\n}\n\nexport function decodeSourceId(value: string): GitLabSourceReference | null {\n return decodeOpaque(value, GITLAB_SOURCE_PREFIX, isSourceReference);\n}\n\nexport function encodeIssueReference(reference: GitLabIssueReference): string {\n if (reference.host) {\n return `${GITLAB_ISSUE_PREFIX}${encodeOpaque({\n version: 2,\n host: normalizeGitLabHost(reference.host),\n projectId: reference.projectId,\n issueIid: reference.issueIid,\n })}`;\n }\n if (!reference.connectionId || !reference.projectPath) {\n throw new Error('GitLab issue reference is missing its instance host.');\n }\n return `${GITLAB_ISSUE_PREFIX}${encodeOpaque(reference)}`;\n}\n\nexport function decodeIssueReference(value: string): GitLabIssueReference | null {\n return decodeOpaque(value, GITLAB_ISSUE_PREFIX, isIssueReference);\n}\n\nexport function decodeMergeRequestReference(value: string): GitLabMergeRequestReference | null {\n return decodeOpaque(value, GITLAB_MERGE_REQUEST_PREFIX, isMergeRequestReference);\n}\n\nexport function gitlabConnection(connectionId: string): IntegrationConnection {\n return { type: 'oauth', accessToken: `${GITLAB_CONNECTION_TOKEN_PREFIX}${connectionId}` };\n}\n\nfunction connectionIdFromConnection(connection: IntegrationConnection): string | null {\n if (connection.type !== 'oauth' || !connection.accessToken.startsWith(GITLAB_CONNECTION_TOKEN_PREFIX)) return null;\n return connection.accessToken.slice(GITLAB_CONNECTION_TOKEN_PREFIX.length) || null;\n}\n\nfunction encodeOpaque(value: unknown): string {\n return Buffer.from(JSON.stringify(value)).toString('base64url');\n}\n\nfunction decodeOpaque<T>(value: string, prefix: string, guard: (value: unknown) => value is T): T | null {\n if (!value.startsWith(prefix)) return null;\n try {\n const decoded = JSON.parse(Buffer.from(value.slice(prefix.length), 'base64url').toString('utf8')) as unknown;\n return guard(decoded) ? decoded : null;\n } catch {\n return null;\n }\n}\n\nexport function normalizeGitLabHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction isSourceReference(value: unknown): value is GitLabSourceReference {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const ref = value as Record<string, unknown>;\n if (typeof ref.projectId !== 'string' || ref.projectId.length === 0) return false;\n const canonical = ref.version === 2 && typeof ref.host === 'string' && normalizeGitLabHost(ref.host).length > 0;\n const legacy =\n typeof ref.connectionId === 'string' &&\n ref.connectionId.length > 0 &&\n typeof ref.projectPath === 'string' &&\n ref.projectPath.length > 0;\n return canonical || legacy;\n}\n\nfunction isIssueReference(value: unknown): value is GitLabIssueReference {\n return (\n isSourceReference(value) &&\n Number.isSafeInteger((value as GitLabIssueReference).issueIid) &&\n (value as GitLabIssueReference).issueIid > 0\n );\n}\n\nfunction isMergeRequestReference(value: unknown): value is GitLabMergeRequestReference {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const ref = value as Record<string, unknown>;\n return (\n ref.version === 1 &&\n typeof ref.host === 'string' &&\n normalizeGitLabHost(ref.host).length > 0 &&\n Number.isSafeInteger(ref.projectId) &&\n (ref.projectId as number) > 0 &&\n Number.isSafeInteger(ref.mergeRequestIid) &&\n (ref.mergeRequestIid as number) > 0\n );\n}\n\nfunction encodePageCursor(cursor: GitLabPageCursor): string {\n return encodeOpaque(cursor);\n}\n\nfunction decodePageCursor(value: string | undefined): GitLabPageCursor | null {\n if (!value) return { source: 0, page: 1 };\n try {\n const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as Record<string, unknown>;\n if (!Number.isSafeInteger(decoded.source) || Number(decoded.source) < 0) return null;\n if (!Number.isSafeInteger(decoded.page) || Number(decoded.page) < 1) return null;\n return { source: Number(decoded.source), page: Number(decoded.page) };\n } catch {\n return null;\n }\n}\n\nfunction displayName(user: { name?: string | null; username: string } | null | undefined): string | null {\n return user?.name?.trim() || user?.username || null;\n}\n\nfunction parsePositiveInteger(value: string): number | null {\n if (!/^\\d+$/.test(value)) return null;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction parseIssueLocator(value: string): {\n host?: string;\n projectPath: string;\n issueIid: number;\n} | null {\n const shorthand = value.match(/^(.+?)#(\\d+)$/);\n if (shorthand) {\n const issueIid = parsePositiveInteger(shorthand[2]!);\n const projectPath = shorthand[1]!.replace(/^\\/+|\\/+$/g, '');\n return issueIid && projectPath ? { projectPath, issueIid } : null;\n }\n try {\n const url = new URL(value);\n const match = url.pathname.match(/^\\/(.+)\\/-\\/issues\\/(\\d+)\\/?$/);\n if (!match) return null;\n const issueIid = parsePositiveInteger(match[2]!);\n if (!issueIid) return null;\n const projectPath = decodeURIComponent(match[1]!);\n return { host: url.host, projectPath, issueIid };\n } catch {\n return null;\n }\n}\n\nfunction targetStateEvent(input: UpdateIntakeIssueInput): 'close' | 'reopen' | null {\n if (input.state.kind === 'byType') {\n // GitLab issues have only opened/closed states, so canceled is intentionally mapped to close.\n return input.state.stateType === 'completed' || input.state.stateType === 'canceled' ? 'close' : 'reopen';\n }\n const name = input.state.name.trim().toLowerCase();\n if (name === 'closed' || name === 'close') return 'close';\n if (name === 'opened' || name === 'open' || name === 'reopen') return 'reopen';\n return null;\n}\n"],"mappings":";;;;;;;;;;;AAmGA,M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cAAc,eAAe,MAAM,MAAM,cAAc,aAAa,UAAU;CAEnG,MAAM,OAAO,MAAM,MAAM,KAAK,KAAK,CAAC,CAAC,YAAY;CACjD,IAAI,SAAS,YAAY,SAAS,SAAS,OAAO;CAClD,IAAI,SAAS,YAAY,SAAS,UAAU,SAAS,UAAU,OAAO;CACtE,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/issue-reconciler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAI9D,MAAM,MAAM,qBAAqB,GAAG,eAAe,CAAC;AA+EpD,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,IAAI,CACV,qBAAqB,EACrB,QAAQ,GAAG,OAAO,GAAG,6BAA6B,GAAG,2BAA2B,GAAG,iCAAiC,CACrH,EACD,OAAO,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CAkDnC"}
1
+ {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/issue-reconciler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAI9D,MAAM,MAAM,qBAAqB,GAAG,eAAe,CAAC;AA+EpD,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,IAAI,CACV,qBAAqB,EACrB,QAAQ,GAAG,OAAO,GAAG,6BAA6B,GAAG,2BAA2B,GAAG,iCAAiC,CACrH,EACD,OAAO,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CAmDnC"}
@@ -100,6 +100,7 @@ function attachGitLabIssueReconciler(gitlab, context) {
100
100
  intake: gitlab.intake,
101
101
  projects: context.storage.projects,
102
102
  storage: context.runtime.workItems,
103
+ ...context.runtime.keptCards ? { cards: context.runtime.keptCards } : {},
103
104
  isTerminal: (item) => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === "terminal",
104
105
  issueId: (item) => {
105
106
  const issueIid = identityForItem(item)?.issueIid;
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/gitlab/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { IntakeIssue } from '../../capabilities/intake.js';\nimport type { Card } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport { decodeIssueReference } from './integration.js';\nimport type { GitLabIntegrationBase } from './integration.js';\nimport { attachGitLabRules } from './rules.js';\nimport type { ParsedGitLabWebhook } from './webhook.js';\n\nexport type GitLabIssueReconciler = IssueReconciler;\n\nfunction stringMetadata(item: Card, key: string): string | undefined {\n const value = item.workItem.metadata?.[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction numberMetadata(item: Card, key: string): number | undefined {\n const value = item.workItem.metadata?.[key];\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction normalizeHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction identityForItem(item: Card): { projectId: number; issueIid: number; host: string } | null {\n const reference = decodeIssueReference(item.externalSource?.externalId ?? '');\n const projectId = Number(reference?.projectId);\n if (!reference || !Number.isSafeInteger(projectId) || projectId <= 0) return null;\n let urlHost: string;\n try {\n urlHost = new URL(item.externalSource?.url ?? '').host;\n } catch {\n return null;\n }\n const host = normalizeHost(reference.host ?? urlHost);\n if (!host || host !== normalizeHost(urlHost)) return null;\n const metadataProjectId = numberMetadata(item, 'gitlabProjectId');\n const metadataIssueIid = numberMetadata(item, 'gitlabIssueIid');\n const metadataHost = stringMetadata(item, 'gitlabHost');\n if (\n (metadataProjectId && metadataProjectId !== projectId) ||\n (metadataIssueIid && metadataIssueIid !== reference.issueIid) ||\n (metadataHost && normalizeHost(metadataHost) !== host)\n ) {\n return null;\n }\n return { projectId, issueIid: reference.issueIid, host };\n}\n\nfunction closedIssueEvent(\n issue: IntakeIssue,\n identity: { projectId: number; issueIid: number; host: string },\n): ParsedGitLabWebhook {\n const { projectId, issueIid, host } = identity;\n const projectPath = issue.source?.trim();\n if (!projectPath) {\n throw new Error('GitLab issue work item is missing canonical reconciliation metadata.');\n }\n const username = issue.authorUsername?.trim() || 'factory-reconciler';\n return {\n event: 'Issue Hook',\n deliveryId: `reconcile:issue:${normalizeHost(host)}:${projectId}:${issueIid}:${issue.updatedAt}:closed`,\n instanceHost: host,\n payload: {\n user_username: username,\n user: { username },\n project: {\n id: projectId,\n path_with_namespace: projectPath,\n web_url: `https://${host}/${projectPath}`,\n },\n object_attributes: {\n iid: issueIid,\n title: issue.title,\n url: issue.url,\n state: 'closed',\n action: 'close',\n created_at: issue.createdAt,\n updated_at: issue.updatedAt,\n author: { username },\n assignees: (issue.assignees ?? []).map(username => ({ username })),\n labels: issue.labels,\n },\n },\n };\n}\n\nexport function attachGitLabIssueReconciler(\n gitlab: Pick<\n GitLabIntegrationBase,\n 'intake' | 'rules' | 'getProjectMemberAccessLevel' | 'getWorkItemAuthorUsername' | 'isProjectMemberTrustedForSource'\n >,\n context: IntegrationContext,\n): GitLabIssueReconciler | undefined {\n if (!context.runtime || !gitlab.intake.resolveIntakeDispatch) return undefined;\n const ingest = attachGitLabRules(gitlab, context);\n if (!ingest) return undefined;\n const boards = context.runtime.boards;\n const reconciledMetadata = async (item: Card, issue: IntakeIssue, sourceId: string) => {\n const identity = identityForItem(item);\n return {\n ...(identity && {\n gitlabHost: identity.host,\n gitlabProjectId: identity.projectId,\n gitlabIssueIid: identity.issueIid,\n }),\n identifier: issue.identifier,\n state: issue.state,\n stateType: issue.stateType,\n author: issue.author,\n authorTrusted: issue.authorUsername\n ? await gitlab.isProjectMemberTrustedForSource(sourceId, issue.authorUsername)\n : false,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n labels: issue.labels,\n labelColors: issue.labelColors ?? {},\n updatedAt: issue.updatedAt,\n };\n };\n\n return createIssueReconciler({\n integrationId: 'gitlab',\n intake: gitlab.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => {\n const issueIid = identityForItem(item)?.issueIid;\n return issueIid ? String(issueIid) : undefined;\n },\n metadata: (item, issue, dispatch) => {\n if (!dispatch.sourceId) throw new Error('GitLab reconciliation did not resolve a source identity.');\n return reconciledMetadata(item, issue, dispatch.sourceId);\n },\n onClosed: async (item, issue, _project, dispatch) => {\n if (!dispatch.sourceId) throw new Error('GitLab reconciliation did not resolve a source identity.');\n const identity = identityForItem(item);\n if (!identity) throw new Error('GitLab issue work item is missing canonical reconciliation metadata.');\n await ingest(closedIssueEvent(issue, identity));\n return reconciledMetadata(item, issue, dispatch.sourceId);\n },\n });\n}\n"],"mappings":";;;;;;;AAcA,SAAS,eAAe,MAAY,KAAiC;CACnE,MAAM,QAAQ,KAAK,SAAS,WAAW;CACvC,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE;AAEA,SAAS,eAAe,MAAY,KAAiC;CACnE,MAAM,QAAQ,KAAK,SAAS,WAAW;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,QAAQ,IAAI,QAAQ,KAAA;AACzF;AAEA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,KAAK,CAAC,CAAC,Y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AO,mBAAmB,MAAM,OAAO,SAAS,QAAQ;EAC1D;EACA,UAAU,OAAO,MAAM,OAAO,UAAU,aAAa;GACnD,IAAI,CAAC,SAAS,UAAU,MAAM,IAAI,MAAM,0DAA0D;GAClG,MAAM,WAAW,gBAAgB,IAAI;GACrC,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,sEAAsE;GACrG,MAAM,OAAO,iBAAiB,OAAO,QAAQ,CAAC;GAC9C,OAAO,mBAAmB,MAAM,OAAO,SAAS,QAAQ;EAC1D;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/gitlab/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { IntakeIssue } from '../../capabilities/intake.js';\nimport type { Card } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport { decodeIssueReference } from './integration.js';\nimport type { GitLabIntegrationBase } from './integration.js';\nimport { attachGitLabRules } from './rules.js';\nimport type { ParsedGitLabWebhook } from './webhook.js';\n\nexport type GitLabIssueReconciler = IssueReconciler;\n\nfunction stringMetadata(item: Card, key: string): string | undefined {\n const value = item.workItem.metadata?.[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction numberMetadata(item: Card, key: string): number | undefined {\n const value = item.workItem.metadata?.[key];\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction normalizeHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction identityForItem(item: Card): { projectId: number; issueIid: number; host: string } | null {\n const reference = decodeIssueReference(item.externalSource?.externalId ?? '');\n const projectId = Number(reference?.projectId);\n if (!reference || !Number.isSafeInteger(projectId) || projectId <= 0) return null;\n let urlHost: string;\n try {\n urlHost = new URL(item.externalSource?.url ?? '').host;\n } catch {\n return null;\n }\n const host = normalizeHost(reference.host ?? urlHost);\n if (!host || host !== normalizeHost(urlHost)) return null;\n const metadataProjectId = numberMetadata(item, 'gitlabProjectId');\n const metadataIssueIid = numberMetadata(item, 'gitlabIssueIid');\n const metadataHost = stringMetadata(item, 'gitlabHost');\n if (\n (metadataProjectId && metadataProjectId !== projectId) ||\n (metadataIssueIid && metadataIssueIid !== reference.issueIid) ||\n (metadataHost && normalizeHost(metadataHost) !== host)\n ) {\n return null;\n }\n return { projectId, issueIid: reference.issueIid, host };\n}\n\nfunction closedIssueEvent(\n issue: IntakeIssue,\n identity: { projectId: number; issueIid: number; host: string },\n): ParsedGitLabWebhook {\n const { projectId, issueIid, host } = identity;\n const projectPath = issue.source?.trim();\n if (!projectPath) {\n throw new Error('GitLab issue work item is missing canonical reconciliation metadata.');\n }\n const username = issue.authorUsername?.trim() || 'factory-reconciler';\n return {\n event: 'Issue Hook',\n deliveryId: `reconcile:issue:${normalizeHost(host)}:${projectId}:${issueIid}:${issue.updatedAt}:closed`,\n instanceHost: host,\n payload: {\n user_username: username,\n user: { username },\n project: {\n id: projectId,\n path_with_namespace: projectPath,\n web_url: `https://${host}/${projectPath}`,\n },\n object_attributes: {\n iid: issueIid,\n title: issue.title,\n url: issue.url,\n state: 'closed',\n action: 'close',\n created_at: issue.createdAt,\n updated_at: issue.updatedAt,\n author: { username },\n assignees: (issue.assignees ?? []).map(username => ({ username })),\n labels: issue.labels,\n },\n },\n };\n}\n\nexport function attachGitLabIssueReconciler(\n gitlab: Pick<\n GitLabIntegrationBase,\n 'intake' | 'rules' | 'getProjectMemberAccessLevel' | 'getWorkItemAuthorUsername' | 'isProjectMemberTrustedForSource'\n >,\n context: IntegrationContext,\n): GitLabIssueReconciler | undefined {\n if (!context.runtime || !gitlab.intake.resolveIntakeDispatch) return undefined;\n const ingest = attachGitLabRules(gitlab, context);\n if (!ingest) return undefined;\n const boards = context.runtime.boards;\n const reconciledMetadata = async (item: Card, issue: IntakeIssue, sourceId: string) => {\n const identity = identityForItem(item);\n return {\n ...(identity && {\n gitlabHost: identity.host,\n gitlabProjectId: identity.projectId,\n gitlabIssueIid: identity.issueIid,\n }),\n identifier: issue.identifier,\n state: issue.state,\n stateType: issue.stateType,\n author: issue.author,\n authorTrusted: issue.authorUsername\n ? await gitlab.isProjectMemberTrustedForSource(sourceId, issue.authorUsername)\n : false,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n labels: issue.labels,\n labelColors: issue.labelColors ?? {},\n updatedAt: issue.updatedAt,\n };\n };\n\n return createIssueReconciler({\n integrationId: 'gitlab',\n intake: gitlab.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => {\n const issueIid = identityForItem(item)?.issueIid;\n return issueIid ? String(issueIid) : undefined;\n },\n metadata: (item, issue, dispatch) => {\n if (!dispatch.sourceId) throw new Error('GitLab reconciliation did not resolve a source identity.');\n return reconciledMetadata(item, issue, dispatch.sourceId);\n },\n onClosed: async (item, issue, _project, dispatch) => {\n if (!dispatch.sourceId) throw new Error('GitLab reconciliation did not resolve a source identity.');\n const identity = identityForItem(item);\n if (!identity) throw new Error('GitLab issue work item is missing canonical reconciliation metadata.');\n await ingest(closedIssueEvent(issue, identity));\n return reconciledMetadata(item, issue, dispatch.sourceId);\n },\n });\n}\n"],"mappings":";;;;;;;AAcA,SAAS,eAAe,MAAY,KAAiC;CACnE,MAAM,QAAQ,KAAK,SAAS,WAAW;CACvC,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE;AAEA,SAAS,eAAe,MAAY,KAAiC;CACnE,MAAM,QAAQ,KAAK,SAAS,WAAW;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,QAAQ,IAAI,QAAQ,KA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,EAAE;GACxC,OAAO,WAAW,OAAO,QAAQ,IAAI,KAAA;EACvC;EACA,WAAW,MAAM,OAAO,aAAa;GACnC,IAAI,CAAC,SAAS,UAAU,MAAM,IAAI,MAAM,0DAA0D;GAClG,OAAO,mBAAmB,MAAM,OAAO,SAAS,QAAQ;EAC1D;EACA,UAAU,OAAO,MAAM,OAAO,UAAU,aAAa;GACnD,IAAI,CAAC,SAAS,UAAU,MAAM,IAAI,MAAM,0DAA0D;GAClG,MAAM,WAAW,gBAAgB,IAAI;GACrC,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,sEAAsE;GACrG,MAAM,OAAO,iBAAiB,OAAO,QAAQ,CAAC;GAC9C,OAAO,mBAAmB,MAAM,OAAO,SAAS,QAAQ;EAC1D;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"merge-request-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/merge-request-reconciler.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAuI9D,MAAM,MAAM,4BAA4B,GAAG,MAAM,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAahF,wBAAgB,kCAAkC,CAChD,MAAM,EAAE,IAAI,CACV,qBAAqB,EACnB,gBAAgB,GAChB,OAAO,GACP,6BAA6B,GAC7B,2BAA2B,GAC3B,gCAAgC,CACnC,GACC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,oBAAoB,CAAC,CAAC,EAC5D,OAAO,EAAE,kBAAkB,GAC1B,4BAA4B,GAAG,SAAS,CAyL1C"}
1
+ {"version":3,"file":"merge-request-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/merge-request-reconciler.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAGpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAuI9D,MAAM,MAAM,4BAA4B,GAAG,MAAM,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAahF,wBAAgB,kCAAkC,CAChD,MAAM,EAAE,IAAI,CACV,qBAAqB,EACnB,gBAAgB,GAChB,OAAO,GACP,6BAA6B,GAC7B,2BAA2B,GAC3B,gCAAgC,CACnC,GACC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,oBAAoB,CAAC,CAAC,EAC5D,OAAO,EAAE,kBAAkB,GAC1B,4BAA4B,GAAG,SAAS,CAqM1C"}
@@ -2,6 +2,7 @@ import { resolveBoardClosure, workItemPhaseSemantics } from "../../boards/semant
2
2
  import "../../boards/index.js";
3
3
  import { toBoardSource } from "../../boards/project-boards.js";
4
4
  import { FACTORY_PULL_REQUEST_RECONCILIATION_KEY } from "../../storage/domains/work-items/base.js";
5
+ import { storageCards } from "../kept-cards.js";
5
6
  import { decodeMergeRequestReference, gitlabConnection } from "./integration.js";
6
7
  import { attachGitLabRules } from "./rules.js";
7
8
  import { retireMergeRequestSubscriptions } from "./subscriptions.js";
@@ -109,6 +110,10 @@ function attachGitLabMergeRequestReconciler(gitlab, context) {
109
110
  const ingest = attachGitLabRules(gitlab, context);
110
111
  if (!ingest) return void 0;
111
112
  const boards = context.runtime.boards;
113
+ const source = context.runtime.keptCards ?? storageCards({
114
+ projects: context.storage.projects,
115
+ workItems: context.runtime.workItems
116
+ });
112
117
  return async () => {
113
118
  const summary = {
114
119
  projects: 0,
@@ -119,16 +124,27 @@ function attachGitLabMergeRequestReconciler(gitlab, context) {
119
124
  failed: 0,
120
125
  errors: []
121
126
  };
122
- for (const project of await context.storage.projects.listAll()) {
123
- await toBoardSource(boards).load({
124
- orgId: project.orgId,
125
- factoryProjectId: project.id
126
- });
127
- const items = (await context.runtime.workItems.listShared({
128
- orgId: project.orgId,
129
- factoryProjectId: project.id
130
- })).filter((item) => {
131
- if (item.externalSource?.integrationId !== "gitlab" || item.externalSource.type !== "pull-request") return false;
127
+ for (const project of await source.projects()) {
128
+ let mergeRequests;
129
+ try {
130
+ mergeRequests = (await source.cards({
131
+ orgId: project.orgId,
132
+ factoryProjectId: project.id
133
+ })).filter((item) => item.externalSource?.integrationId === "gitlab" && item.externalSource.type === "pull-request");
134
+ if (mergeRequests.length === 0) continue;
135
+ await toBoardSource(boards).load({
136
+ orgId: project.orgId,
137
+ factoryProjectId: project.id
138
+ });
139
+ } catch (error) {
140
+ summary.failed += 1;
141
+ summary.errors.push({
142
+ projectId: project.id,
143
+ error: error instanceof Error ? error.message : String(error)
144
+ });
145
+ continue;
146
+ }
147
+ const items = mergeRequests.filter((item) => {
132
148
  if (workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind !== "terminal") return true;
133
149
  const outcome = reconciledOutcome(item.workItem.metadata ?? {});
134
150
  return outcome === void 0 || item.metadata?.["factoryPullRequestReconciliation"] !== outcome;