@mastra/factory 0.11.1 → 0.12.0-alpha.1

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 (157) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/factory.d.ts +2 -22
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +21 -59
  5. package/dist/factory.js.map +1 -1
  6. package/dist/feed-events.d.ts +13 -0
  7. package/dist/feed-events.d.ts.map +1 -0
  8. package/dist/feed-events.js +25 -0
  9. package/dist/feed-events.js.map +1 -0
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/integrations/base.d.ts +5 -13
  13. package/dist/integrations/base.d.ts.map +1 -1
  14. package/dist/integrations/github/config.d.ts +4 -4
  15. package/dist/integrations/github/config.d.ts.map +1 -1
  16. package/dist/integrations/github/config.js +3 -3
  17. package/dist/integrations/github/config.js.map +1 -1
  18. package/dist/integrations/github/integration.d.ts.map +1 -1
  19. package/dist/integrations/github/integration.js +2 -4
  20. package/dist/integrations/github/integration.js.map +1 -1
  21. package/dist/integrations/github/reconcile-worker.d.ts +0 -5
  22. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  23. package/dist/integrations/github/reconcile-worker.js +1 -8
  24. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  25. package/dist/integrations/github/routes.d.ts +6 -5
  26. package/dist/integrations/github/routes.d.ts.map +1 -1
  27. package/dist/integrations/github/routes.js +36 -263
  28. package/dist/integrations/github/routes.js.map +1 -1
  29. package/dist/integrations/github/sandbox-release.d.ts +17 -47
  30. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox-release.js +24 -103
  32. package/dist/integrations/github/sandbox-release.js.map +1 -1
  33. package/dist/integrations/github/sandbox.d.ts +25 -139
  34. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  35. package/dist/integrations/github/sandbox.js +24 -212
  36. package/dist/integrations/github/sandbox.js.map +1 -1
  37. package/dist/integrations/github/webhook.d.ts.map +1 -1
  38. package/dist/integrations/github/webhook.js +1 -2
  39. package/dist/integrations/github/webhook.js.map +1 -1
  40. package/dist/integrations/issue-reconcile-worker.js +1 -1
  41. package/dist/integrations/platform/github/event-worker.d.ts +0 -2
  42. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  43. package/dist/integrations/platform/github/event-worker.js +1 -8
  44. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  45. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  46. package/dist/integrations/platform/github/integration.js +5 -7
  47. package/dist/integrations/platform/github/integration.js.map +1 -1
  48. package/dist/integrations/platform/linear/event-worker.js +1 -1
  49. package/dist/routes/attention-activity.d.ts +24 -0
  50. package/dist/routes/attention-activity.d.ts.map +1 -0
  51. package/dist/routes/attention-activity.js +143 -0
  52. package/dist/routes/attention-activity.js.map +1 -0
  53. package/dist/routes/attention-providers.d.ts +31 -1
  54. package/dist/routes/attention-providers.d.ts.map +1 -1
  55. package/dist/routes/attention-providers.js +4 -4
  56. package/dist/routes/attention-providers.js.map +1 -1
  57. package/dist/routes/attention.d.ts.map +1 -1
  58. package/dist/routes/attention.js +39 -11
  59. package/dist/routes/attention.js.map +1 -1
  60. package/dist/routes/config.d.ts.map +1 -1
  61. package/dist/routes/config.js +3 -1
  62. package/dist/routes/config.js.map +1 -1
  63. package/dist/routes/fs.d.ts +4 -6
  64. package/dist/routes/fs.d.ts.map +1 -1
  65. package/dist/routes/fs.js +28 -34
  66. package/dist/routes/fs.js.map +1 -1
  67. package/dist/routes/skills.d.ts.map +1 -1
  68. package/dist/routes/skills.js +6 -3
  69. package/dist/routes/skills.js.map +1 -1
  70. package/dist/routes/surface.d.ts +4 -9
  71. package/dist/routes/surface.d.ts.map +1 -1
  72. package/dist/routes/surface.js +3 -5
  73. package/dist/routes/surface.js.map +1 -1
  74. package/dist/sandbox/materialization.d.ts +36 -0
  75. package/dist/sandbox/materialization.d.ts.map +1 -0
  76. package/dist/sandbox/materialization.js +18 -0
  77. package/dist/sandbox/materialization.js.map +1 -0
  78. package/dist/sandbox/session-retirement.d.ts +8 -6
  79. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  80. package/dist/sandbox/session-retirement.js +28 -123
  81. package/dist/sandbox/session-retirement.js.map +1 -1
  82. package/dist/sandbox/session-sandbox.d.ts +117 -0
  83. package/dist/sandbox/session-sandbox.d.ts.map +1 -0
  84. package/dist/sandbox/session-sandbox.js +132 -0
  85. package/dist/sandbox/session-sandbox.js.map +1 -0
  86. package/dist/sandbox/workdir.d.ts +30 -0
  87. package/dist/sandbox/workdir.d.ts.map +1 -0
  88. package/dist/sandbox/workdir.js +48 -0
  89. package/dist/sandbox/workdir.js.map +1 -0
  90. package/dist/session/filesystem-capture.d.ts +2 -1
  91. package/dist/session/filesystem-capture.d.ts.map +1 -1
  92. package/dist/session/filesystem-capture.js +45 -4
  93. package/dist/session/filesystem-capture.js.map +1 -1
  94. package/dist/session/first-exec-capture.d.ts +1 -0
  95. package/dist/session/first-exec-capture.d.ts.map +1 -1
  96. package/dist/session/first-exec-capture.js +1 -1
  97. package/dist/session/first-exec-capture.js.map +1 -1
  98. package/dist/storage/domains/comments/activity.d.ts +40 -0
  99. package/dist/storage/domains/comments/activity.d.ts.map +1 -0
  100. package/dist/storage/domains/comments/activity.js +94 -0
  101. package/dist/storage/domains/comments/activity.js.map +1 -0
  102. package/dist/storage/domains/comments/base.d.ts +13 -1
  103. package/dist/storage/domains/comments/base.d.ts.map +1 -1
  104. package/dist/storage/domains/comments/base.js +41 -3
  105. package/dist/storage/domains/comments/base.js.map +1 -1
  106. package/dist/storage/domains/comments/domain.d.ts +4 -1
  107. package/dist/storage/domains/comments/domain.d.ts.map +1 -1
  108. package/dist/storage/domains/comments/domain.js +17 -5
  109. package/dist/storage/domains/comments/domain.js.map +1 -1
  110. package/dist/storage/domains/comments/parse.d.ts +1 -0
  111. package/dist/storage/domains/comments/parse.d.ts.map +1 -1
  112. package/dist/storage/domains/comments/parse.js +2 -2
  113. package/dist/storage/domains/comments/parse.js.map +1 -1
  114. package/dist/storage/domains/comments/routes.d.ts +2 -0
  115. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  116. package/dist/storage/domains/comments/routes.js +49 -3
  117. package/dist/storage/domains/comments/routes.js.map +1 -1
  118. package/dist/storage/domains/comments/schema.d.ts +1 -0
  119. package/dist/storage/domains/comments/schema.d.ts.map +1 -1
  120. package/dist/storage/domains/comments/schema.js +45 -1
  121. package/dist/storage/domains/comments/schema.js.map +1 -1
  122. package/dist/storage/domains/integrations/base.d.ts +1 -1
  123. package/dist/storage/domains/integrations/base.js +1 -1
  124. package/dist/storage/domains/integrations/base.js.map +1 -1
  125. package/dist/storage/domains/source-control/base.d.ts +0 -144
  126. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  127. package/dist/storage/domains/source-control/base.js +3 -290
  128. package/dist/storage/domains/source-control/base.js.map +1 -1
  129. package/dist/storage/domains/source-control/inmemory.d.ts +1 -63
  130. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  131. package/dist/storage/domains/source-control/inmemory.js +0 -89
  132. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  133. package/dist/storage/domains/work-items/base.d.ts +14 -1
  134. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  135. package/dist/storage/domains/work-items/base.js +60 -11
  136. package/dist/storage/domains/work-items/base.js.map +1 -1
  137. package/dist/workspace.d.ts +5 -37
  138. package/dist/workspace.d.ts.map +1 -1
  139. package/dist/workspace.js +107 -245
  140. package/dist/workspace.js.map +1 -1
  141. package/package.json +6 -6
  142. package/dist/sandbox/base-checkpoint-triggers.d.ts +0 -77
  143. package/dist/sandbox/base-checkpoint-triggers.d.ts.map +0 -1
  144. package/dist/sandbox/base-checkpoint-triggers.js +0 -137
  145. package/dist/sandbox/base-checkpoint-triggers.js.map +0 -1
  146. package/dist/sandbox/base-checkpoint.d.ts +0 -59
  147. package/dist/sandbox/base-checkpoint.d.ts.map +0 -1
  148. package/dist/sandbox/base-checkpoint.js +0 -145
  149. package/dist/sandbox/base-checkpoint.js.map +0 -1
  150. package/dist/sandbox/fleet.d.ts +0 -258
  151. package/dist/sandbox/fleet.d.ts.map +0 -1
  152. package/dist/sandbox/fleet.js +0 -356
  153. package/dist/sandbox/fleet.js.map +0 -1
  154. package/dist/sandbox/reattach.d.ts +0 -3
  155. package/dist/sandbox/reattach.d.ts.map +0 -1
  156. package/dist/sandbox/reattach.js +0 -16
  157. package/dist/sandbox/reattach.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"parse.js","names":[],"sources":["../../../../src/storage/domains/comments/parse.ts"],"sourcesContent":["/** Request-body parsing for the comment routes: unknown JSON in, a typed input or `null` out. */\n\nimport type { Context } from 'hono';\n\nimport { isMentionableActorId } from './actor.js';\nimport type { FactoryMentionRef } from './base.js';\nimport { commentBodyError, MAX_COMMENT_MENTIONS, MAX_COMMENT_QUOTE_LENGTH } from './base.js';\n\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst CLIENT_TOKEN_RE = /^[A-Za-z0-9-]{8,64}$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport async function readJson(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\n/** `undefined` when the field is absent, `null` when it is present but malformed. */\nfunction parseMentions(raw: unknown): FactoryMentionRef[] | null | undefined {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw) || raw.length > MAX_COMMENT_MENTIONS) return null;\n const mentions: FactoryMentionRef[] = [];\n for (const entry of raw) {\n if (!isRecord(entry)) return null;\n if (entry.kind !== 'user' || typeof entry.id !== 'string' || !isMentionableActorId(entry.id)) return null;\n mentions.push({ kind: 'user', id: entry.id });\n }\n return mentions;\n}\n\nfunction parseBody(raw: unknown): string | null {\n if (typeof raw !== 'string' || commentBodyError(raw)) return null;\n return raw;\n}\n\nfunction parseClientToken(raw: unknown): string | null | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw !== 'string' || !CLIENT_TOKEN_RE.test(raw)) return null;\n return raw;\n}\n\nfunction parseExpectedRevision(raw: unknown): number | null | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;\n return raw;\n}\n\nfunction parseReplyTo(raw: unknown): { commentId: string; quote?: string } | null | undefined {\n if (raw === undefined) return undefined;\n if (!isRecord(raw)) return null;\n if (typeof raw.commentId !== 'string' || !UUID_RE.test(raw.commentId)) return null;\n if (raw.quote !== undefined && typeof raw.quote !== 'string') return null;\n const quote = typeof raw.quote === 'string' ? raw.quote.slice(0, MAX_COMMENT_QUOTE_LENGTH) : undefined;\n return { commentId: raw.commentId, ...(quote ? { quote } : {}) };\n}\n\nexport interface ParsedCreateComment {\n body: string;\n clientToken?: string;\n replyTo?: { commentId: string; quote?: string };\n mentions?: FactoryMentionRef[];\n}\n\nexport function parseCreateCommentBody(raw: unknown): ParsedCreateComment | null {\n if (!isRecord(raw)) return null;\n\n const body = parseBody(raw.body);\n if (body === null) return null;\n const mentions = parseMentions(raw.mentions);\n if (mentions === null) return null;\n const replyTo = parseReplyTo(raw.replyTo);\n if (replyTo === null) return null;\n const clientToken = parseClientToken(raw.clientToken);\n if (clientToken === null) return null;\n\n return {\n body,\n ...(clientToken ? { clientToken } : {}),\n ...(replyTo ? { replyTo } : {}),\n ...(mentions ? { mentions } : {}),\n };\n}\n\nexport interface ParsedEditComment {\n body: string;\n mentions?: FactoryMentionRef[];\n expectedRevision?: number;\n}\n\nexport function parseEditCommentBody(raw: unknown): ParsedEditComment | null {\n if (!isRecord(raw)) return null;\n\n const body = parseBody(raw.body);\n if (body === null) return null;\n const mentions = parseMentions(raw.mentions);\n if (mentions === null) return null;\n const expectedRevision = parseExpectedRevision(raw.expectedRevision);\n if (expectedRevision === null) return null;\n\n return {\n body,\n ...(mentions ? { mentions } : {}),\n ...(expectedRevision !== undefined ? { expectedRevision } : {}),\n };\n}\n"],"mappings":";;;AAQA,MAAa,UAAU;AACvB,MAAM,kBAAkB;AAExB,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAsB,SAAS,GAA8B;CAC3D,IAAI;EACF,OAAO,MAAM,EAAE,IAAI,KAAK;CAC1B,QAAQ;EACN;CACF;AACF;;AAGA,SAAS,cAAc,KAAsD;CAC3E,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,IAAI,CAAC,MAAM,QAAQ,GAAG,KAAK,IAAI,SAAA,IAA+B,OAAO;CACrE,MAAM,WAAgC,CAAC;CACvC,KAAK,MAAM,SAAS,KAAK;EACvB,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;EAC7B,IAAI,MAAM,SAAS,UAAU,OAAO,MAAM,OAAO,YAAY,CAAC,qBAAqB,MAAM,EAAE,GAAG,OAAO;EACrG,SAAS,KAAK;GAAE,MAAM;GAAQ,IAAI,MAAM;EAAG,CAAC;CAC9C;CACA,OAAO;AACT;AAEA,SAAS,UAAU,KAA6B;CAC9C,IAAI,OAAO,QAAQ,YAAY,iBAAiB,GAAG,GAAG,OAAO;CAC7D,OAAO;AACT;AAEA,SAAS,iBAAiB,KAAyC;CACjE,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,IAAI,OAAO,QAAQ,YAAY,CAAC,gBAAgB,KAAK,GAAG,GAAG,OAAO;CAClE,OAAO;AACT;AAEA,SAAS,sBAAsB,KAAyC;CACtE,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,UAAU,GAAG,GAAG,OAAO;CAC9D,OAAO;AACT;AAEA,SAAS,aAAa,KAAwE;CAC5F,IAAI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AAS,IAAI,CAAC;EAC/B,GAAI,qBAAqB,KAAA,IAAY,EAAE,iBAAiB,IAAI,CAAC;CAC/D;AACF"}
1
+ {"version":3,"file":"parse.js","names":[],"sources":["../../../../src/storage/domains/comments/parse.ts"],"sourcesContent":["/** Request-body parsing for the comment routes: unknown JSON in, a typed input or `null` out. */\n\nimport type { Context } from 'hono';\n\nimport { isMentionableActorId } from './actor.js';\nimport type { FactoryMentionRef } from './base.js';\nimport { commentBodyError, MAX_COMMENT_MENTIONS, MAX_COMMENT_QUOTE_LENGTH } from './base.js';\n\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst CLIENT_TOKEN_RE = /^[A-Za-z0-9-]{8,64}$/;\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport async function readJson(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\n/** `undefined` when the field is absent, `null` when it is present but malformed. */\nfunction parseMentions(raw: unknown): FactoryMentionRef[] | null | undefined {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw) || raw.length > MAX_COMMENT_MENTIONS) return null;\n const mentions: FactoryMentionRef[] = [];\n for (const entry of raw) {\n if (!isRecord(entry)) return null;\n if (entry.kind !== 'user' || typeof entry.id !== 'string' || !isMentionableActorId(entry.id)) return null;\n mentions.push({ kind: 'user', id: entry.id });\n }\n return mentions;\n}\n\nfunction parseBody(raw: unknown): string | null {\n if (typeof raw !== 'string' || commentBodyError(raw)) return null;\n return raw;\n}\n\nfunction parseClientToken(raw: unknown): string | null | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw !== 'string' || !CLIENT_TOKEN_RE.test(raw)) return null;\n return raw;\n}\n\nfunction parseExpectedRevision(raw: unknown): number | null | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;\n return raw;\n}\n\nfunction parseReplyTo(raw: unknown): { commentId: string; quote?: string } | null | undefined {\n if (raw === undefined) return undefined;\n if (!isRecord(raw)) return null;\n if (typeof raw.commentId !== 'string' || !UUID_RE.test(raw.commentId)) return null;\n if (raw.quote !== undefined && typeof raw.quote !== 'string') return null;\n const quote = typeof raw.quote === 'string' ? raw.quote.slice(0, MAX_COMMENT_QUOTE_LENGTH) : undefined;\n return { commentId: raw.commentId, ...(quote ? { quote } : {}) };\n}\n\nexport interface ParsedCreateComment {\n body: string;\n clientToken?: string;\n replyTo?: { commentId: string; quote?: string };\n mentions?: FactoryMentionRef[];\n}\n\nexport function parseCreateCommentBody(raw: unknown): ParsedCreateComment | null {\n if (!isRecord(raw)) return null;\n\n const body = parseBody(raw.body);\n if (body === null) return null;\n const mentions = parseMentions(raw.mentions);\n if (mentions === null) return null;\n const replyTo = parseReplyTo(raw.replyTo);\n if (replyTo === null) return null;\n const clientToken = parseClientToken(raw.clientToken);\n if (clientToken === null) return null;\n\n return {\n body,\n ...(clientToken ? { clientToken } : {}),\n ...(replyTo ? { replyTo } : {}),\n ...(mentions ? { mentions } : {}),\n };\n}\n\nexport interface ParsedEditComment {\n body: string;\n mentions?: FactoryMentionRef[];\n expectedRevision?: number;\n}\n\nexport function parseEditCommentBody(raw: unknown): ParsedEditComment | null {\n if (!isRecord(raw)) return null;\n\n const body = parseBody(raw.body);\n if (body === null) return null;\n const mentions = parseMentions(raw.mentions);\n if (mentions === null) return null;\n const expectedRevision = parseExpectedRevision(raw.expectedRevision);\n if (expectedRevision === null) return null;\n\n return {\n body,\n ...(mentions ? { mentions } : {}),\n ...(expectedRevision !== undefined ? { expectedRevision } : {}),\n };\n}\n"],"mappings":";;;AAQA,MAAa,UAAU;AACvB,MAAM,kBAAkB;AAExB,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAsB,SAAS,GAA8B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AM,GAAA,GAA2B,IAAI,KAAA;CAC7F,OAAO;EAAE,WAAW,IAAI;EAAW,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CAAG;AACjE;AASA,SAAgB,uBAAuB,KAA0C;CAC/E,IAAI,CAAC,SAAS,GAAG,GAAG,OAAO;CAE3B,MAAM,OAAO,UAAU,IAAI,IAAI;CAC/B,IAAI,SAAS,MAAM,OAAO;CAC1B,MAAM,WAAW,cAAc,IAAI,QAAQ;CAC3C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,aAAa,IAAI,OAAO;CACxC,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,cAAc,iBAAiB,IAAI,WAAW;CACpD,IAAI,gBAAgB,MAAM,OAAO;CAEjC,OAAO;EACL;EACA,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;EACrC,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC7B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CACjC;AACF;AAQA,SAAgB,qBAAqB,KAAwC;CAC3E,IAAI,CAAC,SAAS,GAAG,GAAG,OAAO;CAE3B,MAAM,OAAO,UAAU,IAAI,IAAI;CAC/B,IAAI,SAAS,MAAM,OAAO;CAC1B,MAAM,WAAW,cAAc,IAAI,QAAQ;CAC3C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,mBAAmB,sBAAsB,IAAI,gBAAgB;CACnE,IAAI,qBAAqB,MAAM,OAAO;CAEtC,OAAO;EACL;EACA,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;EAC/B,GAAI,qBAAqB,KAAA,IAAY,EAAE,iBAAiB,IAAI,CAAC;CAC/D;AACF"}
@@ -3,6 +3,7 @@
3
3
  * validate the path ids, delegate to a `CommentsDomain` service method, map its
4
4
  * result status to a status code, then emit audit.
5
5
  */
6
+ import type { PubSub } from '@mastra/core/events';
6
7
  import type { ApiRoute } from '@mastra/core/server';
7
8
  import type { RouteAuth } from '../../../routes/route.js';
8
9
  import type { AuditEmitter } from '../audit/domain.js';
@@ -16,6 +17,7 @@ export interface CommentRouteDependencies {
16
17
  comments: WorkItemCommentsStorage;
17
18
  workItems: WorkItemsStorage;
18
19
  projects: FactoryProjectsStorage;
20
+ pubsub: PubSub;
19
21
  audit?: AuditEmitter;
20
22
  }
21
23
  export declare function buildCommentRoutes(dependencies: CommentRouteDependencies): ApiRoute[];
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/routes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AAOjE,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,cAAc,CAAC;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,KAAK,CAAC,EAAE,YAAY,CAAC;CACtB;AAWD,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CA4OrF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/routes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAiB,MAAM,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAOpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AAWjE,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,cAAc,CAAC;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,YAAY,CAAC;CACtB;AAWD,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAyRrF"}
@@ -1,16 +1,20 @@
1
1
  import { getFactoryAuthUser } from "../../../auth.js";
2
- import { decodeCommentCursor } from "./base.js";
2
+ import { feedTopic } from "../../../feed-events.js";
3
3
  import { actorFromAuthUser } from "./actor.js";
4
- import { UUID_RE, parseCreateCommentBody, parseEditCommentBody, readJson } from "./parse.js";
4
+ import { decodeCommentCursor } from "./base.js";
5
+ import { UUID_RE, isRecord, parseCreateCommentBody, parseEditCommentBody, readJson } from "./parse.js";
5
6
  import { toWireComment } from "./wire.js";
6
7
  import { registerApiRoute } from "@mastra/core/server";
8
+ import { streamSSE } from "hono/streaming";
7
9
  //#region src/storage/domains/comments/routes.ts
8
10
  const MAX_AUDIT_BODY_SNAPSHOT = 1024;
11
+ /** Comment frames only — proxies drop an idle stream, and `write` can't detect a dead peer. */
12
+ const FEED_KEEPALIVE_MS = 25e3;
9
13
  function loose(c) {
10
14
  return c;
11
15
  }
12
16
  function buildCommentRoutes(dependencies) {
13
- const { domain, auth, comments, workItems, projects, audit } = dependencies;
17
+ const { domain, auth, comments, workItems, projects, pubsub, audit } = dependencies;
14
18
  async function resolveTenant(c) {
15
19
  await auth.ensureUser(c);
16
20
  const tenant = auth.tenant(c);
@@ -239,6 +243,48 @@ function buildCommentRoutes(dependencies) {
239
243
  const members = query ? roster.filter((member) => (member.name ?? member.id).toLowerCase().startsWith(query)) : roster;
240
244
  return c.json({ members });
241
245
  }
246
+ }),
247
+ registerApiRoute("/web/factory/projects/:id/feed-events", {
248
+ method: "GET",
249
+ handler: async (cc) => {
250
+ const c = loose(cc);
251
+ const tenant = await resolveTenant(c);
252
+ if ("response" in tenant) return tenant.response;
253
+ const projectId = c.req.param("id");
254
+ if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: "Project not found" }, 404);
255
+ await projects.ensureReady();
256
+ if (!await projects.get({
257
+ orgId: tenant.orgId,
258
+ id: projectId
259
+ })) return c.json({ error: "Project not found" }, 404);
260
+ const topic = feedTopic(tenant.orgId, projectId);
261
+ return streamSSE(c, async (stream) => {
262
+ const onEvent = async (event) => {
263
+ if (stream.aborted) return;
264
+ const data = event.data;
265
+ const workItemId = isRecord(data) && typeof data.workItemId === "string" ? data.workItemId : void 0;
266
+ await stream.writeSSE({
267
+ event: "feed",
268
+ data: JSON.stringify(workItemId ? { workItemId } : {})
269
+ });
270
+ };
271
+ const closed = new Promise((resolve) => stream.onAbort(resolve));
272
+ let keepalive;
273
+ try {
274
+ await pubsub.subscribe(topic, onEvent, { startFrom: "latest" });
275
+ if (!stream.aborted) {
276
+ keepalive = setInterval(() => {
277
+ if (stream.aborted) return;
278
+ stream.write(": ping\n\n");
279
+ }, FEED_KEEPALIVE_MS);
280
+ await closed;
281
+ }
282
+ } finally {
283
+ clearInterval(keepalive);
284
+ await pubsub.unsubscribe(topic, onEvent);
285
+ }
286
+ });
287
+ }
242
288
  })
243
289
  ];
244
290
  }
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/storage/domains/comments/routes.ts"],"sourcesContent":["/**\n * HTTP for the item feed. Every handler is the same shape: resolve the tenant,\n * validate the path ids, delegate to a `CommentsDomain` service method, map its\n * result status to a status code, then emit audit.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { getFactoryAuthUser } from '../../../auth.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { AuditEmitter } from '../audit/domain.js';\nimport type { FactoryProjectsStorage } from '../projects/base.js';\nimport type { WorkItemsStorage } from '../work-items/base.js';\nimport { actorFromAuthUser } from './actor.js';\nimport type { WorkItemCommentsStorage } from './base.js';\nimport { decodeCommentCursor } from './base.js';\nimport type { CommentEditor, CommentsDomain } from './domain.js';\nimport { parseCreateCommentBody, parseEditCommentBody, readJson, UUID_RE } from './parse.js';\nimport { toWireComment } from './wire.js';\nimport type { WireCommentPage } from './wire.js';\n\nconst MAX_AUDIT_BODY_SNAPSHOT = 1024;\n\nexport interface CommentRouteDependencies {\n domain: CommentsDomain;\n auth: RouteAuth;\n comments: WorkItemCommentsStorage;\n workItems: WorkItemsStorage;\n projects: FactoryProjectsStorage;\n audit?: AuditEmitter;\n}\n\ninterface Tenant {\n orgId: string;\n userId: string;\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nexport function buildCommentRoutes(dependencies: CommentRouteDependencies): ApiRoute[] {\n const { domain, auth, comments, workItems, projects, audit } = dependencies;\n\n async function resolveTenant(c: Context): Promise<Tenant | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'The item feed requires an organization.' }, 403),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n function editorFor(c: Context, tenant: Tenant): CommentEditor {\n return {\n userId: tenant.userId,\n canModerate: () => auth.isOrganizationAdmin(c, tenant.orgId),\n };\n }\n\n async function emitMentionAudit(\n c: Context,\n target: { factoryProjectId: string; workItemId: string; title?: string },\n commentId: string,\n mentionedIds: string[],\n ): Promise<void> {\n if (mentionedIds.length === 0) return;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_mentioned',\n factoryProjectId: target.factoryProjectId,\n targets: [{ type: 'work_item', id: target.workItemId, ...(target.title ? { name: target.title } : {}) }],\n metadata: { commentId, mentionedIds },\n },\n });\n }\n\n return [\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n await workItems.ensureReady();\n const workItem = await workItems.get({ orgId: tenant.orgId, id: workItemId });\n if (!workItem) return c.json({ error: 'Work item not found' }, 404);\n\n await comments.ensureReady();\n const limitRaw = c.req.query('limit');\n const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;\n const before = c.req.query('before') || undefined;\n if (before && !decodeCommentCursor(before)) return c.json({ error: 'invalid_cursor' }, 422);\n const around = c.req.query('around') || undefined;\n if (around && !UUID_RE.test(around)) return c.json({ error: 'invalid_comment_id' }, 422);\n const page = await comments.list({\n orgId: tenant.orgId,\n factoryProjectId: workItem.factoryProjectId,\n workItemId,\n before,\n ...(around ? { around } : {}),\n ...(limit !== undefined && Number.isFinite(limit) ? { limit } : {}),\n });\n const wirePage: WireCommentPage = {\n comments: page.comments.map(comment => toWireComment(comment, tenant.userId)),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n };\n return c.json(wirePage);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'POST',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n\n const parsed = parseCreateCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.createComment({\n orgId: tenant.orgId,\n workItemId,\n author: actorFromAuthUser(tenant.userId, getFactoryAuthUser(c)),\n body: parsed.body,\n ...(parsed.replyTo ? { replyTo: parsed.replyTo } : {}),\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.clientToken ? { clientToken: parsed.clientToken } : {}),\n });\n if (result.status === 'work_item_not_found') return c.json({ error: 'Work item not found' }, 404);\n if (result.status === 'token_conflict') return c.json({ error: 'comment_token_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment, workItem } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_created',\n factoryProjectId: workItem.factoryProjectId,\n targets: [{ type: 'work_item', id: workItem.id, name: workItem.title }],\n metadata: { commentId: comment.id },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: workItem.factoryProjectId, workItemId: workItem.id, title: workItem.title },\n comment.id,\n comment.mentions.map(mention => mention.id).filter(id => id !== comment.author.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) }, 201);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'PATCH',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const parsed = parseEditCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.editComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n body: parsed.body,\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.expectedRevision !== undefined ? { expectedRevision: parsed.expectedRevision } : {}),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n if (result.status === 'conflict') return c.json({ error: 'comment_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_edited',\n factoryProjectId: comment.factoryProjectId,\n targets: [{ type: 'work_item', id: comment.workItemId }],\n metadata: {\n commentId: comment.id,\n previousBody: result.previousBody.slice(0, MAX_AUDIT_BODY_SNAPSHOT),\n },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: comment.factoryProjectId, workItemId: comment.workItemId },\n comment.id,\n result.addedMentions.map(mention => mention.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'DELETE',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const result = await domain.deleteComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_deleted',\n factoryProjectId: result.comment.factoryProjectId,\n targets: [{ type: 'work_item', id: result.comment.workItemId }],\n metadata: { commentId: result.comment.id },\n },\n });\n return c.json({ comment: toWireComment(result.comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/mention-roster', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n await comments.ensureReady();\n const roster = await domain.mentionRoster({ orgId: tenant.orgId, factoryProjectId: projectId });\n const query = c.req.query('q')?.trim().toLowerCase();\n const members = query\n ? roster.filter(member => (member.name ?? member.id).toLowerCase().startsWith(query))\n : roster;\n return c.json({ members });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,0BAA0B;AAgBhC,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;AAEA,SAAgB,mBAAmB,cAAoD;CACrF,MAAM,EAAE,QAAQ,MAAM,UAAU,WAAW,UAAU,UAAU;CAE/D,eAAe,cAAc,GAAsD;EACjF,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;EACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KAAK;GAAE,OAAO;GAAyB,SAAS;EAA0C,GAAG,GAAG,EAC9G;EAEF,OAAO;GAAE,OAAO,OAAO;GAAO,QAAQ,OAAO;EAAO;CACtD;CAEA,SAAS,UAAU,GAAY,QAA+B;EAC5D,OAAO;GACL,QAAQ,OAAO;GACf,mBAAmB,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AAc,CAAC;IACpC,IAAI,cAAc,QAAQ,OAAO,OAAO;IAExC,MAAM,YAAY,EAAE,IAAI,MAAM,IAAI;IAClC,IAAI,CAAC,aAAa,CAAC,QAAQ,KAAK,SAAS,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,oBAAoB,GAAG,GAAG;IAC7F,MAAM,SAAS,YAAY;IAE3B,IAAI,CAAC,MADiB,SAAS,IAAI;KAAE,OAAO,OAAO;KAAO,IAAI;IAAU,CAAC,GAC3D,OAAO,EAAE,KAAK,EAAE,OAAO,oBAAoB,GAAG,GAAG;IAE/D,MAAM,SAAS,YAAY;IAC3B,MAAM,SAAS,MAAM,OAAO,cAAc;KAAE,OAAO,OAAO;KAAO,kBAAkB;IAAU,CAAC;IAC9F,MAAM,QAAQ,EAAE,IAAI,MAAM,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,YAAY;IACnD,MAAM,UAAU,QACZ,OAAO,QAAO,YAAW,OAAO,QAAQ,OAAO,GAAA,CAAI,YAAY,CAAC,CAAC,WAAW,KAAK,CAAC,IAClF;IACJ,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC;GAC3B;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/storage/domains/comments/routes.ts"],"sourcesContent":["/**\n * HTTP for the item feed. Every handler is the same shape: resolve the tenant,\n * validate the path ids, delegate to a `CommentsDomain` service method, map its\n * result status to a status code, then emit audit.\n */\n\nimport type { EventCallback, PubSub } from '@mastra/core/events';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { streamSSE } from 'hono/streaming';\n\nimport { getFactoryAuthUser } from '../../../auth.js';\nimport { feedTopic } from '../../../feed-events.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { AuditEmitter } from '../audit/domain.js';\nimport type { FactoryProjectsStorage } from '../projects/base.js';\nimport type { WorkItemsStorage } from '../work-items/base.js';\nimport { actorFromAuthUser } from './actor.js';\nimport type { WorkItemCommentsStorage } from './base.js';\nimport { decodeCommentCursor } from './base.js';\nimport type { CommentEditor, CommentsDomain } from './domain.js';\nimport { isRecord, parseCreateCommentBody, parseEditCommentBody, readJson, UUID_RE } from './parse.js';\nimport { toWireComment } from './wire.js';\nimport type { WireCommentPage } from './wire.js';\n\nconst MAX_AUDIT_BODY_SNAPSHOT = 1024;\n/** Comment frames only — proxies drop an idle stream, and `write` can't detect a dead peer. */\nconst FEED_KEEPALIVE_MS = 25_000;\n// Ceiling: one broker subscription per open tab, not per project. A per-replica\n// topic multiplexer is the upgrade path if tab counts ever make that hurt.\n\nexport interface CommentRouteDependencies {\n domain: CommentsDomain;\n auth: RouteAuth;\n comments: WorkItemCommentsStorage;\n workItems: WorkItemsStorage;\n projects: FactoryProjectsStorage;\n pubsub: PubSub;\n audit?: AuditEmitter;\n}\n\ninterface Tenant {\n orgId: string;\n userId: string;\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nexport function buildCommentRoutes(dependencies: CommentRouteDependencies): ApiRoute[] {\n const { domain, auth, comments, workItems, projects, pubsub, audit } = dependencies;\n\n async function resolveTenant(c: Context): Promise<Tenant | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'The item feed requires an organization.' }, 403),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n function editorFor(c: Context, tenant: Tenant): CommentEditor {\n return {\n userId: tenant.userId,\n canModerate: () => auth.isOrganizationAdmin(c, tenant.orgId),\n };\n }\n\n async function emitMentionAudit(\n c: Context,\n target: { factoryProjectId: string; workItemId: string; title?: string },\n commentId: string,\n mentionedIds: string[],\n ): Promise<void> {\n if (mentionedIds.length === 0) return;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_mentioned',\n factoryProjectId: target.factoryProjectId,\n targets: [{ type: 'work_item', id: target.workItemId, ...(target.title ? { name: target.title } : {}) }],\n metadata: { commentId, mentionedIds },\n },\n });\n }\n\n return [\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n await workItems.ensureReady();\n const workItem = await workItems.get({ orgId: tenant.orgId, id: workItemId });\n if (!workItem) return c.json({ error: 'Work item not found' }, 404);\n\n await comments.ensureReady();\n const limitRaw = c.req.query('limit');\n const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;\n const before = c.req.query('before') || undefined;\n if (before && !decodeCommentCursor(before)) return c.json({ error: 'invalid_cursor' }, 422);\n const around = c.req.query('around') || undefined;\n if (around && !UUID_RE.test(around)) return c.json({ error: 'invalid_comment_id' }, 422);\n const page = await comments.list({\n orgId: tenant.orgId,\n factoryProjectId: workItem.factoryProjectId,\n workItemId,\n before,\n ...(around ? { around } : {}),\n ...(limit !== undefined && Number.isFinite(limit) ? { limit } : {}),\n });\n const wirePage: WireCommentPage = {\n comments: page.comments.map(comment => toWireComment(comment, tenant.userId)),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n };\n return c.json(wirePage);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'POST',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n\n const parsed = parseCreateCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.createComment({\n orgId: tenant.orgId,\n workItemId,\n author: actorFromAuthUser(tenant.userId, getFactoryAuthUser(c)),\n body: parsed.body,\n ...(parsed.replyTo ? { replyTo: parsed.replyTo } : {}),\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.clientToken ? { clientToken: parsed.clientToken } : {}),\n });\n if (result.status === 'work_item_not_found') return c.json({ error: 'Work item not found' }, 404);\n if (result.status === 'token_conflict') return c.json({ error: 'comment_token_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment, workItem } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_created',\n factoryProjectId: workItem.factoryProjectId,\n targets: [{ type: 'work_item', id: workItem.id, name: workItem.title }],\n metadata: { commentId: comment.id },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: workItem.factoryProjectId, workItemId: workItem.id, title: workItem.title },\n comment.id,\n comment.mentions.map(mention => mention.id).filter(id => id !== comment.author.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) }, 201);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'PATCH',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const parsed = parseEditCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.editComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n body: parsed.body,\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.expectedRevision !== undefined ? { expectedRevision: parsed.expectedRevision } : {}),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n if (result.status === 'conflict') return c.json({ error: 'comment_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_edited',\n factoryProjectId: comment.factoryProjectId,\n targets: [{ type: 'work_item', id: comment.workItemId }],\n metadata: {\n commentId: comment.id,\n previousBody: result.previousBody.slice(0, MAX_AUDIT_BODY_SNAPSHOT),\n },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: comment.factoryProjectId, workItemId: comment.workItemId },\n comment.id,\n result.addedMentions.map(mention => mention.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'DELETE',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const result = await domain.deleteComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_deleted',\n factoryProjectId: result.comment.factoryProjectId,\n targets: [{ type: 'work_item', id: result.comment.workItemId }],\n metadata: { commentId: result.comment.id },\n },\n });\n return c.json({ comment: toWireComment(result.comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/mention-roster', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n await comments.ensureReady();\n const roster = await domain.mentionRoster({ orgId: tenant.orgId, factoryProjectId: projectId });\n const query = c.req.query('q')?.trim().toLowerCase();\n const members = query\n ? roster.filter(member => (member.name ?? member.id).toLowerCase().startsWith(query))\n : roster;\n return c.json({ members });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/feed-events', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n const topic = feedTopic(tenant.orgId, projectId);\n return streamSSE(c, async stream => {\n const onEvent: EventCallback = async event => {\n if (stream.aborted) return;\n const data = event.data;\n const workItemId = isRecord(data) && typeof data.workItemId === 'string' ? data.workItemId : undefined;\n await stream.writeSSE({ event: 'feed', data: JSON.stringify(workItemId ? { workItemId } : {}) });\n };\n // Claimed before any await: `onAbort` handlers registered after the\n // reader is gone never run, and a broker subscribe is a round trip.\n const closed = new Promise<void>(resolve => stream.onAbort(resolve));\n let keepalive: ReturnType<typeof setInterval> | undefined;\n try {\n // Without `latest`, a retaining broker replays its whole backlog into\n // every new connection as spurious invalidations.\n await pubsub.subscribe(topic, onEvent, { startFrom: 'latest' });\n if (!stream.aborted) {\n keepalive = setInterval(() => {\n if (stream.aborted) return;\n void stream.write(': ping\\n\\n');\n }, FEED_KEEPALIVE_MS);\n // `streamSSE` closes the stream the moment this callback returns.\n await closed;\n }\n } finally {\n clearInterval(keepalive);\n await pubsub.unsubscribe(topic, onEvent);\n }\n });\n },\n }),\n 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,MAAM;MACR;KACF,UAAU;MACR,cAAc,SAAS;MACvB,MAAM,OAAO,YAAY,OAAO,OAAO;KACzC;IACF,CAAC;GACH;EACF,CAAC;CACH;AACF"}
@@ -1,4 +1,5 @@
1
1
  import type { CollectionSchema } from '@mastra/core/storage';
2
2
  export declare const WORK_ITEM_COMMENTS_SCHEMA: CollectionSchema;
3
3
  export declare const WORK_ITEM_COMMENT_MENTIONS_SCHEMA: CollectionSchema;
4
+ export declare const WORK_ITEM_ACTIVITY_SCHEMA: CollectionSchema;
4
5
  //# sourceMappingURL=schema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,eAAO,MAAM,yBAAyB,EAAE,gBA2CvC,CAAC;AAEF,eAAO,MAAM,iCAAiC,EAAE,gBA6B/C,CAAC"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,eAAO,MAAM,yBAAyB,EAAE,gBA2CvC,CAAC;AAEF,eAAO,MAAM,iCAAiC,EAAE,gBA6B/C,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,gBAgCvC,CAAC"}
@@ -129,7 +129,51 @@ const WORK_ITEM_COMMENT_MENTIONS_SCHEMA = {
129
129
  ]
130
130
  }]
131
131
  };
132
+ const WORK_ITEM_ACTIVITY_SCHEMA = {
133
+ name: "work_item_activity",
134
+ columns: {
135
+ id: { type: "uuid-pk" },
136
+ org_id: { type: "text" },
137
+ factory_project_id: { type: "text" },
138
+ work_item_id: { type: "text" },
139
+ participant_id: { type: "text" },
140
+ occurrence: {
141
+ type: "integer",
142
+ default: 1
143
+ },
144
+ latest_comment_id: { type: "text" },
145
+ latest_author_id: { type: "text" },
146
+ latest_author_name: {
147
+ type: "text",
148
+ nullable: true
149
+ },
150
+ occurred_at: { type: "timestamp" },
151
+ created_at: { type: "timestamp" },
152
+ updated_at: { type: "timestamp" }
153
+ },
154
+ uniqueIndexes: [{
155
+ name: "work_item_activity_item_participant_unique",
156
+ columns: ["work_item_id", "participant_id"]
157
+ }],
158
+ indexes: [{
159
+ name: "work_item_activity_inbox_idx",
160
+ columns: [
161
+ "org_id",
162
+ "factory_project_id",
163
+ "participant_id",
164
+ "occurred_at",
165
+ "id"
166
+ ]
167
+ }, {
168
+ name: "work_item_activity_item_idx",
169
+ columns: [
170
+ "org_id",
171
+ "factory_project_id",
172
+ "work_item_id"
173
+ ]
174
+ }]
175
+ };
132
176
  //#endregion
133
- export { WORK_ITEM_COMMENTS_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA };
177
+ export { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA };
134
178
 
135
179
  //# sourceMappingURL=schema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../../../../src/storage/domains/comments/schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nexport const WORK_ITEM_COMMENTS_SCHEMA: CollectionSchema = {\n name: 'work_item_comments',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n kind: { type: 'text', default: 'comment' },\n body: { type: 'text' },\n body_format: { type: 'text', default: 'markdown' },\n author_kind: { type: 'text' },\n author_id: { type: 'text' },\n author_display_name: { type: 'text', nullable: true },\n author_avatar_url: { type: 'text', nullable: true },\n author_external: { type: 'json', nullable: true },\n reply_to_comment_id: { type: 'text', nullable: true },\n reply_quote: { type: 'text', nullable: true },\n reply_to_author_id: { type: 'text', nullable: true },\n reply_to_author_name: { type: 'text', nullable: true },\n mentions: { type: 'json' },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n occurred_at: { type: 'timestamp' },\n edited_at: { type: 'timestamp', nullable: true },\n deleted_at: { type: 'timestamp', nullable: true },\n deleted_by: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_item_comments_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n whereNotNull: 'source_key',\n },\n ],\n indexes: [\n {\n name: 'work_item_comments_feed_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id', 'occurred_at', 'id'],\n },\n ],\n};\n\nexport const WORK_ITEM_COMMENT_MENTIONS_SCHEMA: CollectionSchema = {\n name: 'work_item_comment_mentions',\n columns: {\n id: { type: 'uuid-pk' },\n comment_id: { type: 'text' },\n mentioned_kind: { type: 'text' },\n mentioned_id: { type: 'text' },\n author_id: { type: 'text' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n occurred_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_item_comment_mentions_comment_target_unique',\n columns: ['comment_id', 'mentioned_kind', 'mentioned_id'],\n },\n ],\n indexes: [\n {\n name: 'work_item_comment_mentions_inbox_idx',\n columns: ['org_id', 'factory_project_id', 'mentioned_id', 'occurred_at', 'id'],\n },\n {\n name: 'work_item_comment_mentions_item_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id'],\n },\n ],\n};\n"],"mappings":";AAEA,MAAa,4BAA8C;CACzD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,cAAc,EAAE,MAAM,OAAO;EAC7B,MAAM;GAAE,MAAM;GAAQ,SAAS;EAAU;EACzC,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM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C,cAAc,EAAE,MAAM,OAAO;EAC7B,aAAa,EAAE,MAAM,YAAY;CACnC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS;GAAC;GAAc;GAAkB;EAAc;CAC1D,CACF;CACA,SAAS,CACP;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;GAAgB;GAAe;EAAI;CAC/E,GACA;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;EAAc;CAC1D,CACF;AACF"}
1
+ {"version":3,"file":"schema.js","names":[],"sources":["../../../../src/storage/domains/comments/schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nexport const WORK_ITEM_COMMENTS_SCHEMA: CollectionSchema = {\n name: 'work_item_comments',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n kind: { type: 'text', default: 'comment' },\n body: { type: 'text' },\n body_format: { type: 'text', default: 'markdown' },\n author_kind: { type: 'text' },\n author_id: { type: 'text' },\n author_display_name: { type: 'text', nullable: true },\n author_avatar_url: { type: 'text', nullable: true },\n author_external: { type: 'json', nullable: true },\n reply_to_comment_id: { type: 'text', nullable: true },\n reply_quote: { type: 'text', nullable: true },\n reply_to_author_id: { type: 'text', nullable: true },\n reply_to_author_name: { type: 'text', nullable: true },\n mentions: { type: 'json' },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n occurred_at: { type: 'timestamp' },\n edited_at: { type: 'timestamp', nullable: true },\n deleted_at: { type: 'timestamp', nullable: true },\n deleted_by: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_item_comments_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n whereNotNull: 'source_key',\n },\n ],\n indexes: [\n {\n name: 'work_item_comments_feed_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id', 'occurred_at', 'id'],\n },\n ],\n};\n\nexport const WORK_ITEM_COMMENT_MENTIONS_SCHEMA: CollectionSchema = {\n name: 'work_item_comment_mentions',\n columns: {\n id: { type: 'uuid-pk' },\n comment_id: { type: 'text' },\n mentioned_kind: { type: 'text' },\n mentioned_id: { type: 'text' },\n author_id: { type: 'text' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n occurred_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_item_comment_mentions_comment_target_unique',\n columns: ['comment_id', 'mentioned_kind', 'mentioned_id'],\n },\n ],\n indexes: [\n {\n name: 'work_item_comment_mentions_inbox_idx',\n columns: ['org_id', 'factory_project_id', 'mentioned_id', 'occurred_at', 'id'],\n },\n {\n name: 'work_item_comment_mentions_item_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id'],\n },\n ],\n};\n\nexport const WORK_ITEM_ACTIVITY_SCHEMA: CollectionSchema = {\n name: 'work_item_activity',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n participant_id: { type: 'text' },\n occurrence: { type: 'integer', default: 1 },\n latest_comment_id: { type: 'text' },\n latest_author_id: { type: 'text' },\n latest_author_name: { type: 'text', nullable: true },\n occurred_at: { type: 'timestamp' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_item_activity_item_participant_unique',\n columns: ['work_item_id', 'participant_id'],\n },\n ],\n indexes: [\n {\n name: 'work_item_activity_inbox_idx',\n columns: ['org_id', 'factory_project_id', 'participant_id', 'occurred_at', 'id'],\n },\n {\n name: 'work_item_activity_item_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id'],\n },\n ],\n};\n"],"mappings":";AAEA,MAAa,4BAA8C;CACzD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO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3B,gBAAgB,EAAE,MAAM,OAAO;EAC/B,cAAc,EAAE,MAAM,OAAO;EAC7B,WAAW,EAAE,MAAM,OAAO;EAC1B,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,cAAc,EAAE,MAAM,OAAO;EAC7B,aAAa,EAAE,MAAM,YAAY;CACnC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS;GAAC;GAAc;GAAkB;EAAc;CAC1D,CACF;CACA,SAAS,CACP;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;GAAgB;GAAe;EAAI;CAC/E,GACA;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;EAAc;CAC1D,CACF;AACF;AAEA,MAAa,4BAA8C;CACzD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,cAAc,EAAE,MAAM,OAAO;EAC7B,gBAAgB,EAAE,MAAM,OAAO;EAC/B,YAAY;GAAE,MAAM;GAAW,SAAS;EAAE;EAC1C,mBAAmB,EAAE,MAAM,OAAO;EAClC,kBAAkB,EAAE,MAAM,OAAO;EACjC,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACnD,aAAa,EAAE,MAAM,YAAY;EACjC,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS,CAAC,gBAAgB,gBAAgB;CAC5C,CACF;CACA,SAAS,CACP;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;GAAkB;GAAe;EAAI;CACjF,GACA;EACE,MAAM;EACN,SAAS;GAAC;GAAU;GAAsB;EAAc;CAC1D,CACF;AACF"}
@@ -11,7 +11,7 @@
11
11
  * returned by {@link IntegrationStorage.forIntegration}.
12
12
  *
13
13
  * Source-control integrations additionally use the shared, provider-scoped
14
- * source-control domain for installations, projects, worktrees, and sandboxes.
14
+ * source-control domain for installations, projects, and sessions.
15
15
  *
16
16
  * Payloads (`data` / `config`) are JSON documents typed per-integration via
17
17
  * the handle's generics. JSON round-trips exactly what JSON can represent:
@@ -14,7 +14,7 @@ import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage
14
14
  * returned by {@link IntegrationStorage.forIntegration}.
15
15
  *
16
16
  * Source-control integrations additionally use the shared, provider-scoped
17
- * source-control domain for installations, projects, worktrees, and sandboxes.
17
+ * source-control domain for installations, projects, and sessions.
18
18
  *
19
19
  * Payloads (`data` / `config`) are JSON documents typed per-integration via
20
20
  * the handle's generics. JSON round-trips exactly what JSON can represent:
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#migrateValue","#db"],"sources":["../../../../src/storage/domains/integrations/base.ts"],"sourcesContent":["/**\n * Generic integration storage — the default persistence surface for\n * `FactoryIntegration`s.\n *\n * Most integrations persist the same three shapes: an org-owned OAuth\n * **connection**, **subscriptions** binding external objects to\n * sessions/threads, and per-`(org, user)` **settings**. This built-in domain\n * stores all three in shared collections keyed by `integration_id`, so an\n * integration author writes zero schema, zero DDL, and zero queries — and\n * org scoping is enforced by construction through the pre-scoped handle\n * returned by {@link IntegrationStorage.forIntegration}.\n *\n * Source-control integrations additionally use the shared, provider-scoped\n * source-control domain for installations, projects, worktrees, and sandboxes.\n *\n * Payloads (`data` / `config`) are JSON documents typed per-integration via\n * the handle's generics. JSON round-trips exactly what JSON can represent:\n * store timestamps inside payloads as epoch millis or ISO strings, not\n * `Date`s.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\nexport const INTEGRATION_CONNECTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_connections',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Who connected it (audit only — never scopes reads). */\n user_id: { type: 'text', nullable: true },\n data: { type: 'json' },\n metadata: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'integration_connections_integration_org_unique', columns: ['integration_id', 'org_id'] }],\n};\n\nexport const INTEGRATION_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Canonical external-object key the integration derives (e.g. `pr:{installation}:{repo}:{number}`). */\n target_key: { type: 'text' },\n session_id: { type: 'text', nullable: true },\n resource_id: { type: 'text', nullable: true },\n thread_id: { type: 'text', nullable: true },\n session_scope: { type: 'text', nullable: true },\n status: { type: 'text' },\n data: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'integration_subscriptions_target_idx', columns: ['integration_id', 'target_key'] },\n { name: 'integration_subscriptions_org_idx', columns: ['integration_id', 'org_id'] },\n ],\n};\n\nexport const INTEGRATION_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'integration_settings',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'integration_settings_integration_org_user_unique', columns: ['integration_id', 'org_id', 'user_id'] },\n ],\n};\n\n/** An integration's org-owned connection (typically the OAuth grant). */\nexport interface IntegrationConnection<TData> {\n id: string;\n orgId: string;\n /** Who connected it (audit only). */\n userId: string | null;\n data: TData;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** A subscription binding an external object to a session/thread. */\nexport interface IntegrationSubscription<TData> {\n id: string;\n orgId: string;\n targetKey: string;\n sessionId: string | null;\n resourceId: string | null;\n threadId: string | null;\n sessionScope: string | null;\n status: string;\n data: TData;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type CreateIntegrationSubscriptionInput<TData> = {\n orgId: string;\n targetKey: string;\n sessionId?: string | null;\n resourceId?: string | null;\n threadId?: string | null;\n sessionScope?: string | null;\n /** Defaults to `'active'`. */\n status?: string;\n} & ({} extends TData ? { data?: TData } : { data: TData });\n\n/**\n * Typed query surface pre-scoped to one `integration_id`. Every read and\n * write is automatically filtered/stamped with the integration id, so an\n * integration cannot reach another integration's rows.\n */\nexport interface IntegrationStorageHandle<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n> {\n readonly integrationId: string;\n connections: {\n /** The org's connection, or `null` when not connected. */\n get(orgId: string): Promise<IntegrationConnection<TConnection> | null>;\n /** Insert or replace the org's connection (one per org; `created_at` preserved on update). */\n upsert(\n orgId: string,\n input: { userId?: string | null; data: TConnection; metadata?: Record<string, unknown> },\n ): Promise<void>;\n /**\n * Atomic read-modify-write of the connection's `data` payload (token\n * rotation etc.). Returns the updated connection, or `null` when the org\n * has no connection.\n */\n update(orgId: string, fn: (data: TConnection) => TConnection): Promise<IntegrationConnection<TConnection> | null>;\n /** Remove the org's connection. Returns whether a row was deleted. */\n delete(orgId: string): Promise<boolean>;\n };\n subscriptions: {\n create(input: CreateIntegrationSubscriptionInput<TSubscription>): Promise<IntegrationSubscription<TSubscription>>;\n /** All subscriptions for an external object (webhook fan-out), optionally filtered by status. */\n listByTarget(targetKey: string, opts?: { status?: string }): Promise<IntegrationSubscription<TSubscription>[]>;\n listBySession(sessionId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n listByThread(resourceId: string, threadId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n updateStatus(id: string, status: string): Promise<void>;\n delete(id: string): Promise<boolean>;\n /** Targeted cleanup, always org-scoped. Returns the number of rows deleted. */\n deleteWhere(where: { orgId: string; targetKey?: string; sessionId?: string }): Promise<number>;\n };\n settings: {\n /** The `(org, user)` config, or `null` when never saved. */\n get(orgId: string, userId: string): Promise<TSettings | null>;\n /** Upsert the `(org, user)` config (`created_at` preserved on update). */\n save(orgId: string, userId: string, config: TSettings): Promise<void>;\n };\n}\n\ninterface ConnectionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n user_id: string | null;\n data: unknown;\n metadata: Record<string, unknown>;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface SubscriptionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n target_key: string;\n session_id: string | null;\n resource_id: string | null;\n thread_id: string | null;\n session_scope: string | null;\n status: string;\n data: unknown;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The built-in generic integration domain, written once against the\n * `FactoryStorageOps` surface — works on any `FactoryStorage` backend.\n */\nexport class IntegrationStorage extends FactoryStorageDomain {\n constructor(\n private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption(),\n ) {\n super('integrations');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTEGRATION_CONNECTIONS_SCHEMA,\n INTEGRATION_SUBSCRIPTIONS_SCHEMA,\n INTEGRATION_SETTINGS_SCHEMA,\n ]);\n const [connections, settings] = await Promise.all([\n this.ops.findMany<ConnectionRow>('integration_connections', {}),\n this.ops.findMany<{ id: string; config: unknown }>('integration_settings', {}),\n ]);\n await Promise.all([\n ...connections.map(row => this.#migrateValue('integration_connections', row.id, 'data')),\n ...settings.map(row => this.#migrateValue('integration_settings', row.id, 'config')),\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('integration_subscriptions', {});\n await this.ops.deleteMany('integration_settings', {});\n await this.ops.deleteMany('integration_connections', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #migrateValue(collection: string, id: string, column: 'data' | 'config'): Promise<void> {\n await this.#db.updateAtomic<Record<string, unknown>>(collection, { id }, async row => {\n const decrypted = await this.encryption.decrypt(row[column]);\n return decrypted.needsReencryption ? { [column]: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /** A typed handle pre-scoped to `integrationId`. */\n forIntegration<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n >(integrationId: string): IntegrationStorageHandle<TConnection, TSettings, TSubscription> {\n if (!integrationId) throw new Error('[IntegrationStorage] integrationId is required.');\n const db = () => this.#db;\n const scoped = { integration_id: integrationId };\n\n const mapConnection = async (row: ConnectionRow): Promise<IntegrationConnection<TConnection>> => ({\n id: row.id,\n orgId: row.org_id,\n userId: row.user_id,\n data: (await this.encryption.decrypt<TConnection>(row.data)).value,\n metadata: row.metadata ?? {},\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n const mapSubscription = (row: SubscriptionRow): IntegrationSubscription<TSubscription> => ({\n id: row.id,\n orgId: row.org_id,\n targetKey: row.target_key,\n sessionId: row.session_id,\n resourceId: row.resource_id,\n threadId: row.thread_id,\n sessionScope: row.session_scope,\n status: row.status,\n data: row.data as TSubscription,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n return {\n integrationId,\n connections: {\n get: async orgId => {\n const row = await db().findOne<ConnectionRow>('integration_connections', { ...scoped, org_id: orgId });\n return row ? mapConnection(row) : null;\n },\n upsert: async (orgId, input) => {\n const where = { ...scoped, org_id: orgId };\n const encrypted = await this.encryption.encrypt(input.data);\n const update = async () =>\n db().updateMany('integration_connections', where, {\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne<ConnectionRow>('integration_connections', {\n ...where,\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n update: async (orgId, fn) => {\n const row = await db().updateAtomic<ConnectionRow>(\n 'integration_connections',\n { ...scoped, org_id: orgId },\n async current => {\n const data = (await this.encryption.decrypt<TConnection>(current.data)).value;\n return { data: await this.encryption.encrypt(fn(data)), updated_at: new Date() };\n },\n );\n return row ? mapConnection(row) : null;\n },\n delete: async orgId => {\n const deleted = await db().deleteMany('integration_connections', { ...scoped, org_id: orgId });\n return deleted > 0;\n },\n },\n subscriptions: {\n create: async input => {\n const now = new Date();\n const row = await db().insertOne<SubscriptionRow>('integration_subscriptions', {\n ...scoped,\n org_id: input.orgId,\n target_key: input.targetKey,\n session_id: input.sessionId ?? null,\n resource_id: input.resourceId ?? null,\n thread_id: input.threadId ?? null,\n session_scope: input.sessionScope ?? null,\n status: input.status ?? 'active',\n data: input.data ?? {},\n created_at: now,\n updated_at: now,\n });\n return mapSubscription(row);\n },\n listByTarget: async (targetKey, opts) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, target_key: targetKey, ...(opts?.status !== undefined ? { status: opts.status } : {}) },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listBySession: async sessionId => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, session_id: sessionId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listByThread: async (resourceId, threadId) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, resource_id: resourceId, thread_id: threadId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n updateStatus: async (id, status) => {\n await db().updateMany('integration_subscriptions', { ...scoped, id }, { status, updated_at: new Date() });\n },\n delete: async id => {\n const deleted = await db().deleteMany('integration_subscriptions', { ...scoped, id });\n return deleted > 0;\n },\n deleteWhere: async where => {\n return db().deleteMany('integration_subscriptions', {\n ...scoped,\n org_id: where.orgId,\n ...(where.targetKey !== undefined ? { target_key: where.targetKey } : {}),\n ...(where.sessionId !== undefined ? { session_id: where.sessionId } : {}),\n });\n },\n },\n settings: {\n get: async (orgId, userId) => {\n const row = await db().findOne<{ config: unknown }>('integration_settings', {\n ...scoped,\n org_id: orgId,\n user_id: userId,\n });\n return row ? (await this.encryption.decrypt<TSettings>(row.config)).value : null;\n },\n save: async (orgId, userId, config) => {\n const where = { ...scoped, org_id: orgId, user_id: userId };\n const encrypted = await this.encryption.encrypt(config);\n const update = async () =>\n db().updateMany('integration_settings', where, {\n config: encrypted,\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne('integration_settings', {\n ...where,\n config: encrypted,\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,iCAAmD;CAC9D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,SAAS;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxC,MAAM,EAAE,MAAM,OAAO;EACrB,UAAU,EAAE,MAAM,OAAO;EACzB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAkD,SAAS,CAAC,kBAAkB,QAAQ;CAAE,CAAC;AACnH;AAEA,MAAa,mCAAqD;CAChE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY;GAAE,MA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AAuB,MAAM;OACpD,YAAY;MACd;KACF;KACA,MAAM;IACR;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":["#migrateValue","#db"],"sources":["../../../../src/storage/domains/integrations/base.ts"],"sourcesContent":["/**\n * Generic integration storage — the default persistence surface for\n * `FactoryIntegration`s.\n *\n * Most integrations persist the same three shapes: an org-owned OAuth\n * **connection**, **subscriptions** binding external objects to\n * sessions/threads, and per-`(org, user)` **settings**. This built-in domain\n * stores all three in shared collections keyed by `integration_id`, so an\n * integration author writes zero schema, zero DDL, and zero queries — and\n * org scoping is enforced by construction through the pre-scoped handle\n * returned by {@link IntegrationStorage.forIntegration}.\n *\n * Source-control integrations additionally use the shared, provider-scoped\n * source-control domain for installations, projects, and sessions.\n *\n * Payloads (`data` / `config`) are JSON documents typed per-integration via\n * the handle's generics. JSON round-trips exactly what JSON can represent:\n * store timestamps inside payloads as epoch millis or ISO strings, not\n * `Date`s.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\nexport const INTEGRATION_CONNECTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_connections',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Who connected it (audit only — never scopes reads). */\n user_id: { type: 'text', nullable: true },\n data: { type: 'json' },\n metadata: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'integration_connections_integration_org_unique', columns: ['integration_id', 'org_id'] }],\n};\n\nexport const INTEGRATION_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Canonical external-object key the integration derives (e.g. `pr:{installation}:{repo}:{number}`). */\n target_key: { type: 'text' },\n session_id: { type: 'text', nullable: true },\n resource_id: { type: 'text', nullable: true },\n thread_id: { type: 'text', nullable: true },\n session_scope: { type: 'text', nullable: true },\n status: { type: 'text' },\n data: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'integration_subscriptions_target_idx', columns: ['integration_id', 'target_key'] },\n { name: 'integration_subscriptions_org_idx', columns: ['integration_id', 'org_id'] },\n ],\n};\n\nexport const INTEGRATION_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'integration_settings',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'integration_settings_integration_org_user_unique', columns: ['integration_id', 'org_id', 'user_id'] },\n ],\n};\n\n/** An integration's org-owned connection (typically the OAuth grant). */\nexport interface IntegrationConnection<TData> {\n id: string;\n orgId: string;\n /** Who connected it (audit only). */\n userId: string | null;\n data: TData;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** A subscription binding an external object to a session/thread. */\nexport interface IntegrationSubscription<TData> {\n id: string;\n orgId: string;\n targetKey: string;\n sessionId: string | null;\n resourceId: string | null;\n threadId: string | null;\n sessionScope: string | null;\n status: string;\n data: TData;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type CreateIntegrationSubscriptionInput<TData> = {\n orgId: string;\n targetKey: string;\n sessionId?: string | null;\n resourceId?: string | null;\n threadId?: string | null;\n sessionScope?: string | null;\n /** Defaults to `'active'`. */\n status?: string;\n} & ({} extends TData ? { data?: TData } : { data: TData });\n\n/**\n * Typed query surface pre-scoped to one `integration_id`. Every read and\n * write is automatically filtered/stamped with the integration id, so an\n * integration cannot reach another integration's rows.\n */\nexport interface IntegrationStorageHandle<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n> {\n readonly integrationId: string;\n connections: {\n /** The org's connection, or `null` when not connected. */\n get(orgId: string): Promise<IntegrationConnection<TConnection> | null>;\n /** Insert or replace the org's connection (one per org; `created_at` preserved on update). */\n upsert(\n orgId: string,\n input: { userId?: string | null; data: TConnection; metadata?: Record<string, unknown> },\n ): Promise<void>;\n /**\n * Atomic read-modify-write of the connection's `data` payload (token\n * rotation etc.). Returns the updated connection, or `null` when the org\n * has no connection.\n */\n update(orgId: string, fn: (data: TConnection) => TConnection): Promise<IntegrationConnection<TConnection> | null>;\n /** Remove the org's connection. Returns whether a row was deleted. */\n delete(orgId: string): Promise<boolean>;\n };\n subscriptions: {\n create(input: CreateIntegrationSubscriptionInput<TSubscription>): Promise<IntegrationSubscription<TSubscription>>;\n /** All subscriptions for an external object (webhook fan-out), optionally filtered by status. */\n listByTarget(targetKey: string, opts?: { status?: string }): Promise<IntegrationSubscription<TSubscription>[]>;\n listBySession(sessionId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n listByThread(resourceId: string, threadId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n updateStatus(id: string, status: string): Promise<void>;\n delete(id: string): Promise<boolean>;\n /** Targeted cleanup, always org-scoped. Returns the number of rows deleted. */\n deleteWhere(where: { orgId: string; targetKey?: string; sessionId?: string }): Promise<number>;\n };\n settings: {\n /** The `(org, user)` config, or `null` when never saved. */\n get(orgId: string, userId: string): Promise<TSettings | null>;\n /** Upsert the `(org, user)` config (`created_at` preserved on update). */\n save(orgId: string, userId: string, config: TSettings): Promise<void>;\n };\n}\n\ninterface ConnectionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n user_id: string | null;\n data: unknown;\n metadata: Record<string, unknown>;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface SubscriptionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n target_key: string;\n session_id: string | null;\n resource_id: string | null;\n thread_id: string | null;\n session_scope: string | null;\n status: string;\n data: unknown;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The built-in generic integration domain, written once against the\n * `FactoryStorageOps` surface — works on any `FactoryStorage` backend.\n */\nexport class IntegrationStorage extends FactoryStorageDomain {\n constructor(\n private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption(),\n ) {\n super('integrations');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTEGRATION_CONNECTIONS_SCHEMA,\n INTEGRATION_SUBSCRIPTIONS_SCHEMA,\n INTEGRATION_SETTINGS_SCHEMA,\n ]);\n const [connections, settings] = await Promise.all([\n this.ops.findMany<ConnectionRow>('integration_connections', {}),\n this.ops.findMany<{ id: string; config: unknown }>('integration_settings', {}),\n ]);\n await Promise.all([\n ...connections.map(row => this.#migrateValue('integration_connections', row.id, 'data')),\n ...settings.map(row => this.#migrateValue('integration_settings', row.id, 'config')),\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('integration_subscriptions', {});\n await this.ops.deleteMany('integration_settings', {});\n await this.ops.deleteMany('integration_connections', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #migrateValue(collection: string, id: string, column: 'data' | 'config'): Promise<void> {\n await this.#db.updateAtomic<Record<string, unknown>>(collection, { id }, async row => {\n const decrypted = await this.encryption.decrypt(row[column]);\n return decrypted.needsReencryption ? { [column]: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /** A typed handle pre-scoped to `integrationId`. */\n forIntegration<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n >(integrationId: string): IntegrationStorageHandle<TConnection, TSettings, TSubscription> {\n if (!integrationId) throw new Error('[IntegrationStorage] integrationId is required.');\n const db = () => this.#db;\n const scoped = { integration_id: integrationId };\n\n const mapConnection = async (row: ConnectionRow): Promise<IntegrationConnection<TConnection>> => ({\n id: row.id,\n orgId: row.org_id,\n userId: row.user_id,\n data: (await this.encryption.decrypt<TConnection>(row.data)).value,\n metadata: row.metadata ?? {},\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n const mapSubscription = (row: SubscriptionRow): IntegrationSubscription<TSubscription> => ({\n id: row.id,\n orgId: row.org_id,\n targetKey: row.target_key,\n sessionId: row.session_id,\n resourceId: row.resource_id,\n threadId: row.thread_id,\n sessionScope: row.session_scope,\n status: row.status,\n data: row.data as TSubscription,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n return {\n integrationId,\n connections: {\n get: async orgId => {\n const row = await db().findOne<ConnectionRow>('integration_connections', { ...scoped, org_id: orgId });\n return row ? mapConnection(row) : null;\n },\n upsert: async (orgId, input) => {\n const where = { ...scoped, org_id: orgId };\n const encrypted = await this.encryption.encrypt(input.data);\n const update = async () =>\n db().updateMany('integration_connections', where, {\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne<ConnectionRow>('integration_connections', {\n ...where,\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n update: async (orgId, fn) => {\n const row = await db().updateAtomic<ConnectionRow>(\n 'integration_connections',\n { ...scoped, org_id: orgId },\n async current => {\n const data = (await this.encryption.decrypt<TConnection>(current.data)).value;\n return { data: await this.encryption.encrypt(fn(data)), updated_at: new Date() };\n },\n );\n return row ? mapConnection(row) : null;\n },\n delete: async orgId => {\n const deleted = await db().deleteMany('integration_connections', { ...scoped, org_id: orgId });\n return deleted > 0;\n },\n },\n subscriptions: {\n create: async input => {\n const now = new Date();\n const row = await db().insertOne<SubscriptionRow>('integration_subscriptions', {\n ...scoped,\n org_id: input.orgId,\n target_key: input.targetKey,\n session_id: input.sessionId ?? null,\n resource_id: input.resourceId ?? null,\n thread_id: input.threadId ?? null,\n session_scope: input.sessionScope ?? null,\n status: input.status ?? 'active',\n data: input.data ?? {},\n created_at: now,\n updated_at: now,\n });\n return mapSubscription(row);\n },\n listByTarget: async (targetKey, opts) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, target_key: targetKey, ...(opts?.status !== undefined ? { status: opts.status } : {}) },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listBySession: async sessionId => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, session_id: sessionId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listByThread: async (resourceId, threadId) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, resource_id: resourceId, thread_id: threadId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n updateStatus: async (id, status) => {\n await db().updateMany('integration_subscriptions', { ...scoped, id }, { status, updated_at: new Date() });\n },\n delete: async id => {\n const deleted = await db().deleteMany('integration_subscriptions', { ...scoped, id });\n return deleted > 0;\n },\n deleteWhere: async where => {\n return db().deleteMany('integration_subscriptions', {\n ...scoped,\n org_id: where.orgId,\n ...(where.targetKey !== undefined ? { target_key: where.targetKey } : {}),\n ...(where.sessionId !== undefined ? { session_id: where.sessionId } : {}),\n });\n },\n },\n settings: {\n get: async (orgId, userId) => {\n const row = await db().findOne<{ config: unknown }>('integration_settings', {\n ...scoped,\n org_id: orgId,\n user_id: userId,\n });\n return row ? (await this.encryption.decrypt<TSettings>(row.config)).value : null;\n },\n save: async (orgId, userId, config) => {\n const where = { ...scoped, org_id: orgId, user_id: userId };\n const encrypted = await this.encryption.encrypt(config);\n const update = async () =>\n db().updateMany('integration_settings', where, {\n config: encrypted,\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne('integration_settings', {\n ...where,\n config: encrypted,\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,iCAAmD;CAC9D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,SAAS;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxC,MAAM,EAAE,MAAM,OAAO;EACrB,UAAU,EAAE,MAAM,OAAO;EACzB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAkD,SAAS,CAAC,kBAAkB,QAAQ;CAAE,CAAC;AACnH;AAEA,MAAa,mCAAqD;CAChE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC3C,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,eAAe;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC9C,QAAQ,EAAE,MAAM,OAAO;EACvB,MAAM,EAAE,MAAM,OAAO;EACrB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,SAAS,CACP;EAAE,MAAM;EAAwC,SAAS,CAAC,kBAAkB,YAAY;CAAE,GAC1F;EAAE,MAAM;EAAqC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c,KAAA,IAAY,EAAE,YAAY,MAAM,UAAU,IAAI,CAAC;KACzE,CAAC;IACH;GACF;GACA,UAAU;IACR,KAAK,OAAO,OAAO,WAAW;KAC5B,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,QAA6B,wBAAwB;MAC1E,GAAG;MACH,QAAQ;MACR,SAAS;KACX,CAAC;KACD,OAAO,OAAO,MAAM,KAAK,WAAW,QAAmB,IAAI,MAAM,EAAA,CAAG,QAAQ;IAC9E;IACA,MAAM,OAAO,OAAO,QAAQ,WAAW;KACrC,MAAM,QAAQ;MAAE,GAAG;MAAQ,QAAQ;MAAO,SAAS;KAAO;KAC1D,MAAM,YAAY,MAAM,KAAK,WAAW,QAAQ,MAAM;KACtD,MAAM,SAAS,YACb,GAAG,CAAC,CAAC,WAAW,wBAAwB,OAAO;MAC7C,QAAQ;MACR,4BAAY,IAAI,KAAK;KACvB,CAAC;KAEH,IAAI;KACJ,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW;MAC5C,IAAK,MAAM,OAAO,IAAK,GAAG;MAE1B,MAAM,sBAAM,IAAI,KAAK;MACrB,IAAI;OACF,MAAM,GAAG,CAAC,CAAC,UAAU,wBAAwB;QAC3C,GAAG;QACH,QAAQ;QACR,YAAY;QACZ,YAAY;OACd,CAAC;OACD;MACF,SAAS,OAAO;OACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;OACpD,YAAY;MACd;KACF;KACA,MAAM;IACR;GACF;EACF;CACF;AACF"}
@@ -64,25 +64,10 @@ export interface ProjectRepository {
64
64
  sandboxProvider: string;
65
65
  sandboxWorkdir: string;
66
66
  setupCommand: string | null;
67
- /** Base checkpoint metadata — set by the base-checkpoint build job. */
68
- baseCheckpoint: ProjectRepositoryBaseCheckpoint | null;
69
67
  teardownCommand: string | null;
70
68
  createdAt: Date;
71
69
  updatedAt: Date;
72
70
  }
73
- /**
74
- * Metadata for a repo's warm base checkpoint (cloned default branch + setup
75
- * command already run). New sessions boot from it instead of a cold clone.
76
- */
77
- export interface ProjectRepositoryBaseCheckpoint {
78
- /** Provider checkpoint name, e.g. `repo-<projectRepositoryId>`. */
79
- name: string;
80
- /** Default-branch HEAD sha the checkpoint was built at. */
81
- sha: string;
82
- builtAt: Date;
83
- /** Hash of the setup command at build time (null when no setup command) — mismatch invalidates the checkpoint. */
84
- setupCommandHash: string | null;
85
- }
86
71
  export interface ExternalRepositoryProjectTarget {
87
72
  orgId: string;
88
73
  factoryProjectId: string;
@@ -111,56 +96,6 @@ export interface UpdateProjectRepositoryInput {
111
96
  setupCommand?: string | null;
112
97
  teardownCommand?: string | null;
113
98
  }
114
- export interface ProjectRepositorySandbox {
115
- id: string;
116
- projectRepositoryId: string;
117
- userId: string;
118
- sandboxId: string | null;
119
- sandboxWorkdir: string;
120
- materializedAt: Date | null;
121
- createdAt: Date;
122
- }
123
- /**
124
- * A provider sandbox that is no longer bound to any session and can be handed
125
- * to the next session for the same project-repository link instead of
126
- * provisioning a fresh VM. Pooling is per-repository, not per-user: no
127
- * credentials are baked into the VM (tokens are injected per command), so any
128
- * user's session can safely claim it. `userId` records who released it,
129
- * purely as provenance.
130
- */
131
- export interface PooledSandbox {
132
- id: string;
133
- orgId: string;
134
- projectRepositoryId: string;
135
- /** User whose session released this sandbox (provenance, not a claim key). */
136
- userId: string;
137
- sandboxId: string;
138
- sandboxWorkdir: string;
139
- releasedAt: Date;
140
- }
141
- export interface ReleasePooledSandboxInput {
142
- orgId: string;
143
- projectRepositoryId: string;
144
- userId: string;
145
- sandboxId: string;
146
- sandboxWorkdir: string;
147
- }
148
- export interface SourceControlWorktree {
149
- id: string;
150
- projectRepositoryId: string;
151
- userId: string;
152
- branch: string;
153
- baseBranch: string;
154
- worktreePath: string;
155
- createdAt: Date;
156
- }
157
- export interface UpsertSourceControlWorktreeInput {
158
- projectRepositoryId: string;
159
- userId: string;
160
- branch: string;
161
- baseBranch: string;
162
- worktreePath: string;
163
- }
164
99
  /**
165
100
  * Who can open a session: 'org' sessions are visible to every member of the
166
101
  * owning organization, 'private' sessions only to their owner. Stored at
@@ -291,90 +226,11 @@ export interface SourceControlStorageHandle {
291
226
  id: string;
292
227
  input: UpdateProjectRepositoryInput;
293
228
  }): Promise<ProjectRepository | null>;
294
- /**
295
- * Record (or clear, with `checkpoint: null`) the repo's base-checkpoint
296
- * metadata after a build job snapshots the prepared workdir. Writes from a
297
- * build are ignored when the setup command changed while it was running.
298
- */
299
- setBaseCheckpoint(args: {
300
- id: string;
301
- checkpoint: null;
302
- } | {
303
- id: string;
304
- checkpoint: ProjectRepositoryBaseCheckpoint;
305
- expectedSetupCommand: string | null;
306
- }): Promise<void>;
307
229
  unlink(args: {
308
230
  orgId: string;
309
231
  id: string;
310
232
  }): Promise<boolean>;
311
233
  };
312
- readonly sandboxes: {
313
- getOrCreate(args: {
314
- projectRepository: ProjectRepository;
315
- userId: string;
316
- }): Promise<ProjectRepositorySandbox>;
317
- getById(args: {
318
- id: string;
319
- }): Promise<ProjectRepositorySandbox | null>;
320
- /**
321
- * Point the binding at a new workdir and clear `materializedAt` — a moved
322
- * workdir means the checkout must be re-cloned. Used to heal bindings whose
323
- * inherited workdir went stale (e.g. the sandbox provider changed).
324
- */
325
- setWorkdir(args: {
326
- id: string;
327
- sandboxWorkdir: string;
328
- }): Promise<void>;
329
- setSandboxId(args: {
330
- id: string;
331
- sandboxId: string;
332
- }): Promise<void>;
333
- clearBinding(args: {
334
- id: string;
335
- }): Promise<void>;
336
- markMaterialized(args: {
337
- id: string;
338
- }): Promise<void>;
339
- };
340
- readonly sandboxPool: {
341
- /**
342
- * Return a sandbox to the reuse pool. Idempotent per provider sandbox ID —
343
- * releasing the same sandbox twice keeps one pool row.
344
- */
345
- release(args: ReleasePooledSandboxInput): Promise<void>;
346
- /**
347
- * Atomically take one pooled sandbox for the given project-repository
348
- * link, preferring the most recently released (warmest) VM. Returns
349
- * `null` when the pool is empty. Each pooled sandbox is handed to exactly
350
- * one claimer even under concurrent claims.
351
- */
352
- claim(args: {
353
- projectRepositoryId: string;
354
- }): Promise<PooledSandbox | null>;
355
- };
356
- readonly worktrees: {
357
- upsert(args: UpsertSourceControlWorktreeInput): Promise<void>;
358
- list(args: {
359
- projectRepositoryId: string;
360
- userId: string;
361
- }): Promise<SourceControlWorktree[]>;
362
- get(args: {
363
- projectRepositoryId: string;
364
- userId: string;
365
- branch: string;
366
- }): Promise<SourceControlWorktree | null>;
367
- findByPath(args: {
368
- projectRepositoryId: string;
369
- userId: string;
370
- worktreePath: string;
371
- }): Promise<SourceControlWorktree | null>;
372
- delete(args: {
373
- projectRepositoryId: string;
374
- userId: string;
375
- branch: string;
376
- }): Promise<void>;
377
- };
378
234
  readonly sessions: {
379
235
  /**
380
236
  * Viewer-aware listing: every org-visible session for the repository