@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":"project-boards.js","names":[],"sources":["../../src/boards/project-boards.ts"],"sourcesContent":["import type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type {\n BoardMigrationContext,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n} from '../storage/domains/boards/base.js';\nimport { DEFAULT_INTAKE_ROUTE_ACTOR } from '../storage/domains/boards/base.js';\nimport type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { boardRegistryOf, createBoardRegistry, defaultBoards } from './registry.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { boardForWorkItem } from './semantics.js';\nimport { boardDefinitionOf, compileStoredBoard, mergeCodeBehaviour } from './stored-board.js';\nimport { BOARD_MIGRATIONS } from './work-migrations.js';\nimport { workSeedWithTriage } from './work-seeds.js';\nimport { workBoard } from './work.js';\n\nconst DEFAULT_RECHECK_MS = 1000;\n/** A row under the retired Review board's key is never served: the key is the Review board's alone. */\nconst RESERVED_REVIEW_ROW = `Stored board \"${LEGACY_REVIEW_BOARD}\" isn't served: the key is reserved for the retired Review board.`;\nconst PRELOAD_CONCURRENCY = 8;\n/** The phases every release seeded the Review board with; only runners and tools changed between them. */\nconst REVIEW_SEED_PHASES = boardDefinitionOf(reviewBoard).phases.map(({ key, name, kind }) => ({ key, name, kind }));\n\n/**\n * Whether `row` is the Review board as Factory seeded it: written once by Factory, never\n * revised, and shaped like the seed. The actor alone is not proof, as any caller can pass it.\n */\nfunction isUntouchedReviewSeed(row: StoredBoardRecord): boolean {\n if (row.revision !== 1 || row.createdBy !== DEFAULT_INTAKE_ROUTE_ACTOR) return false;\n if (row.updatedBy !== DEFAULT_INTAKE_ROUTE_ACTOR || row.name !== reviewBoard.name) return false;\n const phases = [...row.phases].sort((a, b) => a.position - b.position);\n return (\n phases.length === REVIEW_SEED_PHASES.length &&\n phases.every(\n (phase, index) =>\n phase.key === REVIEW_SEED_PHASES[index]!.key &&\n phase.name === REVIEW_SEED_PHASES[index]!.name &&\n phase.kind === REVIEW_SEED_PHASES[index]!.kind,\n )\n );\n}\nconst SNAPSHOT_ATTEMPTS = 3;\n\n/**\n * The creator Factory records on the Work board it stores in a project as the project is\n * created: that board is today's Work, and reset gives it back. Any other Work row Factory stored\n * is the one with Triage. Only Factory writes this id; a person's writes carry their user id.\n */\nexport const NEW_PROJECT_SEED_ACTOR = 'factory:new-project';\n\n/** Where a board in a project's catalog came from. */\nexport type BoardSourceKind = 'builtin' | 'app' | 'stored';\n\nexport interface StoredBoardDetails {\n source: BoardSourceKind;\n /** Stored boards, the built-in Work board and app boards can all be edited; the retired Review board can't. */\n editable: boolean;\n problems: string[];\n}\n\n/** A project's boards: the code boards plus its stored boards, and what to report about each board. */\nexport interface ProjectBoards {\n readonly registry: BoardRegistry;\n readonly details: ReadonlyMap<string, StoredBoardDetails>;\n /** Problems with stored boards that are left out of the registry. */\n readonly problems: readonly string[];\n}\n\nconst PROJECT_BOARD_SOURCE = Symbol('ProjectBoardSource');\n\n/**\n * Serves each project its boards. `load` is the async entry point that brings a project's\n * boards up to date; `forProject` is the sync read for code that already loaded the project.\n */\nexport interface ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE]: true;\n /** The code boards: built-in and app boards, served to every project as code built them. */\n readonly codeRegistry: BoardRegistry;\n load(scope: StoredBoardScope): Promise<BoardRegistry>;\n forProject(scope: StoredBoardScope): BoardRegistry;\n describe?(scope: StoredBoardScope): Promise<ProjectBoards>;\n}\n\n/** Accepts either a fixed registry (tests, standalone services) or a per-project source. */\nexport function toBoardSource(boards: BoardRegistry | ProjectBoardSource | undefined): ProjectBoardSource {\n const source = boards ?? createBoardRegistry();\n if (isBoardSource(source)) return source;\n return {\n [PROJECT_BOARD_SOURCE]: true,\n codeRegistry: source,\n load: async () => source,\n forProject: () => source,\n };\n}\n\nfunction isBoardSource(boards: BoardRegistry | ProjectBoardSource): boards is ProjectBoardSource {\n return PROJECT_BOARD_SOURCE in boards;\n}\n\ninterface CacheEntry {\n boards: ProjectBoards;\n version: string | null;\n reviewInUse: boolean;\n checkedAt: number;\n}\n\nexport interface ProjectBoardCacheOptions {\n /** The code boards, built-ins included when enabled. */\n codeRegistry: BoardRegistry;\n storage: StoredBoardsStorage;\n /**\n * Lists every project, to warm them at boot, and reads the retired switches the board\n * migrations carry into each project's boards.\n */\n projects?: {\n listAll(): Promise<readonly { orgId: string; id: string }[]>;\n retiredAutomationSettings?(\n project: { orgId: string; id: string },\n ops: FactoryStorageOps,\n ): Promise<RetiredAutomationSettings | null>;\n };\n /** The phases cards sit in on each of the project's boards, which a board migration must not remove. */\n occupiedPhases?: (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ) => Promise<ReadonlyMap<string, ReadonlySet<string>> | null>;\n codeSkills?: readonly InlineSkill[];\n /**\n * Whether the project still uses the retired Review board (an open card is stored on it). Such\n * a project is served Review alongside its boards; without this, no project is.\n */\n reviewBoardInUse?: (scope: StoredBoardScope) => Promise<boolean>;\n recheckMs?: number;\n now?: () => number;\n warn?: (message: string) => void;\n}\n\nfunction scopeKey(scope: StoredBoardScope): string {\n return `${scope.orgId}\\0${scope.factoryProjectId}`;\n}\n\n/**\n * Reads the phases cards sit in on each of a project's boards, for `occupiedPhases`. Null while\n * cards from before the work-item split are still being copied: `listWith` can't see those yet.\n */\nexport function occupiedPhasesOf(workItems: Pick<WorkItemsStorage, 'listWith' | 'legacyBackfillPending'>) {\n return async (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ): Promise<ReadonlyMap<string, ReadonlySet<string>> | null> => {\n if (workItems.legacyBackfillPending) return null;\n const occupied = new Map<string, Set<string>>();\n for (const item of await workItems.listWith(ops, scope)) {\n const board = boardForWorkItem(item);\n const phases = occupied.get(board) ?? new Set<string>();\n for (const stage of item.stages) phases.add(stage);\n occupied.set(board, phases);\n }\n return occupied;\n };\n}\n\n/**\n * The per-project board cache. A project's boards are its rows: the Work and app boards Factory\n * stored in it, in code order, then the others. A Work or app board's row runs with the code\n * behaviour of its board and phase keys that still fits it ({@link mergeCodeBehaviour}). A project\n * that still uses the retired Review board is served it from code, never stored, until its last\n * open card there finishes. The first load of each project in a process stores the\n * boards Factory hasn't stored in it yet, each once ({@link StoredBoardsStorage.seedBoards}); a\n * release never rewrites them. Loads recheck the project's board version at most every\n * `recheckMs` and recompile when it changed, so stored edits on other replicas arrive within that\n * delay.\n */\nexport class ProjectBoardCache implements ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE] = true;\n readonly codeRegistry: BoardRegistry;\n readonly #codeDetails: ReadonlyMap<string, StoredBoardDetails>;\n readonly #storage: StoredBoardsStorage;\n readonly #projects: ProjectBoardCacheOptions['projects'];\n readonly #recheckMs: number;\n readonly #now: () => number;\n readonly #warn: (message: string) => void;\n readonly #entries = new Map<string, CacheEntry>();\n readonly #loading = new Map<string, Promise<ProjectBoards>>();\n readonly #generations = new Map<string, number>();\n readonly #warned = new Set<string>();\n readonly #seeded = new Set<string>();\n readonly #codeSkills: readonly InlineSkill[];\n readonly #seeds: ReadonlyMap<string, StoredBoardInput>;\n /** Boards the app upserted for every project, which a project with no boards gets before Factory's. */\n readonly #appBoards = new Map<string, StoredBoardInput>();\n readonly #reviewBoardInUse: ProjectBoardCacheOptions['reviewBoardInUse'];\n readonly #occupiedPhases: ProjectBoardCacheOptions['occupiedPhases'];\n\n constructor(options: ProjectBoardCacheOptions) {\n this.codeRegistry = options.codeRegistry;\n this.#storage = options.storage;\n this.#reviewBoardInUse = options.reviewBoardInUse;\n this.#occupiedPhases = options.occupiedPhases;\n this.#projects = options.projects;\n this.#codeSkills = options.codeSkills ?? [];\n this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS;\n this.#now = options.now ?? Date.now;\n this.#warn = options.warn ?? (message => console.warn(`[factory] ${message}`));\n this.#codeDetails = new Map(\n [...this.codeRegistry.values()].map(board => [\n board.id,\n {\n source: defaultBoards.includes(board) ? 'builtin' : 'app',\n editable: true,\n problems: this.#skillProblems(board),\n },\n ]),\n );\n this.#seeds = new Map([...this.codeRegistry.values()].map(board => [board.id, boardDefinitionOf(board)]));\n }\n\n /**\n * The boards Factory stores once in a project it didn't create: Work as it was with Triage, so a\n * project from an older release keeps the phases its cards know, then the app boards, in order.\n */\n seeds(): StoredBoardInput[] {\n return [...this.#seeds.values()].map(seed => (this.#isFactoryWork(seed.key) ? workSeedWithTriage() : seed));\n }\n\n /**\n * The definition reset restores for `key`; undefined when there is none. A board the app upserted\n * for every project comes first, so reset never swaps an app's Work for Factory's. Factory's Work\n * is today's Work for a project Factory created with it (`row` created by\n * {@link NEW_PROJECT_SEED_ACTOR}), and Work with Triage for every other project.\n */\n seedFor(key: string, row?: Pick<StoredBoardRecord, 'createdBy'>): StoredBoardInput | undefined {\n const app = this.#appBoards.get(key);\n if (app) return app;\n const seed = this.#seeds.get(key);\n if (!seed || !this.#isFactoryWork(key) || row?.createdBy === NEW_PROJECT_SEED_ACTOR) return seed;\n return workSeedWithTriage();\n }\n\n /**\n * Stores Factory's boards in a project that was just created, with today's Work (no Triage).\n * Only the project-creation route calls this; every other load stores {@link seeds}.\n */\n async seedNewProject(scope: StoredBoardScope): Promise<ProjectBoards> {\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, [...this.#seeds.values()], {\n actor: NEW_PROJECT_SEED_ACTOR,\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n });\n }\n return this.describe(scope);\n }\n\n /**\n * Remembers a board the app upserted for every project, so a project that has no boards yet (one\n * created later, or one that never loaded) gets it on its first load before Factory's own boards;\n * having it, the project then gets no Work from Factory. Kept for this process: an app upserts\n * its boards at every startup.\n */\n rememberBoardForAllProjects(board: StoredBoardInput): void {\n this.#appBoards.set(board.key, board);\n }\n\n /** Whether `key` is Factory's own Work board, rather than none or an app board under its key. */\n #isFactoryWork(key: string): boolean {\n return key === workBoard.id && this.codeRegistry.get(key) === workBoard;\n }\n\n /** Work is stored only into a project with no boards: one that has any keeps what it has. */\n #onlyIntoEmpty(): string[] {\n return this.#isFactoryWork(workBoard.id) ? [workBoard.id] : [];\n }\n\n async load(scope: StoredBoardScope): Promise<BoardRegistry> {\n return (await this.describe(scope)).registry;\n }\n\n /** The project's boards with their source, whether they can be edited, and problems, brought up to date. */\n async describe(scope: StoredBoardScope): Promise<ProjectBoards> {\n const key = scopeKey(scope);\n const entry = this.#entries.get(key);\n if (entry && this.#now() - entry.checkedAt < this.#recheckMs) return entry.boards;\n const inFlight = this.#loading.get(key);\n if (inFlight) return inFlight;\n const generation = this.#generations.get(key) ?? 0;\n const loading = this.#refresh(scope, key, generation).finally(() => {\n if (this.#loading.get(key) === loading) this.#loading.delete(key);\n });\n this.#loading.set(key, loading);\n return loading;\n }\n\n /**\n * The project's loaded boards. Before the project's first load (boot preload not finished, or a\n * project created on another replica) this is the code boards alone, without the project's\n * stored boards.\n */\n forProject(scope: StoredBoardScope): BoardRegistry {\n // Storage asks about a row it is about to insert by its board and stages alone, with no\n // project to look up; the code boards answer for it.\n if (!scope.orgId || !scope.factoryProjectId) return this.codeRegistry;\n const entry = this.#entries.get(scopeKey(scope));\n if (entry) return entry.boards.registry;\n // Warm the project so the next sync read sees its stored boards.\n void this.load(scope).catch(() => {});\n this.#warnOnce(\n `cold:${scopeKey(scope)}`,\n `Boards for project ${scope.factoryProjectId} were read before they were loaded; using the code boards.`,\n true,\n );\n return this.codeRegistry;\n }\n\n /** The code skills stored runners may name. */\n get codeSkills(): readonly InlineSkill[] {\n return this.#codeSkills;\n }\n\n /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */\n invalidate(scope: StoredBoardScope): void {\n const key = scopeKey(scope);\n this.#generations.set(key, (this.#generations.get(key) ?? 0) + 1);\n this.#loading.delete(key);\n const entry = this.#entries.get(key);\n if (entry) entry.checkedAt = Number.NEGATIVE_INFINITY;\n }\n\n /** Loads every project, a few at a time, so sync reads find them warm and each has its boards stored. */\n async preload(): Promise<void> {\n const projects = (await this.#projects?.listAll()) ?? [];\n let next = 0;\n const worker = async () => {\n while (next < projects.length) {\n const project = projects[next++]!;\n // A project that fails to load here loads on first use; the others still load now.\n await this.load({ orgId: project.orgId, factoryProjectId: project.id }).catch(error =>\n this.#warn(\n `Boards for project ${project.id} did not load at startup; they load on first use: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(PRELOAD_CONCURRENCY, projects.length) }, worker));\n }\n\n async #refresh(scope: StoredBoardScope, key: string, generation: number): Promise<ProjectBoards> {\n await this.#seed(scope, key);\n const current = this.#entries.get(key);\n const version = await this.#storage.readVersion(scope);\n const reviewInUse = (await this.#reviewBoardInUse?.(scope)) ?? false;\n if (current && current.version === version && current.reviewInUse === reviewInUse) {\n if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now();\n return current.boards;\n }\n const snapshot = await this.#consistentSnapshot(scope);\n const boards = this.#compile(scope, snapshot.boards, reviewInUse);\n if ((this.#generations.get(key) ?? 0) === generation) {\n this.#entries.set(key, { boards, version: snapshot.version, reviewInUse, checkedAt: this.#now() });\n }\n return boards;\n }\n\n /** Boards and phases are read in two statements; reread when a write landed between them. */\n async #consistentSnapshot(scope: StoredBoardScope) {\n let snapshot = await this.#storage.snapshot(scope);\n for (let attempt = 1; attempt < SNAPSHOT_ATTEMPTS; attempt++) {\n if ((await this.#storage.readVersion(scope)) === snapshot.version) break;\n snapshot = await this.#storage.snapshot(scope);\n }\n return snapshot;\n }\n\n /**\n * Stores the boards Factory hasn't stored in the project yet, once per process. A failure is\n * logged and retried on the next load; the boards it didn't store aren't served meanwhile.\n */\n async #seed(scope: StoredBoardScope, key: string): Promise<void> {\n if (this.#seeded.has(key)) return;\n try {\n // Read before seeding records Work's key: a project whose list lacked it has no Work of Factory's.\n const seeded = await this.#storage.seededBoardKeys(scope);\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, this.seeds(), {\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n });\n }\n await this.#migrate(scope, seeded);\n this.#seeded.add(key);\n } catch (error) {\n this.#warnOnce(\n `seed:${key}`,\n `Boards for project ${scope.factoryProjectId} could not be stored; Factory stores them on the next load: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Runs the board migrations of the boards Factory stores here that the project hasn't had yet. */\n async #migrate(scope: StoredBoardScope, seededBefore: readonly string[] | null): Promise<void> {\n // A migration of one board rewrites Factory's own board; an app board under the same key keeps\n // its settings. One that carries a project setting into every board rewrites them all. A board\n // Factory never stored in the project (an app wrote the row first), or one the app upserts for\n // every project, is an app's: its one-board migrations are recorded as applied without running.\n const migrations = BOARD_MIGRATIONS.filter(migration => {\n if (migration.boardKey === null) return true;\n const code = this.codeRegistry.get(migration.boardKey);\n return code !== undefined && defaultBoards.includes(code);\n }).map(migration =>\n migration.boardKey !== null &&\n (this.#appBoards.has(migration.boardKey) || (seededBefore !== null && !seededBefore.includes(migration.boardKey)))\n ? { ...migration, migrate: () => undefined }\n : migration,\n );\n const changed = await this.#storage.applyBoardMigrations(scope, migrations, ops =>\n this.#migrationContext(scope, ops),\n );\n if (changed.length === 0) return;\n const filled = changed.map(({ boardKey, filled }) => `${boardKey}: ${filled.join(', ')}`).join('; ');\n console.info(`[factory] Migrated the boards of project ${scope.factoryProjectId} (${filled}).`);\n }\n\n /** Read through the migration transaction's `ops`, so card moves can't slip in unseen on LibSQL. */\n async #migrationContext(scope: StoredBoardScope, ops: FactoryStorageOps): Promise<BoardMigrationContext> {\n const retiredSettings =\n (await this.#projects?.retiredAutomationSettings?.({ orgId: scope.orgId, id: scope.factoryProjectId }, ops)) ??\n null;\n return {\n retiredSettings,\n occupiedPhases: retiredSettings && this.#occupiedPhases ? await this.#occupiedPhases(scope, ops) : null,\n codePhases: boardKey => {\n const code = this.codeRegistry.get(boardKey);\n return code ? new Set(Object.keys(code.phases)) : undefined;\n },\n warn: message =>\n this.#warnOnce(`migration:${scopeKey(scope)}:${message}`, `${message} (project ${scope.factoryProjectId})`),\n };\n }\n\n #compile(scope: StoredBoardScope, rows: readonly StoredBoardRecord[], reviewInUse: boolean): ProjectBoards {\n const byKey = new Map(rows.map(row => [row.key, row]));\n const details = new Map(this.#codeDetails);\n const problems: string[] = [];\n const report = (row: StoredBoardRecord, messages: readonly string[]) => {\n problems.push(...messages);\n for (const message of messages) {\n this.#warnOnce(\n `row:${scopeKey(scope)}:${row.key}:${row.revision}:${message}`,\n `${message} (project ${scope.factoryProjectId})`,\n );\n }\n };\n const boards: InstalledBoard[] = [];\n // Work and app boards keep their code order, each served from its row.\n for (const code of this.codeRegistry.values()) {\n const row = byKey.get(code.id);\n if (!row) {\n details.delete(code.id);\n // Stored once and deleted since, or not stored because storing failed.\n if (!this.#seeded.has(scopeKey(scope))) {\n problems.push(`Board \"${code.id}\" isn't stored in this project yet; Factory stores it on the next load.`);\n }\n continue;\n }\n let merged: ReturnType<typeof mergeCodeBehaviour>;\n try {\n merged = mergeCodeBehaviour(row, code);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n report(row, merged.problems);\n details.set(code.id, {\n ...details.get(code.id)!,\n problems: [...merged.problems, ...this.#skillProblems(merged.board)],\n });\n boards.push(merged.board);\n }\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse) {\n boards.push(reviewBoard);\n details.set(reviewBoard.id, { source: 'builtin', editable: false, problems: [] });\n }\n for (const row of rows) {\n if (this.codeRegistry.has(row.key)) continue;\n if (row.key === LEGACY_REVIEW_BOARD) {\n // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // there is nothing in it to lose, so it is no problem. A person's edits are reported.\n if (isUntouchedReviewSeed(row)) continue;\n report(row, [\n reviewInUse\n ? `Stored board \"${row.key}\" is hidden by the code board with the same key.`\n : RESERVED_REVIEW_ROW,\n ]);\n continue;\n }\n let board: InstalledBoard;\n try {\n board = compileStoredBoard(row);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n boards.push(board);\n details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board) });\n }\n return {\n registry: boardRegistryOf(boards),\n details,\n problems,\n };\n }\n\n #skillProblems(board: InstalledBoard): string[] {\n return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills);\n }\n\n #warnOnce(key: string, message: string, debug = false): void {\n if (this.#warned.has(key)) return;\n this.#warned.add(key);\n if (debug) {\n console.debug(`[factory] ${message}`);\n return;\n }\n this.#warn(message);\n }\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,qBAAqB;;AAE3B,MAAM,sBAAsB,iBAAiB,oBAAoB;AACjE,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAS,sBAAsB,KAAiC;CAC9D,IAAI,IAAI,aAAa,KAAK,IAAI,cAAA,WAA0C,OAAO;CAC/E,IAAI,IAAI,cAAA,aAA4C,IAAI,SAAS,YAAY,MAAM,OAAO;CAC1F,MAAM,SAAS,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;CACrE,OACE,OAAO,WAAW,mBAAmB,UACrC,OAAO,OACJ,OAAO,UACN,MAAM,QAAQ,mBAAmB,MAAM,CAAE,OACzC,MAAM,SAAS,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AAO;IACd,OAAO,KAAK,CACV,UAAU,IAAI,IAAI,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAClG,CAAC;IACD;GACF;GACA,OAAO,KAAK,KAAK;GACjB,QAAQ,IAAI,IAAI,KAAK;IAAE,QAAQ;IAAU,UAAU;IAAM,UAAU,KAAK,eAAe,KAAK;GAAE,CAAC;EACjG;EACA,OAAO;GACL,UAAU,gBAAgB,MAAM;GAChC;GACA;EACF;CACF;CAEA,eAAe,OAAiC;EAC9C,OAAO,uBAAuB,gBAAgB,CAAC,KAAK,CAAC,GAAG,KAAK,WAAW;CAC1E;CAEA,UAAU,KAAa,SAAiB,QAAQ,OAAa;EAC3D,IAAI,KAAK,QAAQ,IAAI,GAAG,GAAG;EAC3B,KAAK,QAAQ,IAAI,GAAG;EACpB,IAAI,OAAO;GACT,QAAQ,MAAM,aAAa,SAAS;GACpC;EACF;EACA,KAAK,MAAM,OAAO;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"project-boards.js","names":[],"sources":["../../src/boards/project-boards.ts"],"sourcesContent":["import type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type {\n BoardMigrationContext,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n} from '../storage/domains/boards/base.js';\nimport { DEFAULT_INTAKE_ROUTE_ACTOR, readStoredBoard } from '../storage/domains/boards/base.js';\nimport type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport type { ReviewBoardInUse } from '../storage/domains/work-items/legacy-review.js';\nimport { boardRegistryOf, createBoardRegistry, defaultBoards } from './registry.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { boardForWorkItem } from './semantics.js';\nimport { boardDefinitionOf, compileStoredBoard, mergeCodeBehaviour } from './stored-board.js';\nimport { BOARD_MIGRATIONS } from './work-migrations.js';\nimport { workSeedWithTriage } from './work-seeds.js';\nimport { workBoard } from './work.js';\n\nconst DEFAULT_RECHECK_MS = 1000;\nconst PRELOAD_CONCURRENCY = 8;\n/** The phases every release seeded the Review board with; only runners and tools changed between them. */\nconst REVIEW_SEED_PHASES = boardDefinitionOf(reviewBoard).phases.map(({ key, name, kind }) => ({ key, name, kind }));\n\n/**\n * Whether `row` is the Review board as Factory seeded it: written once by Factory, never\n * revised, and shaped like the seed. The actor alone is not proof, as any caller can pass it.\n */\nexport function isUntouchedReviewSeed(row: StoredBoardRecord): boolean {\n if (row.revision !== 1 || row.createdBy !== DEFAULT_INTAKE_ROUTE_ACTOR) return false;\n if (row.updatedBy !== DEFAULT_INTAKE_ROUTE_ACTOR || row.name !== reviewBoard.name) return false;\n const phases = [...row.phases].sort((a, b) => a.position - b.position);\n return (\n phases.length === REVIEW_SEED_PHASES.length &&\n phases.every(\n (phase, index) =>\n phase.key === REVIEW_SEED_PHASES[index]!.key &&\n phase.name === REVIEW_SEED_PHASES[index]!.name &&\n phase.kind === REVIEW_SEED_PHASES[index]!.kind,\n )\n );\n}\n\n/**\n * Whether a project has a board of its own under `review`: a stored row other than the seed an\n * earlier release left behind. Cards stored on it are its own; anywhere else they are the retired\n * Review board's. An app that defines the board owns it in a project from when its row is stored\n * there. Without stored boards (`stored: false`) the app's boards are served as they are.\n */\nexport function ownReviewBoard(codeRegistry: BoardRegistry, { stored = true } = {}): ReviewBoardInUse {\n if (!stored) return async () => codeRegistry.has(LEGACY_REVIEW_BOARD);\n return async (ops, scope) => {\n const row = await readStoredBoard(ops, scope, LEGACY_REVIEW_BOARD);\n return row !== null && !isUntouchedReviewSeed(row);\n };\n}\n\nconst SNAPSHOT_ATTEMPTS = 3;\n\n/**\n * The creator Factory records on the Work board it stores in a project as the project is\n * created: that board is today's Work, and reset gives it back. Any other Work row Factory stored\n * is the one with Triage. Only Factory writes this id; a person's writes carry their user id.\n */\nexport const NEW_PROJECT_SEED_ACTOR = 'factory:new-project';\n\n/** Where a board in a project's catalog came from. */\nexport type BoardSourceKind = 'builtin' | 'app' | 'stored';\n\nexport interface StoredBoardDetails {\n source: BoardSourceKind;\n /** Stored boards, the built-in Work board and app boards can all be edited; the retired Review board can't. */\n editable: boolean;\n problems: string[];\n}\n\n/** A project's boards: the code boards plus its stored boards, and what to report about each board. */\nexport interface ProjectBoards {\n readonly registry: BoardRegistry;\n readonly details: ReadonlyMap<string, StoredBoardDetails>;\n /** Problems with stored boards that are left out of the registry. */\n readonly problems: readonly string[];\n}\n\nconst PROJECT_BOARD_SOURCE = Symbol('ProjectBoardSource');\n\n/**\n * Serves each project its boards. `load` is the async entry point that brings a project's\n * boards up to date; `forProject` is the sync read for code that already loaded the project.\n */\nexport interface ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE]: true;\n /** The code boards: built-in and app boards, served to every project as code built them. */\n readonly codeRegistry: BoardRegistry;\n load(scope: StoredBoardScope): Promise<BoardRegistry>;\n forProject(scope: StoredBoardScope): BoardRegistry;\n describe?(scope: StoredBoardScope): Promise<ProjectBoards>;\n}\n\n/** Accepts either a fixed registry (tests, standalone services) or a per-project source. */\nexport function toBoardSource(boards: BoardRegistry | ProjectBoardSource | undefined): ProjectBoardSource {\n const source = boards ?? createBoardRegistry();\n if (isBoardSource(source)) return source;\n return {\n [PROJECT_BOARD_SOURCE]: true,\n codeRegistry: source,\n load: async () => source,\n forProject: () => source,\n };\n}\n\nfunction isBoardSource(boards: BoardRegistry | ProjectBoardSource): boards is ProjectBoardSource {\n return PROJECT_BOARD_SOURCE in boards;\n}\n\ninterface CacheEntry {\n boards: ProjectBoards;\n version: string | null;\n reviewInUse: boolean;\n checkedAt: number;\n}\n\nexport interface ProjectBoardCacheOptions {\n /** The code boards, built-ins included when enabled. */\n codeRegistry: BoardRegistry;\n storage: StoredBoardsStorage;\n /**\n * Lists every project, to warm them at boot, and reads the retired switches the board\n * migrations carry into each project's boards.\n */\n projects?: {\n listAll(): Promise<readonly { orgId: string; id: string }[]>;\n retiredAutomationSettings?(\n project: { orgId: string; id: string },\n ops: FactoryStorageOps,\n ): Promise<RetiredAutomationSettings | null>;\n };\n /** The phases cards sit in on each of the project's boards, which a board migration must not remove. */\n occupiedPhases?: (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ) => Promise<ReadonlyMap<string, ReadonlySet<string>> | null>;\n codeSkills?: readonly InlineSkill[];\n /**\n * Whether the project still uses the retired Review board (an open card is stored on it). Such\n * a project is served Review alongside its boards; without this, no project is.\n */\n reviewBoardInUse?: (scope: StoredBoardScope) => Promise<boolean>;\n /**\n * Stores the Work placement of every card the retired Review board left on `review`, through\n * `ops`. Run in the transaction that stores an app's board under that key in a project.\n */\n releaseReviewCards?: (ops: FactoryStorageOps, scope: StoredBoardScope) => Promise<void>;\n recheckMs?: number;\n now?: () => number;\n warn?: (message: string) => void;\n}\n\nfunction scopeKey(scope: StoredBoardScope): string {\n return `${scope.orgId}\\0${scope.factoryProjectId}`;\n}\n\n/**\n * Reads the phases cards sit in on each of a project's boards, for `occupiedPhases`. Null while\n * cards from before the work-item split are still being copied: `listWith` can't see those yet.\n */\nexport function occupiedPhasesOf(workItems: Pick<WorkItemsStorage, 'listWith' | 'legacyBackfillPending'>) {\n return async (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ): Promise<ReadonlyMap<string, ReadonlySet<string>> | null> => {\n if (workItems.legacyBackfillPending) return null;\n const occupied = new Map<string, Set<string>>();\n for (const item of await workItems.listWith(ops, scope)) {\n const board = boardForWorkItem(item);\n const phases = occupied.get(board) ?? new Set<string>();\n for (const stage of item.stages) phases.add(stage);\n occupied.set(board, phases);\n }\n return occupied;\n };\n}\n\n/**\n * The per-project board cache. A project's boards are its rows: the Work and app boards Factory\n * stored in it, in code order, then the others. A Work or app board's row runs with the code\n * behaviour of its board and phase keys that still fits it ({@link mergeCodeBehaviour}). A project\n * that still uses the retired Review board is served it from code, never stored, until its last\n * open card there finishes. The first load of each project in a process stores the\n * boards Factory hasn't stored in it yet, each once ({@link StoredBoardsStorage.seedBoards}); a\n * release never rewrites them. Loads recheck the project's board version at most every\n * `recheckMs` and recompile when it changed, so stored edits on other replicas arrive within that\n * delay.\n */\nexport class ProjectBoardCache implements ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE] = true;\n readonly codeRegistry: BoardRegistry;\n readonly #codeDetails: ReadonlyMap<string, StoredBoardDetails>;\n readonly #storage: StoredBoardsStorage;\n readonly #projects: ProjectBoardCacheOptions['projects'];\n readonly #recheckMs: number;\n readonly #now: () => number;\n readonly #warn: (message: string) => void;\n readonly #entries = new Map<string, CacheEntry>();\n readonly #loading = new Map<string, Promise<ProjectBoards>>();\n readonly #generations = new Map<string, number>();\n readonly #warned = new Set<string>();\n readonly #seeded = new Set<string>();\n readonly #codeSkills: readonly InlineSkill[];\n readonly #seeds: ReadonlyMap<string, StoredBoardInput>;\n /** Boards the app upserted for every project, which a project with no boards gets before Factory's. */\n readonly #appBoards = new Map<string, StoredBoardInput>();\n readonly #reviewBoardInUse: ProjectBoardCacheOptions['reviewBoardInUse'];\n readonly #releaseReviewCards: ProjectBoardCacheOptions['releaseReviewCards'];\n readonly #occupiedPhases: ProjectBoardCacheOptions['occupiedPhases'];\n\n constructor(options: ProjectBoardCacheOptions) {\n this.codeRegistry = options.codeRegistry;\n this.#storage = options.storage;\n this.#reviewBoardInUse = options.reviewBoardInUse;\n this.#releaseReviewCards = options.releaseReviewCards;\n this.#occupiedPhases = options.occupiedPhases;\n this.#projects = options.projects;\n this.#codeSkills = options.codeSkills ?? [];\n this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS;\n this.#now = options.now ?? Date.now;\n this.#warn = options.warn ?? (message => console.warn(`[factory] ${message}`));\n this.#codeDetails = new Map(\n [...this.codeRegistry.values()].map(board => [\n board.id,\n {\n source: defaultBoards.includes(board) ? 'builtin' : 'app',\n editable: true,\n problems: this.#skillProblems(board),\n },\n ]),\n );\n this.#seeds = new Map([...this.codeRegistry.values()].map(board => [board.id, boardDefinitionOf(board)]));\n }\n\n /**\n * The boards Factory stores once in a project it didn't create: Work as it was with Triage, so a\n * project from an older release keeps the phases its cards know, then the app boards, in order.\n */\n seeds(): StoredBoardInput[] {\n return [...this.#seeds.values()].map(seed => (this.#isFactoryWork(seed.key) ? workSeedWithTriage() : seed));\n }\n\n /**\n * The definition reset restores for `key`; undefined when there is none. A board the app upserted\n * for every project comes first, so reset never swaps an app's Work for Factory's. Factory's Work\n * is today's Work for a project Factory created with it (`row` created by\n * {@link NEW_PROJECT_SEED_ACTOR}), and Work with Triage for every other project.\n */\n seedFor(key: string, row?: Pick<StoredBoardRecord, 'createdBy'>): StoredBoardInput | undefined {\n const app = this.#appBoards.get(key);\n if (app) return app;\n const seed = this.#seeds.get(key);\n if (!seed || !this.#isFactoryWork(key) || row?.createdBy === NEW_PROJECT_SEED_ACTOR) return seed;\n return workSeedWithTriage();\n }\n\n /**\n * Stores Factory's boards in a project that was just created, with today's Work (no Triage).\n * Only the project-creation route calls this; every other load stores {@link seeds}.\n */\n async seedNewProject(scope: StoredBoardScope): Promise<ProjectBoards> {\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, [...this.#seeds.values()], {\n actor: NEW_PROJECT_SEED_ACTOR,\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n });\n }\n return this.describe(scope);\n }\n\n /**\n * Remembers a board the app upserted for every project, so a project that has no boards yet (one\n * created later, or one that never loaded) gets it on its first load before Factory's own boards;\n * having it, the project then gets no Work from Factory. Kept for this process: an app upserts\n * its boards at every startup.\n */\n rememberBoardForAllProjects(board: StoredBoardInput): void {\n this.#appBoards.set(board.key, board);\n }\n\n /** Whether `key` is Factory's own Work board, rather than none or an app board under its key. */\n #isFactoryWork(key: string): boolean {\n return key === workBoard.id && this.codeRegistry.get(key) === workBoard;\n }\n\n /** Work is stored only into a project with no boards: one that has any keeps what it has. */\n #onlyIntoEmpty(): string[] {\n return this.#isFactoryWork(workBoard.id) ? [workBoard.id] : [];\n }\n\n async load(scope: StoredBoardScope): Promise<BoardRegistry> {\n return (await this.describe(scope)).registry;\n }\n\n /** The project's boards with their source, whether they can be edited, and problems, brought up to date. */\n async describe(scope: StoredBoardScope): Promise<ProjectBoards> {\n const key = scopeKey(scope);\n const entry = this.#entries.get(key);\n if (entry && this.#now() - entry.checkedAt < this.#recheckMs) return entry.boards;\n const inFlight = this.#loading.get(key);\n if (inFlight) return inFlight;\n const generation = this.#generations.get(key) ?? 0;\n const loading = this.#refresh(scope, key, generation).finally(() => {\n if (this.#loading.get(key) === loading) this.#loading.delete(key);\n });\n this.#loading.set(key, loading);\n return loading;\n }\n\n /**\n * The project's loaded boards. Before the project's first load (boot preload not finished, or a\n * project created on another replica) this is the code boards alone, without the project's\n * stored boards.\n */\n forProject(scope: StoredBoardScope): BoardRegistry {\n // Storage asks about a row it is about to insert by its board and stages alone, with no\n // project to look up; the code boards answer for it.\n if (!scope.orgId || !scope.factoryProjectId) return this.codeRegistry;\n const entry = this.#entries.get(scopeKey(scope));\n if (entry) return entry.boards.registry;\n // Warm the project so the next sync read sees its stored boards.\n void this.load(scope).catch(() => {});\n this.#warnOnce(\n `cold:${scopeKey(scope)}`,\n `Boards for project ${scope.factoryProjectId} were read before they were loaded; using the code boards.`,\n true,\n );\n return this.codeRegistry;\n }\n\n /** The code skills stored runners may name. */\n get codeSkills(): readonly InlineSkill[] {\n return this.#codeSkills;\n }\n\n /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */\n invalidate(scope: StoredBoardScope): void {\n const key = scopeKey(scope);\n this.#generations.set(key, (this.#generations.get(key) ?? 0) + 1);\n this.#loading.delete(key);\n const entry = this.#entries.get(key);\n if (entry) entry.checkedAt = Number.NEGATIVE_INFINITY;\n }\n\n /** Loads every project, a few at a time, so sync reads find them warm and each has its boards stored. */\n async preload(): Promise<void> {\n const projects = (await this.#projects?.listAll()) ?? [];\n let next = 0;\n const worker = async () => {\n while (next < projects.length) {\n const project = projects[next++]!;\n // A project that fails to load here loads on first use; the others still load now.\n await this.load({ orgId: project.orgId, factoryProjectId: project.id }).catch(error =>\n this.#warn(\n `Boards for project ${project.id} did not load at startup; they load on first use: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(PRELOAD_CONCURRENCY, projects.length) }, worker));\n }\n\n async #refresh(scope: StoredBoardScope, key: string, generation: number): Promise<ProjectBoards> {\n await this.#seed(scope, key);\n const current = this.#entries.get(key);\n const version = await this.#storage.readVersion(scope);\n const reviewInUse = (await this.#reviewBoardInUse?.(scope)) ?? false;\n if (current && current.version === version && current.reviewInUse === reviewInUse) {\n if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now();\n return current.boards;\n }\n const snapshot = await this.#consistentSnapshot(scope);\n const boards = this.#compile(scope, snapshot.boards, reviewInUse);\n if ((this.#generations.get(key) ?? 0) === generation) {\n this.#entries.set(key, { boards, version: snapshot.version, reviewInUse, checkedAt: this.#now() });\n }\n return boards;\n }\n\n /** Boards and phases are read in two statements; reread when a write landed between them. */\n async #consistentSnapshot(scope: StoredBoardScope) {\n let snapshot = await this.#storage.snapshot(scope);\n for (let attempt = 1; attempt < SNAPSHOT_ATTEMPTS; attempt++) {\n if ((await this.#storage.readVersion(scope)) === snapshot.version) break;\n snapshot = await this.#storage.snapshot(scope);\n }\n return snapshot;\n }\n\n /**\n * Stores the boards Factory hasn't stored in the project yet, once per process. A failure is\n * logged and retried on the next load; the boards it didn't store aren't served meanwhile.\n */\n async #seed(scope: StoredBoardScope, key: string): Promise<void> {\n if (this.#seeded.has(key)) return;\n try {\n // Read before seeding records Work's key: a project whose list lacked it has no Work of Factory's.\n const seeded = await this.#storage.seededBoardKeys(scope);\n const release = this.#releaseReviewCards;\n const review = this.#seeds.get(LEGACY_REVIEW_BOARD);\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, this.seeds(), {\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n // An app's board under `review` starts without the cards the retired Review board left there.\n before: async (ops, board) => {\n if (board === LEGACY_REVIEW_BOARD) await release?.(ops, scope);\n },\n });\n }\n // The row an earlier release seeded for the retired board becomes the app's board.\n if (review) {\n await this.#storage.adoptSeed(scope, review, {\n when: isUntouchedReviewSeed,\n before: ops => release?.(ops, scope) ?? Promise.resolve(),\n });\n }\n await this.#migrate(scope, seeded);\n this.#seeded.add(key);\n } catch (error) {\n this.#warnOnce(\n `seed:${key}`,\n `Boards for project ${scope.factoryProjectId} could not be stored; Factory stores them on the next load: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Runs the board migrations of the boards Factory stores here that the project hasn't had yet. */\n async #migrate(scope: StoredBoardScope, seededBefore: readonly string[] | null): Promise<void> {\n // A migration of one board rewrites Factory's own board; an app board under the same key keeps\n // its settings. One that carries a project setting into every board rewrites them all. A board\n // Factory never stored in the project (an app wrote the row first), or one the app upserts for\n // every project, is an app's: its one-board migrations are recorded as applied without running.\n const migrations = BOARD_MIGRATIONS.filter(migration => {\n if (migration.boardKey === null) return true;\n const code = this.codeRegistry.get(migration.boardKey);\n return code !== undefined && defaultBoards.includes(code);\n }).map(migration =>\n migration.boardKey !== null &&\n (this.#appBoards.has(migration.boardKey) || (seededBefore !== null && !seededBefore.includes(migration.boardKey)))\n ? { ...migration, migrate: () => undefined }\n : migration,\n );\n const changed = await this.#storage.applyBoardMigrations(scope, migrations, ops =>\n this.#migrationContext(scope, ops),\n );\n if (changed.length === 0) return;\n const filled = changed.map(({ boardKey, filled }) => `${boardKey}: ${filled.join(', ')}`).join('; ');\n console.info(`[factory] Migrated the boards of project ${scope.factoryProjectId} (${filled}).`);\n }\n\n /** Read through the migration transaction's `ops`, so card moves can't slip in unseen on LibSQL. */\n async #migrationContext(scope: StoredBoardScope, ops: FactoryStorageOps): Promise<BoardMigrationContext> {\n const retiredSettings =\n (await this.#projects?.retiredAutomationSettings?.({ orgId: scope.orgId, id: scope.factoryProjectId }, ops)) ??\n null;\n return {\n retiredSettings,\n occupiedPhases: retiredSettings && this.#occupiedPhases ? await this.#occupiedPhases(scope, ops) : null,\n codePhases: boardKey => {\n const code = this.codeRegistry.get(boardKey);\n return code ? new Set(Object.keys(code.phases)) : undefined;\n },\n warn: message =>\n this.#warnOnce(`migration:${scopeKey(scope)}:${message}`, `${message} (project ${scope.factoryProjectId})`),\n };\n }\n\n #compile(scope: StoredBoardScope, rows: readonly StoredBoardRecord[], reviewInUse: boolean): ProjectBoards {\n const byKey = new Map(rows.map(row => [row.key, row]));\n const details = new Map(this.#codeDetails);\n const problems: string[] = [];\n const report = (row: StoredBoardRecord, messages: readonly string[]) => {\n problems.push(...messages);\n for (const message of messages) {\n this.#warnOnce(\n `row:${scopeKey(scope)}:${row.key}:${row.revision}:${message}`,\n `${message} (project ${scope.factoryProjectId})`,\n );\n }\n };\n const boards: InstalledBoard[] = [];\n // Work and app boards keep their code order, each served from its row.\n for (const code of this.codeRegistry.values()) {\n const row = byKey.get(code.id);\n // Still the retired board's seed: the app's board is served once its row replaces it.\n if (row && code.id === LEGACY_REVIEW_BOARD && isUntouchedReviewSeed(row)) {\n details.delete(code.id);\n continue;\n }\n if (!row) {\n details.delete(code.id);\n // Stored once and deleted since, or not stored because storing failed.\n if (!this.#seeded.has(scopeKey(scope))) {\n problems.push(`Board \"${code.id}\" isn't stored in this project yet; Factory stores it on the next load.`);\n }\n continue;\n }\n let merged: ReturnType<typeof mergeCodeBehaviour>;\n try {\n merged = mergeCodeBehaviour(row, code);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n report(row, merged.problems);\n details.set(code.id, {\n ...details.get(code.id)!,\n problems: [...merged.problems, ...this.#skillProblems(merged.board)],\n });\n boards.push(merged.board);\n }\n // A board of the project's own under the retired Review board's key is served like any other.\n const reviewRow = byKey.get(LEGACY_REVIEW_BOARD);\n const ownsReview = reviewRow !== undefined && !isUntouchedReviewSeed(reviewRow);\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse && !ownsReview) {\n boards.push(reviewBoard);\n details.set(reviewBoard.id, { source: 'builtin', editable: false, problems: [] });\n }\n for (const row of rows) {\n if (this.codeRegistry.has(row.key)) continue;\n // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // it is not a board the project made, so it is not served.\n if (row.key === LEGACY_REVIEW_BOARD && !ownsReview) continue;\n let board: InstalledBoard;\n try {\n board = compileStoredBoard(row);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n boards.push(board);\n details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board) });\n }\n return {\n registry: boardRegistryOf(boards),\n details,\n problems,\n };\n }\n\n #skillProblems(board: InstalledBoard): string[] {\n return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills);\n }\n\n #warnOnce(key: string, message: string, debug = false): void {\n if (this.#warned.has(key)) return;\n this.#warned.add(key);\n if (debug) {\n console.debug(`[factory] ${message}`);\n return;\n }\n this.#warn(message);\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAgB,sBAAsB,KAAiC;CACrE,IAAI,IAAI,aAAa,KAAK,IAAI,cAAA,WAA0C,OAAO;CAC/E,IAAI,IAAI,cAAA,aAA4C,IAAI,SAAS,YAAY,MAAM,OAAO;CAC1F,MAAM,SAAS,CAAC,GAAG,IAAI,MAAM,CAAC,C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,GAAG,KAAK,WAAW;CAC1E;CAEA,UAAU,KAAa,SAAiB,QAAQ,OAAa;EAC3D,IAAI,KAAK,QAAQ,IAAI,GAAG,GAAG;EAC3B,KAAK,QAAQ,IAAI,GAAG;EACpB,IAAI,OAAO;GACT,QAAQ,MAAM,aAAa,SAAS;GACpC;EACF;EACA,KAAK,MAAM,OAAO;CACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/boards/registry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/boards/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAGzD,MAAM,MAAM,cAAc,GAAG,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7D,MAAM,WAAW,aAAc,SAAQ,QAAQ,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAAC;IAC5C,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,IAAI,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC;IACtC,OAAO,IAAI,WAAW,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;CAClD;AAED,eAAO,MAAM,aAAa,EAAiC,SAAS,cAAc,EAAE,CAAC;AAErF;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,SAAS,cAAc,EAAE,CAAA;CAAO,GAAG,aAAa,CAYvG;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,aAAa,CAmBhF"}
|
package/dist/boards/registry.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { LEGACY_REVIEW_BOARD } from "../storage/domains/work-items/legacy-review.js";
|
|
2
|
-
import { reviewBoard } from "./review.js";
|
|
3
1
|
import { workBoard } from "./work.js";
|
|
4
2
|
// src/boards/registry.ts
|
|
5
3
|
const defaultBoards = Object.freeze([workBoard]);
|
|
@@ -20,7 +18,6 @@ function createBoardRegistry(options = {}) {
|
|
|
20
18
|
function boardRegistryOf(boards) {
|
|
21
19
|
const registry = /* @__PURE__ */ new Map();
|
|
22
20
|
for (const board of boards) {
|
|
23
|
-
if (board.id === "review" && board !== reviewBoard) throw new Error(`MastraFactory: board id '${LEGACY_REVIEW_BOARD}' is reserved for the retired Review board.`);
|
|
24
21
|
if (registry.has(board.id)) throw new Error(`MastraFactory: duplicate board id '${board.id}' in 'boards'.`);
|
|
25
22
|
registry.set(board.id, board);
|
|
26
23
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","names":[],"sources":["../../src/boards/registry.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"registry.js","names":[],"sources":["../../src/boards/registry.ts"],"sourcesContent":["import type { BoardDefinition } from './define-board.js';\nimport { workBoard } from './work.js';\n\nexport type InstalledBoard = BoardDefinition<string, string>;\nexport interface BoardRegistry extends Iterable<[string, InstalledBoard]> {\n readonly size: number;\n get(id: string): InstalledBoard | undefined;\n has(id: string): boolean;\n keys(): MapIterator<string>;\n values(): MapIterator<InstalledBoard>;\n entries(): MapIterator<[string, InstalledBoard]>;\n}\n\nexport const defaultBoards = Object.freeze([workBoard]) as readonly InstalledBoard[];\n\n/**\n * Factory's boards: its Work board, then `boards`. Work is always installed; to run another Work,\n * store it under the `work` key with `factory.upsertBoard()`. The exported `workBoard` itself is\n * accepted in `boards` and installed once.\n */\nexport function createBoardRegistry(options: { boards?: readonly InstalledBoard[] } = {}): BoardRegistry {\n const boards = (options.boards ?? []).filter(board => !defaultBoards.includes(board));\n for (const board of boards) {\n const builtIn = defaultBoards.find(candidate => candidate.id === board.id);\n if (builtIn) {\n throw new Error(\n `MastraFactory: board id '${board.id}' is Factory's ${builtIn.name} board, which every project has. ` +\n `To run your own, store it under '${board.id}' with factory.upsertBoard(board, { projects: 'all' }).`,\n );\n }\n }\n return boardRegistryOf([...defaultBoards, ...boards]);\n}\n\n/** A registry of exactly `boards`, in order, such as the boards a project stored. */\nexport function boardRegistryOf(boards: readonly InstalledBoard[]): BoardRegistry {\n const registry = new Map<string, InstalledBoard>();\n\n for (const board of boards) {\n if (registry.has(board.id)) {\n throw new Error(`MastraFactory: duplicate board id '${board.id}' in 'boards'.`);\n }\n registry.set(board.id, board);\n }\n\n return Object.freeze({\n size: registry.size,\n get: registry.get.bind(registry),\n has: registry.has.bind(registry),\n keys: registry.keys.bind(registry),\n values: registry.values.bind(registry),\n entries: registry.entries.bind(registry),\n [Symbol.iterator]: registry[Symbol.iterator].bind(registry),\n });\n}\n"],"mappings":";;AAaA,MAAa,gBAAgB,OAAO,OAAO,CAAC,SAAS,CAAC;;;;;;AAOtD,SAAgB,oBAAoB,UAAkD,CAAC,GAAkB;CACvG,MAAM,UAAU,QAAQ,UAAU,CAAC,EAAA,CAAG,QAAO,UAAS,CAAC,cAAc,SAAS,KAAK,CAAC;CACpF,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,UAAU,cAAc,MAAK,cAAa,UAAU,OAAO,MAAM,EAAE;EACzE,IAAI,SACF,MAAM,IAAI,MACR,4BAA4B,MAAM,GAAG,iBAAiB,QAAQ,KAAK,oEAC7B,MAAM,GAAG,wDACjD;CAEJ;CACA,OAAO,gBAAgB,CAAC,GAAG,eAAe,GAAG,MAAM,CAAC;AACtD;;AAGA,SAAgB,gBAAgB,QAAkD;CAChF,MAAM,2BAAW,IAAI,IAA4B;CAEjD,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,SAAS,IAAI,MAAM,EAAE,GACvB,MAAM,IAAI,MAAM,sCAAsC,MAAM,GAAG,eAAe;EAEhF,SAAS,IAAI,MAAM,IAAI,KAAK;CAC9B;CAEA,OAAO,OAAO,OAAO;EACnB,MAAM,SAAS;EACf,KAAK,SAAS,IAAI,KAAK,QAAQ;EAC/B,KAAK,SAAS,IAAI,KAAK,QAAQ;EAC/B,MAAM,SAAS,KAAK,KAAK,QAAQ;EACjC,QAAQ,SAAS,OAAO,KAAK,QAAQ;EACrC,SAAS,SAAS,QAAQ,KAAK,QAAQ;GACtC,OAAO,WAAW,SAAS,OAAO,SAAS,CAAC,KAAK,QAAQ;CAC5D,CAAC;AACH"}
|
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"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AED,2FAA2F;IAC3F,IAAI,iBAAiB,IAAI,OAAO,CAE/B;IAED,gGAAgG;IAC1F,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC,CAIvC;IAED;;;;;OAKG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAsBrF;IAED;;;;OAIG;IACH,QAAQ,CAAC,gBAAgB,UAAW,mBAAmB,KAAG,IAAI,CAa5D;IAEF;;;;;;;;;OASG;IACH,QAAQ,CAAC,kBAAkB,cAAe,MAAM,KAAG,IAAI,CAmBrD;IAEF;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,EAAE,qBAAqB,CAqCnC;CACH"}
|
|
@@ -3,23 +3,38 @@ import { probeSchedulesAvailable } from "./build-schedule.js";
|
|
|
3
3
|
import { ENVIRONMENT_BUILD_WORKFLOW_ID, createEnvironmentBuildWorkflow } from "./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,QAAQ,uBACP,MAAM,wBAAwB,eAAe,SAAS,WAAW;EACpE,OAAO;GACL,MACE,MAAM,+BACJ,SACA,aACA,OACA,cAAc,gBACd,KAAK,MAAM,WACb,EAAA,CACA;GACF,UAAU,YAAY;EACxB;CACF;;;;;;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K;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,MAAo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C,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
|
|
7
|
-
* hand-off
|
|
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;AAGH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"build-workflow.d.ts","sourceRoot":"","sources":["../../src/environment/build-workflow.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAWxB,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEhF,eAAO,MAAM,6BAA6B,8BAA8B,CAAC;AACzE,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAE5C,eAAO,MAAM,2BAA2B;;;;;;;;iBAGtC,CAAC;AAWH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;iBAOvC,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
|
|
13
|
-
* hand-off
|
|
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
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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:
|
|
123
|
-
reason:
|
|
111
|
+
status: build.status,
|
|
112
|
+
...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
|
|
124
113
|
};
|
|
125
|
-
await sleep(pollMs);
|
|
126
114
|
}
|
|
127
|
-
|
|
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,
|
|
151
|
+
export { DEFAULT_BUILD_POLL_MS, ENVIRONMENT_BUILD_WORKFLOW_ID, createEnvironmentBuildWorkflow, environmentBuildInputSchema, environmentBuildOutputSchema };
|
|
148
152
|
|
|
149
153
|
//# sourceMappingURL=build-workflow.js.map
|