@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
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport { maskSandboxEnvValues, resolveSandboxEnv, sandboxBuildContext } from '../sandbox/sandbox-env.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SandboxEnvStore } from '../storage/domains/sandbox-envs/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\n\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n /** The Factory's sandbox environment variables; Build ones reach the template build. */\n sandboxEnvs?: Pick<SandboxEnvStore, 'resolve'>;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n): FactorySandboxContext {\n return {\n sessionId: environmentBuildSessionId(project.id),\n factoryId: project.id,\n factoryName: project.name,\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => versionControl.getRepositoryAccess(args),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * {@link environmentBuildContext} with the Factory's Build variables, plus the\n * build revision for {@link environmentBuildInputs}. Every build path (start,\n * status read, poll) goes through this so all of them name the same template.\n */\nexport async function environmentBuildContextWithEnv(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n sandboxEnvs: Pick<SandboxEnvStore, 'resolve'> | undefined,\n): Promise<{ ctx: FactorySandboxContext; buildEnvRevision: string | undefined }> {\n const env = sandboxEnvs\n ? await resolveSandboxEnv(sandboxEnvs, { orgId: project.orgId, projectId: project.id })\n : undefined;\n const build = sandboxBuildContext(env);\n return {\n ctx: { ...environmentBuildContext(project, environment, heads, versionControl), ...build },\n buildEnvRevision: build.buildEnvRevision,\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory, and the Build variables' revision (a random id, never a value).\n * A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment, buildEnvRevision?: string): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n // Only when set, so fingerprints recorded before Build variables existed still match.\n ...(buildEnvRevision ? { buildEnvRevision } : {}),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. Saving settings never builds.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved`.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0], buildEnv?: Record<string, string>) => {\n const reason = maskSandboxEnvValues(errorReason(error), buildEnv);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n environment = await resolveProjectEnvironment(sourceControl.storage, project);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n const built = await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n sourceControl.versionControl,\n deps.sandboxEnvs,\n );\n ctx = built.ctx;\n buildInputs = environmentBuildInputs(environment, built.buildEnvRevision);\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it.\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(\n error,\n { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted },\n ctx.buildEnv,\n );\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAsCvE,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;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C/D;EACF;CACF,UAAU;EACR,cAAc,OAAO;CACvB;AACF"}
1
+ {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport { maskSandboxEnvValues, resolveSandboxEnv, sandboxBuildContext } from '../sandbox/sandbox-env.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SandboxEnvStore } from '../storage/domains/sandbox-envs/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\nimport { groupedRepositoryAccess } from './repository-access.js';\n\n/** `settings`: a saved change to the environment; builds only when the template inputs changed. */\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push', 'settings'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n /** The Factory's sandbox environment variables; Build ones reach the template build. */\n sandboxEnvs?: Pick<SandboxEnvStore, 'resolve'>;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_template` (a `settings` run before the first build), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>,\n): FactorySandboxContext {\n const repositoryAccess = groupedRepositoryAccess(\n versionControl,\n project.orgId,\n environment.repos.map(repo => repo.repositoryId),\n );\n return {\n sessionId: environmentBuildSessionId(project.id),\n factoryId: project.id,\n factoryName: project.name,\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => repositoryAccess(args.repositoryId),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * {@link environmentBuildContext} with the Factory's Build variables, plus the\n * build revision for {@link environmentBuildInputs}. Every build path (start,\n * status read, poll) goes through this so all of them name the same template.\n */\nexport async function environmentBuildContextWithEnv(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>,\n sandboxEnvs: Pick<SandboxEnvStore, 'resolve'> | undefined,\n): Promise<{ ctx: FactorySandboxContext; buildEnvRevision: string | undefined }> {\n return withBuildEnv(project, environment, heads, versionControl, await environmentBuildEnv(project, sandboxEnvs));\n}\n\n/** The Factory's Build variables as a build context hands them to the provider. */\nasync function environmentBuildEnv(\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n sandboxEnvs: Pick<SandboxEnvStore, 'resolve'> | undefined,\n): Promise<ReturnType<typeof sandboxBuildContext>> {\n const env = sandboxEnvs\n ? await resolveSandboxEnv(sandboxEnvs, { orgId: project.orgId, projectId: project.id })\n : undefined;\n return sandboxBuildContext(env);\n}\n\nfunction withBuildEnv(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>,\n build: ReturnType<typeof sandboxBuildContext>,\n): { ctx: FactorySandboxContext; buildEnvRevision: string | undefined } {\n return {\n ctx: { ...environmentBuildContext(project, environment, heads, versionControl), ...build },\n buildEnvRevision: build.buildEnvRevision,\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory, and the Build variables' revision (a random id, never a value).\n * A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment, buildEnvRevision?: string): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n // Only when set, so fingerprints recorded before Build variables existed still match.\n ...(buildEnvRevision ? { buildEnvRevision } : {}),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** How long the build workflow polls a started build before it gives up on it. */\nexport const MAX_BUILD_WAIT_MS = 30 * 60_000;\n\n/**\n * How long after a lapsed lease a provider that cannot list builds keeps every\n * trigger from building. The lapsed run started its build, if it did, before\n * its lease expired, so by now that build has outlived the workflow's own wait\n * and is treated as failed.\n */\nexport const UNRESOLVED_BUILD_START_TIMEOUT_MS = MAX_BUILD_WAIT_MS;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. `settings` (a saved environment change) builds only once the\n * project has a template and the template inputs differ from the last\n * build's, whatever the heads; it skips as `no_template` before the first\n * build, and saving the same inputs twice skips as `unchanged`.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved` until\n * `UNRESOLVED_BUILD_START_TIMEOUT_MS` after the lapse, when the run gives\n * up on that build as failed, clears the mark and carries on.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const readInputs = async (project: FactoryProject) => {\n const environment = await resolveProjectEnvironment(sourceControl.storage, project);\n const buildEnv = await environmentBuildEnv(project, deps.sandboxEnvs);\n return { environment, buildEnv, buildInputs: environmentBuildInputs(environment, buildEnv.buildEnvRevision) };\n };\n // A `settings` run builds only for a project with a template whose inputs\n // moved; checked before any head lookup, so a save that changed nothing the\n // template bakes never calls GitHub or the provider.\n const settingsSkip = (project: FactoryProject, read: Awaited<ReturnType<typeof readInputs>>) =>\n input.trigger !== 'settings'\n ? undefined\n : read.environment.repos.length === 0\n ? 'no_environment'\n : !project.activeTemplateId && !project.lastBuildId\n ? 'no_template'\n : project.lastBuildInputs === read.buildInputs\n ? 'unchanged'\n : undefined;\n if (input.trigger === 'settings') {\n // Also checked before the lease, so a save that changes nothing never\n // holds it against a Build now right behind it.\n const reason = settingsSkip(initial, await readInputs(initial));\n if (reason) return { outcome: 'skipped', reason };\n }\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0], buildEnv?: Record<string, string>) => {\n const reason = maskSandboxEnvValues(errorReason(error), buildEnv);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n const read = await readInputs(project);\n ({ environment, buildInputs } = read);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n const skip = settingsSkip(project, read);\n if (skip) {\n await release();\n return { outcome: 'skipped', reason: skip };\n }\n const buildEnv = read.buildEnv;\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n ctx = withBuildEnv(project, environment, heads, sourceControl.versionControl, buildEnv).ctx;\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it until that build, if it\n // exists, has outlived the workflow's own wait.\n const since = project.buildStartUncertainSince ?? now();\n if (now().getTime() - since.getTime() < UNRESOLVED_BUILD_START_TIMEOUT_MS) {\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n resolved = true;\n deps.logger?.info('environment build gave up on an unrecorded build start', {\n factoryProjectId: project.id,\n trigger: input.trigger,\n uncertainSince: since.toISOString(),\n });\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(\n error,\n { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted },\n ctx.buildEnv,\n );\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;CAAQ;AAAU;;AAsCnF,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,CAAC,CAAC,QAAQ,6CAA6C,KAAK;AAC/G;;AAGA,SAAgB,YAAY,OAAwB;CAClD,OAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACjF;;;;;;;AAQA,SAAgB,wBACd,SACA,aACA,OACA,gBACuB;CACvB,MAAM,mBAAmB,wBACvB,gBACA,QAAQ,OACR,YAAY,MAAM,KAAI,SAAQ,KAAK,YAAY,CACjD;CACA,OAAO;EACL,WAAW,0BAA0B,QAAQ,EA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S,QAAQ;EAAQ;EAC7F,MAAM,UAAU;GAAE,aAAa,QAAQ;GAAS,gBAAgB;GAAO,iBAAiB;GAAa,GAAG;EAAU;EAClH,IAAI;EACJ,KAAK,IAAI,UAAU,GAAG,aAAa,KAAA,GAAW,WAC5C,IAAI;GACF,WAAW,MAAM,QAAQ,OAAO;EAClC,SAAS,OAAO;GACd,IAAI,WAAW,iBAAiB;IAG9B,KAAK,QAAQ,KAAK,8CAA8C;KAAE,GAAG;KAAK,QAAQ,YAAY,KAAK;IAAE,CAAC;IACtG,OAAO;KAAE,SAAS;KAAU,QAAQ;KAAgB,SAAS,QAAQ;IAAQ;GAC/E;GACA,MAAM,MAAM,MAAO,MAAM,UAAU,EAAE;EACvC;EAEF,IAAI,CAAC,UAAU;GAGb,KAAK,QAAQ,KAAK,gCAAgC,GAAG;GACrD,OAAO;IAAE,SAAS;IAAU,QAAQ;IAAc,SAAS,QAAQ;GAAQ;EAC7E;EACA,IAAI;GACF,KAAK,QAAQ,KAAK,6BAA6B;IAAE,GAAG;IAAK,YAAY,QAAQ;GAAW,CAAC;EAC3F,QAAQ,CAER;EACA,OAAO;GACL,SAAS;GACT,SAAS,QAAQ;GACjB,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D;EACF;CACF,UAAU;EACR,cAAc,OAAO;CACvB;AACF"}
@@ -28,7 +28,7 @@ export interface HeadRepository {
28
28
  }
29
29
  /** Current head of every repository's pinned ref, keyed by slug. Throws when any lookup fails. */
30
30
  export declare function resolveCurrentHeads(github: {
31
- versionControl: Pick<VersionControl, 'getRepositoryAccess'>;
31
+ versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>;
32
32
  }, input: {
33
33
  orgId: string;
34
34
  repositories: HeadRepository[];
@@ -1 +1 @@
1
- {"version":3,"file":"heads.d.ts","sourceRoot":"","sources":["../../src/environment/heads.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KA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AAsH;AACtH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAkBjE;AAED,8GAA8G;AAC9G,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAOlG;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,gBAAgB,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAM/G;AAED,gIAAgI;AAChI,wBAAgB,YAAY,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAMlG;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,oFAAoF;IACpF,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,kGAAkG;AAClG,wBAAsB,mBAAmB,CACvC,MAAM,EAAE;IAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,qBAAqB,GAAG,uBAAuB,CAAC,CAAA;CAAE,EACjG,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,cAAc,EAAE,CAAA;CAAE,GACvD,OAAO,CAAC,gBAAgB,CAAC,CAoB3B"}
@@ -1,4 +1,5 @@
1
1
  import { getBranchHead } from "../integrations/github/commits.js";
2
+ import { groupedRepositoryAccess } from "./repository-access.js";
2
3
  // src/environment/heads.ts
3
4
  /** `owner/repo` from a clone URL in any common spelling, lower-cased, `.git` stripped; undefined when unparseable. */
4
5
  function cloneUrlSlug(cloneUrl) {
@@ -43,8 +44,10 @@ function headsChanged(recorded, current) {
43
44
  }
44
45
  /** Current head of every repository's pinned ref, keyed by slug. Throws when any lookup fails. */
45
46
  async function resolveCurrentHeads(github, input) {
47
+ const repositoryAccess = groupedRepositoryAccess(github.versionControl, input.orgId, input.repositories.map((repository) => repository.id));
48
+ const grouped = { versionControl: { getRepositoryAccess: ({ repositoryId }) => repositoryAccess(repositoryId) } };
46
49
  const heads = {};
47
- for (const repository of input.repositories) heads[repository.slug] = await getBranchHead(github, {
50
+ for (const repository of input.repositories) heads[repository.slug] = await getBranchHead(grouped, {
48
51
  orgId: input.orgId,
49
52
  repository: {
50
53
  id: repository.id,
@@ -1 +1 @@
1
- {"version":3,"file":"heads.js","names":[],"sources":["../../src/environment/heads.ts"],"sourcesContent":["/**\n * Which commit each environment repository pins to.\n *\n * The repo templates key `resolveHead` by clone URL; the factory records heads\n * by repository slug. These helpers translate between the two and decide\n * whether a set of current heads differs from the recorded one.\n */\n\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport { getBranchHead } from '../integrations/github/commits.js';\n\nexport type EnvironmentHeads = Record<string, string>;\n\n/** `owner/repo` from a clone URL in any common spelling, lower-cased, `.git` stripped; undefined when unparseable. */\nexport function cloneUrlSlug(cloneUrl: string): string | undefined {\n let path: string;\n const scp = /^[^@/]+@[^:/]+:(.+)$/.exec(cloneUrl.trim());\n if (scp) {\n path = scp[1]!;\n } else {\n try {\n path = new URL(cloneUrl.trim()).pathname;\n } catch {\n return undefined;\n }\n }\n const parts = path\n .replace(/\\.git$/i, '')\n .split('/')\n .filter(Boolean);\n if (parts.length < 2) return undefined;\n return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`.toLowerCase();\n}\n\n/** The environment slug a clone URL names, in the environment's own spelling; undefined when none matches. */\nexport function matchEnvironmentSlug(cloneUrl: string, slugs: Iterable<string>): string | undefined {\n const wanted = cloneUrlSlug(cloneUrl);\n if (!wanted) return undefined;\n for (const slug of slugs) {\n if (slug.toLowerCase() === wanted) return slug;\n }\n return undefined;\n}\n\n/**\n * A `resolveHead` that answers from recorded heads only: the template pins to\n * what the last build used, so its identity moves when a build does. A URL\n * outside the recorded set resolves undefined and the template falls back to\n * its own lookup for that repository.\n */\nexport function recordedHeadResolver(heads: EnvironmentHeads): (cloneUrl: string) => Promise<string | undefined> {\n const slugs = Object.keys(heads);\n return async cloneUrl => {\n const slug = matchEnvironmentSlug(cloneUrl, slugs);\n return slug ? heads[slug] : undefined;\n };\n}\n\n/** True when any repository's current head differs from the recorded one, or either side names a repository the other lacks. */\nexport function headsChanged(recorded: EnvironmentHeads | null, current: EnvironmentHeads): boolean {\n if (!recorded) return true;\n const recordedKeys = Object.keys(recorded);\n const currentKeys = Object.keys(current);\n if (recordedKeys.length !== currentKeys.length) return true;\n return currentKeys.some(slug => recorded[slug] !== current[slug]);\n}\n\nexport interface HeadRepository {\n id: string;\n slug: string;\n /** The ref the environment pins: the link's branch, else the repository default. */\n branch: string;\n}\n\n/** Current head of every repository's pinned ref, keyed by slug. Throws when any lookup fails. */\nexport async function resolveCurrentHeads(\n github: { versionControl: Pick<VersionControl, 'getRepositoryAccess'> },\n input: { orgId: string; repositories: HeadRepository[] },\n): Promise<EnvironmentHeads> {\n const heads: EnvironmentHeads = {};\n for (const repository of input.repositories) {\n heads[repository.slug] = await getBranchHead(github, {\n orgId: input.orgId,\n repository: { id: repository.id, slug: repository.slug },\n branch: repository.branch,\n });\n }\n return heads;\n}\n"],"mappings":";;;AAcA,SAAgB,aAAa,UAAsC;CACjE,IAAI;CACJ,MAAM,MAAM,uBAAuB,KAAK,SAAS,KAAK,CAAC;CACvD,IAAI,KACF,OAAO,IAAI;MAEX,IAAI;EACF,OAAO,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,CAAC;CAClC,QAAQ;EACN;CACF;CAEF,MAAM,QAAQ,KACX,QAAQ,WAAW,EAAE,CAAC,CACtB,MAAM,GAAG,CAAC,CACV,OAAO,OAAO;CACjB,IAAI,MAAM,SAAS,GAAG,OAAO,KAAA;CAC7B,OAAO,GAAG,MAAM,MAAM,SAAS,GAAG,GAAG,MAAM,MAAM,SAAS,KAAK,YAAY;AAC7E;;AAGA,SAAgB,qBAAqB,UAAkB,OAA6C;CAClG,MAAM,SAAS,aAAa,QAAQ;CACpC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,YAAY,MAAM,QAAQ,OAAO;AAG9C;;;;;;;AAQA,SAAgB,qBAAqB,OAA4E;CAC/G,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,OAAO,OAAM,aAAY;EACvB,MAAM,OAAO,qBAAqB,UAAU,KAAK;EACjD,OAAO,OAAO,MAAM,QAAQ,KAAA;CAC9B;AACF;;AAGA,SAAgB,aAAa,UAAmC,SAAoC;CAClG,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,MAAM,cAAc,OAAO,KAAK,OAAO;CACvC,IAAI,aAAa,WAAW,YAAY,QAAQ,OAAO;CACvD,OAAO,YAAY,MAAK,SAAQ,SAAS,UAAU,QAAQ,KAAK;AAClE;;AAUA,eAAsB,oBACpB,QACA,OAC2B;CAC3B,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,cAC7B,MAAM,WAAW,QAAQ,MAAM,cAAc,QAAQ;EACnD,OAAO,MAAM;EACb,YAAY;GAAE,IAAI,WAAW;GAAI,MAAM,WAAW;EAAK;EACvD,QAAQ,WAAW;CACrB,CAAC;CAEH,OAAO;AACT"}
1
+ {"version":3,"file":"heads.js","names":[],"sources":["../../src/environment/heads.ts"],"sourcesContent":["/**\n * Which commit each environment repository pins to.\n *\n * The repo templates key `resolveHead` by clone URL; the factory records heads\n * by repository slug. These helpers translate between the two and decide\n * whether a set of current heads differs from the recorded one.\n */\n\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport { getBranchHead } from '../integrations/github/commits.js';\nimport { groupedRepositoryAccess } from './repository-access.js';\n\nexport type EnvironmentHeads = Record<string, string>;\n\n/** `owner/repo` from a clone URL in any common spelling, lower-cased, `.git` stripped; undefined when unparseable. */\nexport function cloneUrlSlug(cloneUrl: string): string | undefined {\n let path: string;\n const scp = /^[^@/]+@[^:/]+:(.+)$/.exec(cloneUrl.trim());\n if (scp) {\n path = scp[1]!;\n } else {\n try {\n path = new URL(cloneUrl.trim()).pathname;\n } catch {\n return undefined;\n }\n }\n const parts = path\n .replace(/\\.git$/i, '')\n .split('/')\n .filter(Boolean);\n if (parts.length < 2) return undefined;\n return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`.toLowerCase();\n}\n\n/** The environment slug a clone URL names, in the environment's own spelling; undefined when none matches. */\nexport function matchEnvironmentSlug(cloneUrl: string, slugs: Iterable<string>): string | undefined {\n const wanted = cloneUrlSlug(cloneUrl);\n if (!wanted) return undefined;\n for (const slug of slugs) {\n if (slug.toLowerCase() === wanted) return slug;\n }\n return undefined;\n}\n\n/**\n * A `resolveHead` that answers from recorded heads only: the template pins to\n * what the last build used, so its identity moves when a build does. A URL\n * outside the recorded set resolves undefined and the template falls back to\n * its own lookup for that repository.\n */\nexport function recordedHeadResolver(heads: EnvironmentHeads): (cloneUrl: string) => Promise<string | undefined> {\n const slugs = Object.keys(heads);\n return async cloneUrl => {\n const slug = matchEnvironmentSlug(cloneUrl, slugs);\n return slug ? heads[slug] : undefined;\n };\n}\n\n/** True when any repository's current head differs from the recorded one, or either side names a repository the other lacks. */\nexport function headsChanged(recorded: EnvironmentHeads | null, current: EnvironmentHeads): boolean {\n if (!recorded) return true;\n const recordedKeys = Object.keys(recorded);\n const currentKeys = Object.keys(current);\n if (recordedKeys.length !== currentKeys.length) return true;\n return currentKeys.some(slug => recorded[slug] !== current[slug]);\n}\n\nexport interface HeadRepository {\n id: string;\n slug: string;\n /** The ref the environment pins: the link's branch, else the repository default. */\n branch: string;\n}\n\n/** Current head of every repository's pinned ref, keyed by slug. Throws when any lookup fails. */\nexport async function resolveCurrentHeads(\n github: { versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'> },\n input: { orgId: string; repositories: HeadRepository[] },\n): Promise<EnvironmentHeads> {\n const repositoryAccess = groupedRepositoryAccess(\n github.versionControl,\n input.orgId,\n input.repositories.map(repository => repository.id),\n );\n const grouped = {\n versionControl: {\n getRepositoryAccess: ({ repositoryId }: { repositoryId: string }) => repositoryAccess(repositoryId),\n },\n };\n const heads: EnvironmentHeads = {};\n for (const repository of input.repositories) {\n heads[repository.slug] = await getBranchHead(grouped, {\n orgId: input.orgId,\n repository: { id: repository.id, slug: repository.slug },\n branch: repository.branch,\n });\n }\n return heads;\n}\n"],"mappings":";;;;AAeA,SAAgB,aAAa,UAAsC;CACjE,IAAI;CACJ,MAAM,MAAM,uBAAuB,KAAK,SAAS,KAAK,CAAC;CACvD,IAAI,KACF,OAAO,IAAI;MAEX,IAAI;EACF,OAAO,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,CAAC;CAClC,QAAQ;EACN;CACF;CAEF,MAAM,QAAQ,KACX,QAAQ,WAAW,EAAE,CAAC,CACtB,MAAM,GAAG,CAAC,CACV,OAAO,OAAO;CACjB,IAAI,MAAM,SAAS,GAAG,OAAO,KAAA;CAC7B,OAAO,GAAG,MAAM,MAAM,SAAS,GAAG,GAAG,MAAM,MAAM,SAAS,KAAK,YAAY;AAC7E;;AAGA,SAAgB,qBAAqB,UAAkB,OAA6C;CAClG,MAAM,SAAS,aAAa,QAAQ;CACpC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,YAAY,MAAM,QAAQ,OAAO;AAG9C;;;;;;;AAQA,SAAgB,qBAAqB,OAA4E;CAC/G,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,OAAO,OAAM,aAAY;EACvB,MAAM,OAAO,qBAAqB,UAAU,KAAK;EACjD,OAAO,OAAO,MAAM,QAAQ,KAAA;CAC9B;AACF;;AAGA,SAAgB,aAAa,UAAmC,SAAoC;CAClG,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,MAAM,cAAc,OAAO,KAAK,OAAO;CACvC,IAAI,aAAa,WAAW,YAAY,QAAQ,OAAO;CACvD,OAAO,YAAY,MAAK,SAAQ,SAAS,UAAU,QAAQ,KAAK;AAClE;;AAUA,eAAsB,oBACpB,QACA,OAC2B;CAC3B,MAAM,mBAAmB,wBACvB,OAAO,gBACP,MAAM,OACN,MAAM,aAAa,KAAI,eAAc,WAAW,EAAE,CACpD;CACA,MAAM,UAAU,EACd,gBAAgB,EACd,sBAAsB,EAAE,mBAA6C,iBAAiB,YAAY,EACpG,EACF;CACA,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,cAC7B,MAAM,WAAW,QAAQ,MAAM,cAAc,SAAS;EACpD,OAAO,MAAM;EACb,YAAY;GAAE,IAAI,WAAW;GAAI,MAAM,WAAW;EAAK;EACvD,QAAQ,WAAW;CACrB,CAAC;CAEH,OAAO;AACT"}
@@ -0,0 +1,13 @@
1
+ import type { RepositoryAccess, VersionControl } from '../capabilities/version-control.js';
2
+ /**
3
+ * Access to each of an environment's repositories, minted a group at a time.
4
+ * Asking for one repository asks for its group of up to ten, so a provider
5
+ * that can grant a group mints one token for it and serves every repository in
6
+ * it from that token, instead of minting one per repository (eleven
7
+ * repositories: two mints, not eleven). The group token stays with these
8
+ * callers: a plain `getRepositoryAccess` elsewhere still gets a token for its
9
+ * own repository only. A group the provider can't grant falls back to the
10
+ * repository's own token.
11
+ */
12
+ export declare function groupedRepositoryAccess(versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>, orgId: string, repositoryIds: readonly string[], now?: () => number): (repositoryId: string) => Promise<RepositoryAccess>;
13
+ //# sourceMappingURL=repository-access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repository-access.d.ts","sourceRoot":"","sources":["../../src/environment/repository-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAsB,gBAAgB,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAa/G;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACrC,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,qBAAqB,GAAG,uBAAuB,CAAC,EACrF,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,SAAS,MAAM,EAAE,EAChC,GAAG,GAAE,MAAM,MAAiB,GAC3B,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,gBAAgB,CAAC,CA+BrD"}
@@ -0,0 +1,55 @@
1
+ // src/environment/repository-access.ts
2
+ /** The most repositories one Platform GitHub token can name. */
3
+ const REPOSITORIES_PER_TOKEN = 10;
4
+ /**
5
+ * How long a group the provider refused or failed to mint is skipped. A failed
6
+ * group mint is often a rate limit, so retrying it for every repository in the
7
+ * group would add requests exactly when there is no budget for them.
8
+ */
9
+ const GROUP_RETRY_AFTER_MS = 6e4;
10
+ /**
11
+ * Access to each of an environment's repositories, minted a group at a time.
12
+ * Asking for one repository asks for its group of up to ten, so a provider
13
+ * that can grant a group mints one token for it and serves every repository in
14
+ * it from that token, instead of minting one per repository (eleven
15
+ * repositories: two mints, not eleven). The group token stays with these
16
+ * callers: a plain `getRepositoryAccess` elsewhere still gets a token for its
17
+ * own repository only. A group the provider can't grant falls back to the
18
+ * repository's own token.
19
+ */
20
+ function groupedRepositoryAccess(versionControl, orgId, repositoryIds, now = Date.now) {
21
+ const ids = [...new Set(repositoryIds)];
22
+ const groups = [];
23
+ for (let i = 0; i < ids.length; i += REPOSITORIES_PER_TOKEN) groups.push(ids.slice(i, i + REPOSITORIES_PER_TOKEN));
24
+ const skipUntil = /* @__PURE__ */ new Map();
25
+ const pending = /* @__PURE__ */ new Map();
26
+ const groupAccess = (group, getRepositoriesAccess) => {
27
+ let request = pending.get(group);
28
+ if (!request) {
29
+ request = getRepositoriesAccess({
30
+ orgId,
31
+ repositoryIds: group
32
+ }).catch(() => void 0).then((access) => {
33
+ if (!access) skipUntil.set(group, now() + GROUP_RETRY_AFTER_MS);
34
+ return access;
35
+ }).finally(() => pending.delete(group));
36
+ pending.set(group, request);
37
+ }
38
+ return request;
39
+ };
40
+ return async (repositoryId) => {
41
+ const group = groups.find((candidate) => candidate.includes(repositoryId));
42
+ const getRepositoriesAccess = versionControl.getRepositoriesAccess?.bind(versionControl);
43
+ if (group && group.length > 1 && getRepositoriesAccess && (skipUntil.get(group) ?? 0) <= now()) {
44
+ const own = (await groupAccess(group, getRepositoriesAccess))?.repositories?.[repositoryId];
45
+ if (own) return own;
46
+ }
47
+ return versionControl.getRepositoryAccess({
48
+ orgId,
49
+ repositoryId
50
+ });
51
+ };
52
+ }
53
+ export { groupedRepositoryAccess };
54
+
55
+ //# sourceMappingURL=repository-access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repository-access.js","names":[],"sources":["../../src/environment/repository-access.ts"],"sourcesContent":["import type { RepositoriesAccess, RepositoryAccess, VersionControl } from '../capabilities/version-control.js';\n\ntype GetRepositoriesAccess = NonNullable<VersionControl['getRepositoriesAccess']>;\n\n/** The most repositories one Platform GitHub token can name. */\nconst REPOSITORIES_PER_TOKEN = 10;\n/**\n * How long a group the provider refused or failed to mint is skipped. A failed\n * group mint is often a rate limit, so retrying it for every repository in the\n * group would add requests exactly when there is no budget for them.\n */\nconst GROUP_RETRY_AFTER_MS = 60_000;\n\n/**\n * Access to each of an environment's repositories, minted a group at a time.\n * Asking for one repository asks for its group of up to ten, so a provider\n * that can grant a group mints one token for it and serves every repository in\n * it from that token, instead of minting one per repository (eleven\n * repositories: two mints, not eleven). The group token stays with these\n * callers: a plain `getRepositoryAccess` elsewhere still gets a token for its\n * own repository only. A group the provider can't grant falls back to the\n * repository's own token.\n */\nexport function groupedRepositoryAccess(\n versionControl: Pick<VersionControl, 'getRepositoryAccess' | 'getRepositoriesAccess'>,\n orgId: string,\n repositoryIds: readonly string[],\n now: () => number = Date.now,\n): (repositoryId: string) => Promise<RepositoryAccess> {\n const ids = [...new Set(repositoryIds)];\n const groups: string[][] = [];\n for (let i = 0; i < ids.length; i += REPOSITORIES_PER_TOKEN) groups.push(ids.slice(i, i + REPOSITORIES_PER_TOKEN));\n const skipUntil = new Map<string[], number>();\n const pending = new Map<string[], Promise<RepositoriesAccess | undefined>>();\n const groupAccess = (group: string[], getRepositoriesAccess: GetRepositoriesAccess) => {\n let request = pending.get(group);\n if (!request) {\n // Best-effort: the repository's own token still works without it.\n request = getRepositoriesAccess({ orgId, repositoryIds: group })\n .catch(() => undefined)\n .then(access => {\n if (!access) skipUntil.set(group, now() + GROUP_RETRY_AFTER_MS);\n return access;\n })\n .finally(() => pending.delete(group));\n pending.set(group, request);\n }\n return request;\n };\n return async repositoryId => {\n const group = groups.find(candidate => candidate.includes(repositoryId));\n const getRepositoriesAccess = versionControl.getRepositoriesAccess?.bind(versionControl);\n if (group && group.length > 1 && getRepositoriesAccess && (skipUntil.get(group) ?? 0) <= now()) {\n // Parallel callers share one group request.\n const own = (await groupAccess(group, getRepositoriesAccess))?.repositories?.[repositoryId];\n if (own) return own;\n }\n return versionControl.getRepositoryAccess({ orgId, repositoryId });\n };\n}\n"],"mappings":";;AAKA,MAAM,yBAAyB;;;;;;AAM/B,MAAM,uBAAuB;;;;;;;;;;;AAY7B,SAAgB,wBACd,gBACA,OACA,eACA,MAAoB,KAAK,KAC4B;CACrD,MAAM,MAAM,CAAC,GAAG,IAAI,IAAI,aAAa,CAAC;CACtC,MAAM,SAAqB,CAAC;CAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,wBAAwB,OAAO,KAAK,IAAI,MAAM,GAAG,IAAI,sBAAsB,CAAC;CACjH,MAAM,4BAAY,IAAI,IAAsB;CAC5C,MAAM,0BAAU,IAAI,IAAuD;CAC3E,MAAM,eAAe,OAAiB,0BAAiD;EACrF,IAAI,UAAU,QAAQ,IAAI,KAAK;EAC/B,IAAI,CAAC,SAAS;GAEZ,UAAU,sBAAsB;IAAE;IAAO,eAAe;GAAM,CAAC,CAAC,CAC7D,YAAY,KAAA,CAAS,CAAC,CACtB,MAAK,WAAU;IACd,IAAI,CAAC,QAAQ,UAAU,IAAI,OAAO,IAAI,IAAI,oBAAoB;IAC9D,OAAO;GACT,CAAC,CAAC,CACD,cAAc,QAAQ,OAAO,KAAK,CAAC;GACtC,QAAQ,IAAI,OAAO,OAAO;EAC5B;EACA,OAAO;CACT;CACA,OAAO,OAAM,iBAAgB;EAC3B,MAAM,QAAQ,OAAO,MAAK,cAAa,UAAU,SAAS,YAAY,CAAC;EACvE,MAAM,wBAAwB,eAAe,uBAAuB,KAAK,cAAc;EACvF,IAAI,SAAS,MAAM,SAAS,KAAK,0BAA0B,UAAU,IAAI,KAAK,KAAK,MAAM,IAAI,GAAG;GAE9F,MAAM,OAAO,MAAM,YAAY,OAAO,qBAAqB,EAAA,EAAI,eAAe;GAC9E,IAAI,KAAK,OAAO;EAClB;EACA,OAAO,eAAe,oBAAoB;GAAE;GAAO;EAAa,CAAC;CACnE;AACF"}
package/dist/factory.d.ts CHANGED
@@ -275,8 +275,11 @@ export declare class MastraFactory {
275
275
  * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or
276
276
  * event rules). The board is validated once, as the boards API does, and each write is audited
277
277
  * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a
278
- * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `reserved_board` for the
279
- * retired Review board's key, `phase_in_use` when cards sit in a phase it removes, `project_not_found`).
278
+ * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use` when cards
279
+ * sit in a phase it removes, `board_in_use` when the key is `review` and the retired Review board
280
+ * still has an open card in the project, `project_not_found`). Projects are written one at a
281
+ * time and the call stops at the first one that refuses: the projects before it keep the board,
282
+ * so fix what was refused and run it again.
280
283
  * Available after `prepare()`.
281
284
  *
282
285
  * @example
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AASH,OAAO,KAAK,EAAiC,aAAa,EAAE,M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KACH,CAAC;CACH;AAED,YAAY,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC3G,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D;;;;GAIG;AACH,MAAM,WAAW,6BAA6B;IAC5C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAsID,qBAAa,aAAa;;IAkCxB,YAAY,MAAM,EAAE,mBAAmB,EAuBtC;IAED;;;;OAIG;IACH,IAAI,kBAAkB,IAAI,yBAAyB,GAAG,SAAS,CAI9D;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACG,WAAW,CACf,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE;QAAE,QAAQ,EAAE,KAAK,GAAG,SAAS,gBAAgB,EAAE,CAAA;KAAE,GACzD,OAAO,CAAC;QAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC;QAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC;QAAC,SAAS,EAAE,gBAAgB,EAAE,CAAA;KAAE,CAAC,CA6CvG;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,qBAAqB,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAKtG;IAED;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,CA0rDnC;IAED;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAsB9B;IAED,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAsC9B;CACF"}
package/dist/factory.js CHANGED
@@ -2,7 +2,7 @@ import { buildAuthDisabledRoutes, buildAuthRoutes, createFactoryAuthGate, create
2
2
  import { BoardWriteError, BoardWrites } from "./boards/board-writes.js";
3
3
  import { isDefinedBoard } from "./boards/define-board.js";
4
4
  import "./boards/index.js";
5
- import { ProjectBoardCache, occupiedPhasesOf, toBoardSource } from "./boards/project-boards.js";
5
+ import { ProjectBoardCache, occupiedPhasesOf, ownReviewBoard, toBoardSource } from "./boards/project-boards.js";
6
6
  import { publishDispatchWake, subscribeDispatchWakes } from "./dispatch-wake.js";
7
7
  import { EnvironmentBuildRunner } from "./environment/build-runner.js";
8
8
  import { ENVIRONMENT_BUILD_WORKFLOW_ID } from "./environment/build-workflow.js";
@@ -38,8 +38,9 @@ import { createTerminalStageCleanup } from "./rules/terminal-cleanup.js";
38
38
  import { createFactoryTransitionTools } from "./rules/tools.js";
39
39
  import { FactoryTransitionService } from "./rules/transition-service.js";
40
40
  import { assertFactoryConfigVersion } from "./rules/validation.js";
41
- import { resolveFactoryToolScope } from "./tools/scope.js";
42
41
  import { CallbackFactorySandbox } from "./sandbox/callback-factory-sandbox.js";
42
+ import { resolveFactoryToolScope } from "./tools/scope.js";
43
+ import { controllerRunInFlight, createContextSandboxStops, createTerminalSandboxStops } from "./sandbox/context-sandboxes.js";
43
44
  import { isValidGitRef } from "./sandbox/git-ref.js";
44
45
  import { LocalFactorySandbox } from "./sandbox/local-factory-sandbox.js";
45
46
  import { CachedSandboxEnvs } from "./sandbox/sandbox-env-cache.js";
@@ -48,8 +49,8 @@ import { peekSessionSandbox } from "./sandbox/session-sandbox.js";
48
49
  import { createPlaintextFactorySecretEncryption } from "./secret-encryption.js";
49
50
  import { handleServerError } from "./server-error.js";
50
51
  import { resolveFactoryCredentialTenant, resolveFactoryModelPolicy } from "./session/credential-policy.js";
51
- import { hydrateSessionDefaultModel } from "./session/default-model-hydration.js";
52
52
  import { applyFactoryToolPermissions } from "./tools/permissions.js";
53
+ import { hydrateSessionDefaultModel } from "./session/default-model-hydration.js";
53
54
  import { environmentSlugs, resolveSessionRepositories } from "./session/environment-repositories.js";
54
55
  import { FactoryEnvironmentStateProcessor } from "./session/environment-state-processor.js";
55
56
  import { createSourceControlSessionLookup } from "./session/factory-session.js";
@@ -296,8 +297,11 @@ var MastraFactory = class {
296
297
  * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or
297
298
  * event rules). The board is validated once, as the boards API does, and each write is audited
298
299
  * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a
299
- * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `reserved_board` for the
300
- * retired Review board's key, `phase_in_use` when cards sit in a phase it removes, `project_not_found`).
300
+ * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use` when cards
301
+ * sit in a phase it removes, `board_in_use` when the key is `review` and the retired Review board
302
+ * still has an open card in the project, `project_not_found`). Projects are written one at a
303
+ * time and the call stops at the first one that refuses: the projects before it keep the board,
304
+ * so fix what was refused and run it again.
301
305
  * Available after `prepare()`.
302
306
  *
303
307
  * @example
@@ -524,6 +528,7 @@ var MastraFactory = class {
524
528
  if (error === void 0) continue;
525
529
  console.error(`[factory] storage domain "${domain}" failed to initialize; features that use it stay unavailable until it does:`, error);
526
530
  }
531
+ workItemsStorage.useOwnReviewBoard(ownReviewBoard(this.#boards, { stored: storage.isDomainReady("boards") }));
527
532
  if (storage.isDomainReady("boards") && storage.isDomainReady("projects")) {
528
533
  const projectBoards = new ProjectBoardCache({
529
534
  codeRegistry: this.#boards,
@@ -532,6 +537,7 @@ var MastraFactory = class {
532
537
  codeSkills: this.#skills,
533
538
  ...storage.isDomainReady("work-items") ? {
534
539
  reviewBoardInUse: (scope) => workItemsStorage.reviewBoardInUse(scope),
540
+ releaseReviewCards: (ops, scope) => workItemsStorage.releaseReviewCards(ops, scope, { open: "move" }),
535
541
  occupiedPhases: occupiedPhasesOf(workItemsStorage)
536
542
  } : {}
537
543
  });
@@ -649,24 +655,11 @@ var MastraFactory = class {
649
655
  invalidateSession: (sessionId) => workspaceRegistry.invalidateSession(sessionId),
650
656
  sandbox: sandboxConfig
651
657
  }) : void 0;
652
- const retireTerminalSessions = sessionRetirement && workItemsReady ? async ({ orgId, workItemId }) => {
653
- const item = await workItemsStorage.get({
654
- orgId,
655
- id: workItemId
656
- });
657
- if (!item) return;
658
- const sessionIds = [...new Set(Object.values(item.sessions).map((session) => session.sessionId))];
659
- await Promise.all(sessionIds.map(async (sessionId) => {
660
- const sourceControl = await sourceControlSessions.getSourceControlBySessionId(sessionId);
661
- if (!sourceControl) return;
662
- await sessionRetirement.retireSession({
663
- sourceControl,
664
- orgId,
665
- sessionId,
666
- deleteSession: false
667
- });
668
- }));
669
- } : void 0;
658
+ const retireTerminalSessions = sessionRetirement && workItemsReady ? createTerminalSandboxStops({
659
+ workItems: workItemsStorage,
660
+ sessions: sourceControlSessions,
661
+ retirement: sessionRetirement
662
+ }) : void 0;
670
663
  const terminalCleanup = workItemsReady ? createTerminalStageCleanup({
671
664
  workItems: workItemsStorage,
672
665
  reconcileBinding: async (binding) => {
@@ -749,12 +742,20 @@ var MastraFactory = class {
749
742
  revision: args.revision,
750
743
  ...args.actor.type === "agent" ? { initiatingBindingId: args.actor.bindingId } : {}
751
744
  }) : retireTerminalSessions;
745
+ const stopLeftContextSandbox = sessionRetirement && workItemsReady ? createContextSandboxStops({
746
+ workItems: workItemsStorage,
747
+ boards,
748
+ sessions: sourceControlSessions,
749
+ retirement: sessionRetirement,
750
+ runInFlight: controllerRunInFlight(async (sessionId) => this.#prepared?.base.controller.getSession(sessionId))
751
+ }) : void 0;
752
752
  const transitionService = workItemsReady ? new FactoryTransitionService({
753
753
  configVersion,
754
754
  boards,
755
755
  storage: workItemsStorage,
756
756
  audit: auditDomain,
757
757
  ...onTerminalStage ? { onTerminalStage } : {},
758
+ ...stopLeftContextSandbox ? { onContextLeft: stopLeftContextSandbox } : {},
758
759
  onTransitionCommitted: (() => {
759
760
  const notifyStageChange = createStageChangeNotifier({
760
761
  workItems: workItemsStorage,
@@ -1302,7 +1303,10 @@ var MastraFactory = class {
1302
1303
  publicOrigin,
1303
1304
  stateSigner,
1304
1305
  sandbox: sandboxConfig,
1305
- ...environmentBuilds ? { onRepositoryPush: environmentBuilds.onRepositoryPush } : {},
1306
+ ...environmentBuilds ? {
1307
+ onRepositoryPush: environmentBuilds.onRepositoryPush,
1308
+ onEnvironmentSaved: environmentBuilds.onEnvironmentSaved
1309
+ } : {},
1306
1310
  sessionRetirement,
1307
1311
  moveThread: async ({ threadId, resourceId }) => {
1308
1312
  const sessionMemory = getDynamicMemory(storage.getMastraStorage(), vector);
@@ -1349,6 +1353,7 @@ var MastraFactory = class {
1349
1353
  }) !== null;
1350
1354
  },
1351
1355
  reconcileToolResults: () => factoryProcessor?.reconcileAllBoundThreads() ?? Promise.resolve(),
1356
+ reconcileRunBinding: (binding) => factoryProcessor?.reconcileBinding(binding) ?? Promise.resolve(),
1352
1357
  prepareBinding,
1353
1358
  ...githubIntegration ? {
1354
1359
  dismissStaleReviews: async (decision) => {
@@ -1395,7 +1400,8 @@ var MastraFactory = class {
1395
1400
  projects: factoryProjectsStorage,
1396
1401
  sandboxEnvs: sandboxEnvsStorage,
1397
1402
  writable: !secretsUnencrypted,
1398
- audit: auditDomain
1403
+ audit: auditDomain,
1404
+ ...environmentBuilds ? { onEnvironmentSaved: environmentBuilds.onEnvironmentSaved } : {}
1399
1405
  }).routes(),
1400
1406
  ...buildFeedEventsRoutes({
1401
1407
  auth: routeAuth,
@@ -1548,6 +1554,7 @@ var MastraFactory = class {
1548
1554
  boardRegistry: this.#projectBoards ?? this.#boards,
1549
1555
  factoryReady,
1550
1556
  domains,
1557
+ ...this.#environmentBuilds ? { onRepositoryPush: this.#environmentBuilds.onRepositoryPush } : {},
1551
1558
  ...githubIntegration ? { sourceControlOwnerId: "github" } : {}
1552
1559
  }, integration.id)));
1553
1560
  return {