@mastra/factory 0.28.0-alpha.12 → 0.28.0-alpha.14

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 (89) hide show
  1. package/README.md +33 -20
  2. package/dist/environment/build-runner.d.ts +13 -2
  3. package/dist/environment/build-runner.d.ts.map +1 -1
  4. package/dist/environment/build-runner.js +42 -0
  5. package/dist/environment/build-runner.js.map +1 -1
  6. package/dist/environment/build-workflow.d.ts +6 -4
  7. package/dist/environment/build-workflow.d.ts.map +1 -1
  8. package/dist/environment/build-workflow.js +70 -66
  9. package/dist/environment/build-workflow.js.map +1 -1
  10. package/dist/environment/build.d.ts +19 -4
  11. package/dist/environment/build.d.ts.map +1 -1
  12. package/dist/environment/build.js +70 -14
  13. package/dist/environment/build.js.map +1 -1
  14. package/dist/factory.d.ts.map +1 -1
  15. package/dist/factory.js +21 -21
  16. package/dist/factory.js.map +1 -1
  17. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  18. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  19. package/dist/integrations/github/sandbox-release.js +16 -1
  20. package/dist/integrations/github/sandbox-release.js.map +1 -1
  21. package/dist/routes/board-snapshot.d.ts +5 -0
  22. package/dist/routes/board-snapshot.d.ts.map +1 -1
  23. package/dist/routes/board-snapshot.js +12 -1
  24. package/dist/routes/board-snapshot.js.map +1 -1
  25. package/dist/routes/contracts.d.ts +69 -0
  26. package/dist/routes/contracts.d.ts.map +1 -1
  27. package/dist/routes/contracts.js +48 -3
  28. package/dist/routes/contracts.js.map +1 -1
  29. package/dist/routes/projects.d.ts.map +1 -1
  30. package/dist/routes/projects.js +5 -0
  31. package/dist/routes/projects.js.map +1 -1
  32. package/dist/routes/sandbox-envs.d.ts +2 -0
  33. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  34. package/dist/routes/sandbox-envs.js +3 -0
  35. package/dist/routes/sandbox-envs.js.map +1 -1
  36. package/dist/routes/source-control-settings.d.ts +2 -0
  37. package/dist/routes/source-control-settings.d.ts.map +1 -1
  38. package/dist/routes/source-control-settings.js +5 -0
  39. package/dist/routes/source-control-settings.js.map +1 -1
  40. package/dist/routes/surface.d.ts +2 -0
  41. package/dist/routes/surface.d.ts.map +1 -1
  42. package/dist/routes/surface.js +2 -1
  43. package/dist/routes/surface.js.map +1 -1
  44. package/dist/routes/work-item-activity.d.ts +11 -0
  45. package/dist/routes/work-item-activity.d.ts.map +1 -0
  46. package/dist/routes/work-item-activity.js +25 -0
  47. package/dist/routes/work-item-activity.js.map +1 -0
  48. package/dist/routes/work-item-selection.d.ts +2 -0
  49. package/dist/routes/work-item-selection.d.ts.map +1 -1
  50. package/dist/routes/work-item-selection.js +6 -1
  51. package/dist/routes/work-item-selection.js.map +1 -1
  52. package/dist/routes/work-item-starters.d.ts +29 -0
  53. package/dist/routes/work-item-starters.d.ts.map +1 -0
  54. package/dist/routes/work-item-starters.js +169 -0
  55. package/dist/routes/work-item-starters.js.map +1 -0
  56. package/dist/routes/work-items.d.ts.map +1 -1
  57. package/dist/routes/work-items.js +64 -4
  58. package/dist/routes/work-items.js.map +1 -1
  59. package/dist/rules/transition-service.d.ts +20 -2
  60. package/dist/rules/transition-service.d.ts.map +1 -1
  61. package/dist/rules/transition-service.js +40 -18
  62. package/dist/rules/transition-service.js.map +1 -1
  63. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  64. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  65. package/dist/sandbox/context-sandboxes.js +120 -0
  66. package/dist/sandbox/context-sandboxes.js.map +1 -0
  67. package/dist/sandbox/session-retirement.d.ts +11 -4
  68. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  69. package/dist/sandbox/session-retirement.js +39 -13
  70. package/dist/sandbox/session-retirement.js.map +1 -1
  71. package/dist/storage/domains/projects/base.d.ts +8 -2
  72. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  73. package/dist/storage/domains/projects/base.js +21 -4
  74. package/dist/storage/domains/projects/base.js.map +1 -1
  75. package/dist/tools/annotations.d.ts.map +1 -1
  76. package/dist/tools/annotations.js +4 -0
  77. package/dist/tools/annotations.js.map +1 -1
  78. package/dist/tools/audit-events-tool.d.ts +29 -0
  79. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  80. package/dist/tools/audit-events-tool.js +180 -0
  81. package/dist/tools/audit-events-tool.js.map +1 -0
  82. package/dist/tools/index.d.ts +2 -1
  83. package/dist/tools/index.d.ts.map +1 -1
  84. package/dist/tools/index.js +2 -0
  85. package/dist/tools/index.js.map +1 -1
  86. package/dist/tools/permissions.d.ts.map +1 -1
  87. package/dist/tools/permissions.js +1 -0
  88. package/dist/tools/permissions.js.map +1 -1
  89. package/package.json +9 -9
package/README.md CHANGED
@@ -58,9 +58,11 @@ function summarizeCard(card: Card) {
58
58
 
59
59
  Each work item has one board item. Factory's card-to-card parent link is `parentBoardItemId`. Provider sub-issue ancestry is not populated into `card.workItem.parentWorkItemId`; migrated work items leave that field null. Existing card IDs, comments, subscriptions, run bindings, and `/work-items/:id` URLs stay unchanged. The work item gets its own ID. For one release, work-item API responses also retain the legacy top-level title, external source, and merged metadata fields.
60
60
 
61
- `GET /web/factory/projects/:id/work-items` lists a project's cards. Pass `sessionId` to list only the cards holding that session and the cards related to them: a card's parent and children, and a pull request with the card whose session branch it was pushed from. Repeat `sessionId` to list several sessions' cards. Pass `scope=sessions` to list the cards holding any session and the cards related to them, without naming the sessions; it can't be combined with `sessionId`. Pass `started=false` to list the cards holding no session, most recently updated first: `limit` sets how many are sent (20 unless given, 50 at most), `q` keeps the cards whose title, key, number or source id contains every word in it, in any case, and `total` in the response counts every card that matched, sent or not. `started=false` can't be combined with `scope` or `sessionId`, and `q` is accepted only with it. Repeat `source` (up to 100 values) to list the cards filed from those sources, each named by its source id or its URL, whatever sessions the cards hold; it can't be combined with `started`, `scope` or `sessionId`. A query the route can't answer gets a 400, never the whole board. Apart from `total`, the response has the same shape in every case, and `runningSessionIds` and `parkedSessionIds` cover only the listed cards.
61
+ `GET /web/factory/projects/:id/work-items` lists a project's cards. Pass `sessionId` to list only the cards holding that session and the cards related to them: a card's parent and children, and a pull request with the card whose session branch it was pushed from. Repeat `sessionId` to list several sessions' cards. Pass `scope=sessions` to list the cards holding any session and the cards related to them, without naming the sessions; it can't be combined with `sessionId`. Pass `started=false` to list the cards holding no session, most recently updated first: `limit` sets how many are sent (20 unless given, 50 at most), `q` keeps the cards whose title, key, number or source id contains every word in it, in any case, and `total` in the response counts every card that matched, sent or not. `started=false` can't be combined with `scope` or `sessionId`, and `q` is accepted only with it. Repeat `source` (up to 100 values) to list the cards filed from those sources, each named by its source id or its URL, whatever sessions the cards hold; it can't be combined with `started`, `scope` or `sessionId`. Repeat `workItemId` (up to 100 values) to list the cards with those ids and no other, whatever sessions they hold; an id no card has is left out, so asking for one card that was deleted answers 200 with an empty list. It can't be combined with `source`, `started`, `scope` or `sessionId`. A query the route can't answer gets a 400, never the whole board. Apart from `total`, the response has the same shape in every case, and `runningSessionIds` and `parkedSessionIds` cover only the listed cards.
62
62
 
63
- The whole-board listing also returns a `cursor`, and each card carries `changedAt`, when it last changed. Send the cursor back as `since` to get only what moved since that read: `workItems` then holds the cards changed, `removedIds` the cards deleted, and `check` a value naming every card on the board and when it last changed, with the next `cursor`. A reader merges these into the board it kept, then compares `boardCheck` of its merged cards (exported from `@mastra/factory/work-items/board-check`) with `check`, and reads the board whole again when they differ. A `since` the server can't answer from is ignored, not refused, so the answer is the listing as it would be without it, with no `removedIds`: a malformed cursor, a board that returned no `cursor`, or a listing narrowed by `sessionId`, `scope`, `started` or `source`.
63
+ The whole-board listing also returns a `cursor`, and each card carries `changedAt`, when it last changed. Send the cursor back as `since` to get only what moved since that read: `workItems` then holds the cards changed, `removedIds` the cards deleted, and `check` a value naming every card on the board and when it last changed, with the next `cursor`. A reader merges these into the board it kept, then compares `boardCheck` of its merged cards (exported from `@mastra/factory/work-items/board-check`) with `check`, and reads the board whole again when they differ. A `since` the server can't answer from is ignored, not refused, so the answer is the listing as it would be without it, with no `removedIds`: a malformed cursor, a board that returned no `cursor`, or a listing narrowed by `sessionId`, `scope`, `started`, `source` or `workItemId`.
64
+
65
+ Two reads answer questions about a project's cards without listing them. `GET /web/factory/projects/:id/work-items/starters` counts the cards on the default board that each new-session starter would act on: cards whose run failed, pull requests with changes requested, pull requests waiting for review (with when the oldest was opened), triaged cards waiting on a person, untriaged cards, bugs with no plan, the label with the most cards not started, and stale pull requests. Failed runs are read from the 50 newest run decisions, as on the cards. `GET /web/factory/projects/:id/work-items/activity?since=<ISO 8601 instant>` returns how many cards the project has, and when cards were created and completed from `since` on; a missing or malformed `since` is a 400. Its answer carries an `ETag`: ask again for the same `since` with `If-None-Match`, and an answer that did not change comes back as a 304 with no body.
64
66
 
65
67
  #### Migration and dry run
66
68
 
@@ -585,6 +587,16 @@ phases: {
585
587
 
586
588
  **Remaining limitations:** `factory-ui` still renders the built-in stage and role pipeline.
587
589
 
590
+ #### Card sandboxes
591
+
592
+ Each session context a card uses (`triage`, `work`, `review`, or a custom board's `runner.context`) is its own session with its own sandbox, so a card can hold one sandbox per context. Factory stops a context's sandbox as soon as the card no longer needs it:
593
+
594
+ - **Leaving a context.** When a move takes the card out of the last phase of a context into a phase that runs in another context (or none), Factory stops that context's sandbox, for example Triage → Planning stops the triage sandbox. Moves within one context stop nothing: Planning → Building keeps the `work` sandbox running. A run still in flight on the left session in this process, such as the agent whose own tool call made the move or a person chatting in it, keeps the sandbox until it ends, and Factory stops it then unless the card is back in that context.
595
+ - **Finishing.** Entering a terminal phase stops every sandbox the card holds. A Factory process that never opened a sandbox stops it by identity through the configured sandbox provider, so a card finished on any replica stops its sandboxes.
596
+ - **Coming back.** Stopping keeps the session, its branch and its files. A card that comes back to a context (PR review → Triage) resumes the same sandbox: E2B resumes the paused VM, Docker restarts the container, and the local sandbox reuses its directory. Platform sandboxes are not stopped remotely; they idle out under the environment's policy and the next run reattaches.
597
+
598
+ Stopping is best-effort: a committed move never fails because a sandbox did not stop, and a card moved again before the stop runs keeps its sandbox. Deleting a session still destroys its sandbox.
599
+
588
600
  #### The pull request loop on any board
589
601
 
590
602
  Nothing in Factory's runtime reads Work's board key or phase keys. Each part of the issue → build → self-review → pull request → review → merge loop is found by what a board's phases declare, so a board you create in the UI, through the API or in code runs the same loop under its own key and phase names:
@@ -1244,24 +1256,25 @@ A repository maintainer with write or admin access can start a Factory review fr
1244
1256
 
1245
1257
  A person's own Factory session (a user session) gets tools to find, file and manage the Factory's work items through its agent. Factory scopes the tools from the stored session row, never from the thread's `factoryProjectId` tag: the session must belong to a Factory in the caller's organization, and a private session only works for its owner. With authentication disabled, the shared `local` tenant applies. Sessions doing work for someone else, either bound to a work item's run or started as a side session, only get `factory_message_origin`, so they can report back and answer messages.
1246
1258
 
1247
- | Tool | Input |
1248
- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
1249
- | `factory_list_work_items` | Optional `query` (title text or `#number`), `stage`, `board`, `role`, `active`, `requestedBy: 'me'`, `subscribed`, `limit` (default 25, max 50) |
1250
- | `factory_inspect_work_item` | `workItem` (id or `#number`) |
1251
- | `factory_list_attention` | Optional `limit` (max 50) |
1252
- | `factory_create_work_item` | `title`, `description`, optional `repository` (`owner/name`, one this Factory links) |
1253
- | `factory_update_work_item` | `workItem` plus any of `title`, `description`, `repository`, `parentWorkItem` (or `null` to detach) |
1254
- | `factory_subscribe_work_item` | `workItem` |
1255
- | `factory_unsubscribe_work_item` | `workItem` |
1256
- | `factory_transition_work_item` | `workItem`, `stage` |
1257
- | `factory_retry_decision` | `decisionId` |
1258
- | `factory_dismiss_decision` | `decisionId` |
1259
- | `factory_resolve_proposal` | `decisionId`, `action` (`approve` or `dismiss`) |
1260
- | `factory_start_session` | `prompt` (up to 8000 characters), optional `title`, optional `model`; for a work-item role, `workItem` and `role` |
1261
- | `factory_answer_approval` | `sessionId`, `toolCallId`, `decision` (approve or decline), optional `reason` |
1262
- | `factory_switch_session_model` | `sessionId`, `modelId` |
1263
- | `factory_signal_session` | `sessionId`, `message` (up to 4000 characters), optional `priority` (`low`, `medium`, `high`, `urgent`; default `medium`) |
1264
- | `factory_message_origin` | `message`, optional `inReplyTo` (the message's notification id), optional `status` (`progress`, `blocked`, `done`, `failed`) |
1259
+ | Tool | Input |
1260
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1261
+ | `factory_list_work_items` | Optional `query` (title text or `#number`), `stage`, `board`, `role`, `active`, `requestedBy: 'me'`, `subscribed`, `limit` (default 25, max 50) |
1262
+ | `factory_inspect_work_item` | `workItem` (id or `#number`) |
1263
+ | `factory_list_attention` | Optional `limit` (max 50) |
1264
+ | `factory_list_audit_events` | Optional `actor` (`me`, a user id or `agent:<threadId>`), `includeAgentRuns`, `namespace`, `actions`, `workItem`, `since`, `until`, `cursor`, `limit` (max 50) |
1265
+ | `factory_create_work_item` | `title`, `description`, optional `repository` (`owner/name`, one this Factory links) |
1266
+ | `factory_update_work_item` | `workItem` plus any of `title`, `description`, `repository`, `parentWorkItem` (or `null` to detach) |
1267
+ | `factory_subscribe_work_item` | `workItem` |
1268
+ | `factory_unsubscribe_work_item` | `workItem` |
1269
+ | `factory_transition_work_item` | `workItem`, `stage` |
1270
+ | `factory_retry_decision` | `decisionId` |
1271
+ | `factory_dismiss_decision` | `decisionId` |
1272
+ | `factory_resolve_proposal` | `decisionId`, `action` (`approve` or `dismiss`) |
1273
+ | `factory_start_session` | `prompt` (up to 8000 characters), optional `title`, optional `model`; for a work-item role, `workItem` and `role` |
1274
+ | `factory_answer_approval` | `sessionId`, `toolCallId`, `decision` (approve or decline), optional `reason` |
1275
+ | `factory_switch_session_model` | `sessionId`, `modelId` |
1276
+ | `factory_signal_session` | `sessionId`, `message` (up to 4000 characters), optional `priority` (`low`, `medium`, `high`, `urgent`; default `medium`) |
1277
+ | `factory_message_origin` | `message`, optional `inReplyTo` (the message's notification id), optional `status` (`progress`, `blocked`, `done`, `failed`) |
1265
1278
 
1266
1279
  Read tools and `factory_message_origin` are available on every turn. The other tools only appear on turns a signed-in person started, so text arriving from a notification, webhook or channel can't drive them. The one exception is `factory_signal_session`: on those turns it can still message the side sessions this session started and the active sessions of work items it follows, so the session can answer the sessions it is waiting on. None of them asks for approval: they are allowed on the session when it's created, unless the person has set their own policy for the tool or for the `mcp` category.
1267
1280
 
@@ -10,7 +10,7 @@ import type { ScheduleService } from './build-schedule.js';
10
10
  import type { EnvironmentBuildWorkflowOptions } from './build-workflow.js';
11
11
  import type { EnvironmentBuildDeps, EnvironmentBuildOutcome, EnvironmentBuildTrigger } from './build.js';
12
12
  export type StartEnvironmentBuild = (projectId: string, trigger: EnvironmentBuildTrigger) => Promise<EnvironmentBuildOutcome>;
13
- export interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart'> {
13
+ export interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart' | 'onSettled'> {
14
14
  /** The booted instance; `undefined` until the host finished `finalize()`. */
15
15
  getMastra: () => Mastra | undefined;
16
16
  logger?: {
@@ -26,7 +26,7 @@ export declare class EnvironmentBuildRunner {
26
26
  #private;
27
27
  readonly workflow: import("@mastra/core/workflows").Workflow<import("@mastra/core/workflows").DefaultEngineType, import("@mastra/core/workflows").Step<string, unknown, unknown, unknown, unknown, unknown, any, unknown>[], "factory-environment-build", unknown, {
28
28
  projectId: string;
29
- trigger: "manual" | "push" | "schedule";
29
+ trigger: "manual" | "push" | "schedule" | "settings";
30
30
  }, {
31
31
  outcome: "failed" | "skipped" | "started" | "unavailable";
32
32
  buildId?: string | undefined;
@@ -60,6 +60,17 @@ export declare class EnvironmentBuildRunner {
60
60
  * builds. Fire and forget: the webhook never waits on it.
61
61
  */
62
62
  readonly onRepositoryPush: (event: RepositoryPushEvent) => void;
63
+ /**
64
+ * A saved change to a project's environment (settings, setup commands,
65
+ * repositories, Build variables) starts a `settings` run, which builds only
66
+ * when the template inputs changed. A run skipped because another one
67
+ * holds the build-start lease or its build is running (either may have read
68
+ * the environment before this save) stays pending until that run is over.
69
+ * A lease held by another process is retried, a second apart and doubling
70
+ * up to `SETTINGS_RETRY_MAX_MS`, until it is released or lapses. Fire and
71
+ * forget: the save never waits on it or fails because of it.
72
+ */
73
+ readonly onEnvironmentSaved: (projectId: string) => void;
63
74
  /**
64
75
  * Start a run and resolve with the first step's answer; the poll step keeps
65
76
  * running in the background. Resolves `unavailable` before the host booted
@@ -1 +1 @@
1
- {"version":3,"file":"build-runner.d.ts","sourceRoot":"","sources":["../../src/environment/build-runner.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAGnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAGzG,MAAM,MAAM,qBAAqB,GAAG,CAClC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,uBAAuB,KAC7B,OAAO,CAAC,uBAAuB,CAAC,CAAC;AAEtC,MAAM,WAAW,6BAA8B,SAAQ,IAAI,CAAC,+BAA+B,EAAE,SAAS,CAAC;IACrG,6EAA6E;IAC7E,SAAS,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IACpC,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;KAAE,CAAC;CAC1E;AAED,qEAAqE;AACrE,MAAM,WAAW,2BAA2B;IAC1C,GAA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build-workflow.js";
4
4
  import { environmentBuildContextWithEnv, errorReason, resolveEnvironmentHeads } from "./build.js";
5
5
  // src/environment/build-runner.ts
6
+ /** Longest wait between `settings` runs that find another process holding the build-start lease. */
7
+ const SETTINGS_RETRY_MAX_MS = 3e4;
6
8
  var EnvironmentBuildRunner = class {
7
9
  workflow;
8
10
  #deps;
9
11
  #getMastra;
10
12
  #logger;
11
13
  #pending = /* @__PURE__ */ new Map();
14
+ #sleep;
15
+ /** Projects with a saved change that a run of theirs skipped; that run's end builds it. */
16
+ #awaitingRun = /* @__PURE__ */ new Set();
12
17
  #scheduleAvailable = false;
13
18
  constructor(deps, options) {
14
19
  const { getMastra, logger, ...workflowOptions } = options;
15
20
  this.#deps = deps;
16
21
  this.#getMastra = getMastra;
17
22
  this.#logger = logger;
23
+ this.#sleep = workflowOptions.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
18
24
  this.workflow = createEnvironmentBuildWorkflow(deps, {
19
25
  ...workflowOptions,
20
26
  onStart: (runId, outcome) => {
21
27
  this.#pending.get(runId)?.(outcome);
22
28
  this.#pending.delete(runId);
29
+ },
30
+ onSettled: (projectId, result) => {
31
+ if (result.outcome === "started") {
32
+ this.#awaitingRun.delete(projectId);
33
+ this.onEnvironmentSaved(projectId);
34
+ return;
35
+ }
36
+ if (result.outcome === "skipped" && (result.reason === "starting" || result.reason === "in_progress")) return;
37
+ if (this.#awaitingRun.delete(projectId)) this.onEnvironmentSaved(projectId);
23
38
  }
24
39
  });
25
40
  }
@@ -72,6 +87,33 @@ var EnvironmentBuildRunner = class {
72
87
  });
73
88
  };
74
89
  /**
90
+ * A saved change to a project's environment (settings, setup commands,
91
+ * repositories, Build variables) starts a `settings` run, which builds only
92
+ * when the template inputs changed. A run skipped because another one
93
+ * holds the build-start lease or its build is running (either may have read
94
+ * the environment before this save) stays pending until that run is over.
95
+ * A lease held by another process is retried, a second apart and doubling
96
+ * up to `SETTINGS_RETRY_MAX_MS`, until it is released or lapses. Fire and
97
+ * forget: the save never waits on it or fails because of it.
98
+ */
99
+ onEnvironmentSaved = (projectId) => {
100
+ (async () => {
101
+ for (let delay = 1e3;; delay = Math.min(delay * 2, SETTINGS_RETRY_MAX_MS)) {
102
+ const outcome = await this.start(projectId, "settings");
103
+ if (outcome.outcome !== "skipped" || outcome.reason !== "starting" && outcome.reason !== "in_progress") return;
104
+ this.#awaitingRun.add(projectId);
105
+ if (outcome.reason === "in_progress") return;
106
+ await this.#sleep(delay);
107
+ if (!this.#awaitingRun.has(projectId)) return;
108
+ }
109
+ })().catch((error) => {
110
+ this.#logger?.info("environment build settings hand-off failed", {
111
+ factoryProjectId: projectId,
112
+ reason: errorReason(error)
113
+ });
114
+ });
115
+ };
116
+ /**
75
117
  * Start a run and resolve with the first step's answer; the poll step keeps
76
118
  * running in the background. Resolves `unavailable` before the host booted
77
119
  * or when the host never registered the workflow, and `failed` when the run
@@ -1 +1 @@
1
- {"version":3,"file":"build-runner.js","names":[],"sources":["../../src/environment/build-runner.ts"],"sourcesContent":["/**\n * Starts `factory-environment-build` runs on the booted `Mastra`. Every\n * trigger goes through a workflow run so the start decision and the poll are\n * recorded the same way whether a route, the scheduler or a webhook asked.\n */\n\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { FactorySandboxContext } from '@mastra/core/workspace';\nimport type { RepositoryPushEvent } from '../integrations/base.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport { probeSchedulesAvailable } from './build-schedule.js';\nimport type { ScheduleService } from './build-schedule.js';\nimport { createEnvironmentBuildWorkflow, ENVIRONMENT_BUILD_WORKFLOW_ID } from './build-workflow.js';\nimport type { EnvironmentBuildWorkflowOptions } from './build-workflow.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome, EnvironmentBuildTrigger } from './build.js';\nimport { environmentBuildContextWithEnv, errorReason, resolveEnvironmentHeads } from './build.js';\n\nexport type StartEnvironmentBuild = (\n projectId: string,\n trigger: EnvironmentBuildTrigger,\n) => Promise<EnvironmentBuildOutcome>;\n\nexport interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart'> {\n /** The booted instance; `undefined` until the host finished `finalize()`. */\n getMastra: () => Mastra | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n}\n\n/** What a read of a build's status or history hands the provider. */\nexport interface EnvironmentBuildReadContext {\n ctx: FactorySandboxContext;\n settings: Record<string, unknown>;\n}\n\nexport class EnvironmentBuildRunner {\n readonly workflow;\n readonly #deps: EnvironmentBuildDeps;\n readonly #getMastra: () => Mastra | undefined;\n readonly #logger: EnvironmentBuildRunnerOptions['logger'];\n readonly #pending = new Map<string, (outcome: EnvironmentBuildOutcome) => void>();\n #scheduleAvailable = false;\n\n constructor(deps: EnvironmentBuildDeps, options: EnvironmentBuildRunnerOptions) {\n const { getMastra, logger, ...workflowOptions } = options;\n this.#deps = deps;\n this.#getMastra = getMastra;\n this.#logger = logger;\n this.workflow = createEnvironmentBuildWorkflow(deps, {\n ...workflowOptions,\n onStart: (runId, outcome) => {\n this.#pending.get(runId)?.(outcome);\n this.#pending.delete(runId);\n },\n });\n }\n\n /** The schedule service of the booted host, `undefined` before boot. */\n schedules(): ScheduleService | undefined {\n return this.#getMastra()?.schedules;\n }\n\n /** Whether the host's storage implements schedules; false until `probeSchedules()` ran. */\n get scheduleAvailable(): boolean {\n return this.#scheduleAvailable;\n }\n\n /** Probe once after the host booted; a storage without the domain disables the cron trigger. */\n async probeSchedules(): Promise<boolean> {\n const schedules = this.schedules();\n this.#scheduleAvailable = schedules ? await probeSchedulesAvailable(schedules) : false;\n return this.#scheduleAvailable;\n }\n\n /**\n * The context a status or history read hands the provider. Heads come from\n * the stored last attempt (the build being read was pinned to them), else\n * the active template, so a read never calls GitHub; before the first build\n * they are resolved live once.\n */\n async readContext(projectId: string): Promise<EnvironmentBuildReadContext | undefined> {\n const sourceControl = this.#deps.sourceControl;\n if (!sourceControl) return undefined;\n const project = await this.#deps.projects.getById({ id: projectId });\n if (!project) return undefined;\n const environment = await resolveProjectEnvironment(sourceControl.storage, project);\n const heads =\n project.lastBuildHeads ??\n project.activeTemplateHeads ??\n (await resolveEnvironmentHeads(sourceControl, project, environment));\n return {\n ctx: (\n await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n sourceControl.versionControl,\n this.#deps.sandboxEnvs,\n )\n ).ctx,\n settings: environment.settings,\n };\n }\n\n /**\n * A push to an environment repository's default branch starts a `push` run\n * when the project opted in; the run's debounce claim decides whether it\n * builds. Fire and forget: the webhook never waits on it.\n */\n readonly onRepositoryPush = (event: RepositoryPushEvent): void => {\n if (!event.projectRepository.inEnvironment) return;\n const branch = event.defaultBranch;\n if (event.ref !== `refs/heads/${branch}`) return;\n void this.#deps.projects\n .getById({ id: event.factoryProjectId })\n .then(project => (project?.buildOnPushEnabled ? this.start(project.id, 'push') : undefined))\n .catch((error: unknown) => {\n this.#logger?.info('environment build push hand-off failed', {\n factoryProjectId: event.factoryProjectId,\n reason: errorReason(error),\n });\n });\n };\n\n /**\n * Start a run and resolve with the first step's answer; the poll step keeps\n * running in the background. Resolves `unavailable` before the host booted\n * or when the host never registered the workflow, and `failed` when the run\n * could not be created; a caller that already saved its own change must not\n * fail on the build it merely requested.\n */\n readonly start: StartEnvironmentBuild = async (projectId, trigger) => {\n const mastra = this.#getMastra();\n if (!mastra) return { outcome: 'unavailable', reason: 'not_ready' };\n let run: Awaited<ReturnType<typeof this.workflow.createRun>>;\n try {\n run = await mastra.getWorkflow(ENVIRONMENT_BUILD_WORKFLOW_ID).createRun();\n } catch (error) {\n const reason = errorReason(error);\n this.#logger?.info('environment build run could not be created', { factoryProjectId: projectId, reason });\n return mastra.listWorkflows()[ENVIRONMENT_BUILD_WORKFLOW_ID]\n ? { outcome: 'failed', reason }\n : { outcome: 'unavailable', reason: 'no_workflow' };\n }\n const outcome = new Promise<EnvironmentBuildOutcome>(resolve => this.#pending.set(run.runId, resolve));\n run\n .start({ inputData: { projectId, trigger } })\n .then(result => {\n if (result.status !== 'success') {\n this.#logger?.info('environment build run did not succeed', {\n factoryProjectId: projectId,\n runId: run.runId,\n });\n }\n })\n .catch((error: unknown) => {\n this.#logger?.info('environment build run threw', {\n factoryProjectId: projectId,\n runId: run.runId,\n reason: errorReason(error),\n });\n })\n .finally(() => {\n // A run that failed before its first step answered must not hang the caller.\n this.#pending.get(run.runId)?.({ outcome: 'failed', reason: 'The build run ended before it started a build.' });\n this.#pending.delete(run.runId);\n });\n return outcome;\n };\n}\n"],"mappings":";;;;;AAkCA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA,2BAAoB,IAAI,IAAwD;CAChF,qBAAqB;CAErB,YAAY,MAA4B,SAAwC;EAC9E,MAAM,EAAE,WAAW,QAAQ,GAAG,oBAAoB;EAClD,KAAK,QAAQ;EACb,KAAK,aAAa;EAClB,KAAK,UAAU;EACf,KAAK,WAAW,+BAA+B,MAAM;GACnD,GAAG;GACH,UAAU,OAAO,YAAY;IAC3B,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,OAAO;IAClC,KAAK,SAAS,OAAO,KAAK;GAC5B;EACF,CAAC;CACH;;CAGA,YAAyC;EACvC,OAAO,KAAK,WAAW,CAAC,EAAE;CAC5B;;CAGA,IAAI,oBAA6B;EAC/B,OAAO,KAAK;CACd;;CAGA,MAAM,iBAAmC;EACvC,MAAM,YAAY,KAAK,UAAU;EACjC,KAAK,qBAAqB,YAAY,MAAM,wBAAwB,SAAS,IAAI;EACjF,OAAO,KAAK;CACd;;;;;;;CAQA,MAAM,YAAY,WAAqE;EACrF,MAAM,gBAAgB,KAAK,MAAM;EACjC,IAAI,CAAC,eAAe,OAAO,KAAA;EAC3B,MAAM,UAAU,MAAM,KAAK,MAAM,SAAS,QAAQ,EAAE,IAAI,UAAU,CAAC;EACnE,IAAI,CAAC,SAAS,OAAO,KAAA;EACrB,MAAM,cAAc,MAAM,0BAA0B,cAAc,SAAS,OAAO;EAClF,MAAM,QACJ,QAAQ,kBACR,QAA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C1D,kBAAkB;IAClB,OAAO,IAAI;GACb,CAAC;EAEL,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,KAAK,SAAS,KAAK,+BAA+B;IAChD,kBAAkB;IAClB,OAAO,IAAI;IACX,QAAQ,YAAY,KAAK;GAC3B,CAAC;EACH,CAAC,CAAC,CACD,cAAc;GAEb,KAAK,SAAS,IAAI,IAAI,KAAK,CAAC,GAAG;IAAE,SAAS;IAAU,QAAQ;GAAiD,CAAC;GAC9G,KAAK,SAAS,OAAO,IAAI,KAAK;EAChC,CAAC;EACH,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"build-runner.js","names":[],"sources":["../../src/environment/build-runner.ts"],"sourcesContent":["/**\n * Starts `factory-environment-build` runs on the booted `Mastra`. Every\n * trigger goes through a workflow run so the start decision and the poll are\n * recorded the same way whether a route, the scheduler or a webhook asked.\n */\n\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { FactorySandboxContext } from '@mastra/core/workspace';\nimport type { RepositoryPushEvent } from '../integrations/base.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport { probeSchedulesAvailable } from './build-schedule.js';\nimport type { ScheduleService } from './build-schedule.js';\nimport { createEnvironmentBuildWorkflow, ENVIRONMENT_BUILD_WORKFLOW_ID } from './build-workflow.js';\nimport type { EnvironmentBuildWorkflowOptions } from './build-workflow.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome, EnvironmentBuildTrigger } from './build.js';\nimport { environmentBuildContextWithEnv, errorReason, resolveEnvironmentHeads } from './build.js';\n\n/** Longest wait between `settings` runs that find another process holding the build-start lease. */\nconst SETTINGS_RETRY_MAX_MS = 30_000;\n\nexport type StartEnvironmentBuild = (\n projectId: string,\n trigger: EnvironmentBuildTrigger,\n) => Promise<EnvironmentBuildOutcome>;\n\nexport interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart' | 'onSettled'> {\n /** The booted instance; `undefined` until the host finished `finalize()`. */\n getMastra: () => Mastra | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n}\n\n/** What a read of a build's status or history hands the provider. */\nexport interface EnvironmentBuildReadContext {\n ctx: FactorySandboxContext;\n settings: Record<string, unknown>;\n}\n\nexport class EnvironmentBuildRunner {\n readonly workflow;\n readonly #deps: EnvironmentBuildDeps;\n readonly #getMastra: () => Mastra | undefined;\n readonly #logger: EnvironmentBuildRunnerOptions['logger'];\n readonly #pending = new Map<string, (outcome: EnvironmentBuildOutcome) => void>();\n readonly #sleep: (ms: number) => Promise<void>;\n /** Projects with a saved change that a run of theirs skipped; that run's end builds it. */\n readonly #awaitingRun = new Set<string>();\n #scheduleAvailable = false;\n\n constructor(deps: EnvironmentBuildDeps, options: EnvironmentBuildRunnerOptions) {\n const { getMastra, logger, ...workflowOptions } = options;\n this.#deps = deps;\n this.#getMastra = getMastra;\n this.#logger = logger;\n this.#sleep = workflowOptions.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n this.workflow = createEnvironmentBuildWorkflow(deps, {\n ...workflowOptions,\n onStart: (runId, outcome) => {\n this.#pending.get(runId)?.(outcome);\n this.#pending.delete(runId);\n },\n // Fires for every run of the registered workflow, scheduled ones included.\n // A started build always checks once more, since a save (here or in\n // another process) may have been skipped against it; a run that held the\n // lease without building hands back a save skipped meanwhile. A run that\n // was itself skipped against the lease or a running build hands back\n // nothing: the run it deferred to is still going.\n onSettled: (projectId, result) => {\n if (result.outcome === 'started') {\n this.#awaitingRun.delete(projectId);\n this.onEnvironmentSaved(projectId);\n return;\n }\n if (result.outcome === 'skipped' && (result.reason === 'starting' || result.reason === 'in_progress')) return;\n if (this.#awaitingRun.delete(projectId)) this.onEnvironmentSaved(projectId);\n },\n });\n }\n\n /** The schedule service of the booted host, `undefined` before boot. */\n schedules(): ScheduleService | undefined {\n return this.#getMastra()?.schedules;\n }\n\n /** Whether the host's storage implements schedules; false until `probeSchedules()` ran. */\n get scheduleAvailable(): boolean {\n return this.#scheduleAvailable;\n }\n\n /** Probe once after the host booted; a storage without the domain disables the cron trigger. */\n async probeSchedules(): Promise<boolean> {\n const schedules = this.schedules();\n this.#scheduleAvailable = schedules ? await probeSchedulesAvailable(schedules) : false;\n return this.#scheduleAvailable;\n }\n\n /**\n * The context a status or history read hands the provider. Heads come from\n * the stored last attempt (the build being read was pinned to them), else\n * the active template, so a read never calls GitHub; before the first build\n * they are resolved live once.\n */\n async readContext(projectId: string): Promise<EnvironmentBuildReadContext | undefined> {\n const sourceControl = this.#deps.sourceControl;\n if (!sourceControl) return undefined;\n const project = await this.#deps.projects.getById({ id: projectId });\n if (!project) return undefined;\n const environment = await resolveProjectEnvironment(sourceControl.storage, project);\n const heads =\n project.lastBuildHeads ??\n project.activeTemplateHeads ??\n (await resolveEnvironmentHeads(sourceControl, project, environment));\n return {\n ctx: (\n await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n sourceControl.versionControl,\n this.#deps.sandboxEnvs,\n )\n ).ctx,\n settings: environment.settings,\n };\n }\n\n /**\n * A push to an environment repository's default branch starts a `push` run\n * when the project opted in; the run's debounce claim decides whether it\n * builds. Fire and forget: the webhook never waits on it.\n */\n readonly onRepositoryPush = (event: RepositoryPushEvent): void => {\n if (!event.projectRepository.inEnvironment) return;\n const branch = event.defaultBranch;\n if (event.ref !== `refs/heads/${branch}`) return;\n void this.#deps.projects\n .getById({ id: event.factoryProjectId })\n .then(project => (project?.buildOnPushEnabled ? this.start(project.id, 'push') : undefined))\n .catch((error: unknown) => {\n this.#logger?.info('environment build push hand-off failed', {\n factoryProjectId: event.factoryProjectId,\n reason: errorReason(error),\n });\n });\n };\n\n /**\n * A saved change to a project's environment (settings, setup commands,\n * repositories, Build variables) starts a `settings` run, which builds only\n * when the template inputs changed. A run skipped because another one\n * holds the build-start lease or its build is running (either may have read\n * the environment before this save) stays pending until that run is over.\n * A lease held by another process is retried, a second apart and doubling\n * up to `SETTINGS_RETRY_MAX_MS`, until it is released or lapses. Fire and\n * forget: the save never waits on it or fails because of it.\n */\n readonly onEnvironmentSaved = (projectId: string): void => {\n void (async () => {\n for (let delay = 1000; ; delay = Math.min(delay * 2, SETTINGS_RETRY_MAX_MS)) {\n const outcome = await this.start(projectId, 'settings');\n if (outcome.outcome !== 'skipped' || (outcome.reason !== 'starting' && outcome.reason !== 'in_progress')) {\n return;\n }\n this.#awaitingRun.add(projectId);\n if (outcome.reason === 'in_progress') return;\n await this.#sleep(delay);\n // A run of this process ended meanwhile and handed the save back.\n if (!this.#awaitingRun.has(projectId)) return;\n }\n })().catch((error: unknown) => {\n this.#logger?.info('environment build settings hand-off failed', {\n factoryProjectId: projectId,\n reason: errorReason(error),\n });\n });\n };\n\n /**\n * Start a run and resolve with the first step's answer; the poll step keeps\n * running in the background. Resolves `unavailable` before the host booted\n * or when the host never registered the workflow, and `failed` when the run\n * could not be created; a caller that already saved its own change must not\n * fail on the build it merely requested.\n */\n readonly start: StartEnvironmentBuild = async (projectId, trigger) => {\n const mastra = this.#getMastra();\n if (!mastra) return { outcome: 'unavailable', reason: 'not_ready' };\n let run: Awaited<ReturnType<typeof this.workflow.createRun>>;\n try {\n run = await mastra.getWorkflow(ENVIRONMENT_BUILD_WORKFLOW_ID).createRun();\n } catch (error) {\n const reason = errorReason(error);\n this.#logger?.info('environment build run could not be created', { factoryProjectId: projectId, reason });\n return mastra.listWorkflows()[ENVIRONMENT_BUILD_WORKFLOW_ID]\n ? { outcome: 'failed', reason }\n : { outcome: 'unavailable', reason: 'no_workflow' };\n }\n const outcome = new Promise<EnvironmentBuildOutcome>(resolve => this.#pending.set(run.runId, resolve));\n run\n .start({ inputData: { projectId, trigger } })\n .then(result => {\n if (result.status !== 'success') {\n this.#logger?.info('environment build run did not succeed', {\n factoryProjectId: projectId,\n runId: run.runId,\n });\n }\n })\n .catch((error: unknown) => {\n this.#logger?.info('environment build run threw', {\n factoryProjectId: projectId,\n runId: run.runId,\n reason: errorReason(error),\n });\n })\n .finally(() => {\n // A run that failed before its first step answered must not hang the caller.\n this.#pending.get(run.runId)?.({ outcome: 'failed', reason: 'The build run ended before it started a build.' });\n this.#pending.delete(run.runId);\n });\n return outcome;\n };\n}\n"],"mappings":";;;;;;AAkBA,MAAM,wBAAwB;AAmB9B,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA,2BAAoB,IAAI,IAAwD;CAChF;;CAEA,+BAAwB,IAAI,IAAY;CACxC,qBAAqB;CAErB,YAAY,MAA4B,SAAwC;EAC9E,MAAM,EAAE,WAAW,QAAQ,GAAG,oBAAoB;EAClD,KAAK,QAAQ;EACb,KAAK,aAAa;EAClB,KAAK,UAAU;EACf,KAAK,SAAS,gBAAgB,WAAU,OAAM,IAAI,SAAc,YAAW,WAAW,SAAS,EAAE,CAAC;EAClG,KAAK,WAAW,+BAA+B,MAAM;GACnD,GAAG;GACH,UAAU,OAAO,YAAY;IAC3B,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,OAAO;IAClC,KAAK,SAAS,OAAO,KAAK;GAC5B;GAOA,YAAY,WAAW,WAAW;IAChC,IAAI,OAAO,YAAY,WAAW;KAChC,KAAK,aAAa,OAAO,SAAS;KAClC,KAAK,mBAAmB,SAAS;KACjC;IACF;IACA,IAAI,OAAO,YAAY,cAAc,OAAO,WAAW,cAAc,OAAO,WAAW,gBAAgB;IACvG,IAAI,KAAK,aAAa,OAAO,SAAS,GAAG,KAAK,mBAAmB,SAAS;GAC5E;EACF,CAAC;CACH;;CAGA,YAAyC;EACvC,OAAO,KAAK,WAAW,CAAC,EAAE;CAC5B;;CAGA,IAAI,oBAA6B;EAC/B,OAAO,KAAK;CACd;;CAGA,MAAM,iBAAmC;EACvC,MAAM,YAAY,KAAK,UAAU;EACjC,KAAK,qBAAqB,YAAY,MAAM,wBAAwB,SAAS,IAAI;EACjF,OAAO,KAAK;CACd;;;;;;;CAQA,MAAM,YAAY,WAAqE;EACrF,MAAM,gBAAgB,KAAK,MAAM;EACjC,IAAI,CAAC,eAAe,OAAO,KAAA;EAC3B,MA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C;IAC/D,kBAAkB;IAClB,QAAQ,YAAY,KAAK;GAC3B,CAAC;EACH,CAAC;CACH;;;;;;;;CASA,QAAwC,OAAO,WAAW,YAAY;EACpE,MAAM,SAAS,KAAK,WAAW;EAC/B,IAAI,CAAC,QAAQ,OAAO;GAAE,SAAS;GAAe,QAAQ;EAAY;EAClE,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,OAAO,YAAY,6BAA6B,CAAC,CAAC,UAAU;EAC1E,SAAS,OAAO;GACd,MAAM,SAAS,YAAY,KAAK;GAChC,KAAK,SAAS,KAAK,8CAA8C;IAAE,kBAAkB;IAAW;GAAO,CAAC;GACxG,OAAO,OAAO,cAAc,CAAC,CAAA,+BACzB;IAAE,SAAS;IAAU;GAAO,IAC5B;IAAE,SAAS;IAAe,QAAQ;GAAc;EACtD;EACA,MAAM,UAAU,IAAI,SAAiC,YAAW,KAAK,SAAS,IAAI,IAAI,OAAO,OAAO,CAAC;EACrG,IACG,MAAM,EAAE,WAAW;GAAE;GAAW;EAAQ,EAAE,CAAC,CAAC,CAC5C,MAAK,WAAU;GACd,IAAI,OAAO,WAAW,WACpB,KAAK,SAAS,KAAK,yCAAyC;IAC1D,kBAAkB;IAClB,OAAO,IAAI;GACb,CAAC;EAEL,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,KAAK,SAAS,KAAK,+BAA+B;IAChD,kBAAkB;IAClB,OAAO,IAAI;IACX,QAAQ,YAAY,KAAK;GAC3B,CAAC;EACH,CAAC,CAAC,CACD,cAAc;GAEb,KAAK,SAAS,IAAI,IAAI,KAAK,CAAC,GAAG;IAAE,SAAS;IAAU,QAAQ;GAAiD,CAAC;GAC9G,KAAK,SAAS,OAAO,IAAI,KAAK;EAChC,CAAC;EACH,OAAO;CACT;AACF"}
@@ -3,20 +3,20 @@
3
3
  * build (`runEnvironmentBuild`), step two polls the provider until the build
4
4
  * settles and pins the active template on the project row. Registered by
5
5
  * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by
6
- * the Build now route, the per-project cron schedule and the GitHub push
7
- * hand-off. Saving settings never starts it.
6
+ * the Build now route, the per-project cron schedule, the GitHub push
7
+ * hand-off and saved template inputs.
8
8
  */
9
9
  import { z } from 'zod';
10
10
  import type { EnvironmentBuildDeps, EnvironmentBuildOutcome } from './build.js';
11
11
  export declare const ENVIRONMENT_BUILD_WORKFLOW_ID = "factory-environment-build";
12
12
  export declare const DEFAULT_BUILD_POLL_MS = 15000;
13
- export declare const MAX_BUILD_WAIT_MS: number;
14
13
  export declare const environmentBuildInputSchema: z.ZodObject<{
15
14
  projectId: z.ZodString;
16
15
  trigger: z.ZodEnum<{
17
16
  manual: "manual";
18
17
  push: "push";
19
18
  schedule: "schedule";
19
+ settings: "settings";
20
20
  }>;
21
21
  }, z.core.$strip>;
22
22
  export declare const environmentBuildOutputSchema: z.ZodObject<{
@@ -42,10 +42,12 @@ export interface EnvironmentBuildWorkflowOptions {
42
42
  maxWaitMs?: number;
43
43
  /** Called with the first step's answer so a caller can return it without waiting for the poll. */
44
44
  onStart?: (runId: string, outcome: EnvironmentBuildOutcome) => void;
45
+ /** Called once a run is over, whoever started it (a route, the scheduler or a hand-off). */
46
+ onSettled?: (projectId: string, result: EnvironmentBuildWorkflowResult) => void;
45
47
  }
46
48
  export declare function createEnvironmentBuildWorkflow(deps: EnvironmentBuildDeps, options?: EnvironmentBuildWorkflowOptions): import("@mastra/core/workflows").Workflow<import("@mastra/core/workflows").DefaultEngineType, import("@mastra/core/workflows").Step<string, unknown, unknown, unknown, unknown, unknown, any, unknown>[], "factory-environment-build", unknown, {
47
49
  projectId: string;
48
- trigger: "manual" | "push" | "schedule";
50
+ trigger: "manual" | "push" | "schedule" | "settings";
49
51
  }, {
50
52
  outcome: "failed" | "skipped" | "started" | "unavailable";
51
53
  buildId?: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"build-workflow.d.ts","sourceRoot":"","sources":["../../src/environment/build-workflow.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;A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C,CAAC;AAEH,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAE1F,MAAM,WAAW,+BAA+B;IAC9C,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kGAAkG;IAClG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,uBAAuB,KAAK,IAAI,CAAC;IACpE,4FAA4F;IAC5F,SAAS,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,8BAA8B,KAAK,IAAI,CAAC;CACjF;AAED,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,oBAAoB,EAC1B,OAAO,GAAE,+BAAoC;;;;;;;;;;;;;;;eAmG9C"}
@@ -9,12 +9,11 @@ import { createStep, createWorkflow } from "@mastra/core/workflows";
9
9
  * build (`runEnvironmentBuild`), step two polls the provider until the build
10
10
  * settles and pins the active template on the project row. Registered by
11
11
  * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by
12
- * the Build now route, the per-project cron schedule and the GitHub push
13
- * hand-off. Saving settings never starts it.
12
+ * the Build now route, the per-project cron schedule, the GitHub push
13
+ * hand-off and saved template inputs.
14
14
  */
15
15
  const ENVIRONMENT_BUILD_WORKFLOW_ID = "factory-environment-build";
16
16
  const DEFAULT_BUILD_POLL_MS = 15e3;
17
- const MAX_BUILD_WAIT_MS = 18e5;
18
17
  const environmentBuildInputSchema = z.object({
19
18
  projectId: z.string().min(1),
20
19
  trigger: z.enum(ENVIRONMENT_BUILD_TRIGGERS)
@@ -67,75 +66,80 @@ function createEnvironmentBuildWorkflow(deps, options = {}) {
67
66
  };
68
67
  }
69
68
  });
70
- const awaitBuild = createStep({
71
- id: "await-build",
72
- inputSchema: startOutputSchema,
73
- outputSchema: environmentBuildOutputSchema,
74
- execute: async ({ inputData }) => {
75
- const { projectId, heads, ...result } = inputData;
76
- if (result.outcome !== "started" || !result.buildId || !heads) return result;
77
- const builds = deps.sandbox?.builds;
78
- const project = await deps.projects.getById({ id: projectId });
79
- if (!builds || !deps.sourceControl || !project) return {
80
- ...result,
81
- status: "unknown"
82
- };
83
- const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);
84
- const { ctx } = await environmentBuildContextWithEnv(project, environment, heads, deps.sourceControl.versionControl, deps.sandboxEnvs);
85
- const startedAt = now().getTime();
86
- try {
87
- for (;;) {
88
- const build = await builds.get(ctx, environment.settings, result.buildId);
89
- if (build.status === "ready") {
90
- const templateId = build.templateId ?? result.templateId ?? result.buildId;
91
- const pinned = await deps.projects.pinActiveTemplate({
92
- id: project.id,
93
- buildId: result.buildId,
94
- templateId,
95
- heads
96
- });
97
- deps.logger?.info(pinned ? "environment build ready" : "environment build ready but superseded", {
98
- factoryProjectId: project.id,
99
- templateId
100
- });
101
- return {
102
- ...result,
103
- templateId,
104
- status: "ready"
105
- };
106
- }
107
- if (build.status === "failed" || build.status === "unknown") {
108
- deps.logger?.info("environment build did not complete", {
109
- factoryProjectId: project.id,
110
- buildId: result.buildId,
111
- status: build.status,
112
- ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
113
- });
114
- return {
115
- ...result,
116
- status: build.status,
117
- ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
118
- };
119
- }
120
- if (now().getTime() - startedAt >= maxWaitMs) return {
69
+ const pollUntilSettled = async (inputData) => {
70
+ const { projectId, heads, ...result } = inputData;
71
+ if (result.outcome !== "started" || !result.buildId || !heads) return result;
72
+ const builds = deps.sandbox?.builds;
73
+ const project = await deps.projects.getById({ id: projectId });
74
+ if (!builds || !deps.sourceControl || !project) return {
75
+ ...result,
76
+ status: "unknown"
77
+ };
78
+ const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);
79
+ const { ctx } = await environmentBuildContextWithEnv(project, environment, heads, deps.sourceControl.versionControl, deps.sandboxEnvs);
80
+ const startedAt = now().getTime();
81
+ try {
82
+ for (;;) {
83
+ const build = await builds.get(ctx, environment.settings, result.buildId);
84
+ if (build.status === "ready") {
85
+ const templateId = build.templateId ?? result.templateId ?? result.buildId;
86
+ const pinned = await deps.projects.pinActiveTemplate({
87
+ id: project.id,
88
+ buildId: result.buildId,
89
+ templateId,
90
+ heads
91
+ });
92
+ deps.logger?.info(pinned ? "environment build ready" : "environment build ready but superseded", {
93
+ factoryProjectId: project.id,
94
+ templateId
95
+ });
96
+ return {
97
+ ...result,
98
+ templateId,
99
+ status: "ready"
100
+ };
101
+ }
102
+ if (build.status === "failed" || build.status === "unknown") {
103
+ deps.logger?.info("environment build did not complete", {
104
+ factoryProjectId: project.id,
105
+ buildId: result.buildId,
106
+ status: build.status,
107
+ ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
108
+ });
109
+ return {
121
110
  ...result,
122
- status: "unknown",
123
- reason: "Build wait timed out."
111
+ status: build.status,
112
+ ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
124
113
  };
125
- await sleep(pollMs);
126
114
  }
127
- } catch (error) {
128
- const reason = maskSandboxEnvValues(errorReason(error), ctx.buildEnv);
129
- deps.logger?.info("environment build status read failed", {
130
- factoryProjectId: project.id,
131
- reason
132
- });
133
- return {
115
+ if (now().getTime() - startedAt >= maxWaitMs) return {
134
116
  ...result,
135
117
  status: "unknown",
136
- reason
118
+ reason: "Build wait timed out."
137
119
  };
120
+ await sleep(pollMs);
138
121
  }
122
+ } catch (error) {
123
+ const reason = maskSandboxEnvValues(errorReason(error), ctx.buildEnv);
124
+ deps.logger?.info("environment build status read failed", {
125
+ factoryProjectId: project.id,
126
+ reason
127
+ });
128
+ return {
129
+ ...result,
130
+ status: "unknown",
131
+ reason
132
+ };
133
+ }
134
+ };
135
+ const awaitBuild = createStep({
136
+ id: "await-build",
137
+ inputSchema: startOutputSchema,
138
+ outputSchema: environmentBuildOutputSchema,
139
+ execute: async ({ inputData }) => {
140
+ const settled = await pollUntilSettled(inputData);
141
+ options.onSettled?.(inputData.projectId, settled);
142
+ return settled;
139
143
  }
140
144
  });
141
145
  return createWorkflow({
@@ -144,6 +148,6 @@ function createEnvironmentBuildWorkflow(deps, options = {}) {
144
148
  outputSchema: environmentBuildOutputSchema
145
149
  }).then(start).then(awaitBuild).commit();
146
150
  }
147
- export { DEFAULT_BUILD_POLL_MS, ENVIRONMENT_BUILD_WORKFLOW_ID, MAX_BUILD_WAIT_MS, createEnvironmentBuildWorkflow, environmentBuildInputSchema, environmentBuildOutputSchema };
151
+ export { DEFAULT_BUILD_POLL_MS, ENVIRONMENT_BUILD_WORKFLOW_ID, createEnvironmentBuildWorkflow, environmentBuildInputSchema, environmentBuildOutputSchema };
148
152
 
149
153
  //# sourceMappingURL=build-workflow.js.map
@@ -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 and the GitHub push\n * hand-off. Saving settings never starts it.\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 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;\nexport const MAX_BUILD_WAIT_MS = 30 * 60_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}\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 const awaitBuild = createStep({\n id: 'await-build',\n inputSchema: startOutputSchema,\n outputSchema: environmentBuildOutputSchema,\n execute: async ({ inputData }): 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\n return createWorkflow({\n id: ENVIRONMENT_BUILD_WORKFLOW_ID,\n inputSchema: environmentBuildInputSchema,\n outputSchema: environmentBuildOutputSchema,\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QAAQ;OAC1B,SAAS,OAAO;OAChB,QAAQ,MAAM;OACd,GAAI,MAAM,QAAQ,EAAE,QAAQ,qBAAqB,kBAAkB,MAAM,KAAK,GAAG,IAAI,QAAQ,EAAE,IAAI,CAAC;MACtG,CAAC;MACD,OAAO;OACL,GAAG;OACH,QAAQ,MAAM;OACd,GAAI,MAAM,QAAQ,EAAE,QAAQ,qBAAqB,kBAAkB,MAAM,KAAK,GAAG,IAAI,QAAQ,EAAE,IAAI,CAAC;MACtG;KACF;KACA,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,aAAa,WACjC,OAAO;MAAE,GAAG;MAAQ,QAAQ;MAAW,QAAQ;KAAwB;KAEzE,MAAM,MAAM,MAAM;IACpB;GACF,SAAS,OAAO;IACd,MAAM,SAAS,qBAAqB,YAAY,KAAK,GAAG,IAAI,QAAQ;IACpE,KAAK,QAAQ,KAAK,wCAAwC;KAAE,kBAAkB,QAAQ;KAAI;IAAO,CAAC;IAClG,OAAO;KAAE,GAAG;KAAQ,QAAQ;KAAW;IAAO;GAChD;EACF;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"}
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;AAErC,MAAa,8BAA8B,EAAE,OAAO;CAClD,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC3B,SAAS,EAAE,KAAK,0BAA0B;AAC5C,CAAC;AAED,MAAM,oBAAoB,EAAE,OAAO;CACjC,WAAW,EAAE,OAAO;CACpB,SAAS,EAAE,KAAK;EAAC;EAAW;EAAW;EAAe;CAAQ,CAAC;CAC/D,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS;CAC5B,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;AACnD,CAAC;AAED,MAAa,+BAA+B,EAAE,OAAO;CACnD,SAAS,EAAE,KAAK;EAAC;EAAW;EAAW;EAAe;CAAQ,CAAC;CAC/D,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE5B,QAAQ,EAAE,KAAK;EAAC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Ac;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
- export declare const ENVIRONMENT_BUILD_TRIGGERS: readonly ['manual', 'schedule', 'push'];
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. Saving settings never builds.
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