@mastra/factory 0.28.0-alpha.13 → 0.28.0-alpha.15
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.
- package/README.md +43 -28
- package/dist/boards/board-writes.d.ts +3 -3
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +24 -20
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/project-boards.d.ts +20 -0
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +35 -11
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/registry.d.ts.map +1 -1
- package/dist/boards/registry.js +0 -3
- package/dist/boards/registry.js.map +1 -1
- package/dist/environment/build-runner.d.ts +13 -2
- package/dist/environment/build-runner.d.ts.map +1 -1
- package/dist/environment/build-runner.js +42 -0
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.d.ts +6 -4
- package/dist/environment/build-workflow.d.ts.map +1 -1
- package/dist/environment/build-workflow.js +70 -66
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.d.ts +19 -4
- package/dist/environment/build.d.ts.map +1 -1
- package/dist/environment/build.js +70 -14
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts +5 -2
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +29 -24
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +12 -0
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
- package/dist/integrations/github/sandbox-release.js +16 -1
- package/dist/integrations/github/sandbox-release.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +24 -12
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +5 -1
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +5 -0
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +12 -1
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/boards.d.ts +2 -3
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/contracts.d.ts +66 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +41 -1
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +5 -0
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/sandbox-envs.d.ts +2 -0
- package/dist/routes/sandbox-envs.d.ts.map +1 -1
- package/dist/routes/sandbox-envs.js +3 -0
- package/dist/routes/sandbox-envs.js.map +1 -1
- package/dist/routes/source-control-settings.d.ts +2 -0
- package/dist/routes/source-control-settings.d.ts.map +1 -1
- package/dist/routes/source-control-settings.js +5 -0
- package/dist/routes/source-control-settings.js.map +1 -1
- package/dist/routes/surface.d.ts +2 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-activity.d.ts +11 -0
- package/dist/routes/work-item-activity.d.ts.map +1 -0
- package/dist/routes/work-item-activity.js +25 -0
- package/dist/routes/work-item-activity.js.map +1 -0
- package/dist/routes/work-item-starters.d.ts +29 -0
- package/dist/routes/work-item-starters.d.ts.map +1 -0
- package/dist/routes/work-item-starters.js +169 -0
- package/dist/routes/work-item-starters.js.map +1 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +59 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +49 -14
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/transition-service.d.ts +20 -2
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +40 -18
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/context-sandboxes.d.ts +70 -0
- package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
- package/dist/sandbox/context-sandboxes.js +120 -0
- package/dist/sandbox/context-sandboxes.js.map +1 -0
- package/dist/sandbox/session-retirement.d.ts +11 -4
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +39 -13
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +25 -5
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +57 -20
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +8 -2
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +21 -4
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +17 -4
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +24 -4
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
- package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
- package/dist/storage/domains/work-items/legacy-review.js +47 -2
- package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
- package/dist/tools/annotations.d.ts.map +1 -1
- package/dist/tools/annotations.js +4 -0
- package/dist/tools/annotations.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +29 -0
- package/dist/tools/audit-events-tool.d.ts.map +1 -0
- package/dist/tools/audit-events-tool.js +180 -0
- package/dist/tools/audit-events-tool.js.map +1 -0
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/permissions.d.ts.map +1 -1
- package/dist/tools/permissions.js +1 -0
- package/dist/tools/permissions.js.map +1 -1
- package/dist/tools/sessions-state-processor.js +1 -1
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-workflow.js","names":[],"sources":["../../src/environment/build-workflow.ts"],"sourcesContent":["/**\n * The `factory-environment-build` workflow: step one decides and starts a\n * build (`runEnvironmentBuild`), step two polls the provider until the build\n * settles and pins the active template on the project row. Registered by\n * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by\n * the Build now route, the per-project cron schedule
|
|
1
|
+
{"version":3,"file":"build-workflow.js","names":[],"sources":["../../src/environment/build-workflow.ts"],"sourcesContent":["/**\n * The `factory-environment-build` workflow: step one decides and starts a\n * build (`runEnvironmentBuild`), step two polls the provider until the build\n * settles and pins the active template on the project row. Registered by\n * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by\n * the Build now route, the per-project cron schedule, the GitHub push\n * hand-off and saved template inputs.\n */\n\nimport { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\nimport { maskSandboxEnvValues } from '../sandbox/sandbox-env.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport {\n ENVIRONMENT_BUILD_TRIGGERS,\n environmentBuildContextWithEnv,\n errorReason,\n MAX_BUILD_WAIT_MS,\n redactCredentials,\n runEnvironmentBuild,\n} from './build.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome } from './build.js';\n\nexport const ENVIRONMENT_BUILD_WORKFLOW_ID = 'factory-environment-build';\nexport const DEFAULT_BUILD_POLL_MS = 15_000;\n\nexport const environmentBuildInputSchema = z.object({\n projectId: z.string().min(1),\n trigger: z.enum(ENVIRONMENT_BUILD_TRIGGERS),\n});\n\nconst startOutputSchema = z.object({\n projectId: z.string(),\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n heads: z.record(z.string(), z.string()).optional(),\n});\n\nexport const environmentBuildOutputSchema = z.object({\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n /** Where the started build ended: `ready`, `failed`, or `unknown` when the provider lost it or the wait ran out. */\n status: z.enum(['ready', 'failed', 'unknown']).optional(),\n});\n\nexport type EnvironmentBuildWorkflowResult = z.infer<typeof environmentBuildOutputSchema>;\n\nexport interface EnvironmentBuildWorkflowOptions {\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n maxWaitMs?: number;\n /** Called with the first step's answer so a caller can return it without waiting for the poll. */\n onStart?: (runId: string, outcome: EnvironmentBuildOutcome) => void;\n /** Called once a run is over, whoever started it (a route, the scheduler or a hand-off). */\n onSettled?: (projectId: string, result: EnvironmentBuildWorkflowResult) => void;\n}\n\nexport function createEnvironmentBuildWorkflow(\n deps: EnvironmentBuildDeps,\n options: EnvironmentBuildWorkflowOptions = {},\n) {\n const sleep = options.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n const pollMs = options.pollMs ?? DEFAULT_BUILD_POLL_MS;\n const maxWaitMs = options.maxWaitMs ?? MAX_BUILD_WAIT_MS;\n const now = deps.now ?? (() => new Date());\n\n const start = createStep({\n id: 'start',\n inputSchema: environmentBuildInputSchema,\n outputSchema: startOutputSchema,\n execute: async ({ inputData, runId }) => {\n const outcome = await runEnvironmentBuild(deps, inputData);\n options.onStart?.(runId, outcome);\n return { projectId: inputData.projectId, ...outcome };\n },\n });\n\n // Polls a started build until it settles and pins its template.\n const pollUntilSettled = async (\n inputData: z.infer<typeof startOutputSchema>,\n ): Promise<EnvironmentBuildWorkflowResult> => {\n const { projectId, heads, ...result } = inputData;\n if (result.outcome !== 'started' || !result.buildId || !heads) return result;\n const builds = deps.sandbox?.builds;\n const project = await deps.projects.getById({ id: projectId });\n if (!builds || !deps.sourceControl || !project) return { ...result, status: 'unknown' };\n const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);\n const { ctx } = await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n deps.sourceControl.versionControl,\n deps.sandboxEnvs,\n );\n const startedAt = now().getTime();\n try {\n for (;;) {\n const build = await builds.get(ctx, environment.settings, result.buildId);\n if (build.status === 'ready') {\n const templateId = build.templateId ?? result.templateId ?? result.buildId;\n // A newer run may have replaced `last_build_id` while this one\n // polled; the pin is skipped then so the stale image never wins.\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: result.buildId,\n templateId,\n heads,\n });\n deps.logger?.info(pinned ? 'environment build ready' : 'environment build ready but superseded', {\n factoryProjectId: project.id,\n templateId,\n });\n return { ...result, templateId, status: 'ready' };\n }\n if (build.status === 'failed' || build.status === 'unknown') {\n deps.logger?.info('environment build did not complete', {\n factoryProjectId: project.id,\n buildId: result.buildId,\n status: build.status,\n ...(build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}),\n });\n return {\n ...result,\n status: build.status,\n ...(build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}),\n };\n }\n if (now().getTime() - startedAt >= maxWaitMs) {\n return { ...result, status: 'unknown', reason: 'Build wait timed out.' };\n }\n await sleep(pollMs);\n }\n } catch (error) {\n const reason = maskSandboxEnvValues(errorReason(error), ctx.buildEnv);\n deps.logger?.info('environment build status read failed', { factoryProjectId: project.id, reason });\n return { ...result, status: 'unknown', reason };\n }\n };\n\n const awaitBuild = createStep({\n id: 'await-build',\n inputSchema: startOutputSchema,\n outputSchema: environmentBuildOutputSchema,\n execute: async ({ inputData }): Promise<EnvironmentBuildWorkflowResult> => {\n const settled = await pollUntilSettled(inputData);\n options.onSettled?.(inputData.projectId, settled);\n return settled;\n },\n });\n\n return createWorkflow({\n id: ENVIRONMENT_BUILD_WORKFLOW_ID,\n inputSchema: environmentBuildInputSchema,\n outputSchema: environmentBuildOutputSchema,\n })\n .then(start)\n .then(awaitBuild)\n .commit();\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAa,gCAAgC;AAC7C,MAAa,wBAAwB;AA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,QAAQ,MAAM;MACd,GAAI,MAAM,QAAQ,EAAE,QAAQ,qBAAqB,kBAAkB,MAAM,KAAK,GAAG,IAAI,QAAQ,EAAE,IAAI,CAAC;KACtG;IACF;IACA,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,aAAa,WACjC,OAAO;KAAE,GAAG;KAAQ,QAAQ;KAAW,QAAQ;IAAwB;IAEzE,MAAM,MAAM,MAAM;GACpB;EACF,SAAS,OAAO;GACd,MAAM,SAAS,qBAAqB,YAAY,KAAK,GAAG,IAAI,QAAQ;GACpE,KAAK,QAAQ,KAAK,wCAAwC;IAAE,kBAAkB,QAAQ;IAAI;GAAO,CAAC;GAClG,OAAO;IAAE,GAAG;IAAQ,QAAQ;IAAW;GAAO;EAChD;CACF;CAEA,MAAM,aAAa,WAAW;EAC5B,IAAI;EACJ,aAAa;EACb,cAAc;EACd,SAAS,OAAO,EAAE,gBAAyD;GACzE,MAAM,UAAU,MAAM,iBAAiB,SAAS;GAChD,QAAQ,YAAY,UAAU,WAAW,OAAO;GAChD,OAAO;EACT;CACF,CAAC;CAED,OAAO,eAAe;EACpB,IAAI;EACJ,aAAa;EACb,cAAc;CAChB,CAAC,CAAC,CACC,KAAK,KAAK,CAAC,CACX,KAAK,UAAU,CAAC,CAChB,OAAO;AACZ"}
|
|
@@ -13,7 +13,8 @@ import type { SandboxEnvStore } from '../storage/domains/sandbox-envs/base.js';
|
|
|
13
13
|
import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
|
|
14
14
|
import type { SessionEnvironment } from '../workspace.js';
|
|
15
15
|
import type { EnvironmentHeads } from './heads.js';
|
|
16
|
-
|
|
16
|
+
/** `settings`: a saved change to the environment; builds only when the template inputs changed. */
|
|
17
|
+
export declare const ENVIRONMENT_BUILD_TRIGGERS: readonly ['manual', 'schedule', 'push', 'settings'];
|
|
17
18
|
export type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];
|
|
18
19
|
export interface EnvironmentBuildSourceControl {
|
|
19
20
|
storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;
|
|
@@ -40,7 +41,7 @@ export interface EnvironmentBuildOutcome {
|
|
|
40
41
|
outcome: 'started' | 'skipped' | 'unavailable' | 'failed';
|
|
41
42
|
buildId?: string;
|
|
42
43
|
templateId?: string;
|
|
43
|
-
/** 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. */
|
|
44
|
+
/** 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. */
|
|
44
45
|
reason?: string;
|
|
45
46
|
/** The heads the started build pins; the workflow stores them once the build is ready. */
|
|
46
47
|
heads?: EnvironmentHeads;
|
|
@@ -91,6 +92,15 @@ export declare function resolveEnvironmentHeads(sourceControl: EnvironmentBuildS
|
|
|
91
92
|
* its run died or stalled.
|
|
92
93
|
*/
|
|
93
94
|
export declare const BUILD_START_LEASE_MS: number;
|
|
95
|
+
/** How long the build workflow polls a started build before it gives up on it. */
|
|
96
|
+
export declare const MAX_BUILD_WAIT_MS: number;
|
|
97
|
+
/**
|
|
98
|
+
* How long after a lapsed lease a provider that cannot list builds keeps every
|
|
99
|
+
* trigger from building. The lapsed run started its build, if it did, before
|
|
100
|
+
* its lease expired, so by now that build has outlived the workflow's own wait
|
|
101
|
+
* and is treated as failed.
|
|
102
|
+
*/
|
|
103
|
+
export declare const UNRESOLVED_BUILD_START_TIMEOUT_MS: number;
|
|
94
104
|
/**
|
|
95
105
|
* Start a build for `projectId` when `trigger` calls for one. Every trigger
|
|
96
106
|
* takes the project's build-start lease before reading build state and renews
|
|
@@ -101,13 +111,18 @@ export declare const BUILD_START_LEASE_MS: number;
|
|
|
101
111
|
* build is ready and neither a head nor any other template input changed;
|
|
102
112
|
* `manual` otherwise always builds. A `push` that would build then takes the
|
|
103
113
|
* leading-edge debounce claim, so only a push that starts a build opens the
|
|
104
|
-
* window.
|
|
114
|
+
* window. `settings` (a saved environment change) builds only once the
|
|
115
|
+
* project has a template and the template inputs differ from the last
|
|
116
|
+
* build's, whatever the heads; it skips as `no_template` before the first
|
|
117
|
+
* build, and saving the same inputs twice skips as `unchanged`.
|
|
105
118
|
*
|
|
106
119
|
* Taking over a lapsed lease leaves the start uncertain: the lapsed run may
|
|
107
120
|
* have started a build it never recorded. The mark persists until resolved.
|
|
108
121
|
* While it stands, a provider that lists builds is asked for a running one
|
|
109
122
|
* (and every trigger skips as `in_progress` on it); with a provider that
|
|
110
|
-
* cannot list, every trigger skips as `unresolved
|
|
123
|
+
* cannot list, every trigger skips as `unresolved` until
|
|
124
|
+
* `UNRESOLVED_BUILD_START_TIMEOUT_MS` after the lapse, when the run gives
|
|
125
|
+
* up on that build as failed, clears the mark and carries on.
|
|
111
126
|
*
|
|
112
127
|
* The result is written as the lease is released, and only while this run
|
|
113
128
|
* still holds it. A failed `builds.start` clears the last build id, so a later
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/environment/build.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAC/E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AA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
|
12
12
|
* (`build-workflow.ts`), so a request that only needs the start answer never
|
|
13
13
|
* waits on the provider.
|
|
14
14
|
*/
|
|
15
|
+
/** `settings`: a saved change to the environment; builds only when the template inputs changed. */
|
|
15
16
|
const ENVIRONMENT_BUILD_TRIGGERS = [
|
|
16
17
|
"manual",
|
|
17
18
|
"schedule",
|
|
18
|
-
"push"
|
|
19
|
+
"push",
|
|
20
|
+
"settings"
|
|
19
21
|
];
|
|
20
22
|
/** The synthetic session id a project's build runs under; never a session. */
|
|
21
23
|
function environmentBuildSessionId(projectId) {
|
|
@@ -57,11 +59,17 @@ function environmentBuildContext(project, environment, heads, versionControl) {
|
|
|
57
59
|
* status read, poll) goes through this so all of them name the same template.
|
|
58
60
|
*/
|
|
59
61
|
async function environmentBuildContextWithEnv(project, environment, heads, versionControl, sandboxEnvs) {
|
|
62
|
+
return withBuildEnv(project, environment, heads, versionControl, await environmentBuildEnv(project, sandboxEnvs));
|
|
63
|
+
}
|
|
64
|
+
/** The Factory's Build variables as a build context hands them to the provider. */
|
|
65
|
+
async function environmentBuildEnv(project, sandboxEnvs) {
|
|
60
66
|
const env = sandboxEnvs ? await resolveSandboxEnv(sandboxEnvs, {
|
|
61
67
|
orgId: project.orgId,
|
|
62
68
|
projectId: project.id
|
|
63
69
|
}) : void 0;
|
|
64
|
-
|
|
70
|
+
return sandboxBuildContext(env);
|
|
71
|
+
}
|
|
72
|
+
function withBuildEnv(project, environment, heads, versionControl, build) {
|
|
65
73
|
return {
|
|
66
74
|
ctx: {
|
|
67
75
|
...environmentBuildContext(project, environment, heads, versionControl),
|
|
@@ -113,6 +121,15 @@ async function resolveEnvironmentHeads(sourceControl, project, environment) {
|
|
|
113
121
|
* its run died or stalled.
|
|
114
122
|
*/
|
|
115
123
|
const BUILD_START_LEASE_MS = 6e5;
|
|
124
|
+
/** How long the build workflow polls a started build before it gives up on it. */
|
|
125
|
+
const MAX_BUILD_WAIT_MS = 18e5;
|
|
126
|
+
/**
|
|
127
|
+
* How long after a lapsed lease a provider that cannot list builds keeps every
|
|
128
|
+
* trigger from building. The lapsed run started its build, if it did, before
|
|
129
|
+
* its lease expired, so by now that build has outlived the workflow's own wait
|
|
130
|
+
* and is treated as failed.
|
|
131
|
+
*/
|
|
132
|
+
const UNRESOLVED_BUILD_START_TIMEOUT_MS = MAX_BUILD_WAIT_MS;
|
|
116
133
|
/** Tries at recording a started build before the run leaves its lease to lapse. */
|
|
117
134
|
const RECORD_ATTEMPTS = 5;
|
|
118
135
|
/**
|
|
@@ -125,13 +142,18 @@ const RECORD_ATTEMPTS = 5;
|
|
|
125
142
|
* build is ready and neither a head nor any other template input changed;
|
|
126
143
|
* `manual` otherwise always builds. A `push` that would build then takes the
|
|
127
144
|
* leading-edge debounce claim, so only a push that starts a build opens the
|
|
128
|
-
* window.
|
|
145
|
+
* window. `settings` (a saved environment change) builds only once the
|
|
146
|
+
* project has a template and the template inputs differ from the last
|
|
147
|
+
* build's, whatever the heads; it skips as `no_template` before the first
|
|
148
|
+
* build, and saving the same inputs twice skips as `unchanged`.
|
|
129
149
|
*
|
|
130
150
|
* Taking over a lapsed lease leaves the start uncertain: the lapsed run may
|
|
131
151
|
* have started a build it never recorded. The mark persists until resolved.
|
|
132
152
|
* While it stands, a provider that lists builds is asked for a running one
|
|
133
153
|
* (and every trigger skips as `in_progress` on it); with a provider that
|
|
134
|
-
* cannot list, every trigger skips as `unresolved
|
|
154
|
+
* cannot list, every trigger skips as `unresolved` until
|
|
155
|
+
* `UNRESOLVED_BUILD_START_TIMEOUT_MS` after the lapse, when the run gives
|
|
156
|
+
* up on that build as failed, clears the mark and carries on.
|
|
135
157
|
*
|
|
136
158
|
* The result is written as the lease is released, and only while this run
|
|
137
159
|
* still holds it. A failed `builds.start` clears the last build id, so a later
|
|
@@ -164,6 +186,23 @@ async function runEnvironmentBuild(deps, input) {
|
|
|
164
186
|
outcome: "skipped",
|
|
165
187
|
reason: "debounced"
|
|
166
188
|
};
|
|
189
|
+
const readInputs = async (project) => {
|
|
190
|
+
const environment = await resolveProjectEnvironment(sourceControl.storage, project);
|
|
191
|
+
const buildEnv = await environmentBuildEnv(project, deps.sandboxEnvs);
|
|
192
|
+
return {
|
|
193
|
+
environment,
|
|
194
|
+
buildEnv,
|
|
195
|
+
buildInputs: environmentBuildInputs(environment, buildEnv.buildEnvRevision)
|
|
196
|
+
};
|
|
197
|
+
};
|
|
198
|
+
const settingsSkip = (project, read) => input.trigger !== "settings" ? void 0 : read.environment.repos.length === 0 ? "no_environment" : !project.activeTemplateId && !project.lastBuildId ? "no_template" : project.lastBuildInputs === read.buildInputs ? "unchanged" : void 0;
|
|
199
|
+
if (input.trigger === "settings") {
|
|
200
|
+
const reason = settingsSkip(initial, await readInputs(initial));
|
|
201
|
+
if (reason) return {
|
|
202
|
+
outcome: "skipped",
|
|
203
|
+
reason
|
|
204
|
+
};
|
|
205
|
+
}
|
|
167
206
|
const token = randomUUID();
|
|
168
207
|
const lease = {
|
|
169
208
|
id: initial.id,
|
|
@@ -218,7 +257,8 @@ async function runEnvironmentBuild(deps, input) {
|
|
|
218
257
|
let buildInputs;
|
|
219
258
|
try {
|
|
220
259
|
project = await deps.projects.getById({ id: initial.id }) ?? initial;
|
|
221
|
-
|
|
260
|
+
const read = await readInputs(project);
|
|
261
|
+
({environment, buildInputs} = read);
|
|
222
262
|
if (environment.repos.length === 0) {
|
|
223
263
|
await release();
|
|
224
264
|
return {
|
|
@@ -226,10 +266,17 @@ async function runEnvironmentBuild(deps, input) {
|
|
|
226
266
|
reason: "no_environment"
|
|
227
267
|
};
|
|
228
268
|
}
|
|
269
|
+
const skip = settingsSkip(project, read);
|
|
270
|
+
if (skip) {
|
|
271
|
+
await release();
|
|
272
|
+
return {
|
|
273
|
+
outcome: "skipped",
|
|
274
|
+
reason: skip
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
const buildEnv = read.buildEnv;
|
|
229
278
|
heads = await resolveEnvironmentHeads(sourceControl, project, environment);
|
|
230
|
-
|
|
231
|
-
ctx = built.ctx;
|
|
232
|
-
buildInputs = environmentBuildInputs(environment, built.buildEnvRevision);
|
|
279
|
+
ctx = withBuildEnv(project, environment, heads, sourceControl.versionControl, buildEnv).ctx;
|
|
233
280
|
if (claim.uncertain) {
|
|
234
281
|
if (builds.list) {
|
|
235
282
|
const running = (await builds.list(ctx, environment.settings)).find((build) => build.status === "pending" || build.status === "building");
|
|
@@ -243,11 +290,20 @@ async function runEnvironmentBuild(deps, input) {
|
|
|
243
290
|
}
|
|
244
291
|
resolved = true;
|
|
245
292
|
} else {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
293
|
+
const since = project.buildStartUncertainSince ?? now();
|
|
294
|
+
if (now().getTime() - since.getTime() < 18e5) {
|
|
295
|
+
await release();
|
|
296
|
+
return {
|
|
297
|
+
outcome: "skipped",
|
|
298
|
+
reason: "unresolved"
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
resolved = true;
|
|
302
|
+
deps.logger?.info("environment build gave up on an unrecorded build start", {
|
|
303
|
+
factoryProjectId: project.id,
|
|
304
|
+
trigger: input.trigger,
|
|
305
|
+
uncertainSince: since.toISOString()
|
|
306
|
+
});
|
|
251
307
|
}
|
|
252
308
|
}
|
|
253
309
|
if (project.lastBuildId) {
|
|
@@ -367,6 +423,6 @@ async function runEnvironmentBuild(deps, input) {
|
|
|
367
423
|
clearInterval(renewal);
|
|
368
424
|
}
|
|
369
425
|
}
|
|
370
|
-
export { BUILD_START_LEASE_MS, ENVIRONMENT_BUILD_TRIGGERS, environmentBuildContext, environmentBuildContextWithEnv, environmentBuildInputs, environmentBuildSessionId, errorReason, redactCredentials, resolveEnvironmentHeads, runEnvironmentBuild };
|
|
426
|
+
export { BUILD_START_LEASE_MS, ENVIRONMENT_BUILD_TRIGGERS, MAX_BUILD_WAIT_MS, UNRESOLVED_BUILD_START_TIMEOUT_MS, environmentBuildContext, environmentBuildContextWithEnv, environmentBuildInputs, environmentBuildSessionId, errorReason, redactCredentials, resolveEnvironmentHeads, runEnvironmentBuild };
|
|
371
427
|
|
|
372
428
|
//# sourceMappingURL=build.js.map
|
|
@@ -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';\nimport { groupedRepositoryAccess } from './repository-access.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' | '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_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 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":";;;;;;;;;;;;;;AAuBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAsCvE,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,EAAE;EAC/C,WAAW,QAAQ;EACnB,aAAa,QAAQ;EACrB,GAAG,0BAA0B,aAAa;GACxC,OAAO,QAAQ;GACf,sBAAqB,SAAQ,iBAAiB,KAAK,YAAY;GAC/D,aAAa,qBAAqB,KAAK;EACzC,CAAC;CACH;AACF;;;;;;AAOA,eAAsB,+BACpB,SACA,aACA,OACA,gBACA,aAC+E;CAC/E,MAAM,MAAM,cACR,MAAM,kBAAkB,aAAa;EAAE,OAAO,QAAQ;EAAO,WAAW,QAAQ;CAAG,CAAC,IACpF,KAAA;CACJ,MAAM,QAAQ,oBAAoB,GAAG;CACrC,OAAO;EACL,KAAK;GAAE,GAAG,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,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"}
|
|
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"],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O;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"}
|
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`, `
|
|
279
|
-
*
|
|
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
|
package/dist/factory.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AASH,OAAO,KAAK,EAAiC,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAA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;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";
|
|
@@ -40,6 +40,7 @@ import { FactoryTransitionService } from "./rules/transition-service.js";
|
|
|
40
40
|
import { assertFactoryConfigVersion } from "./rules/validation.js";
|
|
41
41
|
import { CallbackFactorySandbox } from "./sandbox/callback-factory-sandbox.js";
|
|
42
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`, `
|
|
300
|
-
*
|
|
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 ?
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
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 ? {
|
|
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);
|
|
@@ -1396,7 +1400,8 @@ var MastraFactory = class {
|
|
|
1396
1400
|
projects: factoryProjectsStorage,
|
|
1397
1401
|
sandboxEnvs: sandboxEnvsStorage,
|
|
1398
1402
|
writable: !secretsUnencrypted,
|
|
1399
|
-
audit: auditDomain
|
|
1403
|
+
audit: auditDomain,
|
|
1404
|
+
...environmentBuilds ? { onEnvironmentSaved: environmentBuilds.onEnvironmentSaved } : {}
|
|
1400
1405
|
}).routes(),
|
|
1401
1406
|
...buildFeedEventsRoutes({
|
|
1402
1407
|
auth: routeAuth,
|