@mastra/factory 0.28.0-alpha.9 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -42
- 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/capabilities/version-control.d.ts +6 -1
- package/dist/capabilities/version-control.d.ts.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-schedule.js +1 -1
- package/dist/environment/build-schedule.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 +22 -7
- package/dist/environment/build.d.ts.map +1 -1
- package/dist/environment/build.js +73 -15
- package/dist/environment/build.js.map +1 -1
- package/dist/environment/heads.d.ts +1 -1
- package/dist/environment/heads.d.ts.map +1 -1
- package/dist/environment/heads.js +4 -1
- package/dist/environment/heads.js.map +1 -1
- package/dist/environment/repository-access.d.ts +13 -0
- package/dist/environment/repository-access.d.ts.map +1 -0
- package/dist/environment/repository-access.js +55 -0
- package/dist/environment/repository-access.js.map +1 -0
- package/dist/factory.d.ts +5 -2
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +32 -25
- 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/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +137 -105
- 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/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +7 -4
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +3 -5
- package/dist/mcp/routes.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +17 -1
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +54 -7
- 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 +102 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +96 -6
- 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-selection.d.ts +18 -0
- package/dist/routes/work-item-selection.d.ts.map +1 -0
- package/dist/routes/work-item-selection.js +61 -0
- package/dist/routes/work-item-selection.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 +162 -15
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +4 -0
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +84 -16
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +2 -0
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +18 -4
- package/dist/rules/processor.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/session/live-sessions.d.ts +1 -1
- package/dist/session/live-sessions.d.ts.map +1 -1
- package/dist/session/live-sessions.js +12 -2
- package/dist/session/live-sessions.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 +47 -6
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +161 -17
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +1 -0
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +32 -8
- package/dist/storage/domains/work-items/cards.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 +62 -3
- package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +46 -18
- package/dist/storage/domains/work-items/work-item-schema.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/dist/work-items/board-check.d.ts +11 -0
- package/dist/work-items/board-check.d.ts.map +1 -0
- package/dist/work-items/board-check.js +20 -0
- package/dist/work-items/board-check.js.map +1 -0
- package/dist/work-items/related-cards.d.ts +21 -0
- package/dist/work-items/related-cards.d.ts.map +1 -0
- package/dist/work-items/related-cards.js +45 -0
- package/dist/work-items/related-cards.js.map +1 -0
- package/dist/work-items/split-migration.d.ts.map +1 -1
- package/dist/work-items/split-migration.js +6 -2
- package/dist/work-items/split-migration.js.map +1 -1
- package/dist/workspace.d.ts +0 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +49 -32
- package/dist/workspace.js.map +1 -1
- package/factory-skills/factory-build/SKILL.md +1 -1
- package/factory-skills/factory-self-review/SKILL.md +1 -1
- package/factory-skills/factory-triage/SKILL.md +4 -4
- package/package.json +16 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_ROUTE_EVENTS, routeEventsProblem } from '../../../boards/board-events.js';\nimport type { StatusEvent } from '../../../boards/board-events.js';\nimport type { FactoryPhaseTool } from '../../../boards/define-board.js';\nimport { DEFAULT_INTAKE_ROUTES } from '../../../boards/work-routes.js';\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport type { RetiredAutomationSettings } from '../projects/base.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n /** The objective the phase's runs pursue as a goal. */\n goal?: { objective: string; maxRuns?: number };\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n /** Factory tools the phase grants the session working the card there. */\n tools?: FactoryPhaseTool[] | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\n/** What a board migration may know about the project besides the board it rewrites. */\nexport interface BoardMigrationContext {\n /** The project switches the boards replaced, as the project last stored them; null when unknown. */\n readonly retiredSettings: RetiredAutomationSettings | null;\n /** The phases of each board that cards sit in, by board key; null when the cards can't be read. */\n readonly occupiedPhases: ReadonlyMap<string, ReadonlySet<string>> | null;\n /**\n * The phases the code board under this key declares; undefined for a board only the project\n * stores. A row that drops one runs without its code rules (`mergeCodeBehaviour`).\n */\n codePhases(boardKey: string): ReadonlySet<string> | undefined;\n /** Tells the operator about a board a migration left as it is. */\n warn(message: string): void;\n}\n\n/** A one-time rewrite of a stored board, keyed so each project gets it once. */\nexport interface StoredBoardMigration {\n key: string;\n /** The board it rewrites; `null` rewrites every board the project stores. */\n boardKey: string | null;\n /** The board to write instead, with what changed; undefined leaves it as it is. */\n migrate(\n board: StoredBoardRecord,\n context: BoardMigrationContext,\n ): { board: Omit<StoredBoardInput, 'key'>; filled: string[] } | undefined;\n}\n\nconst EMPTY_MIGRATION_CONTEXT: BoardMigrationContext = {\n retiredSettings: null,\n occupiedPhases: new Map(),\n codePhases: () => undefined,\n warn: () => {},\n};\n\nexport interface AppliedBoardMigration {\n key: string;\n boardKey: string;\n filled: string[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /**\n * Unset lands the card in the board's first phase. On a route that joins a closed issue's\n * card, the phase that card moves to when its board allows it; unset leaves it where it is.\n */\n phaseKey?: string | null;\n /**\n * Files a pull request on the card of the issue it closes, which must be on `boardKey`, as one\n * more source instead of a card of its own. The route doesn't match any other arrival.\n */\n joinClosedIssue?: boolean;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n /** The status events the route handles; unset handles new cards (`work_item.created`). */\n on?: StatusEvent[];\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null; joinClosedIssue: boolean };\n on: StatusEvent[];\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit'\n | 'invalid_intake_route';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n// Work's routes are its seed data, kept with the board they target.\nexport {\n DEFAULT_INTAKE_ROUTE,\n PULL_REQUEST_INTAKE_ROUTE,\n CLOSED_COMPLETED_ROUTE,\n CLOSED_CANCELED_ROUTE,\n REOPENED_ROUTE,\n PULL_REQUEST_MERGED_ROUTE,\n PULL_REQUEST_CLOSED_ROUTE,\n PULL_REQUEST_CLOSED_ISSUE_ROUTE,\n PULL_REQUEST_UPDATED_ROUTE,\n PULL_REQUEST_REVIEW_REQUESTED_ROUTE,\n CLOSES_ISSUE_INTAKE_ROUTE,\n CATCH_ALL_INTAKE_ROUTE,\n DEFAULT_INTAKE_ROUTES,\n} from '../../../boards/work-routes.js';\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface VersionRow extends Record<string, unknown> {\n version: string;\n /** Keys of the boards Factory stored in the project; null on rows written before the list. */\n seeded_boards: string[] | null;\n /** Keys of the board migrations applied to the project; null before the first one. */\n applied_migrations: string[] | null;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n /** Null on rows written before routes named events: they place new cards. */\n on_events: StatusEvent[] | null;\n join_closed_issue: boolean | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\nconst MIGRATION_ACTOR = 'factory';\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n tools: row.tools ?? null,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n async get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n const row = await this.ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await this.ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n }\n\n /** Creates a board through the API. */\n async create(scope: StoredBoardScope, input: StoredBoardInput, actor: string): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n if (rows.some(row => row.board_key === input.key)) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /**\n * Stores Factory's boards (Work, app and seed boards) in the project, each key once: a key the\n * project has had before is skipped even if its board was deleted since, and a stored board is\n * never rewritten. A project stored before the list was kept counts the boards it has as stored.\n * Reads one row when every key was stored before. Returns the keys it inserted.\n *\n * A key in `onlyIntoEmpty` is inserted only into a project that has no boards at all: one that\n * already has any board, such as one an app stored under that key, is left as it is. The key\n * is still recorded as stored, so it never goes in later, even after the project's boards are\n * deleted: that project chose its boards, and Work is never added beside or after them. The\n * `intoEmpty` boards (an app's, for every project) go first into a project with no boards, so\n * Factory's own under the same key, or in `onlyIntoEmpty`, then stay out. `actor` is recorded\n * as the inserted boards' creator.\n */\n async seedBoards(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: { actor?: string; onlyIntoEmpty?: readonly string[]; intoEmpty?: readonly StoredBoardInput[] } = {},\n ): Promise<string[]> {\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.seeded_boards && boards.every(board => marker.seeded_boards!.includes(board.key))) return [];\n return this.#insertOnce(scope, boards, {\n actor: options.actor ?? DEFAULT_INTAKE_ROUTE_ACTOR,\n skipSeeded: true,\n onlyIntoEmpty: options.onlyIntoEmpty ?? [],\n intoEmpty: options.intoEmpty ?? [],\n });\n }\n\n /** The keys of the boards Factory stored in the project; null before it kept the list. */\n async seededBoardKeys(scope: StoredBoardScope): Promise<string[] | null> {\n return (await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))?.seeded_boards ?? null;\n }\n\n /**\n * Inserts a board into the project unless one is stored under its key, and records the key as\n * stored, so seeding never adds it again. Unlike seeding, it inserts a key the project deleted.\n * Returns whether it inserted the board.\n */\n async insertIfMissing(scope: StoredBoardScope, board: StoredBoardInput, actor: string): Promise<boolean> {\n return (await this.#insertOnce(scope, [board], { actor, skipSeeded: false })).length > 0;\n }\n\n async #insertOnce(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: {\n actor: string;\n skipSeeded: boolean;\n onlyIntoEmpty?: readonly string[];\n intoEmpty?: readonly StoredBoardInput[];\n },\n ): Promise<string[]> {\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const marker = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const present = new Set(rows.map(row => row.board_key));\n const seeded = new Set(marker.seeded_boards ?? present);\n // The `intoEmpty` boards go into a project with no boards, first; `onlyIntoEmpty` keys then\n // go in only when nothing is stored yet, so a project holding them gets no default beside them.\n const candidates = [...(rows.length === 0 ? (options.intoEmpty ?? []) : []), ...boards];\n let position = nextPosition(rows);\n const inserted: string[] = [];\n for (const board of candidates) {\n if (present.has(board.key) || (options.skipSeeded && seeded.has(board.key))) continue;\n if (present.size > 0 && options.onlyIntoEmpty?.includes(board.key)) continue;\n await insertBoard(ops, scope, board, { position: position++, actor: options.actor });\n present.add(board.key);\n inserted.push(board.key);\n }\n const next = [...new Set([...seeded, ...candidates.map(board => board.key)])];\n const unchanged = marker.seeded_boards !== null && next.length === marker.seeded_boards.length;\n if (inserted.length === 0 && unchanged) return inserted;\n // Compare-and-set on the version, and every marker write takes a new one: two replicas\n // recording different keys can't both match the version they read, so neither key is lost.\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: marker.version },\n {\n seeded_boards: next,\n version: randomUUID(),\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return inserted;\n });\n }\n\n /**\n * Runs each migration the project hasn't had yet, once: the keys applied are recorded on the\n * project's version row in the same transaction as the board writes, and the compare-and-set on\n * its version makes a concurrent first load retry from fresh reads, where it finds them applied.\n * A migration whose board the project doesn't have is recorded without running, and the version\n * only changes when a board was rewritten. Reads one row\n * when every key was applied before. Returns what each migration that rewrote a board filled.\n */\n async applyBoardMigrations(\n scope: StoredBoardScope,\n migrations: readonly StoredBoardMigration[],\n /**\n * Read through the transaction's `ops`, again on every retry, and only when a migration is still\n * pending, so what it reports is as fresh as the boards the migrations rewrite.\n */\n context: (ops: FactoryStorageOps) => Promise<BoardMigrationContext> = async () => EMPTY_MIGRATION_CONTEXT,\n ): Promise<AppliedBoardMigration[]> {\n if (migrations.length === 0) return [];\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.applied_migrations && migrations.every(({ key }) => marker.applied_migrations!.includes(key))) {\n return [];\n }\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const current = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const applied = current.applied_migrations ?? [];\n const pending = migrations.filter(({ key }) => !applied.includes(key));\n if (pending.length === 0) return [];\n const project = await context(ops);\n const changed: AppliedBoardMigration[] = [];\n for (const migration of pending) {\n const rows =\n migration.boardKey === null\n ? await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope))\n : await ops.findMany<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: migration.boardKey });\n for (const row of rows) {\n const phases = await ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n const result = migration.migrate(toRecord(row, phases), project);\n if (!result) continue;\n await writeBoard(ops, scope, row, { ...result.board, key: row.board_key }, MIGRATION_ACTOR);\n changed.push({ key: migration.key, boardKey: row.board_key, filled: result.filled });\n }\n }\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: current.version },\n {\n applied_migrations: [...applied, ...pending.map(({ key }) => key)],\n // Only a rewritten board is news to the other replicas' caches.\n version: changed.length > 0 ? randomUUID() : current.version,\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return changed;\n });\n }\n\n /** Rewrites a board to `definition` (Factory's current one for its key), raising its revision. */\n async resetTo(\n scope: StoredBoardScope,\n key: string,\n definition: StoredBoardInput,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { ...definition, key }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /**\n * Adds a route after the project's last one. A route that places new cards goes just ahead of the\n * first route that takes every new card instead, since after it it would never place one.\n */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n checkRouteEvents(input.on ?? DEFAULT_ROUTE_EVENTS, input.when ?? null);\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n const position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n await insertIntakeRoute(ops, scope, { id, input, position, actor });\n const ahead = (input.on ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created')\n ? rows.findIndex(catchesEveryNewCard)\n : -1;\n if (ahead >= 0) {\n const added = (await readIntakeRoutes(ops, scope)).find(row => row.id === id)!;\n await placeIntakeRoutes(ops, rows.toSpliced(ahead, 0, added), actor);\n }\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n checkRouteEvents(patch.on ?? routeEvents(row), patch.when !== undefined ? patch.when : row.when_condition);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.on !== undefined && { on_events: patch.on }),\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n join_closed_issue: patch.target.joinClosedIssue ?? false,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n const first: string[] = [];\n for (const { route, first: leads } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n const id = randomUUID();\n await insertIntakeRoute(ops, scope, {\n id,\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n if (leads) first.push(id);\n }\n // A project that had routes before gets a leading default ahead of them.\n if (first.length > 0 && rows.length > 0) {\n const placed = await readIntakeRoutes(ops, scope);\n const leading = new Set(first);\n await placeIntakeRoutes(ops, [\n ...first.map(id => placed.find(row => row.id === id)!),\n ...placed.filter(row => !leading.has(row.id)),\n ]);\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n tools: phase.tools?.length ? phase.tools : null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction routeEvents(row: IntakeRouteRow): StatusEvent[] {\n return row.on_events ?? [...DEFAULT_ROUTE_EVENTS];\n}\n\nfunction checkRouteEvents(on: readonly string[], when: RuleGroup | null): void {\n const problem = routeEventsProblem(on, when);\n if (problem) throw new StoredBoardError('invalid_intake_route', problem);\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key, joinClosedIssue: row.join_closed_issue === true },\n on: routeEvents(row),\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\n/** Whether `row` places every new card that reaches it, as the seeded \"Everything else\" route does. */\nfunction catchesEveryNewCard(row: IntakeRouteRow): boolean {\n return (\n row.enabled &&\n row.when_condition === null &&\n (row.on_events ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created') &&\n !row.join_closed_issue\n );\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n on_events: route.input.on ?? null,\n join_closed_issue: route.input.target.joinClosedIssue ?? false,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;;AA2HA,MAAM,0BAAiD;CACrD,iBAAiB;CACjB,gCAAgB,IAAI,IAAI;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AAmB;EACzD,UAAU;EACV,YAAY,MAAM;EAClB,YAAY;EACZ,YAAY,MAAM;EAClB,YAAY;CACd,CAAC;AACH;;;;;AAMA,eAAe,iBAAiB,KAAwB,OAAoD;CAC1G,IAAK,MAAM,IAAI,WAAW,oBAAoB,WAAW,KAAK,GAAG,EAAE,2BAAW,IAAI,KAAK,EAAE,CAAC,MAAO,GAC/F,MAAM,IAAI,qBAAqB;CAEjC,OAAO,iBAAiB,KAAK,KAAK;AACpC;;AAGA,eAAe,kBAAkB,KAAwB,MAAwB,OAA+B;CAC9G,MAAM,SAAS,KAAK,SAAS,KAAK,aAAc,IAAI,aAAa,WAAW,CAAC,IAAI,CAAC;EAAE;EAAK;CAAS,CAAC,CAAE;CACrG,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,CAAC,OAAO,EAAE,KAAK,eAAe,OAAO,QAAQ,GAAG;EACzD,MAAM,WAAW,MAAM,qBAAqB,KAAK,KAAK;GACpD,UAAU,EAAE,QAAQ;GACpB,GAAI,UAAU,KAAA,KAAa,EAAE,YAAY,MAAM;EACjD,CAAC;EACD,OAAO,KAAK;GAAE,IAAI,IAAI;GAAI;GAAU;EAAS,CAAC;CAChD;CACA,KAAK,MAAM,EAAE,IAAI,UAAU,cAAc,QACvC,IAAK,MAAM,IAAI,WAAW,eAAe;EAAE;EAAI;CAAS,GAAG,EAAE,SAAS,CAAC,MAAO,GAAG,MAAM,IAAI,qBAAqB;AAEpH"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_ROUTE_EVENTS, routeEventsProblem } from '../../../boards/board-events.js';\nimport type { StatusEvent } from '../../../boards/board-events.js';\nimport type { FactoryPhaseTool } from '../../../boards/define-board.js';\nimport { DEFAULT_INTAKE_ROUTES } from '../../../boards/work-routes.js';\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport type { RetiredAutomationSettings } from '../projects/base.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n /** The objective the phase's runs pursue as a goal. */\n goal?: { objective: string; maxRuns?: number };\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n /** Factory tools the phase grants the session working the card there. */\n tools?: FactoryPhaseTool[] | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\n/** What a board migration may know about the project besides the board it rewrites. */\nexport interface BoardMigrationContext {\n /** The project switches the boards replaced, as the project last stored them; null when unknown. */\n readonly retiredSettings: RetiredAutomationSettings | null;\n /** The phases of each board that cards sit in, by board key; null when the cards can't be read. */\n readonly occupiedPhases: ReadonlyMap<string, ReadonlySet<string>> | null;\n /**\n * The phases the code board under this key declares; undefined for a board only the project\n * stores. A row that drops one runs without its code rules (`mergeCodeBehaviour`).\n */\n codePhases(boardKey: string): ReadonlySet<string> | undefined;\n /** Tells the operator about a board a migration left as it is. */\n warn(message: string): void;\n}\n\n/** A one-time rewrite of a stored board, keyed so each project gets it once. */\nexport interface StoredBoardMigration {\n key: string;\n /** The board it rewrites; `null` rewrites every board the project stores. */\n boardKey: string | null;\n /** The board to write instead, with what changed; undefined leaves it as it is. */\n migrate(\n board: StoredBoardRecord,\n context: BoardMigrationContext,\n ): { board: Omit<StoredBoardInput, 'key'>; filled: string[] } | undefined;\n}\n\nconst EMPTY_MIGRATION_CONTEXT: BoardMigrationContext = {\n retiredSettings: null,\n occupiedPhases: new Map(),\n codePhases: () => undefined,\n warn: () => {},\n};\n\nexport interface AppliedBoardMigration {\n key: string;\n boardKey: string;\n filled: string[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /**\n * Unset lands the card in the board's first phase. On a route that joins a closed issue's\n * card, the phase that card moves to when its board allows it; unset leaves it where it is.\n */\n phaseKey?: string | null;\n /**\n * Files a pull request on the card of the issue it closes, which must be on `boardKey`, as one\n * more source instead of a card of its own. The route doesn't match any other arrival.\n */\n joinClosedIssue?: boolean;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n /** The status events the route handles; unset handles new cards (`work_item.created`). */\n on?: StatusEvent[];\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null; joinClosedIssue: boolean };\n on: StatusEvent[];\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit'\n | 'invalid_intake_route';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n// Work's routes are its seed data, kept with the board they target.\nexport {\n DEFAULT_INTAKE_ROUTE,\n PULL_REQUEST_INTAKE_ROUTE,\n CLOSED_COMPLETED_ROUTE,\n CLOSED_CANCELED_ROUTE,\n REOPENED_ROUTE,\n PULL_REQUEST_MERGED_ROUTE,\n PULL_REQUEST_CLOSED_ROUTE,\n PULL_REQUEST_CLOSED_ISSUE_ROUTE,\n PULL_REQUEST_UPDATED_ROUTE,\n PULL_REQUEST_REVIEW_REQUESTED_ROUTE,\n CLOSES_ISSUE_INTAKE_ROUTE,\n CATCH_ALL_INTAKE_ROUTE,\n DEFAULT_INTAKE_ROUTES,\n} from '../../../boards/work-routes.js';\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface VersionRow extends Record<string, unknown> {\n version: string;\n /** Keys of the boards Factory stored in the project; null on rows written before the list. */\n seeded_boards: string[] | null;\n /** Keys of the board migrations applied to the project; null before the first one. */\n applied_migrations: string[] | null;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n /** Null on rows written before routes named events: they place new cards. */\n on_events: StatusEvent[] | null;\n join_closed_issue: boolean | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\nconst MIGRATION_ACTOR = 'factory';\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n tools: row.tools ?? null,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** Runs inside a board write's transaction, before the board is written. */\nexport type BoardWriteStep = (ops: FactoryStorageOps) => Promise<void>;\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n return readStoredBoard(this.ops, scope, key);\n }\n\n /**\n * Creates a board through the API. `before` runs in the same transaction, once the key is known\n * to be free. A row under the key that `over` accepts does not hold it: the board is written\n * over that row.\n */\n async create(\n scope: StoredBoardScope,\n input: StoredBoardInput,\n actor: string,\n before?: BoardWriteStep,\n over?: (row: StoredBoardRecord) => boolean,\n ): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const taken = rows.find(row => row.board_key === input.key);\n const stored = taken && over ? await readStoredBoard(ops, scope, input.key) : null;\n if (taken && !(stored && over?.(stored))) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await before?.(ops);\n if (taken) await writeBoard(ops, scope, taken, input, actor);\n else await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string; before?: BoardWriteStep },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await options.before?.(ops);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /**\n * Stores Factory's boards (Work, app and seed boards) in the project, each key once: a key the\n * project has had before is skipped even if its board was deleted since, and a stored board is\n * never rewritten. A project stored before the list was kept counts the boards it has as stored.\n * Reads one row when every key was stored before. Returns the keys it inserted.\n *\n * A key in `onlyIntoEmpty` is inserted only into a project that has no boards at all: one that\n * already has any board, such as one an app stored under that key, is left as it is. The key\n * is still recorded as stored, so it never goes in later, even after the project's boards are\n * deleted: that project chose its boards, and Work is never added beside or after them. The\n * `intoEmpty` boards (an app's, for every project) go first into a project with no boards, so\n * Factory's own under the same key, or in `onlyIntoEmpty`, then stay out. `actor` is recorded\n * as the inserted boards' creator. `before` runs in the same\n * transaction ahead of each board it inserts.\n */\n async seedBoards(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: {\n actor?: string;\n onlyIntoEmpty?: readonly string[];\n intoEmpty?: readonly StoredBoardInput[];\n before?: (ops: FactoryStorageOps, key: string) => Promise<void>;\n } = {},\n ): Promise<string[]> {\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.seeded_boards && boards.every(board => marker.seeded_boards!.includes(board.key))) return [];\n return this.#insertOnce(scope, boards, {\n actor: options.actor ?? DEFAULT_INTAKE_ROUTE_ACTOR,\n skipSeeded: true,\n onlyIntoEmpty: options.onlyIntoEmpty ?? [],\n intoEmpty: options.intoEmpty ?? [],\n before: options.before,\n });\n }\n\n /** The keys of the boards Factory stored in the project; null before it kept the list. */\n async seededBoardKeys(scope: StoredBoardScope): Promise<string[] | null> {\n return (await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))?.seeded_boards ?? null;\n }\n\n /**\n * Rewrites the board stored under `seed.key` to `seed` at its next revision when `when` says the\n * row is nobody's: one an earlier release seeded for a board Factory no longer has, under a key\n * the app now defines. `before` runs in the same transaction. Returns whether it rewrote the row.\n */\n async adoptSeed(\n scope: StoredBoardScope,\n seed: StoredBoardInput,\n options: { when: (row: StoredBoardRecord) => boolean; before?: BoardWriteStep },\n ): Promise<boolean> {\n return this.#write(scope, async ops => {\n const stored = await readStoredBoard(ops, scope, seed.key);\n if (!stored || !options.when(stored)) return { result: false, changed: false };\n await options.before?.(ops);\n await writeBoard(ops, scope, await findBoard(ops, scope, seed.key), seed, DEFAULT_INTAKE_ROUTE_ACTOR);\n return { result: true, changed: true };\n });\n }\n\n /**\n * Inserts a board into the project unless one is stored under its key, and records the key as\n * stored, so seeding never adds it again. Unlike seeding, it inserts a key the project deleted.\n * Returns whether it inserted the board. `before` runs in the same transaction when it does.\n */\n async insertIfMissing(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n actor: string,\n before?: BoardWriteStep,\n ): Promise<boolean> {\n return (await this.#insertOnce(scope, [board], { actor, skipSeeded: false, before })).length > 0;\n }\n\n async #insertOnce(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: {\n actor: string;\n skipSeeded: boolean;\n onlyIntoEmpty?: readonly string[];\n intoEmpty?: readonly StoredBoardInput[];\n before?: (ops: FactoryStorageOps, key: string) => Promise<void>;\n },\n ): Promise<string[]> {\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const marker = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const present = new Set(rows.map(row => row.board_key));\n const seeded = new Set(marker.seeded_boards ?? present);\n // The `intoEmpty` boards go into a project with no boards, first; `onlyIntoEmpty` keys then\n // go in only when nothing is stored yet, so a project holding them gets no default beside them.\n const candidates = [...(rows.length === 0 ? (options.intoEmpty ?? []) : []), ...boards];\n let position = nextPosition(rows);\n const inserted: string[] = [];\n for (const board of candidates) {\n if (present.has(board.key) || (options.skipSeeded && seeded.has(board.key))) continue;\n if (present.size > 0 && options.onlyIntoEmpty?.includes(board.key)) continue;\n await options.before?.(ops, board.key);\n await insertBoard(ops, scope, board, { position: position++, actor: options.actor });\n present.add(board.key);\n inserted.push(board.key);\n }\n const next = [...new Set([...seeded, ...candidates.map(board => board.key)])];\n const unchanged = marker.seeded_boards !== null && next.length === marker.seeded_boards.length;\n if (inserted.length === 0 && unchanged) return inserted;\n // Compare-and-set on the version, and every marker write takes a new one: two replicas\n // recording different keys can't both match the version they read, so neither key is lost.\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: marker.version },\n {\n seeded_boards: next,\n version: randomUUID(),\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return inserted;\n });\n }\n\n /**\n * Runs each migration the project hasn't had yet, once: the keys applied are recorded on the\n * project's version row in the same transaction as the board writes, and the compare-and-set on\n * its version makes a concurrent first load retry from fresh reads, where it finds them applied.\n * A migration whose board the project doesn't have is recorded without running, and the version\n * only changes when a board was rewritten. Reads one row\n * when every key was applied before. Returns what each migration that rewrote a board filled.\n */\n async applyBoardMigrations(\n scope: StoredBoardScope,\n migrations: readonly StoredBoardMigration[],\n /**\n * Read through the transaction's `ops`, again on every retry, and only when a migration is still\n * pending, so what it reports is as fresh as the boards the migrations rewrite.\n */\n context: (ops: FactoryStorageOps) => Promise<BoardMigrationContext> = async () => EMPTY_MIGRATION_CONTEXT,\n ): Promise<AppliedBoardMigration[]> {\n if (migrations.length === 0) return [];\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.applied_migrations && migrations.every(({ key }) => marker.applied_migrations!.includes(key))) {\n return [];\n }\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const current = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const applied = current.applied_migrations ?? [];\n const pending = migrations.filter(({ key }) => !applied.includes(key));\n if (pending.length === 0) return [];\n const project = await context(ops);\n const changed: AppliedBoardMigration[] = [];\n for (const migration of pending) {\n const rows =\n migration.boardKey === null\n ? await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope))\n : await ops.findMany<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: migration.boardKey });\n for (const row of rows) {\n const phases = await ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n const result = migration.migrate(toRecord(row, phases), project);\n if (!result) continue;\n await writeBoard(ops, scope, row, { ...result.board, key: row.board_key }, MIGRATION_ACTOR);\n changed.push({ key: migration.key, boardKey: row.board_key, filled: result.filled });\n }\n }\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: current.version },\n {\n applied_migrations: [...applied, ...pending.map(({ key }) => key)],\n // Only a rewritten board is news to the other replicas' caches.\n version: changed.length > 0 ? randomUUID() : current.version,\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return changed;\n });\n }\n\n /** Rewrites a board to `definition` (Factory's current one for its key), raising its revision. */\n async resetTo(\n scope: StoredBoardScope,\n key: string,\n definition: StoredBoardInput,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { ...definition, key }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /**\n * Adds a route after the project's last one. A route that places new cards goes just ahead of the\n * first route that takes every new card instead, since after it it would never place one.\n */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n checkRouteEvents(input.on ?? DEFAULT_ROUTE_EVENTS, input.when ?? null);\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n const position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n await insertIntakeRoute(ops, scope, { id, input, position, actor });\n const ahead = (input.on ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created')\n ? rows.findIndex(catchesEveryNewCard)\n : -1;\n if (ahead >= 0) {\n const added = (await readIntakeRoutes(ops, scope)).find(row => row.id === id)!;\n await placeIntakeRoutes(ops, rows.toSpliced(ahead, 0, added), actor);\n }\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n checkRouteEvents(patch.on ?? routeEvents(row), patch.when !== undefined ? patch.when : row.when_condition);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.on !== undefined && { on_events: patch.on }),\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n join_closed_issue: patch.target.joinClosedIssue ?? false,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n const first: string[] = [];\n for (const { route, first: leads } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n const id = randomUUID();\n await insertIntakeRoute(ops, scope, {\n id,\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n if (leads) first.push(id);\n }\n // A project that had routes before gets a leading default ahead of them.\n if (first.length > 0 && rows.length > 0) {\n const placed = await readIntakeRoutes(ops, scope);\n const leading = new Set(first);\n await placeIntakeRoutes(ops, [\n ...first.map(id => placed.find(row => row.id === id)!),\n ...placed.filter(row => !leading.has(row.id)),\n ]);\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\n/** The project's board under `key`, read through `ops` so a caller inside a transaction reads within it. */\nexport async function readStoredBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n key: string,\n): Promise<StoredBoardRecord | null> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n tools: phase.tools?.length ? phase.tools : null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction routeEvents(row: IntakeRouteRow): StatusEvent[] {\n return row.on_events ?? [...DEFAULT_ROUTE_EVENTS];\n}\n\nfunction checkRouteEvents(on: readonly string[], when: RuleGroup | null): void {\n const problem = routeEventsProblem(on, when);\n if (problem) throw new StoredBoardError('invalid_intake_route', problem);\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key, joinClosedIssue: row.join_closed_issue === true },\n on: routeEvents(row),\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\n/** Whether `row` places every new card that reaches it, as the seeded \"Everything else\" route does. */\nfunction catchesEveryNewCard(row: IntakeRouteRow): boolean {\n return (\n row.enabled &&\n row.when_condition === null &&\n (row.on_events ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created') &&\n !row.join_closed_issue\n );\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n on_events: route.input.on ?? null,\n join_closed_issue: route.input.target.joinClosedIssue ?? false,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;;AA2HA,MAAM,0BAAiD;CACrD,iBAAiB;CACjB,gCAAgB,IAAI,IAAI;CACxB,kBAAkB,KAAA;CAClB,YAAY,CAAC;AACf;;AAiEA,MAAa,oBAAoB;;AAoBjC,MAAM,wBAAwB,CAAC,iBAAiB;;AAGhD,MAAa,6BAA6B;AAE1C,IAAa,mBAAb,cAAsC,MAAM;CAG/B;CAFX,OAAgB;CAChB,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;CAIX;AACF;AAoEA,SAAS,eAAe,MAAoC;CAC1D,OAAO,KAAK,mBAAmB;AACjC;AAEA,SAAS,gBAAgB,MAAoE;CAC3F,MAAM,SAAS,IAAI,IAAI,eAAe,IAAI,CAAC;CAC3C,OAAO,sBAAsB,QAAQ,EAAE,UAAU,CAAC,OAAO,IAAI,GAAG,CAAC;AACnE;AAEA,MAAM,SAAS;AACf,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB;AAExB,SAAS,WAAW,EAAE,OAAO,oBAAsC;CACjE,OAAO;EAAE,QAAQ;EAAO,oBAAoB;CAAiB;AAC/D;AAEA,SAAS,cAAc,KAAkC;CACvD,OAAO;EACL,KAAK,IAAI;EACT,UAAU,IAAI;EACd,MAAM,IAAI;EACV,aAAa,IAAI;EACjB,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,YAAY,IAAI;EAChB,WAAW,IAAI;EACf,eAAe,IAAI;EACnB,UAAU,IAAI;EACd,OAAO,IAAI,SAAS;CACtB;AACF;AAEA,SAAS,SAAS,KAAe,QAAuC;CACtE,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,kBAAkB,IAAI;EACtB,KAAK,IAAI;EACT,MAAM,IAAI;EACV,a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iBAAiB,KAAK,KAAK;AACpC;;AAGA,eAAe,kBAAkB,KAAwB,MAAwB,OAA+B;CAC9G,MAAM,SAAS,KAAK,SAAS,KAAK,aAAc,IAAI,aAAa,WAAW,CAAC,IAAI,CAAC;EAAE;EAAK;CAAS,CAAC,CAAE;CACrG,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,CAAC,OAAO,EAAE,KAAK,eAAe,OAAO,QAAQ,GAAG;EACzD,MAAM,WAAW,MAAM,qBAAqB,KAAK,KAAK;GACpD,UAAU,EAAE,QAAQ;GACpB,GAAI,UAAU,KAAA,KAAa,EAAE,YAAY,MAAM;EACjD,CAAC;EACD,OAAO,KAAK;GAAE,IAAI,IAAI;GAAI;GAAU;EAAS,CAAC;CAChD;CACA,KAAK,MAAM,EAAE,IAAI,UAAU,cAAc,QACvC,IAAK,MAAM,IAAI,WAAW,eAAe;EAAE;EAAI;CAAS,GAAG,EAAE,SAAS,CAAC,MAAO,GAAG,MAAM,IAAI,qBAAqB;AAEpH"}
|
|
@@ -54,9 +54,12 @@ export interface FactoryProject {
|
|
|
54
54
|
lastPushBuildAt: Date | null;
|
|
55
55
|
/**
|
|
56
56
|
* A run's build-start lease lapsed, so a build it may have started is not
|
|
57
|
-
* on record. Cleared once a run reconciles it with a provider that lists
|
|
57
|
+
* on record. Cleared once a run reconciles it with a provider that lists
|
|
58
|
+
* builds, or gives up on it after `UNRESOLVED_BUILD_START_TIMEOUT_MS`.
|
|
58
59
|
*/
|
|
59
60
|
buildStartUncertain: boolean;
|
|
61
|
+
/** The latest moment the unrecorded build behind `buildStartUncertain` may have started. */
|
|
62
|
+
buildStartUncertainSince: Date | null;
|
|
60
63
|
/** Whether a push to an environment repository's default branch starts a build. */
|
|
61
64
|
buildOnPushEnabled: boolean;
|
|
62
65
|
/** Minutes after a push-triggered attempt during which further pushes do not build. */
|
|
@@ -155,7 +158,10 @@ export declare class FactoryProjectsStorage extends FactoryStorageDomain {
|
|
|
155
158
|
* only expires when its run died or stalled. Taking over an expired lease
|
|
156
159
|
* marks the start uncertain (that run's build may have reached the provider
|
|
157
160
|
* unrecorded), and the mark stays until a release resolves it; `uncertain`
|
|
158
|
-
* reports it.
|
|
161
|
+
* reports it. The mark's `build_start_uncertain_since` is the lapsed lease's
|
|
162
|
+
* expiry, the latest that run could have started a build; a mark written
|
|
163
|
+
* before that column existed is dated by the first claim that reads it.
|
|
164
|
+
* Only the claim is transactional; provider calls run outside it.
|
|
159
165
|
*/
|
|
160
166
|
claimBuildStart({ id, token, leaseMs, now, }: {
|
|
161
167
|
id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/projects/base.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIhF,eAAO,MAAM,mCAAmC,KAAK,CAAC;AACtD,eAAO,MAAM,oBAAoB,YAAI,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AACtE,iGAAiG;AACjG,MAAM,MAAM,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;AAEvE;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,GAAG,SAAS,GAAG,mBAAmB,CAG7G;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,SAA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I,CAAC,CAWhC;CACF"}
|
|
@@ -103,6 +103,10 @@ const FACTORY_PROJECTS_SCHEMA = {
|
|
|
103
103
|
type: "boolean",
|
|
104
104
|
default: false
|
|
105
105
|
},
|
|
106
|
+
build_start_uncertain_since: {
|
|
107
|
+
type: "timestamp",
|
|
108
|
+
nullable: true
|
|
109
|
+
},
|
|
106
110
|
build_start_claim: {
|
|
107
111
|
type: "text",
|
|
108
112
|
nullable: true
|
|
@@ -161,6 +165,7 @@ function toFactoryProject(row) {
|
|
|
161
165
|
lastBuildAttemptedAt: row.last_build_attempted_at ?? null,
|
|
162
166
|
lastPushBuildAt: row.last_push_build_at ?? null,
|
|
163
167
|
buildStartUncertain: row.build_start_uncertain ?? false,
|
|
168
|
+
buildStartUncertainSince: row.build_start_uncertain_since ?? null,
|
|
164
169
|
buildOnPushEnabled: row.build_on_push_enabled ?? false,
|
|
165
170
|
buildPushDebounceMinutes: row.build_push_debounce_minutes ?? 10,
|
|
166
171
|
createdAt: row.created_at,
|
|
@@ -285,7 +290,10 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
|
|
|
285
290
|
* only expires when its run died or stalled. Taking over an expired lease
|
|
286
291
|
* marks the start uncertain (that run's build may have reached the provider
|
|
287
292
|
* unrecorded), and the mark stays until a release resolves it; `uncertain`
|
|
288
|
-
* reports it.
|
|
293
|
+
* reports it. The mark's `build_start_uncertain_since` is the lapsed lease's
|
|
294
|
+
* expiry, the latest that run could have started a build; a mark written
|
|
295
|
+
* before that column existed is dated by the first claim that reads it.
|
|
296
|
+
* Only the claim is transactional; provider calls run outside it.
|
|
289
297
|
*/
|
|
290
298
|
async claimBuildStart({ id, token, leaseMs, now = /* @__PURE__ */ new Date() }) {
|
|
291
299
|
const result = {
|
|
@@ -296,11 +304,17 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
|
|
|
296
304
|
const expiresAt = current.build_start_claim_expires_at;
|
|
297
305
|
if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;
|
|
298
306
|
result.claimed = true;
|
|
299
|
-
|
|
307
|
+
const lapsedAt = current.build_start_claim ? expiresAt ?? now : null;
|
|
308
|
+
const markedAt = current.build_start_uncertain === true ? current.build_start_uncertain_since ?? now : null;
|
|
309
|
+
result.uncertain = lapsedAt !== null || markedAt !== null;
|
|
310
|
+
const since = lapsedAt && markedAt ? lapsedAt.getTime() > markedAt.getTime() ? lapsedAt : markedAt : lapsedAt ?? markedAt;
|
|
300
311
|
return {
|
|
301
312
|
build_start_claim: token,
|
|
302
313
|
build_start_claim_expires_at: new Date(now.getTime() + leaseMs),
|
|
303
|
-
...
|
|
314
|
+
...since ? {
|
|
315
|
+
build_start_uncertain: true,
|
|
316
|
+
build_start_uncertain_since: since
|
|
317
|
+
} : {},
|
|
304
318
|
updated_at: now
|
|
305
319
|
};
|
|
306
320
|
}));
|
|
@@ -339,7 +353,10 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
|
|
|
339
353
|
...changes.lastBuildHeads !== void 0 ? { last_build_heads: changes.lastBuildHeads } : {},
|
|
340
354
|
...changes.lastBuildInputs !== void 0 ? { last_build_inputs: changes.lastBuildInputs } : {},
|
|
341
355
|
...changes.lastBuildAttemptedAt !== void 0 ? { last_build_attempted_at: changes.lastBuildAttemptedAt } : {},
|
|
342
|
-
...resolved ? {
|
|
356
|
+
...resolved ? {
|
|
357
|
+
build_start_uncertain: false,
|
|
358
|
+
build_start_uncertain_since: null
|
|
359
|
+
} : {},
|
|
343
360
|
build_start_claim: null,
|
|
344
361
|
build_start_claim_expires_at: null,
|
|
345
362
|
updated_at: now
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists builds.\n */\n buildStartUncertain: boolean;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Project switches the board replaced, as last stored. */\nexport interface RetiredAutomationSettings {\n /** Runs started without a person on every phase. */\n autoRunEnabled: boolean;\n /** Cards on a board with a self-review phase went through it. */\n selfReviewEnabled: boolean;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A phase starts on its own with `autoStart`; the\n // `auto-run-switch-v1` board migration reads it once to carry it into the project's boards.\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n // Retired project switch: no longer read or written. The review skill decides whether to publish its test check.\n review_test_checks_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A board self-reviews when it has a self-review\n // phase; the `self-review-switch-v1` board migration reads it once to carry it into its boards.\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * The retired automation switches as the project last stored them, read only by the one-time\n * board migrations that carry them into its boards. Null when the project doesn't exist.\n */\n async retiredAutomationSettings(\n { orgId, id }: { orgId: string; id: string },\n /** A transaction's ops, to read it inside that transaction. */\n ops: FactoryStorageOps = this.#db,\n ): Promise<RetiredAutomationSettings | null> {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n return { autoRunEnabled: Boolean(row.auto_run_enabled), selfReviewEnabled: Boolean(row.self_review_enabled) };\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n result.uncertain = Boolean(current.build_start_claim) || current.build_start_uncertain === true;\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(result.uncertain ? { build_start_uncertain: true } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryProject(row);\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;AAOA,MAAa,sCAAsC;AACnD,MAAa,uBAAuB;CAAC;CAAW;CAAQ;AAAQ;;;;;AAShE,SAAgB,oBAAoB,OAA0B,SAAiD;CAC7G,IAAI,UAAU,UAAU,OAAO,YAAY,QAAQ,YAAY;CAC/D,OAAO;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;GACd;EACF,CAAC,CACH;EACA,OAAO;CACT;;;;;;;;CASA,MAAM,kBAAkB,EACtB,IACA,SACA,YACA,OACA,sBAAM,IAAI,KAAK,KAOI;EACnB,IAAI,SAAS;EACb,MAAM,KAAK,QAAQ,iBAAgB,QACjC,IAAI,aAAkC,oBAAoB,EAAE,GAAG,IAAG,YAAW;GAC3E,IAAI,QAAQ,kBAAkB,SAAS,OAAO;GAC9C,SAAS;GACT,OAAO;IAAE,oBAAoB;IAAY,uBAAuB;IAAO,YAAY;GAAI;EACzF,CAAC,CACH;EACA,OAAO;CACT;;CAGA,MAAM,OACJ,EAAE,OAAO,MACT,SACgC;EAChC,OAAO,KAAK,QAAQ,gBAClB,OAAM,QAAO;GACX,MAAM,MAAM,MAAM,IAAI,QAA6B,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC5F,IAAI,CAAC,KAAK,OAAO;GACjB,MAAM,UAAU,GAAG;GACnB,MAAM,IAAI,WAAW,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC9D,OAAO,iBAAiB,GAAG;EAC7B,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists\n * builds, or gives up on it after `UNRESOLVED_BUILD_START_TIMEOUT_MS`.\n */\n buildStartUncertain: boolean;\n /** The latest moment the unrecorded build behind `buildStartUncertain` may have started. */\n buildStartUncertainSince: Date | null;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Project switches the board replaced, as last stored. */\nexport interface RetiredAutomationSettings {\n /** Runs started without a person on every phase. */\n autoRunEnabled: boolean;\n /** Cards on a board with a self-review phase went through it. */\n selfReviewEnabled: boolean;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A phase starts on its own with `autoStart`; the\n // `auto-run-switch-v1` board migration reads it once to carry it into the project's boards.\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_uncertain_since: { type: 'timestamp', nullable: true },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n // Retired project switch: no longer read or written. The review skill decides whether to publish its test check.\n review_test_checks_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A board self-reviews when it has a self-review\n // phase; the `self-review-switch-v1` board migration reads it once to carry it into its boards.\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_uncertain_since: Date | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildStartUncertainSince: row.build_start_uncertain_since ?? null,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * The retired automation switches as the project last stored them, read only by the one-time\n * board migrations that carry them into its boards. Null when the project doesn't exist.\n */\n async retiredAutomationSettings(\n { orgId, id }: { orgId: string; id: string },\n /** A transaction's ops, to read it inside that transaction. */\n ops: FactoryStorageOps = this.#db,\n ): Promise<RetiredAutomationSettings | null> {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n return { autoRunEnabled: Boolean(row.auto_run_enabled), selfReviewEnabled: Boolean(row.self_review_enabled) };\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. The mark's `build_start_uncertain_since` is the lapsed lease's\n * expiry, the latest that run could have started a build; a mark written\n * before that column existed is dated by the first claim that reads it.\n * Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n const lapsedAt = current.build_start_claim ? (expiresAt ?? now) : null;\n const markedAt = current.build_start_uncertain === true ? (current.build_start_uncertain_since ?? now) : null;\n result.uncertain = lapsedAt !== null || markedAt !== null;\n const since =\n lapsedAt && markedAt\n ? lapsedAt.getTime() > markedAt.getTime()\n ? lapsedAt\n : markedAt\n : (lapsedAt ?? markedAt);\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(since ? { build_start_uncertain: true, build_start_uncertain_since: since } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false, build_start_uncertain_since: null } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryProject(row);\n },\n { isolationLevel: 'serializable' },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