@mastra/factory 0.12.0-alpha.2 → 0.12.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +24 -14
  4. package/dist/factory.js.map +1 -1
  5. package/dist/integrations/base.d.ts +9 -0
  6. package/dist/integrations/base.d.ts.map +1 -1
  7. package/dist/integrations/slack/feed-publisher.d.ts +26 -0
  8. package/dist/integrations/slack/feed-publisher.d.ts.map +1 -0
  9. package/dist/integrations/slack/feed-publisher.js +44 -0
  10. package/dist/integrations/slack/feed-publisher.js.map +1 -0
  11. package/dist/integrations/slack/integration.d.ts +2 -0
  12. package/dist/integrations/slack/integration.d.ts.map +1 -1
  13. package/dist/integrations/slack/integration.js +5 -0
  14. package/dist/integrations/slack/integration.js.map +1 -1
  15. package/dist/integrations/slack/slack.d.ts +13 -1
  16. package/dist/integrations/slack/slack.d.ts.map +1 -1
  17. package/dist/integrations/slack/slack.js +78 -6
  18. package/dist/integrations/slack/slack.js.map +1 -1
  19. package/dist/routes/surface.d.ts +5 -0
  20. package/dist/routes/surface.d.ts.map +1 -1
  21. package/dist/routes/surface.js +4 -1
  22. package/dist/routes/surface.js.map +1 -1
  23. package/dist/storage/domains/comments/base.d.ts.map +1 -1
  24. package/dist/storage/domains/comments/base.js +2 -4
  25. package/dist/storage/domains/comments/base.js.map +1 -1
  26. package/dist/storage/domains/comments/domain.d.ts +9 -2
  27. package/dist/storage/domains/comments/domain.d.ts.map +1 -1
  28. package/dist/storage/domains/comments/domain.js +18 -15
  29. package/dist/storage/domains/comments/domain.js.map +1 -1
  30. package/dist/storage/domains/comments/feed-sync.d.ts +9 -26
  31. package/dist/storage/domains/comments/feed-sync.d.ts.map +1 -1
  32. package/dist/storage/domains/work-items/base.d.ts +19 -0
  33. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  34. package/dist/storage/domains/work-items/base.js +47 -23
  35. package/dist/storage/domains/work-items/base.js.map +1 -1
  36. package/factory-skills/factory-rereview/SKILL.md +13 -12
  37. package/factory-skills/factory-review/SKILL.md +12 -11
  38. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport { factoryLaneForRole, factoryRuleStage } from '../rules/types.js';\nimport type { MastraFactorySandboxConfig } from '../sandbox/session-sandbox.js';\nimport {\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactoryDefaultModelId,\n} from '../session/factory-session.js';\nimport { LiveSessions } from '../session/live-sessions.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport {\n SourceControlConnectionNotFoundError,\n type SourceControlStorage,\n} from '../storage/domains/source-control/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemBranch, workItemBranchSource } from '../work-item-branch.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: MastraFactorySandboxConfig;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n comments: WorkItemCommentsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n try {\n const branch = workItemBranch({\n id: input.item.id,\n source: workItemBranchSource(input.item.externalSource),\n metadata: input.item.metadata,\n });\n // Only the Intake exit derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n const currentStage = factoryRuleStage(input.item.stages);\n const destinationStage = currentStage === 'intake' ? factoryLaneForRole(input.role) : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactorySourceSession({\n sourceControl: github.sourceControlStorage,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n // A human-approved proposal has an interactive user: attribute the run to\n // the approver, not the repo connector.\n attributeToUserId: input.record.approvedBy ?? undefined,\n });\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n defaultModelId: await resolveFactoryDefaultModelId(projects, input.record.factoryProjectId),\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n 'projects' | 'intake' | 'workItems' | 'channelIdentity' | 'memorySettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n new FactoryFeedReader(deps.domains.comments),\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, deps.domains.projects, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n filesystem: deps.domains.filesystem,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n sourceControlSessions: deps.sourceControlStorage.forIntegration('github').sessions,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled },\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async () => deps.factoryStorage?.getMastraStorage().getStore('knowledge'),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n comments: deps.domains.comments,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: new LiveSessions(deps.controller),\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,2BAA2B;CAC/B,eAAe;CACf,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,iBAAiB;CACjB,cAAc;CACd,aAAa;AACf;AAqDA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC;IACxC;GACF;EACF;EAEA,MAAM,gBAAgB,MAAM;EAC5B,OAAO;GACL,GAAG;GACH,eAAe,OAAO,SAA8C;IAClE,MAAM,UAAU,MAAM,cAAc,IAAI;IACxC,OAAO,OAAO,YAA2C;KACvD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA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AK,UAAU;EAChD,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport { factoryLaneForRole, factoryRuleStage } from '../rules/types.js';\nimport type { MastraFactorySandboxConfig } from '../sandbox/session-sandbox.js';\nimport {\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactoryDefaultModelId,\n} from '../session/factory-session.js';\nimport { LiveSessions } from '../session/live-sessions.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type { CommentsDomain } from '../storage/domains/comments/domain.js';\nimport { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport {\n SourceControlConnectionNotFoundError,\n type SourceControlStorage,\n} from '../storage/domains/source-control/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemBranch, workItemBranchSource } from '../work-item-branch.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: MastraFactorySandboxConfig;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n comments: WorkItemCommentsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n /** Work-item feed service, handed to integrations that ingest platform messages. */\n feed: CommentsDomain;\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n try {\n const branch = workItemBranch({\n id: input.item.id,\n source: workItemBranchSource(input.item.externalSource),\n metadata: input.item.metadata,\n });\n // Only the Intake exit derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n const currentStage = factoryRuleStage(input.item.stages);\n const destinationStage = currentStage === 'intake' ? factoryLaneForRole(input.role) : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactorySourceSession({\n sourceControl: github.sourceControlStorage,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n // A human-approved proposal has an interactive user: attribute the run to\n // the approver, not the repo connector.\n attributeToUserId: input.record.approvedBy ?? undefined,\n });\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n defaultModelId: await resolveFactoryDefaultModelId(projects, input.record.factoryProjectId),\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n /** Work-item feed service, so a channel integration can ingest platform messages. */\n feed: CommentsDomain;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n 'projects' | 'intake' | 'workItems' | 'channelIdentity' | 'memorySettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems, feed: deps.feed } : {}),\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n new FactoryFeedReader(deps.domains.comments),\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, deps.domains.projects, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n filesystem: deps.domains.filesystem,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n sourceControlSessions: deps.sourceControlStorage.forIntegration('github').sessions,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled },\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async () => deps.factoryStorage?.getMastraStorage().getStore('knowledge'),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n comments: deps.domains.comments,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: new LiveSessions(deps.controller),\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,2BAA2B;CAC/B,eAAe;CACf,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,iBAAiB;CACjB,cAAc;CACd,aAAa;AACf;AAuDA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC;IACxC;GACF;EACF;EAEA,MAAM,gBAAgB,MAAM;EAC5B,OAAO;GACL,GAAG;GACH,eAAe,OAAO,SAA8C;IAClE,MAAM,UAAU,MAAM,cAAc,IAAI;IACxC,OAAO,OAAO,YAA2C;KACvD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SA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AiB,CAAC,EACtB,KAAK,EACL,gBAAgB,EAChB,KAAW,GACZ,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;CAuD/B"}
@@ -1,4 +1,5 @@
1
1
  import { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA } from "./schema.js";
2
+ import { externalSourceKey } from "../work-items/base.js";
2
3
  import { fanOutWorkItemActivity, listActivityForUser } from "./activity.js";
3
4
  import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage";
4
5
  //#region src/storage/domains/comments/base.ts
@@ -57,10 +58,7 @@ function decodeCommentCursor(cursor) {
57
58
  };
58
59
  }
59
60
  function commentSourceKey(input) {
60
- if (input.externalSource) {
61
- const source = input.externalSource;
62
- return `${source.integrationId}:${source.type}:${source.externalId}`;
63
- }
61
+ if (input.externalSource) return externalSourceKey(input.externalSource);
64
62
  if (input.clientToken) return `local:comment:${input.clientToken}`;
65
63
  return null;
66
64
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#insertWithMentions","#writeMentionRows","#fanOutActivity","#listAround","#listMentionRows"],"sources":["../../../../src/storage/domains/comments/base.ts"],"sourcesContent":["/**\n * Work-item comments domain — one message list per work item, materialized\n * from every source. Local creates and platform mirrors (Slack, Linear,\n * GitHub) share one idempotency story: `external_source` json + derived\n * `source_key` under a partial unique index, a local retry token being just\n * another source (`local:comment:<uuid>`).\n *\n * Ordering is caller-settable `occurred_at`, never insert time — ingest\n * backdates to the platform timestamp and retries arrive out of order.\n * Deletes are soft: the tombstone holds the ordering and its kept\n * `source_key` stops a redelivery from resurrecting the row.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\n\nimport type { ExternalWorkItemSource } from '../work-items/base.js';\nimport { fanOutWorkItemActivity, listActivityForUser, PARTICIPANT_SCAN_LIMIT } from './activity.js';\nimport type { WorkItemActivityRow } from './activity.js';\nimport type { FactoryActorExternalIdentity, FactoryActorRef } from './actor.js';\nimport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type { WorkItemActivityRow } from './activity.js';\nexport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type WorkItemCommentKind = 'comment';\n\nexport interface FactoryMentionRef {\n kind: 'user';\n id: string;\n}\n\nexport interface WorkItemCommentReplyRef {\n commentId: string;\n quote?: string;\n authorId?: string;\n authorName?: string;\n}\n\nexport interface WorkItemCommentRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n kind: WorkItemCommentKind;\n body: string;\n bodyFormat: string;\n author: FactoryActorRef;\n replyTo: WorkItemCommentReplyRef | null;\n mentions: FactoryMentionRef[];\n externalSource: ExternalWorkItemSource | null;\n sourceKey: string | null;\n occurredAt: Date;\n editedAt: Date | null;\n deletedAt: Date | null;\n deletedBy: string | null;\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemCommentInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n author: FactoryActorRef;\n body: string;\n bodyFormat?: string;\n replyTo?: WorkItemCommentReplyRef;\n mentions?: FactoryMentionRef[];\n externalSource?: ExternalWorkItemSource;\n /** Local idempotent-retry token; mutually exclusive with `externalSource`. */\n clientToken?: string;\n occurredAt?: Date;\n}\n\nexport interface EditWorkItemCommentInput {\n orgId: string;\n commentId: string;\n body: string;\n mentions?: FactoryMentionRef[];\n /** The acting user; their own handle never becomes a mention row. */\n editorId?: string;\n /** When set, the edit only lands if the row is still at this revision. */\n expectedRevision?: number;\n now?: Date;\n}\n\nexport interface EditWorkItemCommentResult {\n comment: WorkItemCommentRow;\n addedMentions: FactoryMentionRef[];\n removedMentions: FactoryMentionRef[];\n}\n\nexport interface ListWorkItemCommentsInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n before?: string;\n limit?: number;\n /**\n * Anchor the first page on this comment: it and every comment newer than it,\n * so a deep link opens on the target instead of paging back to find it.\n * Ignored when the comment is gone, or sits further back than one page holds.\n */\n around?: string;\n}\n\n/** The only two work-item columns the feed refresh reads or writes. */\ninterface WorkItemFeedColumns extends Record<string, unknown> {\n comment_count: number;\n feed_activity_at: Date | null;\n}\n\n/** A feed snapshot: how many comments the item had, and when it last moved. */\nexport interface FeedActivitySnapshot {\n commentCount: number;\n feedActivityAt: Date;\n}\n\n/**\n * The refresh reads its snapshot outside the write transaction, so two of them\n * can interleave and the loser can write last. This is the one rule that keeps\n * that from undoing a newer refresh: feed activity never moves backwards, and\n * on the same stamp the fuller count wins.\n *\n * Known ceiling: a soft delete sharing a millisecond with a create leaves the\n * count one high until the next feed mutation recounts. Closing that needs the\n * aggregate read inside the write transaction, which the ops layer cannot do\n * without checking out a second pool connection per open transaction.\n */\nexport function supersedesFeedActivity(next: FeedActivitySnapshot, stored: FeedActivitySnapshot): boolean {\n const drift = next.feedActivityAt.getTime() - stored.feedActivityAt.getTime();\n return drift > 0 || (drift === 0 && next.commentCount >= stored.commentCount);\n}\n\nexport interface WorkItemCommentPage {\n comments: WorkItemCommentRow[];\n nextCursor?: string;\n}\n\nexport interface WorkItemMentionRow {\n id: string;\n commentId: string;\n mentionedKind: 'user';\n mentionedId: string;\n authorId: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n occurredAt: Date;\n}\n\nexport const MAX_COMMENT_BODY_LENGTH = 16_000;\nexport const MAX_COMMENT_QUOTE_LENGTH = 500;\nexport const MAX_COMMENT_MENTIONS = 20;\n\n/** The one body policy: HTTP parsing and the service both reject on it. */\nexport function commentBodyError(body: string): string | undefined {\n if (!body.trim()) return 'Comment body must not be empty.';\n if (body.length > MAX_COMMENT_BODY_LENGTH)\n return `Comment body must be at most ${MAX_COMMENT_BODY_LENGTH} characters.`;\n return undefined;\n}\n\nconst DEFAULT_PAGE_SIZE = 30;\nconst MAX_PAGE_SIZE = 100;\n\nexport function clampCommentLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\nexport function encodeCommentCursor(row: WorkItemCommentRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\nexport function decodeCommentCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport function commentSourceKey(input: {\n externalSource?: ExternalWorkItemSource;\n clientToken?: string;\n}): string | null {\n if (input.externalSource) {\n const source = input.externalSource;\n return `${source.integrationId}:${source.type}:${source.externalId}`;\n }\n if (input.clientToken) return `local:comment:${input.clientToken}`;\n return null;\n}\n\n/** A `clientToken` replay that resolved to a different work item or author. */\nexport class CommentTokenConflictError extends Error {\n constructor() {\n super('Client token already used by a different comment.');\n this.name = 'CommentTokenConflictError';\n }\n}\n\ninterface WorkItemCommentDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n kind: WorkItemCommentKind;\n body: string;\n body_format: string;\n author_kind: FactoryActorRef['kind'];\n author_id: string;\n author_display_name: string | null;\n author_avatar_url: string | null;\n author_external: FactoryActorExternalIdentity | null;\n reply_to_comment_id: string | null;\n reply_quote: string | null;\n reply_to_author_id: string | null;\n reply_to_author_name: string | null;\n mentions: FactoryMentionRef[];\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n occurred_at: Date;\n edited_at: Date | null;\n deleted_at: Date | null;\n deleted_by: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface WorkItemMentionDbRow extends Record<string, unknown> {\n id: string;\n comment_id: string;\n mentioned_kind: 'user';\n mentioned_id: string;\n author_id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n occurred_at: Date;\n}\n\nfunction toComment(row: WorkItemCommentDbRow): WorkItemCommentRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n kind: row.kind,\n body: row.body,\n bodyFormat: row.body_format,\n author: {\n kind: row.author_kind,\n id: row.author_id,\n ...(row.author_display_name ? { displayName: row.author_display_name } : {}),\n ...(row.author_avatar_url ? { avatarUrl: row.author_avatar_url } : {}),\n ...(row.author_external ? { external: row.author_external } : {}),\n },\n replyTo: row.reply_to_comment_id\n ? {\n commentId: row.reply_to_comment_id,\n ...(row.reply_quote ? { quote: row.reply_quote } : {}),\n ...(row.reply_to_author_id ? { authorId: row.reply_to_author_id } : {}),\n ...(row.reply_to_author_name ? { authorName: row.reply_to_author_name } : {}),\n }\n : null,\n mentions: row.mentions,\n externalSource: row.external_source,\n sourceKey: row.source_key,\n occurredAt: row.occurred_at,\n editedAt: row.edited_at,\n deletedAt: row.deleted_at,\n deletedBy: row.deleted_by,\n revision: row.revision,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toMention(row: WorkItemMentionDbRow): WorkItemMentionRow {\n return {\n id: row.id,\n commentId: row.comment_id,\n mentionedKind: row.mentioned_kind,\n mentionedId: row.mentioned_id,\n authorId: row.author_id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n occurredAt: row.occurred_at,\n };\n}\n\nfunction toMentionRef(row: WorkItemMentionRow): FactoryMentionRef {\n return { kind: row.mentionedKind, id: row.mentionedId };\n}\n\nfunction mentionKey(mention: { kind: string; id: string }): string {\n return `${mention.kind}\\0${mention.id}`;\n}\n\nfunction dedupeMentions(mentions: FactoryMentionRef[] | undefined): FactoryMentionRef[] {\n if (!mentions?.length) return [];\n return [...new Map(mentions.map(mention => [mentionKey(mention), mention])).values()];\n}\n\nexport class WorkItemCommentsStorage extends FactoryStorageDomain {\n constructor() {\n super('work-item-comments');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_item_activity', {});\n await this.ops.deleteMany('work_item_comment_mentions', {});\n await this.ops.deleteMany('work_item_comments', {});\n }\n\n async create(input: CreateWorkItemCommentInput): Promise<WorkItemCommentRow> {\n const now = new Date();\n const occurredAt = input.occurredAt ?? now;\n const sourceKey = commentSourceKey(input);\n const author = input.author;\n const row: Partial<WorkItemCommentDbRow> = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n kind: 'comment',\n body: input.body,\n body_format: input.bodyFormat ?? 'markdown',\n author_kind: author.kind,\n author_id: author.id,\n author_display_name: author.displayName ?? null,\n author_avatar_url: author.avatarUrl ?? null,\n author_external: author.external ?? null,\n reply_to_comment_id: input.replyTo?.commentId ?? null,\n reply_quote: input.replyTo?.quote ?? null,\n reply_to_author_id: input.replyTo?.authorId ?? null,\n reply_to_author_name: input.replyTo?.authorName ?? null,\n mentions: dedupeMentions(input.mentions),\n external_source: input.externalSource ?? null,\n source_key: sourceKey,\n occurred_at: occurredAt,\n edited_at: null,\n deleted_at: null,\n deleted_by: null,\n revision: 1,\n created_at: now,\n updated_at: now,\n };\n\n // Insert-or-recover, never upsert: a replayed create must return the\n // existing row untouched (an upsert would clobber a later edit's body).\n // A local token resolving to another item or author is a conflict, not a\n // recovery. External keys stay lenient: a redelivery after a thread\n // re-link maps to a new item id and must still no-op.\n if (sourceKey) {\n const sourceWhere = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey,\n };\n const recover = (found: WorkItemCommentDbRow): WorkItemCommentRow => {\n if (!input.externalSource && (found.work_item_id !== input.workItemId || found.author_id !== author.id)) {\n throw new CommentTokenConflictError();\n }\n return toComment(found);\n };\n const existing = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (existing) return recover(existing);\n try {\n return await this.#insertWithMentions(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (!raced) throw error;\n return recover(raced);\n }\n }\n\n return this.#insertWithMentions(row);\n }\n\n /**\n * The one insert path a genuinely new comment takes — `create()`'s recover\n * branches never reach it, so a replay writes no mention or activity rows.\n */\n async #insertWithMentions(row: Partial<WorkItemCommentDbRow>): Promise<WorkItemCommentRow> {\n const comment = toComment(await this.ops.insertOne<WorkItemCommentDbRow>('work_item_comments', row));\n await this.#writeMentionRows(comment, comment.mentions);\n await this.#fanOutActivity(comment);\n return comment;\n }\n\n /**\n * Participants come off the item's recent authors, so the scan happens here\n * rather than in the fan-out, which must stay free of its own queries.\n */\n async #fanOutActivity(comment: WorkItemCommentRow): Promise<void> {\n const item = await this.ops.findOne<{ created_by: string } & Record<string, unknown>>('work_items', {\n id: comment.workItemId,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n });\n if (!item) return;\n const recent = await this.listRecent({\n orgId: comment.orgId,\n factoryProjectId: comment.factoryProjectId,\n workItemId: comment.workItemId,\n limit: PARTICIPANT_SCAN_LIMIT,\n });\n await fanOutWorkItemActivity(this.ops, {\n comment,\n recentAuthors: recent.filter(row => row.author.kind === 'user').map(row => row.author.id),\n createdBy: item.created_by,\n mentions: comment.mentions,\n });\n }\n\n async listActivityForUser(args: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemActivityRow[]> {\n return listActivityForUser(this.ops, args);\n }\n\n /**\n * Idempotent counter refresh on the parent work item: both columns are read\n * back off the comments (never incremented or stamped with the wall clock —\n * replays and races double an increment, and a replayed create would move a\n * work item in the feed without adding a comment; a read-back can't drift).\n * Read BEFORE `updateAtomic`: its mutator runs inside an open transaction\n * holding a pool connection, and a query in there checks out a second one —\n * concurrent posts would exhaust the pool. Reading outside means two\n * refreshes can interleave, so the write goes through\n * {@link supersedesFeedActivity} rather than landing whatever it read.\n * Touches ONLY the counter columns: `revision`/`updated_at` are the\n * stage-transition concurrency token.\n */\n async refreshWorkItemFeedActivity({\n orgId,\n factoryProjectId,\n workItemId,\n now = new Date(),\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n now?: Date;\n }): Promise<void> {\n const commentCount = await this.countForWorkItem({ orgId, factoryProjectId, workItemId });\n // Every feed mutation stamps `updated_at`, edits and tombstones included,\n // so the newest one is when this feed last moved.\n const [latest] = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n { orderBy: [['updated_at', 'desc']], limit: 1 },\n );\n const feedActivityAt = latest?.updated_at ?? now;\n await this.ops.updateAtomic<WorkItemFeedColumns>(\n 'work_items',\n { id: workItemId, org_id: orgId, factory_project_id: factoryProjectId },\n row => {\n const next = { commentCount, feedActivityAt };\n const stored = row.feed_activity_at;\n if (stored && !supersedesFeedActivity(next, { commentCount: row.comment_count, feedActivityAt: stored })) {\n return null;\n }\n return { comment_count: commentCount, feed_activity_at: feedActivityAt };\n },\n );\n }\n\n async get({ orgId, commentId }: { orgId: string; commentId: string }): Promise<WorkItemCommentRow | null> {\n const row = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', {\n id: commentId,\n org_id: orgId,\n });\n return row ? toComment(row) : null;\n }\n\n async listByIds({ orgId, ids }: { orgId: string; ids: string[] }): Promise<WorkItemCommentRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.ops.findMany<WorkItemCommentDbRow>('work_item_comments', {\n org_id: orgId,\n id: { in: ids },\n });\n return rows.map(toComment);\n }\n\n async list(input: ListWorkItemCommentsInput): Promise<WorkItemCommentPage> {\n const anchored = input.around ? await this.#listAround(input, input.around) : undefined;\n if (anchored) return anchored;\n const limit = clampCommentLimit(input.limit);\n const cursor = input.before ? decodeCommentCursor(input.before) : undefined;\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n },\n );\n const comments = rows.slice(0, limit).map(toComment);\n const hasMore = rows.length > limit;\n const last = comments[comments.length - 1];\n return {\n comments,\n ...(hasMore && last ? { nextCursor: encodeCommentCursor(last) } : {}),\n };\n }\n\n async #listAround(\n { orgId, factoryProjectId, workItemId }: ListWorkItemCommentsInput,\n commentId: string,\n ): Promise<WorkItemCommentPage | undefined> {\n const target = await this.get({ orgId, commentId });\n if (!target || target.factoryProjectId !== factoryProjectId || target.workItemId !== workItemId) return undefined;\n\n const newer = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n {\n orderBy: [\n ['occurred_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: MAX_PAGE_SIZE + 1,\n cursor: { values: [target.occurredAt, target.id] },\n },\n );\n if (newer.length > MAX_PAGE_SIZE) return undefined;\n\n const before = encodeCommentCursor(target);\n const older = await this.list({ orgId, factoryProjectId, workItemId, before, limit: 1 });\n return {\n comments: [...newer.map(toComment).reverse(), target],\n ...(older.comments.length > 0 ? { nextCursor: before } : {}),\n };\n }\n\n /**\n * Newest non-deleted comments for run-context injection, newest-first (the\n * caller reverses for display order).\n */\n async listRecent({\n orgId,\n factoryProjectId,\n workItemId,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n limit: number;\n }): Promise<WorkItemCommentRow[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n return rows.map(toComment);\n }\n\n async edit(input: EditWorkItemCommentInput): Promise<EditWorkItemCommentResult | 'conflict' | null> {\n const now = input.now ?? new Date();\n let rejection: 'deleted' | 'conflict' | undefined;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: input.commentId, org_id: input.orgId },\n current => {\n if (current.deleted_at) {\n rejection = 'deleted';\n return null;\n }\n if (input.expectedRevision !== undefined && Number(current.revision) !== input.expectedRevision) {\n rejection = 'conflict';\n return null;\n }\n return {\n body: input.body,\n mentions: dedupeMentions(input.mentions ?? current.mentions),\n edited_at: now,\n revision: Number(current.revision) + 1,\n updated_at: now,\n };\n },\n );\n if (rejection === 'conflict') return 'conflict';\n if (!updated || rejection) return null;\n const comment = toComment(updated);\n\n const existing = await this.#listMentionRows(comment.id);\n const existingKeys = new Set(existing.map(mention => mentionKey(toMentionRef(mention))));\n const nextKeys = new Set(comment.mentions.map(mentionKey));\n // Self-mentions (author, or the acting editor) never become rows, so they\n // must not report as \"added\" either — they would re-report on every edit.\n const skippedIds = new Set([comment.author.id, ...(input.editorId ? [input.editorId] : [])]);\n const addedMentions = comment.mentions.filter(\n mention => !existingKeys.has(mentionKey(mention)) && !skippedIds.has(mention.id),\n );\n const removedMentions = existing.map(toMentionRef).filter(mention => !nextKeys.has(mentionKey(mention)));\n\n // Stamped with the edit time, not the comment's creation time: the inbox\n // is a keyset on `occurred_at`, and a backdated row lands buried under\n // everything the user already saw.\n await this.#writeMentionRows(comment, addedMentions, now);\n for (const mention of removedMentions) {\n await this.ops.deleteMany('work_item_comment_mentions', {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n });\n }\n return { comment, addedMentions, removedMentions };\n }\n\n async softDelete({\n orgId,\n commentId,\n deletedBy,\n now = new Date(),\n }: {\n orgId: string;\n commentId: string;\n deletedBy: string;\n now?: Date;\n }): Promise<WorkItemCommentRow | null> {\n let alreadyDeleted = false;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.deleted_at) {\n alreadyDeleted = true;\n return null;\n }\n return {\n body: '',\n mentions: [],\n deleted_at: now,\n deleted_by: deletedBy,\n updated_at: now,\n };\n },\n );\n if (!updated || alreadyDeleted) return null;\n await this.ops.deleteMany('work_item_comment_mentions', { comment_id: commentId });\n return toComment(updated);\n }\n\n /**\n * Provenance write-back after an outbound publish. First platform wins, and\n * an existing `source_key` is kept: replacing a `local:comment:<token>` one\n * would let a client retry duplicate the row. So a web-born comment is never\n * key-deduped against its own platform echo — the host's bot-sender check is\n * the only echo layer for those rows (COR-1174).\n */\n async attachExternalSource({\n orgId,\n commentId,\n source,\n }: {\n orgId: string;\n commentId: string;\n source: ExternalWorkItemSource;\n }): Promise<WorkItemCommentRow | null> {\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.external_source) return null;\n return {\n external_source: source,\n source_key: current.source_key ?? commentSourceKey({ externalSource: source }),\n updated_at: new Date(),\n };\n },\n );\n return updated ? toComment(updated) : null;\n }\n\n async listMentionsForComment(commentId: string): Promise<WorkItemMentionRow[]> {\n return this.#listMentionRows(commentId);\n }\n\n /** Keyset inbox read for the mention attention provider, newest-first. */\n async listMentionsForUser({\n orgId,\n factoryProjectId,\n userId,\n before,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_id: userId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n ...(before ? { cursor: { values: [before.occurredAt, before.id] } } : {}),\n },\n );\n return rows.map(toMention);\n }\n\n async countForWorkItem({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<number> {\n if (!this.ops.count) {\n throw new Error('[WorkItemCommentsStorage] storage backend does not support collection counts.');\n }\n return this.ops.count('work_item_comments', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n });\n }\n\n /** Recent distinct comment authors of a project, for the roster fallback. */\n async listRecentAuthors({\n orgId,\n factoryProjectId,\n limit = 200,\n }: {\n orgId: string;\n factoryProjectId: string;\n limit?: number;\n }): Promise<FactoryActorRef[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n const authors = new Map<string, FactoryActorRef>();\n for (const row of rows) {\n if (authors.has(row.author_id)) continue;\n authors.set(row.author_id, toComment(row).author);\n }\n return [...authors.values()];\n }\n\n async #listMentionRows(commentId: string): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>('work_item_comment_mentions', {\n comment_id: commentId,\n });\n return rows.map(toMention);\n }\n\n /**\n * Self-mentions never get rows: the join exists solely for the attention\n * inbox, and `CollectionWhere` cannot express `author_id != userId` at read\n * time, so the filter happens at write time.\n */\n async #writeMentionRows(\n comment: WorkItemCommentRow,\n mentions: FactoryMentionRef[],\n occurredAt = comment.occurredAt,\n ): Promise<void> {\n for (const mention of mentions) {\n if (mention.id === comment.author.id) continue;\n await this.ops.upsertOne<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n ['comment_id', 'mentioned_kind', 'mentioned_id'],\n {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n author_id: comment.author.id,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n work_item_id: comment.workItemId,\n occurred_at: occurredAt,\n },\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkIA,SAAgB,uBAAuB,MAA4B,QAAuC;CACxG,MAAM,QAAQ,KAAK,eAAe,QAAQ,IAAI,OAAO,eAAe,QAAQ;CAC5E,OAAO,QAAQ,KAAM,UAAU,KAAK,KAAK,gBAAgB,OAAO;AAClE;AAmBA,MAAa,0BAA0B;AACvC,MAAa,2BAA2B;AACxC,MAAa,uBAAuB;;AAGpC,SAAgB,iBAAiB,MAAkC;CACjE,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;CACzB,IAAI,KAAK,SAAA,MACP,OAAO,gCAAgC,wBAAwB;AAEnE;AAEA,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAEtB,SAAgB,kBAAkB,OAAmC;CAEnE,OAAO,KAAK,IAAI,KAAK,IADF,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,KAAK,MAAM,KAAK,IAAI,mBACxD,CAAC,GAAG,aAAa;AACxD;AAEA,SAAgB,oBAAoB,KAAiC;CACnE,OAAO,GAAG,IAAI,WAAW,YAAY,EAAE,GAAG,IAAI;AAChD;AAEA,SAAgB,oBAAoB,QAA8D;CAChG,MAAM,MAAM,OAAO,YAAY,GAAG;CAClC,IAAI,OAAO,GAAG,OAAO,KAAA;CACrB,MAAM,aAAa,IAAI,KAAK,OAAO,MAAM,GAAG,GAAG,CAAC;CAChD,MAAM,KAAK,OAAO,MAAM,MAAM,CAAC;CAC/B,IAAI,OAAO,MAAM,WAAW,QAAQ,CAAC,KAAK,CAAC,IAAI,OAA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AAM,KAAK,IAAI,SAC1B,sBACA;GAAE,QAAQ;GAAO,oBAAoB;EAAiB,GACtD;GACE,SAAS,CACP,CAAC,eAAe,MAAM,GACtB,CAAC,MAAM,MAAM,CACf;GACA;EACF,CACF;EACA,MAAM,0BAAU,IAAI,IAA6B;EACjD,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,QAAQ,IAAI,IAAI,SAAS,GAAG;GAChC,QAAQ,IAAI,IAAI,WAAW,UAAU,GAAG,CAAC,CAAC,MAAM;EAClD;EACA,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;CAC7B;CAEA,MAAMA,iBAAiB,WAAkD;EAIvE,QAAO,MAHY,KAAK,IAAI,SAA+B,8BAA8B,EACvF,YAAY,UACd,CAAC,EAAA,CACW,IAAI,SAAS;CAC3B;;;;;;CAOA,MAAMH,kBACJ,SACA,UACA,aAAa,QAAQ,YACN;EACf,KAAK,MAAM,WAAW,UAAU;GAC9B,IAAI,QAAQ,OAAO,QAAQ,OAAO,IAAI;GACtC,MAAM,KAAK,IAAI,UACb,8BACA;IAAC;IAAc;IAAkB;GAAc,GAC/C;IACE,YAAY,QAAQ;IACpB,gBAAgB,QAAQ;IACxB,cAAc,QAAQ;IACtB,WAAW,QAAQ,OAAO;IAC1B,QAAQ,QAAQ;IAChB,oBAAoB,QAAQ;IAC5B,cAAc,QAAQ;IACtB,aAAa;GACf,CACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":["#insertWithMentions","#writeMentionRows","#fanOutActivity","#listAround","#listMentionRows"],"sources":["../../../../src/storage/domains/comments/base.ts"],"sourcesContent":["/**\n * Work-item comments domain — one message list per work item, materialized\n * from every source. Local creates and platform mirrors (Slack, Linear,\n * GitHub) share one idempotency story: `external_source` json + derived\n * `source_key` under a partial unique index, a local retry token being just\n * another source (`local:comment:<uuid>`).\n *\n * Ordering is caller-settable `occurred_at`, never insert time — ingest\n * backdates to the platform timestamp and retries arrive out of order.\n * Deletes are soft: the tombstone holds the ordering and its kept\n * `source_key` stops a redelivery from resurrecting the row.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\n\nimport { externalSourceKey } from '../work-items/base.js';\nimport type { ExternalWorkItemSource } from '../work-items/base.js';\nimport { fanOutWorkItemActivity, listActivityForUser, PARTICIPANT_SCAN_LIMIT } from './activity.js';\nimport type { WorkItemActivityRow } from './activity.js';\nimport type { FactoryActorExternalIdentity, FactoryActorRef } from './actor.js';\nimport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type { WorkItemActivityRow } from './activity.js';\nexport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type WorkItemCommentKind = 'comment';\n\nexport interface FactoryMentionRef {\n kind: 'user';\n id: string;\n}\n\nexport interface WorkItemCommentReplyRef {\n commentId: string;\n quote?: string;\n authorId?: string;\n authorName?: string;\n}\n\nexport interface WorkItemCommentRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n kind: WorkItemCommentKind;\n body: string;\n bodyFormat: string;\n author: FactoryActorRef;\n replyTo: WorkItemCommentReplyRef | null;\n mentions: FactoryMentionRef[];\n externalSource: ExternalWorkItemSource | null;\n sourceKey: string | null;\n occurredAt: Date;\n editedAt: Date | null;\n deletedAt: Date | null;\n deletedBy: string | null;\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemCommentInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n author: FactoryActorRef;\n body: string;\n bodyFormat?: string;\n replyTo?: WorkItemCommentReplyRef;\n mentions?: FactoryMentionRef[];\n externalSource?: ExternalWorkItemSource;\n /** Local idempotent-retry token; mutually exclusive with `externalSource`. */\n clientToken?: string;\n occurredAt?: Date;\n}\n\nexport interface EditWorkItemCommentInput {\n orgId: string;\n commentId: string;\n body: string;\n mentions?: FactoryMentionRef[];\n /** The acting user; their own handle never becomes a mention row. */\n editorId?: string;\n /** When set, the edit only lands if the row is still at this revision. */\n expectedRevision?: number;\n now?: Date;\n}\n\nexport interface EditWorkItemCommentResult {\n comment: WorkItemCommentRow;\n addedMentions: FactoryMentionRef[];\n removedMentions: FactoryMentionRef[];\n}\n\nexport interface ListWorkItemCommentsInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n before?: string;\n limit?: number;\n /**\n * Anchor the first page on this comment: it and every comment newer than it,\n * so a deep link opens on the target instead of paging back to find it.\n * Ignored when the comment is gone, or sits further back than one page holds.\n */\n around?: string;\n}\n\n/** The only two work-item columns the feed refresh reads or writes. */\ninterface WorkItemFeedColumns extends Record<string, unknown> {\n comment_count: number;\n feed_activity_at: Date | null;\n}\n\n/** A feed snapshot: how many comments the item had, and when it last moved. */\nexport interface FeedActivitySnapshot {\n commentCount: number;\n feedActivityAt: Date;\n}\n\n/**\n * The refresh reads its snapshot outside the write transaction, so two of them\n * can interleave and the loser can write last. This is the one rule that keeps\n * that from undoing a newer refresh: feed activity never moves backwards, and\n * on the same stamp the fuller count wins.\n *\n * Known ceiling: a soft delete sharing a millisecond with a create leaves the\n * count one high until the next feed mutation recounts. Closing that needs the\n * aggregate read inside the write transaction, which the ops layer cannot do\n * without checking out a second pool connection per open transaction.\n */\nexport function supersedesFeedActivity(next: FeedActivitySnapshot, stored: FeedActivitySnapshot): boolean {\n const drift = next.feedActivityAt.getTime() - stored.feedActivityAt.getTime();\n return drift > 0 || (drift === 0 && next.commentCount >= stored.commentCount);\n}\n\nexport interface WorkItemCommentPage {\n comments: WorkItemCommentRow[];\n nextCursor?: string;\n}\n\nexport interface WorkItemMentionRow {\n id: string;\n commentId: string;\n mentionedKind: 'user';\n mentionedId: string;\n authorId: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n occurredAt: Date;\n}\n\nexport const MAX_COMMENT_BODY_LENGTH = 16_000;\nexport const MAX_COMMENT_QUOTE_LENGTH = 500;\nexport const MAX_COMMENT_MENTIONS = 20;\n\n/** The one body policy: HTTP parsing and the service both reject on it. */\nexport function commentBodyError(body: string): string | undefined {\n if (!body.trim()) return 'Comment body must not be empty.';\n if (body.length > MAX_COMMENT_BODY_LENGTH)\n return `Comment body must be at most ${MAX_COMMENT_BODY_LENGTH} characters.`;\n return undefined;\n}\n\nconst DEFAULT_PAGE_SIZE = 30;\nconst MAX_PAGE_SIZE = 100;\n\nexport function clampCommentLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\nexport function encodeCommentCursor(row: WorkItemCommentRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\nexport function decodeCommentCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport function commentSourceKey(input: {\n externalSource?: ExternalWorkItemSource;\n clientToken?: string;\n}): string | null {\n if (input.externalSource) return externalSourceKey(input.externalSource);\n if (input.clientToken) return `local:comment:${input.clientToken}`;\n return null;\n}\n\n/** A `clientToken` replay that resolved to a different work item or author. */\nexport class CommentTokenConflictError extends Error {\n constructor() {\n super('Client token already used by a different comment.');\n this.name = 'CommentTokenConflictError';\n }\n}\n\ninterface WorkItemCommentDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n kind: WorkItemCommentKind;\n body: string;\n body_format: string;\n author_kind: FactoryActorRef['kind'];\n author_id: string;\n author_display_name: string | null;\n author_avatar_url: string | null;\n author_external: FactoryActorExternalIdentity | null;\n reply_to_comment_id: string | null;\n reply_quote: string | null;\n reply_to_author_id: string | null;\n reply_to_author_name: string | null;\n mentions: FactoryMentionRef[];\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n occurred_at: Date;\n edited_at: Date | null;\n deleted_at: Date | null;\n deleted_by: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface WorkItemMentionDbRow extends Record<string, unknown> {\n id: string;\n comment_id: string;\n mentioned_kind: 'user';\n mentioned_id: string;\n author_id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n occurred_at: Date;\n}\n\nfunction toComment(row: WorkItemCommentDbRow): WorkItemCommentRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n kind: row.kind,\n body: row.body,\n bodyFormat: row.body_format,\n author: {\n kind: row.author_kind,\n id: row.author_id,\n ...(row.author_display_name ? { displayName: row.author_display_name } : {}),\n ...(row.author_avatar_url ? { avatarUrl: row.author_avatar_url } : {}),\n ...(row.author_external ? { external: row.author_external } : {}),\n },\n replyTo: row.reply_to_comment_id\n ? {\n commentId: row.reply_to_comment_id,\n ...(row.reply_quote ? { quote: row.reply_quote } : {}),\n ...(row.reply_to_author_id ? { authorId: row.reply_to_author_id } : {}),\n ...(row.reply_to_author_name ? { authorName: row.reply_to_author_name } : {}),\n }\n : null,\n mentions: row.mentions,\n externalSource: row.external_source,\n sourceKey: row.source_key,\n occurredAt: row.occurred_at,\n editedAt: row.edited_at,\n deletedAt: row.deleted_at,\n deletedBy: row.deleted_by,\n revision: row.revision,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toMention(row: WorkItemMentionDbRow): WorkItemMentionRow {\n return {\n id: row.id,\n commentId: row.comment_id,\n mentionedKind: row.mentioned_kind,\n mentionedId: row.mentioned_id,\n authorId: row.author_id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n occurredAt: row.occurred_at,\n };\n}\n\nfunction toMentionRef(row: WorkItemMentionRow): FactoryMentionRef {\n return { kind: row.mentionedKind, id: row.mentionedId };\n}\n\nfunction mentionKey(mention: { kind: string; id: string }): string {\n return `${mention.kind}\\0${mention.id}`;\n}\n\nfunction dedupeMentions(mentions: FactoryMentionRef[] | undefined): FactoryMentionRef[] {\n if (!mentions?.length) return [];\n return [...new Map(mentions.map(mention => [mentionKey(mention), mention])).values()];\n}\n\nexport class WorkItemCommentsStorage extends FactoryStorageDomain {\n constructor() {\n super('work-item-comments');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_item_activity', {});\n await this.ops.deleteMany('work_item_comment_mentions', {});\n await this.ops.deleteMany('work_item_comments', {});\n }\n\n async create(input: CreateWorkItemCommentInput): Promise<WorkItemCommentRow> {\n const now = new Date();\n const occurredAt = input.occurredAt ?? now;\n const sourceKey = commentSourceKey(input);\n const author = input.author;\n const row: Partial<WorkItemCommentDbRow> = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n kind: 'comment',\n body: input.body,\n body_format: input.bodyFormat ?? 'markdown',\n author_kind: author.kind,\n author_id: author.id,\n author_display_name: author.displayName ?? null,\n author_avatar_url: author.avatarUrl ?? null,\n author_external: author.external ?? null,\n reply_to_comment_id: input.replyTo?.commentId ?? null,\n reply_quote: input.replyTo?.quote ?? null,\n reply_to_author_id: input.replyTo?.authorId ?? null,\n reply_to_author_name: input.replyTo?.authorName ?? null,\n mentions: dedupeMentions(input.mentions),\n external_source: input.externalSource ?? null,\n source_key: sourceKey,\n occurred_at: occurredAt,\n edited_at: null,\n deleted_at: null,\n deleted_by: null,\n revision: 1,\n created_at: now,\n updated_at: now,\n };\n\n // Insert-or-recover, never upsert: a replayed create must return the\n // existing row untouched (an upsert would clobber a later edit's body).\n // A local token resolving to another item or author is a conflict, not a\n // recovery. External keys stay lenient: a redelivery after a thread\n // re-link maps to a new item id and must still no-op.\n if (sourceKey) {\n const sourceWhere = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey,\n };\n const recover = (found: WorkItemCommentDbRow): WorkItemCommentRow => {\n if (!input.externalSource && (found.work_item_id !== input.workItemId || found.author_id !== author.id)) {\n throw new CommentTokenConflictError();\n }\n return toComment(found);\n };\n const existing = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (existing) return recover(existing);\n try {\n return await this.#insertWithMentions(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (!raced) throw error;\n return recover(raced);\n }\n }\n\n return this.#insertWithMentions(row);\n }\n\n /**\n * The one insert path a genuinely new comment takes — `create()`'s recover\n * branches never reach it, so a replay writes no mention or activity rows.\n */\n async #insertWithMentions(row: Partial<WorkItemCommentDbRow>): Promise<WorkItemCommentRow> {\n const comment = toComment(await this.ops.insertOne<WorkItemCommentDbRow>('work_item_comments', row));\n await this.#writeMentionRows(comment, comment.mentions);\n await this.#fanOutActivity(comment);\n return comment;\n }\n\n /**\n * Participants come off the item's recent authors, so the scan happens here\n * rather than in the fan-out, which must stay free of its own queries.\n */\n async #fanOutActivity(comment: WorkItemCommentRow): Promise<void> {\n const item = await this.ops.findOne<{ created_by: string } & Record<string, unknown>>('work_items', {\n id: comment.workItemId,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n });\n if (!item) return;\n const recent = await this.listRecent({\n orgId: comment.orgId,\n factoryProjectId: comment.factoryProjectId,\n workItemId: comment.workItemId,\n limit: PARTICIPANT_SCAN_LIMIT,\n });\n await fanOutWorkItemActivity(this.ops, {\n comment,\n recentAuthors: recent.filter(row => row.author.kind === 'user').map(row => row.author.id),\n createdBy: item.created_by,\n mentions: comment.mentions,\n });\n }\n\n async listActivityForUser(args: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemActivityRow[]> {\n return listActivityForUser(this.ops, args);\n }\n\n /**\n * Idempotent counter refresh on the parent work item: both columns are read\n * back off the comments (never incremented or stamped with the wall clock —\n * replays and races double an increment, and a replayed create would move a\n * work item in the feed without adding a comment; a read-back can't drift).\n * Read BEFORE `updateAtomic`: its mutator runs inside an open transaction\n * holding a pool connection, and a query in there checks out a second one —\n * concurrent posts would exhaust the pool. Reading outside means two\n * refreshes can interleave, so the write goes through\n * {@link supersedesFeedActivity} rather than landing whatever it read.\n * Touches ONLY the counter columns: `revision`/`updated_at` are the\n * stage-transition concurrency token.\n */\n async refreshWorkItemFeedActivity({\n orgId,\n factoryProjectId,\n workItemId,\n now = new Date(),\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n now?: Date;\n }): Promise<void> {\n const commentCount = await this.countForWorkItem({ orgId, factoryProjectId, workItemId });\n // Every feed mutation stamps `updated_at`, edits and tombstones included,\n // so the newest one is when this feed last moved.\n const [latest] = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n { orderBy: [['updated_at', 'desc']], limit: 1 },\n );\n const feedActivityAt = latest?.updated_at ?? now;\n await this.ops.updateAtomic<WorkItemFeedColumns>(\n 'work_items',\n { id: workItemId, org_id: orgId, factory_project_id: factoryProjectId },\n row => {\n const next = { commentCount, feedActivityAt };\n const stored = row.feed_activity_at;\n if (stored && !supersedesFeedActivity(next, { commentCount: row.comment_count, feedActivityAt: stored })) {\n return null;\n }\n return { comment_count: commentCount, feed_activity_at: feedActivityAt };\n },\n );\n }\n\n async get({ orgId, commentId }: { orgId: string; commentId: string }): Promise<WorkItemCommentRow | null> {\n const row = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', {\n id: commentId,\n org_id: orgId,\n });\n return row ? toComment(row) : null;\n }\n\n async listByIds({ orgId, ids }: { orgId: string; ids: string[] }): Promise<WorkItemCommentRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.ops.findMany<WorkItemCommentDbRow>('work_item_comments', {\n org_id: orgId,\n id: { in: ids },\n });\n return rows.map(toComment);\n }\n\n async list(input: ListWorkItemCommentsInput): Promise<WorkItemCommentPage> {\n const anchored = input.around ? await this.#listAround(input, input.around) : undefined;\n if (anchored) return anchored;\n const limit = clampCommentLimit(input.limit);\n const cursor = input.before ? decodeCommentCursor(input.before) : undefined;\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n },\n );\n const comments = rows.slice(0, limit).map(toComment);\n const hasMore = rows.length > limit;\n const last = comments[comments.length - 1];\n return {\n comments,\n ...(hasMore && last ? { nextCursor: encodeCommentCursor(last) } : {}),\n };\n }\n\n async #listAround(\n { orgId, factoryProjectId, workItemId }: ListWorkItemCommentsInput,\n commentId: string,\n ): Promise<WorkItemCommentPage | undefined> {\n const target = await this.get({ orgId, commentId });\n if (!target || target.factoryProjectId !== factoryProjectId || target.workItemId !== workItemId) return undefined;\n\n const newer = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n {\n orderBy: [\n ['occurred_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: MAX_PAGE_SIZE + 1,\n cursor: { values: [target.occurredAt, target.id] },\n },\n );\n if (newer.length > MAX_PAGE_SIZE) return undefined;\n\n const before = encodeCommentCursor(target);\n const older = await this.list({ orgId, factoryProjectId, workItemId, before, limit: 1 });\n return {\n comments: [...newer.map(toComment).reverse(), target],\n ...(older.comments.length > 0 ? { nextCursor: before } : {}),\n };\n }\n\n /**\n * Newest non-deleted comments for run-context injection, newest-first (the\n * caller reverses for display order).\n */\n async listRecent({\n orgId,\n factoryProjectId,\n workItemId,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n limit: number;\n }): Promise<WorkItemCommentRow[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n return rows.map(toComment);\n }\n\n async edit(input: EditWorkItemCommentInput): Promise<EditWorkItemCommentResult | 'conflict' | null> {\n const now = input.now ?? new Date();\n let rejection: 'deleted' | 'conflict' | undefined;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: input.commentId, org_id: input.orgId },\n current => {\n if (current.deleted_at) {\n rejection = 'deleted';\n return null;\n }\n if (input.expectedRevision !== undefined && Number(current.revision) !== input.expectedRevision) {\n rejection = 'conflict';\n return null;\n }\n return {\n body: input.body,\n mentions: dedupeMentions(input.mentions ?? current.mentions),\n edited_at: now,\n revision: Number(current.revision) + 1,\n updated_at: now,\n };\n },\n );\n if (rejection === 'conflict') return 'conflict';\n if (!updated || rejection) return null;\n const comment = toComment(updated);\n\n const existing = await this.#listMentionRows(comment.id);\n const existingKeys = new Set(existing.map(mention => mentionKey(toMentionRef(mention))));\n const nextKeys = new Set(comment.mentions.map(mentionKey));\n // Self-mentions (author, or the acting editor) never become rows, so they\n // must not report as \"added\" either — they would re-report on every edit.\n const skippedIds = new Set([comment.author.id, ...(input.editorId ? [input.editorId] : [])]);\n const addedMentions = comment.mentions.filter(\n mention => !existingKeys.has(mentionKey(mention)) && !skippedIds.has(mention.id),\n );\n const removedMentions = existing.map(toMentionRef).filter(mention => !nextKeys.has(mentionKey(mention)));\n\n // Stamped with the edit time, not the comment's creation time: the inbox\n // is a keyset on `occurred_at`, and a backdated row lands buried under\n // everything the user already saw.\n await this.#writeMentionRows(comment, addedMentions, now);\n for (const mention of removedMentions) {\n await this.ops.deleteMany('work_item_comment_mentions', {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n });\n }\n return { comment, addedMentions, removedMentions };\n }\n\n async softDelete({\n orgId,\n commentId,\n deletedBy,\n now = new Date(),\n }: {\n orgId: string;\n commentId: string;\n deletedBy: string;\n now?: Date;\n }): Promise<WorkItemCommentRow | null> {\n let alreadyDeleted = false;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.deleted_at) {\n alreadyDeleted = true;\n return null;\n }\n return {\n body: '',\n mentions: [],\n deleted_at: now,\n deleted_by: deletedBy,\n updated_at: now,\n };\n },\n );\n if (!updated || alreadyDeleted) return null;\n await this.ops.deleteMany('work_item_comment_mentions', { comment_id: commentId });\n return toComment(updated);\n }\n\n /**\n * Provenance write-back after an outbound publish. First platform wins, and\n * an existing `source_key` is kept: replacing a `local:comment:<token>` one\n * would let a client retry duplicate the row. So a web-born comment is never\n * key-deduped against its own platform echo — the host's bot-sender check is\n * the only echo layer for those rows (COR-1174).\n */\n async attachExternalSource({\n orgId,\n commentId,\n source,\n }: {\n orgId: string;\n commentId: string;\n source: ExternalWorkItemSource;\n }): Promise<WorkItemCommentRow | null> {\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.external_source) return null;\n return {\n external_source: source,\n source_key: current.source_key ?? commentSourceKey({ externalSource: source }),\n updated_at: new Date(),\n };\n },\n );\n return updated ? toComment(updated) : null;\n }\n\n async listMentionsForComment(commentId: string): Promise<WorkItemMentionRow[]> {\n return this.#listMentionRows(commentId);\n }\n\n /** Keyset inbox read for the mention attention provider, newest-first. */\n async listMentionsForUser({\n orgId,\n factoryProjectId,\n userId,\n before,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_id: userId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n ...(before ? { cursor: { values: [before.occurredAt, before.id] } } : {}),\n },\n );\n return rows.map(toMention);\n }\n\n async countForWorkItem({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<number> {\n if (!this.ops.count) {\n throw new Error('[WorkItemCommentsStorage] storage backend does not support collection counts.');\n }\n return this.ops.count('work_item_comments', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n });\n }\n\n /** Recent distinct comment authors of a project, for the roster fallback. */\n async listRecentAuthors({\n orgId,\n factoryProjectId,\n limit = 200,\n }: {\n orgId: string;\n factoryProjectId: string;\n limit?: number;\n }): Promise<FactoryActorRef[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n const authors = new Map<string, FactoryActorRef>();\n for (const row of rows) {\n if (authors.has(row.author_id)) continue;\n authors.set(row.author_id, toComment(row).author);\n }\n return [...authors.values()];\n }\n\n async #listMentionRows(commentId: string): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>('work_item_comment_mentions', {\n comment_id: commentId,\n });\n return rows.map(toMention);\n }\n\n /**\n * Self-mentions never get rows: the join exists solely for the attention\n * inbox, and `CollectionWhere` cannot express `author_id != userId` at read\n * time, so the filter happens at write time.\n */\n async #writeMentionRows(\n comment: WorkItemCommentRow,\n mentions: FactoryMentionRef[],\n occurredAt = comment.occurredAt,\n ): Promise<void> {\n for (const mention of mentions) {\n if (mention.id === comment.author.id) continue;\n await this.ops.upsertOne<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n ['comment_id', 'mentioned_kind', 'mentioned_id'],\n {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n author_id: comment.author.id,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n work_item_id: comment.workItemId,\n occurred_at: occurredAt,\n },\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA,SAAgB,uBAAuB,MAA4B,QAAuC;CACxG,MAAM,QAAQ,KAAK,eAAe,QAAQ,IAAI,OAAO,eAAe,QAAQ;CAC5E,OAAO,QAAQ,KAAM,UAAU,KAAK,KAAK,gBAAgB,OAAO;AAClE;AAmBA,MAAa,0BAA0B;AACvC,MAAa,2BAA2B;AACxC,MAAa,uBAAuB;;AAGpC,SAAgB,iBAAiB,MAAkC;CACjE,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;CACzB,IAAI,KAAK,SAAA,MACP,OAAO,gCAAgC,wBAAwB;AAEnE;AAEA,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAEtB,SAAgB,kBAAkB,OAAmC;CAEnE,OAAO,KAAK,IAAI,KAAK,IADF,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,KAAK,MAAM,KAAK,IAAI,mBACxD,CAAC,GAAG,aAAa;AACxD;AAEA,SAAgB,oBAAoB,KAAiC;CACnE,OAAO,GAAG,IAAI,WAAW,YAAY,EAAE,GAAG,IAAI;AAChD;AAEA,SAAgB,oBAAoB,QAA8D;CAChG,MAAM,MAAM,OAAO,YAAY,GAAG;CAClC,IAAI,OAAO,GAAG,OAAO,KAAA;CACrB,MAAM,aAAa,IAAI,KAAK,OAAO,MAAM,GA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kBAAkB,EACtB,OACA,kBACA,QAAQ,OAKqB;EAC7B,MAAM,OAAO,MAAM,KAAK,IAAI,SAC1B,sBACA;GAAE,QAAQ;GAAO,oBAAoB;EAAiB,GACtD;GACE,SAAS,CACP,CAAC,eAAe,MAAM,GACtB,CAAC,MAAM,MAAM,CACf;GACA;EACF,CACF;EACA,MAAM,0BAAU,IAAI,IAA6B;EACjD,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,QAAQ,IAAI,IAAI,SAAS,GAAG;GAChC,QAAQ,IAAI,IAAI,WAAW,UAAU,GAAG,CAAC,CAAC,MAAM;EAClD;EACA,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;CAC7B;CAEA,MAAMA,iBAAiB,WAAkD;EAIvE,QAAO,MAHY,KAAK,IAAI,SAA+B,8BAA8B,EACvF,YAAY,UACd,CAAC,EAAA,CACW,IAAI,SAAS;CAC3B;;;;;;CAOA,MAAMH,kBACJ,SACA,UACA,aAAa,QAAQ,YACN;EACf,KAAK,MAAM,WAAW,UAAU;GAC9B,IAAI,QAAQ,OAAO,QAAQ,OAAO,IAAI;GACtC,MAAM,KAAK,IAAI,UACb,8BACA;IAAC;IAAc;IAAkB;GAAc,GAC/C;IACE,YAAY,QAAQ;IACpB,gBAAgB,QAAQ;IACxB,cAAc,QAAQ;IACtB,WAAW,QAAQ,OAAO;IAC1B,QAAQ,QAAQ;IAChB,oBAAoB,QAAQ;IAC5B,cAAc,QAAQ;IACtB,aAAa;GACf,CACF;EACF;CACF;AACF"}
@@ -11,7 +11,7 @@ import type { RouteAuth } from '../../../routes/route.js';
11
11
  import type { AuditEmitter } from '../audit/domain.js';
12
12
  import type { ChannelIdentityStorage } from '../channel-identity/base.js';
13
13
  import type { FactoryProjectsStorage } from '../projects/base.js';
14
- import type { WorkItemRow, WorkItemsStorage } from '../work-items/base.js';
14
+ import type { ExternalWorkItemSource, WorkItemRow, WorkItemsStorage } from '../work-items/base.js';
15
15
  import type { FactoryActorRef } from './actor.js';
16
16
  import type { EditWorkItemCommentResult, FactoryMentionRef, WorkItemCommentRow, WorkItemCommentsStorage } from './base.js';
17
17
  import type { WorkItemFeedPublisher } from './feed-sync.js';
@@ -48,11 +48,18 @@ export interface CreateCommentServiceInput {
48
48
  };
49
49
  mentions?: FactoryMentionRef[];
50
50
  clientToken?: string;
51
+ /** Set when the comment is a platform message being ingested, never by the web UI. */
52
+ externalSource?: ExternalWorkItemSource;
53
+ /** The platform's own timestamp; defaults to now for locally authored comments. */
54
+ occurredAt?: Date;
51
55
  }
52
- export type CreateCommentServiceResult = {
56
+ export type CreateCommentServiceResult =
57
+ /** `mirrored` settles when the platforms have been posted to; nothing in the response waits on it. */
58
+ {
53
59
  status: 'created';
54
60
  comment: WorkItemCommentRow;
55
61
  workItem: WorkItemRow;
62
+ mirrored: Promise<void>;
56
63
  } | {
57
64
  status: 'work_item_not_found';
58
65
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"domain.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/domain.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE3E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,KAAK,EACV,yBAAyB,EACzB,iBAAiB,EAEjB,kBAAkB,EAClB,uBAAuB,EACxB,MAAM,W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AE,CAAC;AAE3C,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,aAAa,CAAC;CACvB;AAED,MAAM,MAAM,0BAA0B,GAClC;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,kBAAkB,CAAA;CAAE,GAClD;IAAE,MAAM,EAAE,WAAW,CAAA;CAAE,GACvB;IAAE,MAAM,EAAE,WAAW,CAAA;CAAE,GACvB;IAAE,MAAM,EAAE,cAAc,CAAA;CAAE,CAAC;AAK/B,qBAAa,cAAc;;gBAYb,EACV,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,eAAe,EACf,OAAO,EACP,KAAK,EACL,UAAU,EACV,MAAM,GACP,EAAE,qBAAqB;IAkBlB,aAAa,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,0BAA0B,CAAC;IAuFpF,WAAW,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAqC9E,aAAa,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,0BAA0B,CAAC;IA8C1F;;;;OAIG;IACG,aAAa,CAAC,EAClB,KAAK,EACL,gBAAgB,GACjB,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;KAC1B,GAAG,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAuDlC,MAAM,IAAI,QAAQ,EAAE;CAWrB;AAED,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC"}
@@ -29,10 +29,7 @@ var CommentsDomain = class {
29
29
  this.#publishers = publishers ?? [];
30
30
  this.#pubsub = pubsub;
31
31
  }
32
- /**
33
- * The one seam every feed mutation routes through — future
34
- * `WorkItemFeedIngest` impls included.
35
- */
32
+ /** The one seam every feed mutation routes through, platform ingest included. */
36
33
  async #touchFeed(scope) {
37
34
  await this.#comments.refreshWorkItemFeedActivity(scope);
38
35
  touchFeed(this.#pubsub, scope, scope.workItemId);
@@ -81,7 +78,9 @@ var CommentsDomain = class {
81
78
  body: input.body,
82
79
  ...replyTo ? { replyTo } : {},
83
80
  ...input.mentions ? { mentions: input.mentions } : {},
84
- ...input.clientToken ? { clientToken: input.clientToken } : {}
81
+ ...input.clientToken ? { clientToken: input.clientToken } : {},
82
+ ...input.externalSource ? { externalSource: input.externalSource } : {},
83
+ ...input.occurredAt ? { occurredAt: input.occurredAt } : {}
85
84
  });
86
85
  } catch (error) {
87
86
  if (error instanceof CommentTokenConflictError) return { status: "token_conflict" };
@@ -92,36 +91,40 @@ var CommentsDomain = class {
92
91
  factoryProjectId: workItem.factoryProjectId,
93
92
  workItemId: input.workItemId
94
93
  });
95
- await this.#mirrorComment(comment, workItem);
96
94
  return {
97
95
  status: "created",
98
96
  comment,
99
- workItem
97
+ workItem,
98
+ mirrored: this.#mirrorComment(comment, workItem)
100
99
  };
101
100
  }
102
101
  /**
103
- * Best-effort: a failed publish never fails the create. The write-back is
104
- * the replay guard a replayed create sees its own platform on the row and
105
- * skips it. Known ceiling, single publisher only: `external_source` is
106
- * single-valued, so with two publishers a replayed create re-publishes to
107
- * the one that is not recorded, and nothing persists a failed attempt for a
108
- * later pass to retry. Both need an outbox if a second publisher ever lands.
102
+ * Runs past the response the comment is stored, the feed frame is already
103
+ * out, and nobody is waiting on Slack. A failed publish never fails the
104
+ * create. The write-back is the replay guard: a replayed create sees its own
105
+ * platform on the row and skips it. Known ceiling, single publisher only:
106
+ * `external_source` is single-valued, so with two publishers a replayed
107
+ * create re-publishes to the one that is not recorded, and a process that
108
+ * restarts mid-flight drops the post. Both need an outbox.
109
109
  */
110
110
  async #mirrorComment(comment, workItem) {
111
111
  let current = comment;
112
112
  for (const publisher of this.#publishers) {
113
113
  if (current.externalSource?.integrationId === publisher.id) continue;
114
114
  try {
115
- const { source } = await publisher.publish(current, workItem);
115
+ const published = await publisher.publish(current, workItem);
116
+ if (!published) continue;
116
117
  current = await this.#comments.attachExternalSource({
117
118
  orgId: current.orgId,
118
119
  commentId: current.id,
119
- source
120
+ source: published.source
120
121
  }) ?? current;
121
122
  } catch (err) {
122
123
  console.warn("[Comments] Failed to mirror a comment to a platform", {
123
124
  publisherId: publisher.id,
124
125
  commentId: current.id,
126
+ orgId: current.orgId,
127
+ workItemId: workItem.id,
125
128
  error: err instanceof Error ? err.message : String(err)
126
129
  });
127
130
  }