@mastra/factory 0.28.0 → 0.29.0-alpha.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 +6 -4
- package/dist/boards/reroute.d.ts +31 -0
- package/dist/boards/reroute.d.ts.map +1 -0
- package/dist/boards/reroute.js +71 -0
- package/dist/boards/reroute.js.map +1 -0
- package/dist/environment/repository-access.d.ts +2 -0
- package/dist/environment/repository-access.d.ts.map +1 -1
- package/dist/environment/repository-access.js +9 -4
- package/dist/environment/repository-access.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +9 -6
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +8 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/dependabot/default-rules.d.ts +38 -0
- package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
- package/dist/integrations/dependabot/default-rules.js +63 -0
- package/dist/integrations/dependabot/default-rules.js.map +1 -0
- package/dist/integrations/dependabot/rules.d.ts +42 -0
- package/dist/integrations/dependabot/rules.d.ts.map +1 -0
- package/dist/integrations/dependabot/rules.js +187 -0
- package/dist/integrations/dependabot/rules.js.map +1 -0
- package/dist/integrations/dependabot/sync.d.ts +76 -0
- package/dist/integrations/dependabot/sync.d.ts.map +1 -0
- package/dist/integrations/dependabot/sync.js +111 -0
- package/dist/integrations/dependabot/sync.js.map +1 -0
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +7 -2
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +12 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +22 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +4 -0
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts +5 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +33 -2
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +19 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +46 -0
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/vanta/integration.d.ts +33 -0
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
- package/dist/integrations/platform/vanta/integration.js +133 -0
- package/dist/integrations/platform/vanta/integration.js.map +1 -0
- package/dist/integrations/vanta/default-rules.d.ts +34 -0
- package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
- package/dist/integrations/vanta/default-rules.js +61 -0
- package/dist/integrations/vanta/default-rules.js.map +1 -0
- package/dist/integrations/vanta/rules.d.ts +40 -0
- package/dist/integrations/vanta/rules.d.ts.map +1 -0
- package/dist/integrations/vanta/rules.js +208 -0
- package/dist/integrations/vanta/rules.js.map +1 -0
- package/dist/integrations/vanta/sync.d.ts +36 -0
- package/dist/integrations/vanta/sync.d.ts.map +1 -0
- package/dist/integrations/vanta/sync.js +73 -0
- package/dist/integrations/vanta/sync.js.map +1 -0
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +1 -1
- package/dist/mcp/routes.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +8 -1
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +23 -2
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/contracts.d.ts +205 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +159 -5
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-routes.d.ts +3 -0
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +44 -0
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/knowledge.d.ts.map +1 -1
- package/dist/routes/knowledge.js +3 -2
- package/dist/routes/knowledge.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +109 -3
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +6 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +72 -9
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-selection.d.ts +0 -4
- package/dist/routes/work-item-selection.d.ts.map +1 -1
- package/dist/routes/work-item-selection.js +4 -21
- package/dist/routes/work-item-selection.js.map +1 -1
- package/dist/routes/work-item-starters.d.ts.map +1 -1
- package/dist/routes/work-item-starters.js +4 -21
- package/dist/routes/work-item-starters.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +112 -36
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +3 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +5 -0
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +39 -18
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/index.d.ts +2 -2
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -2
- package/dist/rules/start-coordinator.d.ts +6 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +6 -2
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +3 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +71 -3
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +10 -2
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +5 -0
- package/dist/rules/validation.js.map +1 -1
- package/dist/session/factory-session.d.ts +20 -5
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +20 -6
- package/dist/session/factory-session.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +2 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/audit/actors.d.ts.map +1 -1
- package/dist/storage/domains/audit/actors.js +1 -1
- package/dist/storage/domains/audit/actors.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +1 -1
- package/dist/storage/domains/intake/base.js +2 -2
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +8 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +11 -1
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +15 -4
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +19 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/approval-tools.d.ts +20 -0
- package/dist/tools/approval-tools.d.ts.map +1 -1
- package/dist/tools/approval-tools.js +79 -30
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +1 -1
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +1 -1
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/read-tools.d.ts +0 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +2 -7
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/reports.d.ts +3 -0
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +3 -3
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +14 -2
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +24 -4
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +17 -6
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +1 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +12 -2
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +1 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +2 -0
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/board-filter-options.d.ts +5 -0
- package/dist/work-items/board-filter-options.d.ts.map +1 -0
- package/dist/work-items/board-filter-options.js +27 -0
- package/dist/work-items/board-filter-options.js.map +1 -0
- package/dist/work-items/board-phases.d.ts +28 -0
- package/dist/work-items/board-phases.d.ts.map +1 -0
- package/dist/work-items/board-phases.js +165 -0
- package/dist/work-items/board-phases.js.map +1 -0
- package/dist/work-items/card-facts.d.ts +24 -0
- package/dist/work-items/card-facts.d.ts.map +1 -0
- package/dist/work-items/card-facts.js +75 -0
- package/dist/work-items/card-facts.js.map +1 -0
- package/dist/work-items/card-labels.d.ts +5 -0
- package/dist/work-items/card-labels.d.ts.map +1 -0
- package/dist/work-items/card-labels.js +13 -0
- package/dist/work-items/card-labels.js.map +1 -0
- package/dist/work-items/card-number.d.ts +10 -0
- package/dist/work-items/card-number.d.ts.map +1 -0
- package/dist/work-items/card-number.js +15 -0
- package/dist/work-items/card-number.js.map +1 -0
- package/dist/work-items/card-people.d.ts +25 -0
- package/dist/work-items/card-people.d.ts.map +1 -0
- package/dist/work-items/card-people.js +100 -0
- package/dist/work-items/card-people.js.map +1 -0
- package/dist/work-items/card-search-text.d.ts +4 -0
- package/dist/work-items/card-search-text.d.ts.map +1 -0
- package/dist/work-items/card-search-text.js +15 -0
- package/dist/work-items/card-search-text.js.map +1 -0
- package/dist/work-items/card-source-filters.d.ts +23 -0
- package/dist/work-items/card-source-filters.d.ts.map +1 -0
- package/dist/work-items/card-source-filters.js +25 -0
- package/dist/work-items/card-source-filters.js.map +1 -0
- package/dist/work-items/create-work-item.d.ts +0 -6
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +2 -7
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/list-related-cards.d.ts +4 -0
- package/dist/work-items/list-related-cards.d.ts.map +1 -0
- package/dist/work-items/list-related-cards.js +24 -0
- package/dist/work-items/list-related-cards.js.map +1 -0
- package/dist/work-items/search-words.d.ts +5 -0
- package/dist/work-items/search-words.d.ts.map +1 -0
- package/dist/work-items/search-words.js +12 -0
- package/dist/work-items/search-words.js.map +1 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +92 -47
- package/dist/workspace.js.map +1 -1
- package/package.json +6 -5
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { resolveTenantProviderDefaultModel } from "../routes/tenant-credentials.js";
|
|
2
|
-
import {
|
|
2
|
+
import { FactoryDispatchError } from "../rules/dispatch-errors.js";
|
|
3
|
+
import { effectiveModelScope, factoryPrincipalId } from "../storage/domains/projects/base.js";
|
|
3
4
|
import { SourceControlConnectionNotFoundError } from "../storage/domains/source-control/base.js";
|
|
4
5
|
import { legacyGithubWorkItemBranch } from "../work-item-branch.js";
|
|
5
6
|
import { resolveEnvironmentRepositories } from "./environment-repositories.js";
|
|
@@ -151,10 +152,9 @@ async function resolvePrimaryEnvironmentRepository(args) {
|
|
|
151
152
|
* repository's pinned or default branch as the base. The sandbox itself boots
|
|
152
153
|
* every environment repository.
|
|
153
154
|
*
|
|
154
|
-
* The run is attributed to `attributeToUserId` when the caller
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
* because a genuinely autonomous run has no interactive user of its own.
|
|
155
|
+
* The run is attributed to `attributeToUserId` when the caller names a person
|
|
156
|
+
* for it, and only otherwise falls back to whoever connected the repository
|
|
157
|
+
* (`connection.createdByUserId`).
|
|
158
158
|
*/
|
|
159
159
|
async function ensureFactorySourceSession(args) {
|
|
160
160
|
const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;
|
|
@@ -250,6 +250,20 @@ async function hydrateFactorySession(session, args) {
|
|
|
250
250
|
}
|
|
251
251
|
return switched ? selectedModelId : void 0;
|
|
252
252
|
}
|
|
253
|
-
|
|
253
|
+
/**
|
|
254
|
+
* A run owned by the Factory reaches models through the organization alone: its stored
|
|
255
|
+
* keys and the providers it configured. With neither it cannot run however often it is
|
|
256
|
+
* retried, so say what to add instead of starting a run that dies on its first model call.
|
|
257
|
+
*/
|
|
258
|
+
async function requireOrganizationModelKey(sources, project) {
|
|
259
|
+
if (!sources?.modelCredentials || sources.deploymentModelProviders?.size) return;
|
|
260
|
+
if ((await sources.modelCredentials.listCredentials(project.orgId, factoryPrincipalId(project.id))).some((credential) => credential.scope === "org")) return;
|
|
261
|
+
if (sources.customProviders) {
|
|
262
|
+
await sources.customProviders.ensureReady();
|
|
263
|
+
if ((await sources.customProviders.list({ orgId: project.orgId })).length) return;
|
|
264
|
+
}
|
|
265
|
+
throw new FactoryDispatchError("factory_org_key_missing", "This Factory runs its cards on the organization's model keys, and none is set. Add an organization key or provider under Settings → Models, then retry.");
|
|
266
|
+
}
|
|
267
|
+
export { FactorySourceControlConflictError, FactorySourceSessionResolutionError, createSourceControlSessionLookup, ensureFactorySourceSession, hydrateFactorySession, requireOrganizationModelKey, resolveFactorySessionModel, resolveFactorySourceControl, resolvePrimaryEnvironmentRepository };
|
|
254
268
|
|
|
255
269
|
//# sourceMappingURL=factory-session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { legacyGithubWorkItemBranch } from '../work-item-branch.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n // Prefer an existing current branch, then the legacy branch on this exact\n // repository and owner. Never reuse another repository's same-number card.\n const legacyBranch = legacyGithubWorkItemBranch(branch);\n const lookup = { projectRepositoryId: resolved.projectRepositoryId, userId };\n const existing = legacyBranch\n ? ((await sourceControl.sessions.getForBranch({ ...lookup, branch })) ??\n (await sourceControl.sessions.getForBranch({ ...lookup, branch: legacyBranch })))\n : null;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch: existing?.branch ?? branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched ? selectedModelId : undefined;\n}\n"],"mappings":";;;;;;;AAmBA,IAAa,oCAAb,cAAuD,MAAM,CAAC;;AAG9D,eAAsB,2BAA2B,MAQkB;CACjE,IAAI,CAAC,KAAK,YAAY,CAAC,KAAK,kBAAkB,MAAM,IAAI,MAAM,sCAAsC;CAEpG,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,KAAK,iBAAiB,CAAC;CACzE,IAAI,CAAC,WAAW,QAAQ,UAAU,KAAK,OAAO,MAAM,IAAI,MAAM,sCAAsC;CACpG,IAAI,oBAAoB,QAAQ,YAAY,KAAK,OAAO,MAAM,WAC5D,OAAO;EAAE,YAAY;EAAW,GAAI,QAAQ,iBAAiB,EAAE,SAAS,QAAQ,eAAe,IAAI,CAAC;CAAG;CAGzG,IAAI;EACF,MAAM,cAAc,MAAM,KAAK,eAAe,IAAI;GAAE,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAY,CAAC;EACjG,OAAO;GAAE,YAAY;GAAQ,GAAI,aAAa,UAAU,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;EAAG;CACjG,SAAS,OAAO;EACd,QAAQ,KAAK,6EAA6E;GACxF,OAAO,KAAK;GACZ,aAAa,KAAK;GAClB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;EACD,OAAO,EAAE,YAAY,OAAO;CAC9B;AACF;;;;;;AAkBA,SAAgB,iCACd,gBAC4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5B;GAAE,OAAO,KAAK;GAAO,QAAQ,KAAK;GAAa,iBAAiB,KAAK;EAAW,GAChF,WACF,CAAC,CAAC,OAAM,UAAS;GACf,QAAQ,KAAK,8DAA8D,EACzE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;EAEH,CAAC,KACoC;CACvC;CACA,IAAI,CAAC,iBAAiB,OAAO,KAAA;CAE7B,IAAI,WAAW;CACf,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,eAAe;CAC5C,SAAS,OAAO;EACd,WAAW;EACX,QAAQ,KAAK,wDAAwD;GACnE,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;CAIA,KAAK,MAAM,aAAa;EAAC;EAAW;EAAQ;CAAS,GACnD,IAAI;EACF,MAAM,QAAQ,UAAU,MAAM,IAAI;GAAE,SAAS;GAAiB;EAAU,CAAC;CAC3E,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE;GAC5E;GACA,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;CAGF,OAAO,WAAW,kBAAkB,KAAA;AACtC"}
|
|
1
|
+
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { legacyGithubWorkItemBranch } from '../work-item-branch.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller names a person\n * for it, and only otherwise falls back to whoever connected the repository\n * (`connection.createdByUserId`).\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n // Prefer an existing current branch, then the legacy branch on this exact\n // repository and owner. Never reuse another repository's same-number card.\n const legacyBranch = legacyGithubWorkItemBranch(branch);\n const lookup = { projectRepositoryId: resolved.projectRepositoryId, userId };\n const existing = legacyBranch\n ? ((await sourceControl.sessions.getForBranch({ ...lookup, branch })) ??\n (await sourceControl.sessions.getForBranch({ ...lookup, branch: legacyBranch })))\n : null;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch: existing?.branch ?? branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched ? selectedModelId : undefined;\n}\n\n/** Where a Factory-owned run can find a model to call. */\nexport interface OrganizationModelSources {\n modelCredentials?: Pick<ModelCredentialsStorage, 'listCredentials'>;\n /** OpenAI-compatible providers the organization configured, each with its own key. */\n customProviders?: Pick<CustomProvidersStorage, 'ensureReady' | 'list'>;\n /** Providers that run on the server process's own credentials, so need no stored key. */\n deploymentModelProviders?: ReadonlySet<string>;\n}\n\n/**\n * A run owned by the Factory reaches models through the organization alone: its stored\n * keys and the providers it configured. With neither it cannot run however often it is\n * retried, so say what to add instead of starting a run that dies on its first model call.\n */\nexport async function requireOrganizationModelKey(\n sources: OrganizationModelSources | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n): Promise<void> {\n if (!sources?.modelCredentials || sources.deploymentModelProviders?.size) return;\n const credentials = await sources.modelCredentials.listCredentials(project.orgId, factoryPrincipalId(project.id));\n if (credentials.some(credential => credential.scope === 'org')) return;\n if (sources.customProviders) {\n await sources.customProviders.ensureReady();\n if ((await sources.customProviders.list({ orgId: project.orgId })).length) return;\n }\n throw new FactoryDispatchError(\n 'factory_org_key_missing',\n \"This Factory runs its cards on the organization's model keys, and none is set. Add an organization key or provider under Settings → Models, then retry.\",\n );\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,oCAAb,cAAuD,MAAM,CAAC;;AAG9D,eAAsB,2BAA2B,MAQkB;CACjE,IAAI,CAAC,KAAK,YAAY,CAAC,KAAK,kBAAkB,MAAM,IAAI,MAAM,sCAAsC;CAEpG,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,KAAK,iBAAiB,CAAC;CACzE,IAAI,CAAC,WAAW,QAAQ,UAAU,KAAK,OAAO,MAAM,IAAI,MAAM,sCAAsC;CACpG,IAAI,oBAAoB,QAAQ,YAAY,KAAK,OAAO,MAAM,WAC5D,OAAO;EAAE,YAAY;EAAW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AACtC;;;;;;AAgBA,eAAsB,4BACpB,SACA,SACe;CACf,IAAI,CAAC,SAAS,oBAAoB,QAAQ,0BAA0B,MAAM;CAE1E,KAAI,MADsB,QAAQ,iBAAiB,gBAAgB,QAAQ,OAAO,mBAAmB,QAAQ,EAAE,CAAC,EAAA,CAChG,MAAK,eAAc,WAAW,UAAU,KAAK,GAAG;CAChE,IAAI,QAAQ,iBAAiB;EAC3B,MAAM,QAAQ,gBAAgB,YAAY;EAC1C,KAAK,MAAM,QAAQ,gBAAgB,KAAK,EAAE,OAAO,QAAQ,MAAM,CAAC,EAAA,CAAG,QAAQ;CAC7E;CACA,MAAM,IAAI,qBACR,2BACA,yJACF;AACF"}
|
|
@@ -11,7 +11,7 @@ export declare const AUDIT_ACTIONS: {
|
|
|
11
11
|
readonly session: readonly ['owner_transferred'];
|
|
12
12
|
readonly board: readonly ['created', 'updated', 'deleted', 'reset'];
|
|
13
13
|
readonly skill: readonly ['updated', 'reverted'];
|
|
14
|
-
readonly intake_route: readonly ['created', 'updated', 'deleted', 'reordered'];
|
|
14
|
+
readonly intake_route: readonly ['created', 'updated', 'deleted', 'reordered', 'rerouted'];
|
|
15
15
|
readonly sandbox_env: readonly ['set', 'updated', 'deleted'];
|
|
16
16
|
};
|
|
17
17
|
export type AuditNamespace = keyof typeof AUDIT_ACTIONS;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,aAAa;aACxB,SAAS,YAAG,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAAE,mBAAmB;aACtG,GAAG,YAAG,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU;aAChF,GAAG,YAAG,QAAQ,EAAE,MAAM,EAAE,WAAW;aACnC,KAAK,YAAG,QA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Ac,CAAC,CAAC;AAElB,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,cAAc,CAEvE;AAED,wBAAgB,eAAe,IAAI,cAAc,EAAE,CAElD;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAIxG;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,WAAW,CAGjE;AAED,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,SAAS,cAAc,EAAE,GAAG,MAAM,EAAE,CAExF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.js","names":[],"sources":["../../../../src/storage/domains/audit/actions.ts"],"sourcesContent":["/**\n * Every action the trail can hold, by namespace. Register new ones in the\n * WorkOS dashboard under Audit Logs → Events before the mirror accepts them.\n */\nexport const AUDIT_ACTIONS = {\n work_item: ['created', 'updated', 'deleted', 'stage_moved', 'transition_rejected', 'labels_reconciled'],\n run: ['started', 'ended', 'approved', 'dismissed', 'retry', 'queued', 'rejected'],\n git: ['commit', 'push', 'pr_opened'],\n agent: ['commit', 'push', 'pr_opened', 'signaled'],\n intake: ['config_updated', 'binding_updated', 'label_route_updated'],\n session: ['owner_transferred'],\n board: ['created', 'updated', 'deleted', 'reset'],\n skill: ['updated', 'reverted'],\n intake_route: ['created', 'updated', 'deleted', 'reordered'],\n sandbox_env: ['set', 'updated', 'deleted'],\n} as const;\n\nexport type AuditNamespace = keyof typeof AUDIT_ACTIONS;\n\nexport type AuditAction = {\n [Namespace in AuditNamespace]: `factory.${Namespace}.${(typeof AUDIT_ACTIONS)[Namespace][number]}`;\n}[AuditNamespace];\n\nexport function isAuditNamespace(value: string): value is AuditNamespace {\n return Object.hasOwn(AUDIT_ACTIONS, value);\n}\n\nexport function auditNamespaces(): AuditNamespace[] {\n return Object.keys(AUDIT_ACTIONS).filter(isAuditNamespace);\n}\n\nexport function parseAuditAction(action: string): { namespace: AuditNamespace; leaf: string } | undefined {\n const [prefix, namespace, leaf, ...rest] = action.split('.');\n if (prefix !== 'factory' || namespace === undefined || leaf === undefined || rest.length > 0) return undefined;\n return isAuditNamespace(namespace) ? { namespace, leaf } : undefined;\n}\n\nexport function isAuditAction(value: string): value is AuditAction {\n const parsed = parseAuditAction(value);\n return parsed !== undefined && AUDIT_ACTIONS[parsed.namespace].some(leaf => leaf === parsed.leaf);\n}\n\nexport function auditActionsInNamespaces(namespaces: readonly AuditNamespace[]): string[] {\n return namespaces.flatMap(namespace => AUDIT_ACTIONS[namespace].map(leaf => `factory.${namespace}.${leaf}`));\n}\n"],"mappings":";;;;;AAIA,MAAa,gBAAgB;CAC3B,WAAW;EAAC;EAAW;EAAW;EAAW;EAAe;EAAuB;CAAmB;CACtG,KAAK;EAAC;EAAW;EAAS;EAAY;EAAa;EAAS;EAAU;CAAU;CAChF,KAAK;EAAC;EAAU;EAAQ;CAAW;CACnC,OAAO;EAAC;EAAU;EAAQ;EAAa;CAAU;CACjD,QAAQ;EAAC;EAAkB;EAAmB;CAAqB;CACnE,SAAS,CAAC,mBAAmB;CAC7B,OAAO;EAAC;EAAW;EAAW;EAAW;CAAO;CAChD,OAAO,CAAC,WAAW,UAAU;CAC7B,cAAc;EAAC;EAAW;EAAW;EAAW;
|
|
1
|
+
{"version":3,"file":"actions.js","names":[],"sources":["../../../../src/storage/domains/audit/actions.ts"],"sourcesContent":["/**\n * Every action the trail can hold, by namespace. Register new ones in the\n * WorkOS dashboard under Audit Logs → Events before the mirror accepts them.\n */\nexport const AUDIT_ACTIONS = {\n work_item: ['created', 'updated', 'deleted', 'stage_moved', 'transition_rejected', 'labels_reconciled'],\n run: ['started', 'ended', 'approved', 'dismissed', 'retry', 'queued', 'rejected'],\n git: ['commit', 'push', 'pr_opened'],\n agent: ['commit', 'push', 'pr_opened', 'signaled'],\n intake: ['config_updated', 'binding_updated', 'label_route_updated'],\n session: ['owner_transferred'],\n board: ['created', 'updated', 'deleted', 'reset'],\n skill: ['updated', 'reverted'],\n intake_route: ['created', 'updated', 'deleted', 'reordered', 'rerouted'],\n sandbox_env: ['set', 'updated', 'deleted'],\n} as const;\n\nexport type AuditNamespace = keyof typeof AUDIT_ACTIONS;\n\nexport type AuditAction = {\n [Namespace in AuditNamespace]: `factory.${Namespace}.${(typeof AUDIT_ACTIONS)[Namespace][number]}`;\n}[AuditNamespace];\n\nexport function isAuditNamespace(value: string): value is AuditNamespace {\n return Object.hasOwn(AUDIT_ACTIONS, value);\n}\n\nexport function auditNamespaces(): AuditNamespace[] {\n return Object.keys(AUDIT_ACTIONS).filter(isAuditNamespace);\n}\n\nexport function parseAuditAction(action: string): { namespace: AuditNamespace; leaf: string } | undefined {\n const [prefix, namespace, leaf, ...rest] = action.split('.');\n if (prefix !== 'factory' || namespace === undefined || leaf === undefined || rest.length > 0) return undefined;\n return isAuditNamespace(namespace) ? { namespace, leaf } : undefined;\n}\n\nexport function isAuditAction(value: string): value is AuditAction {\n const parsed = parseAuditAction(value);\n return parsed !== undefined && AUDIT_ACTIONS[parsed.namespace].some(leaf => leaf === parsed.leaf);\n}\n\nexport function auditActionsInNamespaces(namespaces: readonly AuditNamespace[]): string[] {\n return namespaces.flatMap(namespace => AUDIT_ACTIONS[namespace].map(leaf => `factory.${namespace}.${leaf}`));\n}\n"],"mappings":";;;;;AAIA,MAAa,gBAAgB;CAC3B,WAAW;EAAC;EAAW;EAAW;EAAW;EAAe;EAAuB;CAAmB;CACtG,KAAK;EAAC;EAAW;EAAS;EAAY;EAAa;EAAS;EAAU;CAAU;CAChF,KAAK;EAAC;EAAU;EAAQ;CAAW;CACnC,OAAO;EAAC;EAAU;EAAQ;EAAa;CAAU;CACjD,QAAQ;EAAC;EAAkB;EAAmB;CAAqB;CACnE,SAAS,CAAC,mBAAmB;CAC7B,OAAO;EAAC;EAAW;EAAW;EAAW;CAAO;CAChD,OAAO,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AM,
|
|
1
|
+
{"version":3,"file":"actors.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actors.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,YAAI,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAC;AAEvE,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEhE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAWD,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,IAAI,MAAM,CAS7E"}
|
|
@@ -17,7 +17,7 @@ const AUTOMATION_ACTORS = /* @__PURE__ */ new Set([
|
|
|
17
17
|
]);
|
|
18
18
|
function isHumanActorId(actorId) {
|
|
19
19
|
if (!actorId) return false;
|
|
20
|
-
return !AUTOMATION_ACTORS.has(actorId) && !actorId.startsWith("agent:") && !actorId.startsWith("github:");
|
|
20
|
+
return !AUTOMATION_ACTORS.has(actorId) && !actorId.startsWith("agent:") && !actorId.startsWith("github:") && !actorId.startsWith("factory-project:");
|
|
21
21
|
}
|
|
22
22
|
export { AUDIT_ACTOR_TYPES, isAuditActorType, isHumanActorId };
|
|
23
23
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actors.js","names":[],"sources":["../../../../src/storage/domains/audit/actors.ts"],"sourcesContent":["export const AUDIT_ACTOR_TYPES = ['human', 'agent', 'system'] as const;\n\nexport type AuditActorType = (typeof AUDIT_ACTOR_TYPES)[number];\n\nexport function isAuditActorType(value: unknown): value is AuditActorType {\n return AUDIT_ACTOR_TYPES.some(type => type === value);\n}\n\n/** Ids the factory writes for itself: never a person, so never a profile lookup. */\nconst AUTOMATION_ACTORS = new Set([\n 'factory',\n 'system',\n 'automation',\n 'factory-rule-dispatcher',\n 'factory-tool-result-rule',\n]);\n\nexport function isHumanActorId(actorId: string | undefined): actorId is string {\n if (!actorId) return false;\n return !AUTOMATION_ACTORS.has(actorId)
|
|
1
|
+
{"version":3,"file":"actors.js","names":[],"sources":["../../../../src/storage/domains/audit/actors.ts"],"sourcesContent":["export const AUDIT_ACTOR_TYPES = ['human', 'agent', 'system'] as const;\n\nexport type AuditActorType = (typeof AUDIT_ACTOR_TYPES)[number];\n\nexport function isAuditActorType(value: unknown): value is AuditActorType {\n return AUDIT_ACTOR_TYPES.some(type => type === value);\n}\n\n/** Ids the factory writes for itself: never a person, so never a profile lookup. */\nconst AUTOMATION_ACTORS = new Set([\n 'factory',\n 'system',\n 'automation',\n 'factory-rule-dispatcher',\n 'factory-tool-result-rule',\n]);\n\nexport function isHumanActorId(actorId: string | undefined): actorId is string {\n if (!actorId) return false;\n return (\n !AUTOMATION_ACTORS.has(actorId) &&\n !actorId.startsWith('agent:') &&\n !actorId.startsWith('github:') &&\n // A Factory running its own automatic work (`factoryPrincipalId`).\n !actorId.startsWith('factory-project:')\n );\n}\n"],"mappings":";AAAA,MAAa,oBAAoB;CAAC;CAAS;CAAS;AAAQ;AAI5D,SAAgB,iBAAiB,OAAyC;CACxE,OAAO,kBAAkB,MAAK,SAAQ,SAAS,KAAK;AACtD;;AAGA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,eAAe,SAAgD;CAC7E,IAAI,CAAC,SAAS,OAAO;CACrB,OACE,CAAC,kBAAkB,IAAI,OAAO,KAC9B,CAAC,QAAQ,WAAW,QAAQ,KAC5B,CAAC,QAAQ,WAAW,SAAS,KAE7B,CAAC,QAAQ,WAAW,kBAAkB;AAE1C"}
|
|
@@ -92,7 +92,7 @@ export declare class IntakeStorage extends FactoryStorageDomain {
|
|
|
92
92
|
orgId: string;
|
|
93
93
|
/**
|
|
94
94
|
* When provided, the result contains exactly these integration ids, with
|
|
95
|
-
* unset integrations defaulting to `{ enabled:
|
|
95
|
+
* unset integrations defaulting to `{ enabled: false, sourceIds: null }`.
|
|
96
96
|
*/
|
|
97
97
|
integrationIds?: string[];
|
|
98
98
|
}): Promise<IntakeConfig>;
|
|
@@ -371,7 +371,7 @@ var IntakeStorage = class extends FactoryStorageDomain {
|
|
|
371
371
|
const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);
|
|
372
372
|
if (!integrationIds) return saved;
|
|
373
373
|
return Object.fromEntries(integrationIds.map((integrationId) => [integrationId, saved[integrationId] ?? {
|
|
374
|
-
enabled:
|
|
374
|
+
enabled: false,
|
|
375
375
|
sourceIds: null
|
|
376
376
|
}]));
|
|
377
377
|
}
|
|
@@ -579,7 +579,7 @@ var IntakeStorage = class extends FactoryStorageDomain {
|
|
|
579
579
|
if (nextSelected.length !== selected.length || nextSelected.some((sourceId, index) => sourceId !== selected[index])) {
|
|
580
580
|
const config = structuredClone(configRow.config);
|
|
581
581
|
config[integrationId] = {
|
|
582
|
-
...config[integrationId] ?? { enabled:
|
|
582
|
+
...config[integrationId] ?? { enabled: false },
|
|
583
583
|
sourceIds: nextSelected.length > 0 ? nextSelected : null
|
|
584
584
|
};
|
|
585
585
|
await ops.updateMany("intake_org_settings", { org_id: orgId }, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection\n * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or\n * writes it.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: true }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at: now });\n }\n }\n return { migrations, conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,8BAAb,cAAiD,MAAM;CACrD,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,eAAe,qBAAqB,KAAwB,OAAe,kBAAyC;CAClH,IAAI,CAAE,MAAM,IAAI,QAAQ,oBAAoB;EAAE,QAAQ;EAAO,IAAI;CAAiB,CAAC,GACjF,MAAM,IAAI,4BAA4B;AAE1C;AAWA,MAAa,wBAAsC,CAAC;AAEpD,MAAa,6BAA+C;CAC1D,MAAM;CACN,SAAS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,IAAI,IAAI,SAAS,KAAI,aAAY,aAAa,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAClG,IACE,aAAa,WAAW,SAAS,UACjC,aAAa,MAAM,UAAU,UAAU,aAAa,SAAS,MAAM,GACnE;KACA,MAAM,SAAS,gBAAgB,UAAU,MAAM;KAC/C,OAAO,iBAAiB;MACtB,GAAI,OAAO,kBAAkB,EAAE,SAAS,KAAK;MAC7C,WAAW,aAAa,SAAS,IAAI,eAAe;KACtD;KACA,MAAM,IAAI,WAAW,uBAAuB,EAAE,QAAQ,MAAM,GAAG;MAAE;MAAQ,YAAY;KAAI,CAAC;IAC5F;GACF;GACA,OAAO;IAAE;IAAY,WAAW,CAAC;GAAE;EACrC,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection\n * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or\n * writes it.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: false, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: false, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: false }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at: now });\n }\n }\n return { migrations, conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,8BAAb,cAAiD,MAAM;CACrD,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,eAAe,qBAAqB,KAAwB,OAAe,kBAAyC;CAClH,IAAI,CAAE,MAAM,IAAI,QAAQ,oBAAoB;EAAE,QAAQ;EAAO,IAAI;CAAiB,CAAC,GACjF,MAAM,IAAI,4BAA4B;AAE1C;AAWA,MAAa,wBAAsC,CAAC;AAEpD,MAAa,6BAA+C;CAC1D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAkC,SAAS,CAAC,QAAQ;CAAE,CAAC;AACjF;;AAGA,MAAa,qCAAu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AAS,MAAM;MAC9C,WAAW,aAAa,SAAS,IAAI,eAAe;KACtD;KACA,MAAM,IAAI,WAAW,uBAAuB,EAAE,QAAQ,MAAM,GAAG;MAAE;MAAQ,YAAY;KAAI,CAAC;IAC5F;GACF;GACA,OAAO;IAAE;IAAY,WAAW,CAAC;GAAE;EACrC,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
|
|
@@ -17,6 +17,14 @@ export declare function effectiveModelScope(scope: FactoryModelScope, context: '
|
|
|
17
17
|
* the `local` sentinel, so the prefix cannot collide.
|
|
18
18
|
*/
|
|
19
19
|
export declare function factoryProjectSettingsUserId(factoryProjectId: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* The Factory as the owner of work nobody started: the `user_id` of a phase session a
|
|
22
|
+
* webhook, an automatic phase or a rule opened, and the user its runs authenticate as.
|
|
23
|
+
* It is the settings sentinel, so such a run reads the Factory's own settings rows and,
|
|
24
|
+
* having no personal rows, only ever resolves the organization's model keys.
|
|
25
|
+
*/
|
|
26
|
+
export declare const factoryPrincipalId: typeof factoryProjectSettingsUserId;
|
|
27
|
+
export declare function isFactoryPrincipalId(userId: string | null | undefined): boolean;
|
|
20
28
|
export interface FactoryProject {
|
|
21
29
|
id: string;
|
|
22
30
|
orgId: 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,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;QACX,KAAK,EAAE,MAAM,CAAC;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED;;;;;;OAMG;IACG,iBAAiB,CAAC,EACtB,EAAE,EACF,KAAK,EACL,OAAY,EACZ,QAAgB,EAChB,GAAgB,GACjB,EAAE;QACD,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,IAAI,CACZ,yBAAyB,EACzB,aAAa,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,sBAAsB,CAC9E,CAAC;QACF,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBnB;IAED;;;;;;OAMG;IACG,iBAAiB,CAAC,EACtB,EAAE,EACF,OAAO,EACP,UAAU,EACV,KAAK,EACL,GAAgB,GACjB,EAAE;QACD,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9B,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED,2GAA2G;IACrG,MAAM,CACV,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAC5C,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GAClD,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAWhC;CACF"}
|
|
1
|
+
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/projects/base.ts"],"names":[],"mappings":"AACA,OAA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M,EAAE,MAAM,CAAC,CAAC;QAC9B,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED,2GAA2G;IACrG,MAAM,CACV,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAC5C,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GAClD,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAWhC;CACF"}
|
|
@@ -24,6 +24,16 @@ function effectiveModelScope(scope, context) {
|
|
|
24
24
|
function factoryProjectSettingsUserId(factoryProjectId) {
|
|
25
25
|
return `factory-project:${factoryProjectId}`;
|
|
26
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* The Factory as the owner of work nobody started: the `user_id` of a phase session a
|
|
29
|
+
* webhook, an automatic phase or a rule opened, and the user its runs authenticate as.
|
|
30
|
+
* It is the settings sentinel, so such a run reads the Factory's own settings rows and,
|
|
31
|
+
* having no personal rows, only ever resolves the organization's model keys.
|
|
32
|
+
*/
|
|
33
|
+
const factoryPrincipalId = factoryProjectSettingsUserId;
|
|
34
|
+
function isFactoryPrincipalId(userId) {
|
|
35
|
+
return userId?.startsWith("factory-project:") === true;
|
|
36
|
+
}
|
|
27
37
|
const FACTORY_PROJECTS_SCHEMA = {
|
|
28
38
|
name: "factory_projects",
|
|
29
39
|
columns: {
|
|
@@ -401,6 +411,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
|
|
|
401
411
|
}, { isolationLevel: "serializable" });
|
|
402
412
|
}
|
|
403
413
|
};
|
|
404
|
-
export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope, factoryProjectSettingsUserId };
|
|
414
|
+
export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope, factoryPrincipalId, factoryProjectSettingsUserId, isFactoryPrincipalId };
|
|
405
415
|
|
|
406
416
|
//# sourceMappingURL=base.js.map
|