@mastra/factory 0.28.0-alpha.9 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +61 -42
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/capabilities/version-control.d.ts +6 -1
  14. package/dist/capabilities/version-control.d.ts.map +1 -1
  15. package/dist/environment/build-runner.d.ts +13 -2
  16. package/dist/environment/build-runner.d.ts.map +1 -1
  17. package/dist/environment/build-runner.js +42 -0
  18. package/dist/environment/build-runner.js.map +1 -1
  19. package/dist/environment/build-schedule.js +1 -1
  20. package/dist/environment/build-schedule.js.map +1 -1
  21. package/dist/environment/build-workflow.d.ts +6 -4
  22. package/dist/environment/build-workflow.d.ts.map +1 -1
  23. package/dist/environment/build-workflow.js +70 -66
  24. package/dist/environment/build-workflow.js.map +1 -1
  25. package/dist/environment/build.d.ts +22 -7
  26. package/dist/environment/build.d.ts.map +1 -1
  27. package/dist/environment/build.js +73 -15
  28. package/dist/environment/build.js.map +1 -1
  29. package/dist/environment/heads.d.ts +1 -1
  30. package/dist/environment/heads.d.ts.map +1 -1
  31. package/dist/environment/heads.js +4 -1
  32. package/dist/environment/heads.js.map +1 -1
  33. package/dist/environment/repository-access.d.ts +13 -0
  34. package/dist/environment/repository-access.d.ts.map +1 -0
  35. package/dist/environment/repository-access.js +55 -0
  36. package/dist/environment/repository-access.js.map +1 -0
  37. package/dist/factory.d.ts +5 -2
  38. package/dist/factory.d.ts.map +1 -1
  39. package/dist/factory.js +32 -25
  40. package/dist/factory.js.map +1 -1
  41. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  42. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  43. package/dist/integrations/github/sandbox-release.js +16 -1
  44. package/dist/integrations/github/sandbox-release.js.map +1 -1
  45. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  46. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  47. package/dist/integrations/platform/github/integration.js +137 -105
  48. package/dist/integrations/platform/github/integration.js.map +1 -1
  49. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  50. package/dist/integrations/platform/jira/integration.js +5 -1
  51. package/dist/integrations/platform/jira/integration.js.map +1 -1
  52. package/dist/integrations/slack/integration.d.ts.map +1 -1
  53. package/dist/integrations/slack/integration.js +7 -4
  54. package/dist/integrations/slack/integration.js.map +1 -1
  55. package/dist/mcp/routes.d.ts.map +1 -1
  56. package/dist/mcp/routes.js +3 -5
  57. package/dist/mcp/routes.js.map +1 -1
  58. package/dist/routes/board-snapshot.d.ts +17 -1
  59. package/dist/routes/board-snapshot.d.ts.map +1 -1
  60. package/dist/routes/board-snapshot.js +54 -7
  61. package/dist/routes/board-snapshot.js.map +1 -1
  62. package/dist/routes/boards.d.ts +2 -3
  63. package/dist/routes/boards.d.ts.map +1 -1
  64. package/dist/routes/boards.js.map +1 -1
  65. package/dist/routes/contracts.d.ts +102 -0
  66. package/dist/routes/contracts.d.ts.map +1 -1
  67. package/dist/routes/contracts.js +96 -6
  68. package/dist/routes/contracts.js.map +1 -1
  69. package/dist/routes/projects.d.ts.map +1 -1
  70. package/dist/routes/projects.js +5 -0
  71. package/dist/routes/projects.js.map +1 -1
  72. package/dist/routes/sandbox-envs.d.ts +2 -0
  73. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  74. package/dist/routes/sandbox-envs.js +3 -0
  75. package/dist/routes/sandbox-envs.js.map +1 -1
  76. package/dist/routes/source-control-settings.d.ts +2 -0
  77. package/dist/routes/source-control-settings.d.ts.map +1 -1
  78. package/dist/routes/source-control-settings.js +5 -0
  79. package/dist/routes/source-control-settings.js.map +1 -1
  80. package/dist/routes/surface.d.ts +2 -0
  81. package/dist/routes/surface.d.ts.map +1 -1
  82. package/dist/routes/surface.js +2 -1
  83. package/dist/routes/surface.js.map +1 -1
  84. package/dist/routes/work-item-activity.d.ts +11 -0
  85. package/dist/routes/work-item-activity.d.ts.map +1 -0
  86. package/dist/routes/work-item-activity.js +25 -0
  87. package/dist/routes/work-item-activity.js.map +1 -0
  88. package/dist/routes/work-item-selection.d.ts +18 -0
  89. package/dist/routes/work-item-selection.d.ts.map +1 -0
  90. package/dist/routes/work-item-selection.js +61 -0
  91. package/dist/routes/work-item-selection.js.map +1 -0
  92. package/dist/routes/work-item-starters.d.ts +29 -0
  93. package/dist/routes/work-item-starters.d.ts.map +1 -0
  94. package/dist/routes/work-item-starters.js +169 -0
  95. package/dist/routes/work-item-starters.js.map +1 -0
  96. package/dist/routes/work-items.d.ts.map +1 -1
  97. package/dist/routes/work-items.js +162 -15
  98. package/dist/routes/work-items.js.map +1 -1
  99. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  100. package/dist/rules/dispatch-errors.js +4 -0
  101. package/dist/rules/dispatch-errors.js.map +1 -1
  102. package/dist/rules/dispatcher.d.ts +2 -1
  103. package/dist/rules/dispatcher.d.ts.map +1 -1
  104. package/dist/rules/dispatcher.js +84 -16
  105. package/dist/rules/dispatcher.js.map +1 -1
  106. package/dist/rules/processor.d.ts +2 -0
  107. package/dist/rules/processor.d.ts.map +1 -1
  108. package/dist/rules/processor.js +18 -4
  109. package/dist/rules/processor.js.map +1 -1
  110. package/dist/rules/transition-service.d.ts +20 -2
  111. package/dist/rules/transition-service.d.ts.map +1 -1
  112. package/dist/rules/transition-service.js +40 -18
  113. package/dist/rules/transition-service.js.map +1 -1
  114. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  115. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  116. package/dist/sandbox/context-sandboxes.js +120 -0
  117. package/dist/sandbox/context-sandboxes.js.map +1 -0
  118. package/dist/sandbox/session-retirement.d.ts +11 -4
  119. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  120. package/dist/sandbox/session-retirement.js +39 -13
  121. package/dist/sandbox/session-retirement.js.map +1 -1
  122. package/dist/session/live-sessions.d.ts +1 -1
  123. package/dist/session/live-sessions.d.ts.map +1 -1
  124. package/dist/session/live-sessions.js +12 -2
  125. package/dist/session/live-sessions.js.map +1 -1
  126. package/dist/storage/domains/boards/base.d.ts +25 -5
  127. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  128. package/dist/storage/domains/boards/base.js +57 -20
  129. package/dist/storage/domains/boards/base.js.map +1 -1
  130. package/dist/storage/domains/projects/base.d.ts +8 -2
  131. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  132. package/dist/storage/domains/projects/base.js +21 -4
  133. package/dist/storage/domains/projects/base.js.map +1 -1
  134. package/dist/storage/domains/work-items/base.d.ts +47 -6
  135. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  136. package/dist/storage/domains/work-items/base.js +161 -17
  137. package/dist/storage/domains/work-items/base.js.map +1 -1
  138. package/dist/storage/domains/work-items/cards.d.ts +1 -0
  139. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  140. package/dist/storage/domains/work-items/cards.js +32 -8
  141. package/dist/storage/domains/work-items/cards.js.map +1 -1
  142. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  143. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  144. package/dist/storage/domains/work-items/legacy-review.js +62 -3
  145. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  146. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
  147. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  148. package/dist/storage/domains/work-items/work-item-schema.js +46 -18
  149. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  150. package/dist/tools/annotations.d.ts.map +1 -1
  151. package/dist/tools/annotations.js +4 -0
  152. package/dist/tools/annotations.js.map +1 -1
  153. package/dist/tools/audit-events-tool.d.ts +29 -0
  154. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  155. package/dist/tools/audit-events-tool.js +180 -0
  156. package/dist/tools/audit-events-tool.js.map +1 -0
  157. package/dist/tools/index.d.ts +2 -1
  158. package/dist/tools/index.d.ts.map +1 -1
  159. package/dist/tools/index.js +2 -0
  160. package/dist/tools/index.js.map +1 -1
  161. package/dist/tools/permissions.d.ts.map +1 -1
  162. package/dist/tools/permissions.js +1 -0
  163. package/dist/tools/permissions.js.map +1 -1
  164. package/dist/tools/sessions-state-processor.js +1 -1
  165. package/dist/tools/sessions-state-processor.js.map +1 -1
  166. package/dist/work-items/board-check.d.ts +11 -0
  167. package/dist/work-items/board-check.d.ts.map +1 -0
  168. package/dist/work-items/board-check.js +20 -0
  169. package/dist/work-items/board-check.js.map +1 -0
  170. package/dist/work-items/related-cards.d.ts +21 -0
  171. package/dist/work-items/related-cards.d.ts.map +1 -0
  172. package/dist/work-items/related-cards.js +45 -0
  173. package/dist/work-items/related-cards.js.map +1 -0
  174. package/dist/work-items/split-migration.d.ts.map +1 -1
  175. package/dist/work-items/split-migration.js +6 -2
  176. package/dist/work-items/split-migration.js.map +1 -1
  177. package/dist/workspace.d.ts +0 -1
  178. package/dist/workspace.d.ts.map +1 -1
  179. package/dist/workspace.js +49 -32
  180. package/dist/workspace.js.map +1 -1
  181. package/factory-skills/factory-build/SKILL.md +1 -1
  182. package/factory-skills/factory-self-review/SKILL.md +1 -1
  183. package/factory-skills/factory-triage/SKILL.md +4 -4
  184. package/package.json +16 -16
@@ -26,6 +26,18 @@ export declare function destroyDetachedSessionSandbox(options: {
26
26
  sandbox: FactorySandbox;
27
27
  session: Pick<SourceControlSession, 'id' | 'sandboxId'>;
28
28
  }): Promise<void>;
29
+ /**
30
+ * Stop a session's VM by identity from a process that holds no instance of
31
+ * it, keeping its files for the next start. Like the detached destroy it
32
+ * calls the provider's plain `stop()`, never the `_stop` lifecycle wrapper:
33
+ * E2B pauses the VM it finds by identity, Docker stops the container named
34
+ * after it, and providers with nothing to stop from outside (Platform,
35
+ * local) return.
36
+ */
37
+ export declare function stopDetachedSessionSandbox(options: {
38
+ sandbox: FactorySandbox;
39
+ session: Pick<SourceControlSession, 'id' | 'sandboxId'>;
40
+ }): Promise<void>;
29
41
  /**
30
42
  * Tear down the sandbox a just-deleted user session was holding. The row is
31
43
  * already gone, so the VM is destroyed rather than stopped — nothing will
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-release.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/sandbox-release.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEzF;;;;;;;;;GASG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACnD,2DAA2D;IAC3D,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBhB;AAED;;;;;GAKG;AACH,wBAAsB,6BAA6B,CAAC,OAAO,EAAE;IAC3D,OAAO,EAAE,cAAc,CAAC;IACxB,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,IAAI,GAAG,WAAW,CAAC,CAAC;CACzD,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhB;AAED;;;;GAIG;AACH,wBAAsB,4BAA4B,CAAC,OAAO,EAAE;IAC1D,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;CAC3C,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhB"}
1
+ {"version":3,"file":"sandbox-release.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/sandbox-release.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEzF;;;;;;;;;GASG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACnD,2DAA2D;IAC3D,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBhB;AAED;;;;;GAKG;AACH,wBAAsB,6BAA6B,CAAC,OAAO,EAAE;IAC3D,OAAO,EAAE,cAAc,CAAC;IACxB,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,IAAI,GAAG,WAAW,CAAC,CAAC;CACzD,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhB;AAED;;;;;;;GAOG;AACH,wBAAsB,0BAA0B,CAAC,OAAO,EAAE;IACxD,OAAO,EAAE,cAAc,CAAC;IACxB,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,IAAI,GAAG,WAAW,CAAC,CAAC;CACzD,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhB;AAED;;;;GAIG;AACH,wBAAsB,4BAA4B,CAAC,OAAO,EAAE;IAC1D,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;CAC3C,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhB"}
@@ -39,6 +39,21 @@ async function destroyDetachedSessionSandbox(options) {
39
39
  }, {}).destroy();
40
40
  }
41
41
  /**
42
+ * Stop a session's VM by identity from a process that holds no instance of
43
+ * it, keeping its files for the next start. Like the detached destroy it
44
+ * calls the provider's plain `stop()`, never the `_stop` lifecycle wrapper:
45
+ * E2B pauses the VM it finds by identity, Docker stops the container named
46
+ * after it, and providers with nothing to stop from outside (Platform,
47
+ * local) return.
48
+ */
49
+ async function stopDetachedSessionSandbox(options) {
50
+ await options.sandbox.create({
51
+ sessionId: options.session.id,
52
+ sandboxId: options.session.sandboxId ?? void 0,
53
+ getRepositoryAccess: void 0
54
+ }, {}).stop();
55
+ }
56
+ /**
42
57
  * Tear down the sandbox a just-deleted user session was holding. The row is
43
58
  * already gone, so the VM is destroyed rather than stopped — nothing will
44
59
  * ever resolve this session id again.
@@ -49,6 +64,6 @@ async function reclaimDeletedSessionSandbox(options) {
49
64
  destroy: true
50
65
  });
51
66
  }
52
- export { destroyDetachedSessionSandbox, reclaimDeletedSessionSandbox, releaseSessionSandbox };
67
+ export { destroyDetachedSessionSandbox, reclaimDeletedSessionSandbox, releaseSessionSandbox, stopDetachedSessionSandbox };
53
68
 
54
69
  //# sourceMappingURL=sandbox-release.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-release.js","names":[],"sources":["../../../src/integrations/github/sandbox-release.ts"],"sourcesContent":["import type { FactorySandbox } from '@mastra/core/workspace';\n\nimport { evictSessionSandbox, peekSessionSandbox } from '../../sandbox/session-sandbox.js';\nimport type { SourceControlSession } from '../../storage/domains/source-control/base.js';\n\n/**\n * Stop or destroy the sandbox a session holds in this process, dropping it\n * from the per-process memo first so later opens construct fresh.\n *\n * Sandbox identity is the session id, so there is no reuse pool to publish\n * into — a reopened session resolves the same id through its provider\n * (reconnect/resume, or a fresh VM whose setup hook re-materializes).\n * Sessions never opened in this replica have no memo entry; destroying those\n * goes through {@link destroyDetachedSessionSandbox}.\n */\nexport async function releaseSessionSandbox(options: {\n /** The session's storage row id (the sandbox identity). */\n sessionId: string;\n /** Destroy instead of stop — for sessions that are gone for good. */\n destroy?: boolean;\n}): Promise<void> {\n const entry = peekSessionSandbox(options.sessionId);\n if (!entry) return;\n evictSessionSandbox(options.sessionId);\n const sandbox = entry.sandbox as unknown as {\n _stop?: () => Promise<void>;\n _destroy?: () => Promise<void>;\n stop?: () => Promise<void>;\n destroy?: () => Promise<void>;\n status?: string;\n };\n if (options.destroy) {\n // Constructed here but never started: the lifecycle wrapper treats that as\n // nothing to clean up, yet the VM may exist from an earlier process. The\n // provider's own destroy kills it by identity without resuming.\n if (sandbox.status === 'pending' && sandbox.destroy) {\n await sandbox.destroy();\n return;\n }\n await (sandbox._destroy ? sandbox._destroy() : sandbox.destroy?.());\n return;\n }\n await (sandbox._stop ? sandbox._stop() : sandbox.stop?.());\n}\n\n/**\n * Destroy a session's VM by identity from a process that holds no instance of\n * it. Constructs the provider sandbox (cheap, side-effect-free by contract)\n * and calls its plain `destroy()` — never `start()` and never the `_destroy`\n * lifecycle wrapper, which skips sandboxes this instance never started.\n */\nexport async function destroyDetachedSessionSandbox(options: {\n sandbox: FactorySandbox;\n session: Pick<SourceControlSession, 'id' | 'sandboxId'>;\n}): Promise<void> {\n const sandbox = options.sandbox.create(\n {\n sessionId: options.session.id,\n sandboxId: options.session.sandboxId ?? undefined,\n getRepositoryAccess: undefined,\n },\n {},\n );\n await sandbox.destroy();\n}\n\n/**\n * Tear down the sandbox a just-deleted user session was holding. The row is\n * already gone, so the VM is destroyed rather than stopped — nothing will\n * ever resolve this session id again.\n */\nexport async function reclaimDeletedSessionSandbox(options: {\n session: Pick<SourceControlSession, 'id'>;\n}): Promise<void> {\n await releaseSessionSandbox({ sessionId: options.session.id, destroy: true });\n}\n"],"mappings":";;;;;;;;;;;;AAeA,eAAsB,sBAAsB,SAK1B;CAChB,MAAM,QAAQ,mBAAmB,QAAQ,SAAS;CAClD,IAAI,CAAC,OAAO;CACZ,oBAAoB,QAAQ,SAAS;CACrC,MAAM,UAAU,MAAM;CAOtB,IAAI,QAAQ,SAAS;EAInB,IAAI,QAAQ,WAAW,aAAa,QAAQ,SAAS;GACnD,MAAM,QAAQ,QAAQ;GACtB;EACF;EACA,OAAO,QAAQ,WAAW,QAAQ,SAAS,IAAI,QAAQ,UAAU;EACjE;CACF;CACA,OAAO,QAAQ,QAAQ,QAAQ,MAAM,IAAI,QAAQ,OAAO;AAC1D;;;;;;;AAQA,eAAsB,8BAA8B,SAGlC;CAShB,MARgB,QAAQ,QAAQ,OAC9B;EACE,WAAW,QAAQ,QAAQ;EAC3B,WAAW,QAAQ,QAAQ,aAAa,KAAA;EACxC,qBAAqB,KAAA;CACvB,GACA,CAAC,CAES,CAAC,CAAC,QAAQ;AACxB;;;;;;AAOA,eAAsB,6BAA6B,SAEjC;CAChB,MAAM,sBAAsB;EAAE,WAAW,QAAQ,QAAQ;EAAI,SAAS;CAAK,CAAC;AAC9E"}
1
+ {"version":3,"file":"sandbox-release.js","names":[],"sources":["../../../src/integrations/github/sandbox-release.ts"],"sourcesContent":["import type { FactorySandbox } from '@mastra/core/workspace';\n\nimport { evictSessionSandbox, peekSessionSandbox } from '../../sandbox/session-sandbox.js';\nimport type { SourceControlSession } from '../../storage/domains/source-control/base.js';\n\n/**\n * Stop or destroy the sandbox a session holds in this process, dropping it\n * from the per-process memo first so later opens construct fresh.\n *\n * Sandbox identity is the session id, so there is no reuse pool to publish\n * into — a reopened session resolves the same id through its provider\n * (reconnect/resume, or a fresh VM whose setup hook re-materializes).\n * Sessions never opened in this replica have no memo entry; destroying those\n * goes through {@link destroyDetachedSessionSandbox}.\n */\nexport async function releaseSessionSandbox(options: {\n /** The session's storage row id (the sandbox identity). */\n sessionId: string;\n /** Destroy instead of stop — for sessions that are gone for good. */\n destroy?: boolean;\n}): Promise<void> {\n const entry = peekSessionSandbox(options.sessionId);\n if (!entry) return;\n evictSessionSandbox(options.sessionId);\n const sandbox = entry.sandbox as unknown as {\n _stop?: () => Promise<void>;\n _destroy?: () => Promise<void>;\n stop?: () => Promise<void>;\n destroy?: () => Promise<void>;\n status?: string;\n };\n if (options.destroy) {\n // Constructed here but never started: the lifecycle wrapper treats that as\n // nothing to clean up, yet the VM may exist from an earlier process. The\n // provider's own destroy kills it by identity without resuming.\n if (sandbox.status === 'pending' && sandbox.destroy) {\n await sandbox.destroy();\n return;\n }\n await (sandbox._destroy ? sandbox._destroy() : sandbox.destroy?.());\n return;\n }\n await (sandbox._stop ? sandbox._stop() : sandbox.stop?.());\n}\n\n/**\n * Destroy a session's VM by identity from a process that holds no instance of\n * it. Constructs the provider sandbox (cheap, side-effect-free by contract)\n * and calls its plain `destroy()` — never `start()` and never the `_destroy`\n * lifecycle wrapper, which skips sandboxes this instance never started.\n */\nexport async function destroyDetachedSessionSandbox(options: {\n sandbox: FactorySandbox;\n session: Pick<SourceControlSession, 'id' | 'sandboxId'>;\n}): Promise<void> {\n const sandbox = options.sandbox.create(\n {\n sessionId: options.session.id,\n sandboxId: options.session.sandboxId ?? undefined,\n getRepositoryAccess: undefined,\n },\n {},\n );\n await sandbox.destroy();\n}\n\n/**\n * Stop a session's VM by identity from a process that holds no instance of\n * it, keeping its files for the next start. Like the detached destroy it\n * calls the provider's plain `stop()`, never the `_stop` lifecycle wrapper:\n * E2B pauses the VM it finds by identity, Docker stops the container named\n * after it, and providers with nothing to stop from outside (Platform,\n * local) return.\n */\nexport async function stopDetachedSessionSandbox(options: {\n sandbox: FactorySandbox;\n session: Pick<SourceControlSession, 'id' | 'sandboxId'>;\n}): Promise<void> {\n const sandbox = options.sandbox.create(\n {\n sessionId: options.session.id,\n sandboxId: options.session.sandboxId ?? undefined,\n getRepositoryAccess: undefined,\n },\n {},\n );\n await sandbox.stop();\n}\n\n/**\n * Tear down the sandbox a just-deleted user session was holding. The row is\n * already gone, so the VM is destroyed rather than stopped — nothing will\n * ever resolve this session id again.\n */\nexport async function reclaimDeletedSessionSandbox(options: {\n session: Pick<SourceControlSession, 'id'>;\n}): Promise<void> {\n await releaseSessionSandbox({ sessionId: options.session.id, destroy: true });\n}\n"],"mappings":";;;;;;;;;;;;AAeA,eAAsB,sBAAsB,SAK1B;CAChB,MAAM,QAAQ,mBAAmB,QAAQ,SAAS;CAClD,IAAI,CAAC,OAAO;CACZ,oBAAoB,QAAQ,SAAS;CACrC,MAAM,UAAU,MAAM;CAOtB,IAAI,QAAQ,SAAS;EAInB,IAAI,QAAQ,WAAW,aAAa,QAAQ,SAAS;GACnD,MAAM,QAAQ,QAAQ;GACtB;EACF;EACA,OAAO,QAAQ,WAAW,QAAQ,SAAS,IAAI,QAAQ,UAAU;EACjE;CACF;CACA,OAAO,QAAQ,QAAQ,QAAQ,MAAM,IAAI,QAAQ,OAAO;AAC1D;;;;;;;AAQA,eAAsB,8BAA8B,SAGlC;CAShB,MARgB,QAAQ,QAAQ,OAC9B;EACE,WAAW,QAAQ,QAAQ;EAC3B,WAAW,QAAQ,QAAQ,aAAa,KAAA;EACxC,qBAAqB,KAAA;CACvB,GACA,CAAC,CAES,CAAC,CAAC,QAAQ;AACxB;;;;;;;;;AAUA,eAAsB,2BAA2B,SAG/B;CAShB,MARgB,QAAQ,QAAQ,OAC9B;EACE,WAAW,QAAQ,QAAQ;EAC3B,WAAW,QAAQ,QAAQ,aAAa,KAAA;EACxC,qBAAqB,KAAA;CACvB,GACA,CAAC,CAES,CAAC,CAAC,KAAK;AACrB;;;;;;AAOA,eAAsB,6BAA6B,SAEjC;CAChB,MAAM,sBAAsB;EAAE,WAAW,QAAQ,QAAQ;EAAI,SAAS;CAAK,CAAC;AAC9E"}
@@ -1 +1 @@
1
- {"version":3,"file":"event-worker.js","names":[],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport { DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS } from '../../github/reconcile-worker.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type {\n GithubPullRequestDiscovery,\n GithubPullRequestReconciler,\n ReconcileRepository,\n} from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so base checkpoints rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = { id: number; fullName?: string; installationId: number };\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n discoverPullRequests?: GithubPullRequestDiscovery;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n /** Defaults to five minutes, or the pull request interval when that is shorter. */\n pullRequestDiscoveryIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #discoverPullRequests: GithubPullRequestDiscovery | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #pullRequestDiscoveryIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #lastPullRequestDiscoveryAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#discoverPullRequests = config.discoverPullRequests;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#pullRequestDiscoveryIntervalMs =\n config.pullRequestDiscoveryIntervalMs ??\n Math.min(DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS, this.#pullRequestReconcileIntervalMs);\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestDiscoveryIntervalMs) || this.#pullRequestDiscoveryIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request discovery interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(\n this.#intervalMs,\n this.#pullRequestReconcileIntervalMs,\n this.#issueReconcileIntervalMs,\n this.#pullRequestDiscoveryIntervalMs,\n ) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#discoverRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n const discoverPullRequests = Boolean(\n this.#discoverPullRequests &&\n now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests) return;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#discoverPullRequests(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request discovery completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0 || counts.repaired > 0) {\n this.deps?.logger.info('Platform GitHub pull request discovery replayed missed opens', context);\n } else {\n this.deps?.logger.debug('Platform GitHub pull request discovery completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request discovery failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed missed opens', context);\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n } else {\n this.deps?.logger.debug('Platform GitHub event not forwarded to Factory ingress', {\n repositoryId,\n deliveryId: parsed.deliveryId,\n event: parsed.event,\n action: parsed.payload.action,\n });\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nconst ISSUE_INGESTED_ACTIONS = new Set(['opened', 'reopened', 'edited', 'labeled', 'unlabeled']);\n\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n // Issue opens, reopens, edits and label changes mint and update Work cards.\n // Without them a new issue never becomes a card on the polling path (#24972).\n if (event.event === 'issues' && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // `factory-review` edits its earlier verdict in place on a re-review. The rules\n // engine only acts on edits that leave a request-changes verdict behind.\n if (event.event === 'pull_request_review' && event.payload.action === 'edited') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'edited') {\n const issue = event.payload.issue;\n if (issue && typeof issue === 'object' && 'pull_request' in issue && issue.pull_request) return true;\n }\n // Default-branch pushes drive base-checkpoint rebuilds\n // (`withBaseCheckpointWebhookTrigger` wraps the ingest callback).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AAGjC,MAAM,gCAAgC;AACtC,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC;AAGD,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAgC;CAAC;CAAS;CAAY;AAAO,CAAC;AACjG,MAAM,8BAA8B;AAuDpC,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW,OAAO,WAAW;CAEpD,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CAEb,8BAA8B,OAAO;CACrC,wBAAwB,OAAO;CAC/B,8BAA8B,OAAO;CACrC,YAA+C;EAAE,SA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WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
1
+ {"version":3,"file":"event-worker.js","names":[],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport { DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS } from '../../github/reconcile-worker.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type {\n GithubPullRequestDiscovery,\n GithubPullRequestReconciler,\n ReconcileRepository,\n} from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so environment templates rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = { id: number; fullName?: string; installationId: number };\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n discoverPullRequests?: GithubPullRequestDiscovery;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n /** Defaults to five minutes, or the pull request interval when that is shorter. */\n pullRequestDiscoveryIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #discoverPullRequests: GithubPullRequestDiscovery | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #pullRequestDiscoveryIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #lastPullRequestDiscoveryAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#discoverPullRequests = config.discoverPullRequests;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#pullRequestDiscoveryIntervalMs =\n config.pullRequestDiscoveryIntervalMs ??\n Math.min(DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS, this.#pullRequestReconcileIntervalMs);\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestDiscoveryIntervalMs) || this.#pullRequestDiscoveryIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request discovery interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(\n this.#intervalMs,\n this.#pullRequestReconcileIntervalMs,\n this.#issueReconcileIntervalMs,\n this.#pullRequestDiscoveryIntervalMs,\n ) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#discoverRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n const discoverPullRequests = Boolean(\n this.#discoverPullRequests &&\n now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests) return;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#discoverPullRequests(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request discovery completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0 || counts.repaired > 0) {\n this.deps?.logger.info('Platform GitHub pull request discovery replayed missed opens', context);\n } else {\n this.deps?.logger.debug('Platform GitHub pull request discovery completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request discovery failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed missed opens', context);\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n } else {\n this.deps?.logger.debug('Platform GitHub event not forwarded to Factory ingress', {\n repositoryId,\n deliveryId: parsed.deliveryId,\n event: parsed.event,\n action: parsed.payload.action,\n });\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nconst ISSUE_INGESTED_ACTIONS = new Set(['opened', 'reopened', 'edited', 'labeled', 'unlabeled']);\n\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n // Issue opens, reopens, edits and label changes mint and update Work cards.\n // Without them a new issue never becomes a card on the polling path (#24972).\n if (event.event === 'issues' && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // `factory-review` edits its earlier verdict in place on a re-review. The rules\n // engine only acts on edits that leave a request-changes verdict behind.\n if (event.event === 'pull_request_review' && event.payload.action === 'edited') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'edited') {\n const issue = event.payload.issue;\n if (issue && typeof issue === 'object' && 'pull_request' in issue && issue.pull_request) return true;\n }\n // Default-branch pushes reach the environment build hand-off\n // (`GithubRules` calls the `onRepositoryPush` hook).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\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AAM,CAAC,GAAG,OAAO;CACjG,IAAI,MAAM,UAAU,yBAAyB,MAAM,QAAQ,WAAW,aAAa,OAAO;CAC1F,IAAI,MAAM,UAAU,mBAAmB,MAAM,QAAQ,WAAW,WAAW,OAAO;CAGlF,IAAI,MAAM,UAAU,yBAAyB,MAAM,QAAQ,WAAW,UAAU,OAAO;CACvF,IAAI,MAAM,UAAU,mBAAmB,MAAM,QAAQ,WAAW,UAAU;EACxE,MAAM,QAAQ,MAAM,QAAQ;EAC5B,IAAI,SAAS,OAAO,UAAU,YAAY,kBAAkB,SAAS,MAAM,cAAc,OAAO;CAClG;CAGA,IAAI,MAAM,UAAU,QAAQ,OAAO;CACnC,OAAO;AACT;AAEA,SAAS,WAAW,OAAkD;CACpE,IACE,CAAC,MAAM,MACP,CAAC,MAAM,cACP,CAAC,iBAAiB,IAAI,MAAM,KAAK,KACjC,CAAC,MAAM,WACP,OAAO,MAAM,YAAY,YACzB,MAAM,QAAQ,MAAM,OAAO,GAE3B,OAAO;CAET,OAAO;EACL,OAAO,MAAM;EACb,YAAY,MAAM;EAClB,SAAS,MAAM;CACjB;AACF;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAIxD,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EA0BV,cAAc,EACf,MAAM,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AAI,CAAC,CAGnG;IAEK,qBAAqB,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAWnE;IAEK,cAAc,CAClB,eAAe,EAAE,MAAM,EACvB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EAAE,GACf,OAAO,CAAC,MAAM,EAAE,CAAC,CAOnB;IAEK,gBAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAOnH;IAED,sBAAsB,CAAC,eAAe,EAAE,MAAM,GAAG,UAAU,CAAC,iBAAiB,CAAC,wBAAwB,CAAC,CAAC,CAYvG;CAoaF"}
@@ -13,6 +13,14 @@ import { PlatformGithubEventWorker } from "./event-worker.js";
13
13
  import { registerApiRoute } from "@mastra/core/server";
14
14
  import { Octokit } from "@octokit/rest";
15
15
  // src/integrations/platform/github/integration.ts
16
+ /**
17
+ * Status reason for a settled installation list. A personal install Platform withholds would otherwise
18
+ * read as "nothing installed", so say so; any usable installation still means ready.
19
+ */
20
+ function githubStatusReason(hasUsableInstallation, hiddenPersonalInstallReason) {
21
+ if (hasUsableInstallation) return "ready";
22
+ return hiddenPersonalInstallReason ? "personal_install_hidden" : "not_connected";
23
+ }
16
24
  const PAGE_SIZE = 30;
17
25
  const OPEN_ISSUE_DISCOVERY_MAX_PAGES = 5;
18
26
  const API_PREFIX = "/v1/server";
@@ -33,10 +41,11 @@ const PLATFORM_GITHUB_APP_SLUG = "mastra-platform";
33
41
  const INSTALLATION_REPOS_CACHE_TTL_MS = 3e4;
34
42
  /**
35
43
  * How long a minted repository-scoped token may be reused. GitHub
36
- * installation tokens live ~60 minutes; 5 minutes keeps a wide validity
37
- * margin while collapsing the per-session-materialization mint round trip.
44
+ * installation tokens live ~60 minutes. A session re-mints the token it
45
+ * installed after `GITHUB_TOKEN_REFRESH_AFTER_MS` (30 minutes), so a token
46
+ * served from this cache is at most 50 minutes old when it is replaced.
38
47
  */
39
- const REPOSITORY_ACCESS_CACHE_TTL_MS = 3e5;
48
+ const REPOSITORY_ACCESS_CACHE_TTL_MS = 12e5;
40
49
  /**
41
50
  * How long a collaborator permission lookup may be reused. The reconcile
42
51
  * sweep re-stamps every open card's author and the event tail gates every
@@ -109,6 +118,22 @@ var PlatformGithubIntegration = class {
109
118
  #installationReposCache = /* @__PURE__ */ new Map();
110
119
  /** `orgId:repositoryId` → cached repository access (TTL-bounded). */
111
120
  #repositoryAccessCache = /* @__PURE__ */ new Map();
121
+ /**
122
+ * In-flight mints by the same key as `#repositoryAccessCache`. Sessions that
123
+ * boot together all miss the cache at once; without this each one minted its
124
+ * own token and drained the Platform's per-installation mint budget.
125
+ */
126
+ #repositoryAccessInFlight = /* @__PURE__ */ new Map();
127
+ #mintOnce(cacheKey, mint) {
128
+ const cached = this.#repositoryAccessCache.get(cacheKey);
129
+ if (cached && cached.expiresAt > Date.now()) return Promise.resolve(cached.access);
130
+ this.#repositoryAccessCache.delete(cacheKey);
131
+ const inFlight = this.#repositoryAccessInFlight.get(cacheKey);
132
+ if (inFlight) return inFlight;
133
+ const pending = mint().finally(() => this.#repositoryAccessInFlight.delete(cacheKey));
134
+ this.#repositoryAccessInFlight.set(cacheKey, pending);
135
+ return pending;
136
+ }
112
137
  /** `owner/repo:login` → cached collaborator permission (TTL-bounded). */
113
138
  #collaboratorPermissionCache = /* @__PURE__ */ new Map();
114
139
  /** Same key → lookup already in flight, so overlapping callers share one request. */
@@ -273,68 +298,30 @@ var PlatformGithubIntegration = class {
273
298
  },
274
299
  getRepositoryAccess: async ({ orgId, repositoryId }) => {
275
300
  const cacheKey = `${orgId}:${repositoryId}`;
276
- const cached = this.#repositoryAccessCache.get(cacheKey);
277
- if (cached && cached.expiresAt > Date.now()) return cached.access;
278
- this.#repositoryAccessCache.delete(cacheKey);
279
- const repository = await this.storage.repositories.get({
280
- orgId,
281
- id: repositoryId
282
- });
283
- if (!repository) throw new Error("Version-control repository not found.");
284
- const cloneUrl = `https://github.com/${repository.slug}.git`;
285
- const installation = await this.storage.installations.get({
286
- orgId,
287
- id: repository.installationId
288
- });
289
- if (!installation) throw new Error("Version-control installation not found.");
290
- const installationId = parsePositiveInteger(installation.externalId);
291
- if (installationId === null) throw new Error("GitHub installation id is invalid.");
292
- const repositoryName = splitRepository(repository.slug).repo;
293
- try {
294
- const access = {
295
- cloneUrl,
296
- authorization: {
297
- scheme: "bearer",
298
- token: (await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
299
- repositories: [repositoryName],
300
- permissions: REPOSITORY_TOKEN_PERMISSIONS
301
- })).token
302
- }
303
- };
304
- setBounded(this.#repositoryAccessCache, cacheKey, {
305
- access,
306
- expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
301
+ return this.#mintOnce(cacheKey, async () => {
302
+ const repository = await this.storage.repositories.get({
303
+ orgId,
304
+ id: repositoryId
307
305
  });
308
- return access;
309
- } catch (err) {
310
- if (!isDeadInstallation(err) || !installation.accountName) throw err;
311
- const candidates = (await this.storage.installations.list({ orgId })).map((inst, index) => ({
312
- inst,
313
- index
314
- })).filter(({ inst }) => inst.accountName === installation.accountName && inst.id !== installation.id).sort((a, b) => b.inst.createdAt.getTime() - a.inst.createdAt.getTime() || b.index - a.index).map(({ inst }) => inst);
315
- for (const candidate of candidates) {
316
- const candidateInstallationId = parsePositiveInteger(candidate.externalId);
317
- if (candidateInstallationId === null) continue;
318
- let token;
319
- try {
320
- token = await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${candidateInstallationId}/token`, {
321
- repositories: [repositoryName],
322
- permissions: REPOSITORY_TOKEN_PERMISSIONS
323
- });
324
- } catch (candidateErr) {
325
- if (isDeadInstallation(candidateErr)) continue;
326
- throw candidateErr;
327
- }
328
- await this.storage.repositories.migrateInstallation({
329
- orgId,
330
- id: repositoryId,
331
- newInstallationId: candidate.id
332
- });
306
+ if (!repository) throw new Error("Version-control repository not found.");
307
+ const cloneUrl = `https://github.com/${repository.slug}.git`;
308
+ const installation = await this.storage.installations.get({
309
+ orgId,
310
+ id: repository.installationId
311
+ });
312
+ if (!installation) throw new Error("Version-control installation not found.");
313
+ const installationId = parsePositiveInteger(installation.externalId);
314
+ if (installationId === null) throw new Error("GitHub installation id is invalid.");
315
+ const repositoryName = splitRepository(repository.slug).repo;
316
+ try {
333
317
  const access = {
334
318
  cloneUrl,
335
319
  authorization: {
336
320
  scheme: "bearer",
337
- token: token.token
321
+ token: (await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
322
+ repositories: [repositoryName],
323
+ permissions: REPOSITORY_TOKEN_PERMISSIONS
324
+ })).token
338
325
  }
339
326
  };
340
327
  setBounded(this.#repositoryAccessCache, cacheKey, {
@@ -342,47 +329,88 @@ var PlatformGithubIntegration = class {
342
329
  expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
343
330
  });
344
331
  return access;
332
+ } catch (err) {
333
+ if (!isDeadInstallation(err) || !installation.accountName) throw err;
334
+ const candidates = (await this.storage.installations.list({ orgId })).map((inst, index) => ({
335
+ inst,
336
+ index
337
+ })).filter(({ inst }) => inst.accountName === installation.accountName && inst.id !== installation.id).sort((a, b) => b.inst.createdAt.getTime() - a.inst.createdAt.getTime() || b.index - a.index).map(({ inst }) => inst);
338
+ for (const candidate of candidates) {
339
+ const candidateInstallationId = parsePositiveInteger(candidate.externalId);
340
+ if (candidateInstallationId === null) continue;
341
+ let token;
342
+ try {
343
+ token = await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${candidateInstallationId}/token`, {
344
+ repositories: [repositoryName],
345
+ permissions: REPOSITORY_TOKEN_PERMISSIONS
346
+ });
347
+ } catch (candidateErr) {
348
+ if (isDeadInstallation(candidateErr)) continue;
349
+ throw candidateErr;
350
+ }
351
+ await this.storage.repositories.migrateInstallation({
352
+ orgId,
353
+ id: repositoryId,
354
+ newInstallationId: candidate.id
355
+ });
356
+ const access = {
357
+ cloneUrl,
358
+ authorization: {
359
+ scheme: "bearer",
360
+ token: token.token
361
+ }
362
+ };
363
+ setBounded(this.#repositoryAccessCache, cacheKey, {
364
+ access,
365
+ expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
366
+ });
367
+ return access;
368
+ }
369
+ throw err;
345
370
  }
346
- throw err;
347
- }
371
+ });
348
372
  },
349
373
  getRepositoriesAccess: async ({ orgId, repositoryIds }) => {
350
374
  const ids = [...new Set(repositoryIds)];
351
375
  if (ids.length === 0 || ids.length > MAX_REPOSITORIES_PER_TOKEN) return void 0;
352
376
  const cacheKey = `${orgId}:${[...ids].sort().join(",")}`;
353
- const cached = this.#repositoryAccessCache.get(cacheKey);
354
- if (cached && cached.expiresAt > Date.now()) return cached.access;
355
- this.#repositoryAccessCache.delete(cacheKey);
356
- const repositories = await Promise.all(ids.map((id) => this.storage.repositories.get({
357
- orgId,
358
- id
359
- })));
360
- if (repositories.some((repository) => !repository)) throw new Error("Version-control repository not found.");
361
- const found = repositories;
362
- if (new Set(found.map((repository) => repository.installationId)).size !== 1) return void 0;
363
- const installation = await this.storage.installations.get({
364
- orgId,
365
- id: found[0].installationId
366
- });
367
- if (!installation) throw new Error("Version-control installation not found.");
368
- const installationId = parsePositiveInteger(installation.externalId);
369
- if (installationId === null) throw new Error("GitHub installation id is invalid.");
370
- const token = await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
371
- repositories: found.map((repository) => splitRepository(repository.slug).repo),
372
- permissions: REPOSITORY_TOKEN_PERMISSIONS
373
- });
374
- const access = {
375
- cloneUrl: `https://github.com/${found[0].slug}.git`,
376
- authorization: {
377
+ return this.#mintOnce(cacheKey, async () => {
378
+ const repositories = await Promise.all(ids.map((id) => this.storage.repositories.get({
379
+ orgId,
380
+ id
381
+ })));
382
+ if (repositories.some((repository) => !repository)) throw new Error("Version-control repository not found.");
383
+ const found = repositories;
384
+ if (new Set(found.map((repository) => repository.installationId)).size !== 1) return void 0;
385
+ const installation = await this.storage.installations.get({
386
+ orgId,
387
+ id: found[0].installationId
388
+ });
389
+ if (!installation) throw new Error("Version-control installation not found.");
390
+ const installationId = parsePositiveInteger(installation.externalId);
391
+ if (installationId === null) throw new Error("GitHub installation id is invalid.");
392
+ const authorization = {
377
393
  scheme: "bearer",
378
- token: token.token
379
- }
380
- };
381
- setBounded(this.#repositoryAccessCache, cacheKey, {
382
- access,
383
- expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
394
+ token: (await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
395
+ repositories: found.map((repository) => splitRepository(repository.slug).repo),
396
+ permissions: REPOSITORY_TOKEN_PERMISSIONS
397
+ })).token
398
+ };
399
+ const expiresAt = Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS;
400
+ const access = {
401
+ cloneUrl: `https://github.com/${found[0].slug}.git`,
402
+ authorization,
403
+ repositories: Object.fromEntries(found.map((repository) => [repository.id, {
404
+ cloneUrl: `https://github.com/${repository.slug}.git`,
405
+ authorization
406
+ }]))
407
+ };
408
+ setBounded(this.#repositoryAccessCache, cacheKey, {
409
+ access,
410
+ expiresAt
411
+ });
412
+ return access;
384
413
  });
385
- return access;
386
414
  },
387
415
  listPullRequests: (input) => this.#listPullRequests(input),
388
416
  getPullRequest: (input) => this.#getPullRequest(input),
@@ -538,7 +566,7 @@ var PlatformGithubIntegration = class {
538
566
  reason: "organization_required",
539
567
  diagnostics: this.diagnostics()
540
568
  });
541
- const [installations, userConnection] = await Promise.all([this.#syncInstallations(tenant.orgId, tenant.userId), this.#fetchUserConnection(tenant.userId)]);
569
+ const [{ installations, hiddenPersonalInstallReason }, userConnection] = await Promise.all([this.#syncInstallations(tenant.orgId, tenant.userId), this.#fetchUserConnection(tenant.userId)]);
542
570
  return c.json({
543
571
  enabled: true,
544
572
  sandboxEnabled: !!ctx.sandbox,
@@ -550,7 +578,7 @@ var PlatformGithubIntegration = class {
550
578
  })),
551
579
  userConnected: userConnection.connected,
552
580
  userGithubUsername: userConnection.githubUsername,
553
- reason: installations.length > 0 ? "ready" : "not_connected",
581
+ reason: githubStatusReason(installations.length > 0, hiddenPersonalInstallReason),
554
582
  diagnostics: this.diagnostics()
555
583
  });
556
584
  }
@@ -626,16 +654,20 @@ var PlatformGithubIntegration = class {
626
654
  }
627
655
  }
628
656
  async #syncInstallations(orgId, userId) {
629
- const usableInstallations = (await this.#client.request("GET", `${API_PREFIX}/github-app/installations`)).installations.filter((installation) => installation.usable && !installation.suspendedAt);
630
- return Promise.all(usableInstallations.map((installation) => this.versionControl.registerInstallation({
631
- orgId,
632
- userId,
633
- installation: {
634
- externalId: String(installation.installationId),
635
- accountName: installation.accountLogin,
636
- accountType: installation.accountType
637
- }
638
- })));
657
+ const result = await this.#client.request("GET", `${API_PREFIX}/github-app/installations`);
658
+ const usableInstallations = result.installations.filter((installation) => installation.usable && !installation.suspendedAt);
659
+ return {
660
+ installations: await Promise.all(usableInstallations.map((installation) => this.versionControl.registerInstallation({
661
+ orgId,
662
+ userId,
663
+ installation: {
664
+ externalId: String(installation.installationId),
665
+ accountName: installation.accountLogin,
666
+ accountType: installation.accountType
667
+ }
668
+ }))),
669
+ hiddenPersonalInstallReason: result.hiddenPersonalInstallReason ?? void 0
670
+ };
639
671
  }
640
672
  workers(ctx) {
641
673
  if (!this.#pollingEnabled && !this.#pullRequestReconcileEnabled && !this.#issueReconcileEnabled) return [];