@mastra/factory 0.18.0 → 0.18.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  2. package/dist/integrations/github/default-rules.js +3 -3
  3. package/dist/integrations/github/default-rules.js.map +1 -1
  4. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  5. package/dist/integrations/github/reconcile-worker.js +1 -2
  6. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  7. package/dist/integrations/github/routes.d.ts.map +1 -1
  8. package/dist/integrations/github/routes.js +1 -14
  9. package/dist/integrations/github/routes.js.map +1 -1
  10. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  11. package/dist/integrations/gitlab/version-control.js +4 -5
  12. package/dist/integrations/gitlab/version-control.js.map +1 -1
  13. package/dist/integrations/gitlab/webhook.d.ts.map +1 -1
  14. package/dist/integrations/gitlab/webhook.js +2 -2
  15. package/dist/integrations/gitlab/webhook.js.map +1 -1
  16. package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
  17. package/dist/integrations/issue-reconcile-worker.js +1 -2
  18. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  19. package/dist/integrations/linear/integration.d.ts.map +1 -1
  20. package/dist/integrations/linear/integration.js +10 -30
  21. package/dist/integrations/linear/integration.js.map +1 -1
  22. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  23. package/dist/integrations/platform/github/event-worker.js +1 -2
  24. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  25. package/dist/integrations/platform/gitlab/event-worker.d.ts.map +1 -1
  26. package/dist/integrations/platform/gitlab/event-worker.js +1 -2
  27. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  28. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  29. package/dist/integrations/platform/linear/event-worker.js +1 -2
  30. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  31. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  32. package/dist/integrations/platform/linear/integration.js +9 -9
  33. package/dist/integrations/platform/linear/integration.js.map +1 -1
  34. package/dist/integrations/slack/slack.d.ts.map +1 -1
  35. package/dist/integrations/slack/slack.js +1 -2
  36. package/dist/integrations/slack/slack.js.map +1 -1
  37. package/dist/review-verdict.d.ts +6 -0
  38. package/dist/review-verdict.d.ts.map +1 -0
  39. package/dist/review-verdict.js +14 -0
  40. package/dist/review-verdict.js.map +1 -0
  41. package/dist/routes/oauth.d.ts.map +1 -1
  42. package/dist/routes/oauth.js +3 -3
  43. package/dist/routes/oauth.js.map +1 -1
  44. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  45. package/dist/routes/source-control-sessions.js +1 -2
  46. package/dist/routes/source-control-sessions.js.map +1 -1
  47. package/dist/rules/dispatcher.d.ts.map +1 -1
  48. package/dist/rules/dispatcher.js +1 -2
  49. package/dist/rules/dispatcher.js.map +1 -1
  50. package/dist/rules/processor.d.ts.map +1 -1
  51. package/dist/rules/processor.js +5 -5
  52. package/dist/rules/processor.js.map +1 -1
  53. package/dist/rules/transition-service.d.ts.map +1 -1
  54. package/dist/rules/transition-service.js +1 -2
  55. package/dist/rules/transition-service.js.map +1 -1
  56. package/dist/secret-encryption.js +2 -2
  57. package/dist/secret-encryption.js.map +1 -1
  58. package/dist/session/factory-session.d.ts.map +1 -1
  59. package/dist/session/factory-session.js +1 -2
  60. package/dist/session/factory-session.js.map +1 -1
  61. package/dist/session/source-control-tools.d.ts +9 -0
  62. package/dist/session/source-control-tools.d.ts.map +1 -1
  63. package/dist/session/source-control-tools.js +51 -2
  64. package/dist/session/source-control-tools.js.map +1 -1
  65. package/dist/state-signing.js +3 -3
  66. package/dist/state-signing.js.map +1 -1
  67. package/dist/storage/domains/audit/base.d.ts.map +1 -1
  68. package/dist/storage/domains/audit/base.js +2 -3
  69. package/dist/storage/domains/audit/base.js.map +1 -1
  70. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  71. package/dist/storage/domains/source-control/inmemory.js +5 -6
  72. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  73. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  74. package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
  75. package/factory-skills/factory-rereview/SKILL.md +12 -3
  76. package/factory-skills/factory-review/SKILL.md +12 -3
  77. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"source-control-tools.d.ts","sourceRoot":"","sources":["../../src/session/source-control-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAIhE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,KAAK,EAIV,0BAA0B,EAC3B,MAAM,2CAA2C,CAAC;AAQnD,MAAM,WAAW,yBAAyB;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,0BAA0B,CAAC;IACpC,cAAc,EAAE,cAAc,CAAC;CAChC;AAiGD,wBAAgB,wBAAwB,CAAC,EACvC,cAAc,EACd,SAAS,EACT,KAAK,GACN,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,SAAS,EAAE,SAAS,yBAAyB,EAAE,CAAC;IAChD,KAAK,EAAE,iBAAiB,CAAC;CAC1B,GAAG,gBAAgB,CA4YnB"}
1
+ {"version":3,"file":"source-control-tools.d.ts","sourceRoot":"","sources":["../../src/session/source-control-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAKhE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,KAAK,EAIV,0BAA0B,EAC3B,MAAM,2CAA2C,CAAC;AAQnD,MAAM,WAAW,yBAAyB;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,0BAA0B,CAAC;IACpC,cAAc,EAAE,cAAc,CAAC;CAChC;AAYD,KAAK,WAAW,GAAG,SAAS,GAAG,iBAAiB,GAAG,SAAS,CAAC;AAE7D,kGAAkG;AAClG,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAUrG;AAKD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CASxF;AAuFD,wBAAgB,wBAAwB,CAAC,EACvC,cAAc,EACd,SAAS,EACT,KAAK,GACN,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,SAAS,EAAE,SAAS,yBAAyB,EAAE,CAAC;IAChD,KAAK,EAAE,iBAAiB,CAAC;CAC1B,GAAG,gBAAgB,CAibnB"}
@@ -1,10 +1,32 @@
1
1
  import { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from "../auth.js";
2
2
  import { mergeRequestNumberFromBranch } from "../work-item-branch.js";
3
+ import { normalizedVerdictLine } from "../review-verdict.js";
3
4
  import { resolveSessionWorkdir } from "../sandbox/session-sandbox.js";
4
5
  import { pushRepositoryBranch, refreshMergeRequestCheckout } from "../integrations/github/sandbox.js";
5
6
  import { createTool } from "@mastra/core/tools";
6
7
  import { z } from "zod";
7
8
  //#region src/session/source-control-tools.ts
9
+ /** Returns why a review's leading `Verdict:` line contradicts the submitted event, if it does. */
10
+ function verdictEventMismatch(event, body) {
11
+ const match = /^verdict: ?(approve|request changes|changes requested)\b/.exec(normalizedVerdictLine(body) ?? "");
12
+ if (!match) return void 0;
13
+ const verdict = match[1] === "approve" ? "approve" : "request changes";
14
+ const allowed = verdict === "approve" ? ["approve"] : ["request-changes", "comment"];
15
+ if (allowed.includes(event)) return void 0;
16
+ return `Review body opens with "Verdict: ${verdict}" but event is "${event}". Nothing was posted. Use event ${allowed.map((e) => `"${e}"`).join(" or ")} for this body, or regenerate the body for the verdict you intend.`;
17
+ }
18
+ const REVIEWED_HEAD_LINE = /^[\s*_>-]*reviewed head[*_]*:[*_]*\s*(.*)$/gim;
19
+ const FULL_SHA = /^`?([0-9a-f]{40}|[0-9a-f]{64})`?(?:\s|$)/i;
20
+ /**
21
+ * Returns the full SHA named by the body's `Reviewed head:` lines, `null` when any line is malformed or the lines
22
+ * disagree, or `undefined` when absent.
23
+ */
24
+ function reviewedHeadFromBody(body) {
25
+ const shas = new Set([...(body ?? "").matchAll(REVIEWED_HEAD_LINE)].map((line) => FULL_SHA.exec(line[1].trim())?.[1]?.toLowerCase() ?? null));
26
+ if (shas.size === 0) return void 0;
27
+ if (shas.size > 1) return null;
28
+ return [...shas][0];
29
+ }
8
30
  function authIdentity(requestContext) {
9
31
  const user = getFactoryAuthUserFromContext(requestContext);
10
32
  return {
@@ -404,13 +426,40 @@ function createSourceControlTools({ requestContext, providers, audit }) {
404
426
  }).refine((input) => input.event === "approve" || Boolean(input.body?.trim()), {
405
427
  path: ["body"],
406
428
  message: "request-changes and comment reviews require a body."
429
+ }).superRefine((input, ctx) => {
430
+ const mismatch = verdictEventMismatch(input.event, input.body);
431
+ if (mismatch) ctx.addIssue({
432
+ code: "custom",
433
+ path: ["body"],
434
+ message: mismatch
435
+ });
436
+ const reviewedHead = reviewedHeadFromBody(input.body);
437
+ if (reviewedHead === null) ctx.addIssue({
438
+ code: "custom",
439
+ path: ["body"],
440
+ message: "Every \"Reviewed head:\" line must name the same full 40- or 64-character commit SHA."
441
+ });
442
+ else if (reviewedHead && input.commitId && input.commitId.toLowerCase() !== reviewedHead) ctx.addIssue({
443
+ code: "custom",
444
+ path: ["commitId"],
445
+ message: `Review body says "Reviewed head: ${reviewedHead}" but commitId is ${input.commitId}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`
446
+ });
407
447
  }),
408
448
  execute: async (input) => {
409
449
  const target = await withTarget();
450
+ const reviewedHead = reviewedHeadFromBody(input.body);
451
+ if (reviewedHead) {
452
+ const pullRequest = await target.provider.versionControl.getPullRequest({
453
+ ...await reference(target),
454
+ pullRequestId: changeRequestId(input.changeRequestId)
455
+ });
456
+ if (!pullRequest) throw new Error(`Change request ${input.changeRequestId} was not found; nothing was posted.`);
457
+ if (pullRequest.headSha && pullRequest.headSha.toLowerCase() !== reviewedHead) throw new Error(`Review body says "Reviewed head: ${reviewedHead}" but the current change-request head is ${pullRequest.headSha}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`);
458
+ }
410
459
  const base = {
411
460
  ...await reference(target),
412
461
  pullRequestId: changeRequestId(input.changeRequestId),
413
- ...input.commitId !== void 0 ? { commitId: input.commitId } : {}
462
+ ...input.commitId !== void 0 ? { commitId: input.commitId } : reviewedHead ? { commitId: reviewedHead } : {}
414
463
  };
415
464
  if (input.event === "approve") return target.provider.versionControl.createReview({
416
465
  ...base,
@@ -467,6 +516,6 @@ function createSourceControlTools({ requestContext, providers, audit }) {
467
516
  };
468
517
  }
469
518
  //#endregion
470
- export { createSourceControlTools };
519
+ export { createSourceControlTools, reviewedHeadFromBody, verdictEventMismatch };
471
520
 
472
521
  //# sourceMappingURL=source-control-tools.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"source-control-tools.js","names":[],"sources":["../../src/session/source-control-tools.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { z } from 'zod';\n\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../auth.js';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { pushRepositoryBranch, refreshMergeRequestCheckout } from '../integrations/github/sandbox.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { resolveSessionWorkdir } from '../sandbox/session-sandbox.js';\nimport type { AuditAgentEmitter } from '../storage/domains/audit/domain.js';\nimport type {\n ProjectRepository,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { mergeRequestNumberFromBranch } from '../work-item-branch.js';\n\ntype RepositorySessionState = {\n factoryProjectId?: string;\n projectRepositoryId?: string;\n};\n\nexport interface SourceControlToolProvider {\n id: string;\n storage: SourceControlStorageHandle;\n versionControl: VersionControl;\n}\n\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n provider: SourceControlToolProvider;\n session: SourceControlSession;\n projectRepository: ProjectRepository;\n repository: SourceControlRepository;\n orgId: string;\n userId: string;\n}\n\nfunction authIdentity(requestContext: RequestContext) {\n const user = getFactoryAuthUserFromContext(requestContext);\n return { orgId: getFactoryAuthOrgId(user), userId: getFactoryAuthUserId(user) };\n}\n\nasync function resolveSessionTarget(\n requestContext: RequestContext,\n providers: readonly SourceControlToolProvider[],\n): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const { orgId, userId } = authIdentity(requestContext);\n if (!context?.resourceId || !orgId || !userId) {\n throw new Error('Source-control tools require an authenticated repository session.');\n }\n\n const matches = (\n await Promise.all(\n providers.map(async provider => ({\n provider,\n session: await provider.storage.sessions.getBySessionId(context.resourceId),\n })),\n )\n ).filter(\n (match): match is { provider: SourceControlToolProvider; session: SourceControlSession } => match.session !== null,\n );\n if (matches.length !== 1) {\n throw new Error(\n matches.length === 0\n ? 'The active session is not backed by a source-control repository.'\n : 'The active session is ambiguous across source-control providers.',\n );\n }\n\n const { provider, session } = matches[0]!;\n if (session.orgId !== orgId || (session.visibility === 'private' && session.userId !== userId)) {\n throw new Error('The active source-control session is not available to the authenticated user.');\n }\n const projectRepository = await provider.storage.projectRepositories.get({\n orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error('The active project repository was not found.');\n const state = context.getState();\n if (state.projectRepositoryId && state.projectRepositoryId !== projectRepository.id) {\n throw new Error('The active source-control session does not match its controller repository.');\n }\n const connection = await provider.storage.connections.get({ orgId, id: projectRepository.connectionId });\n if (!connection) throw new Error('The active source-control connection was not found.');\n if (state.factoryProjectId && state.factoryProjectId !== connection.factoryProjectId) {\n throw new Error('The active source-control session does not match its Factory project.');\n }\n const repository = await provider.storage.repositories.get({ orgId, id: projectRepository.repositoryId });\n if (!repository) throw new Error('The active source-control repository was not found.');\n return { context, provider, session, projectRepository, repository, orgId, userId };\n}\n\nfunction changeRequestId(value: string | number): string {\n return String(value);\n}\n\nfunction executableSandbox(value: unknown): WorkspaceSandbox & ExecutableSandbox {\n const sandbox = value as Partial<ExecutableSandbox> | undefined;\n if (!sandbox?.executeCommand) throw new Error('The active Factory workspace has no executable sandbox.');\n return sandbox as WorkspaceSandbox & ExecutableSandbox;\n}\n\nasync function emitAgentAudit(\n audit: AuditAgentEmitter,\n requestContext: RequestContext,\n input: Parameters<AuditAgentEmitter['emitAgent']>[0]['input'],\n): Promise<void> {\n try {\n await audit.emitAgent({ requestContext, input });\n } catch (error) {\n console.warn('[Audit] Failed to record brokered source-control action', {\n action: input.action,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nconst changeRequestSchema = z.object({\n changeRequestId: z.union([z.string().trim().min(1), z.number().int().positive()]),\n});\n\nexport function createSourceControlTools({\n requestContext,\n providers,\n audit,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n audit: AuditAgentEmitter;\n}): IntegrationTools {\n if (!requestContext || typeof (requestContext as { get?: unknown }).get !== 'function') return {};\n const controller = requestContext.get('controller') as\n | AgentControllerRequestContext<RepositorySessionState>\n | undefined;\n const identity = authIdentity(requestContext);\n if (!controller?.resourceId || !identity.orgId || !identity.userId || providers.length === 0) return {};\n\n const withTarget = () => resolveSessionTarget(requestContext, providers);\n const reference = async (target: SessionTarget) => ({\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n });\n\n return {\n source_control_refresh_change_request_checkout: createTool({\n id: 'source_control_refresh_change_request_checkout',\n description:\n 'Refresh the active GitLab review session checkout to its current MR head. The MR, repository, branch, and credential are resolved server-side; no provider credentials enter the agent workspace.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const mergeRequestNumber = mergeRequestNumberFromBranch(target.session.branch);\n if (target.provider.id !== 'gitlab' || mergeRequestNumber === undefined) {\n throw new Error('Checkout refresh is only available in a bound GitLab merge-request review session.');\n }\n const ref = await reference(target);\n const mergeRequest = await target.provider.versionControl.getPullRequest({\n ...ref,\n pullRequestId: String(mergeRequestNumber),\n });\n if (!mergeRequest || mergeRequest.state !== 'open' || mergeRequest.merged) {\n throw new Error('The bound GitLab merge request is no longer open.');\n }\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n const result = await refreshMergeRequestCheckout(sandbox, workdir, {\n branch: target.session.branch,\n mergeRequestNumber,\n expectedHeadSha: mergeRequest.headSha,\n access,\n });\n return result;\n },\n }),\n source_control_push_branch: createTool({\n id: 'source_control_push_branch',\n description:\n 'Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, repository, remote, or branch arguments.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n await pushRepositoryBranch(sandbox, workdir, target.session.branch, access, target.repository.slug);\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.push',\n targets: [{ type: 'repository', id: target.repository.slug }],\n metadata: { branch: target.session.branch, provider: target.provider.id },\n });\n return { pushed: true, branch: target.session.branch, repository: target.repository.slug };\n },\n }),\n source_control_get_change_request: createTool({\n id: 'source_control_get_change_request',\n description:\n 'Read a pull request or merge request in the active Factory repository by its numeric repository-local ID.',\n inputSchema: changeRequestSchema,\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n },\n }),\n source_control_list_change_request_reviews: createTool({\n id: 'source_control_list_change_request_reviews',\n description: 'List submitted reviews and approvals on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listReviews({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_change_request: createTool({\n id: 'source_control_create_change_request',\n description:\n 'Open a pull request or merge request from the active Factory session branch into its persisted base branch. Push the branch with source_control_push_branch first.',\n inputSchema: z.object({\n title: z.string().trim().min(1),\n body: z.string().optional(),\n draft: z.boolean().optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n const created = await target.provider.versionControl.createPullRequest({\n ...(await reference(target)),\n title: input.title,\n ...(input.body !== undefined ? { body: input.body } : {}),\n baseBranch: target.session.baseBranch,\n headBranch: target.session.branch,\n ...(input.draft !== undefined ? { draft: input.draft } : {}),\n });\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.pr_opened',\n targets: [\n { type: 'pull_request', id: created.url },\n { type: 'repository', id: target.repository.slug },\n ],\n metadata: { url: created.url, provider: target.provider.id },\n });\n return created;\n },\n }),\n source_control_update_change_request: createTool({\n id: 'source_control_update_change_request',\n description: 'Update the title, body, target branch, or open/closed state of a change request.',\n inputSchema: changeRequestSchema.extend({\n title: z.string().trim().min(1).optional(),\n body: z.string().nullable().optional(),\n baseBranch: z.string().trim().min(1).optional(),\n state: z.enum(['open', 'closed']).optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updatePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.baseBranch !== undefined ? { baseBranch: input.baseBranch } : {}),\n ...(input.state !== undefined ? { state: input.state } : {}),\n });\n },\n }),\n source_control_comment_change_request: createTool({\n id: 'source_control_comment_change_request',\n description: 'Add a top-level comment to a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.createComment({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n });\n },\n }),\n source_control_list_change_request_comments: createTool({\n id: 'source_control_list_change_request_comments',\n description: 'List top-level comments on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_update_change_request_comment: createTool({\n id: 'source_control_update_change_request_comment',\n description: 'Edit a top-level pull-request or merge-request comment in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updateComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_change_request_comment: createTool({\n id: 'source_control_delete_change_request_comment',\n description: 'Delete a top-level pull-request or merge-request comment in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n await target.provider.versionControl.deleteComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_list_diff_comments: createTool({\n id: 'source_control_list_diff_comments',\n description:\n 'List line-anchored review comments and discussion replies on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listReviewComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_diff_comment: createTool({\n id: 'source_control_create_diff_comment',\n description:\n 'Create a line-anchored review comment or reply to an existing diff discussion. Use replyToId alone for a reply; otherwise provide commitId, path, line, and side.',\n // A root-level union is not representable as provider function parameters, which must be\n // an object schema, so both modes share one object shape and a refinement.\n inputSchema: changeRequestSchema\n .extend({\n body: z.string().trim().min(1),\n replyToId: z.string().trim().min(1).optional(),\n commitId: z.string().trim().min(1).optional(),\n path: z.string().trim().min(1).optional(),\n line: z.number().int().positive().optional(),\n side: z.enum(['left', 'right']).optional(),\n startLine: z.number().int().positive().optional(),\n startSide: z.enum(['left', 'right']).optional(),\n })\n .refine(\n input => {\n const anchorFields = [input.commitId, input.path, input.line, input.side];\n const anchor = anchorFields.every(field => field !== undefined);\n const reply = input.replyToId !== undefined;\n return (\n (reply ? anchorFields.every(field => field === undefined) : anchor) &&\n (input.startLine === undefined) === (input.startSide === undefined)\n );\n },\n {\n message:\n 'Provide replyToId alone to reply to a diff thread, or commitId, path, line, and side to start one. startLine and startSide must be provided together.',\n },\n ),\n execute: async input => {\n const target = await withTarget();\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n };\n if (input.replyToId !== undefined) {\n return target.provider.versionControl.createReviewComment({ ...base, replyToId: input.replyToId });\n }\n if (\n input.commitId === undefined ||\n input.path === undefined ||\n input.line === undefined ||\n input.side === undefined\n ) {\n throw new Error('commitId, path, line, and side are required to start a new diff thread.');\n }\n return target.provider.versionControl.createReviewComment({\n ...base,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side,\n ...(input.startLine !== undefined && input.startSide !== undefined\n ? { startLine: input.startLine, startSide: input.startSide }\n : {}),\n });\n },\n }),\n source_control_update_diff_comment: createTool({\n id: 'source_control_update_diff_comment',\n description: 'Edit a line-anchored review comment or discussion reply in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updateReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_diff_comment: createTool({\n id: 'source_control_delete_diff_comment',\n description: 'Delete a line-anchored review comment or discussion reply in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n await target.provider.versionControl.deleteReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_resolve_diff_thread: createTool({\n id: 'source_control_resolve_diff_thread',\n description:\n 'Resolve or reopen the review thread containing a diff comment. Providers without resolvable threads return an explicit limitation.',\n inputSchema: z.object({\n commentId: z.string().trim().min(1),\n resolved: z.boolean().default(true),\n }),\n execute: async input => {\n const target = await withTarget();\n const resolveReviewThread = target.provider.versionControl.resolveReviewThread;\n if (!resolveReviewThread) {\n throw new Error(`${target.provider.id} does not support resolving review threads.`);\n }\n await resolveReviewThread({\n ...(await reference(target)),\n commentId: input.commentId,\n resolved: input.resolved,\n });\n return { resolved: input.resolved };\n },\n }),\n source_control_review_change_request: createTool({\n id: 'source_control_review_change_request',\n description:\n 'Submit an approve, request-changes, or comment review to a change request. Provider limitations are returned explicitly.',\n inputSchema: changeRequestSchema\n .extend({\n event: z.enum(['approve', 'request-changes', 'comment']),\n body: z.string().optional(),\n commitId: z.string().trim().min(1).optional(),\n })\n .refine(input => input.event === 'approve' || Boolean(input.body?.trim()), {\n path: ['body'],\n message: 'request-changes and comment reviews require a body.',\n }),\n execute: async input => {\n const target = await withTarget();\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.commitId !== undefined ? { commitId: input.commitId } : {}),\n };\n if (input.event === 'approve') {\n return target.provider.versionControl.createReview({\n ...base,\n event: 'approve',\n ...(input.body !== undefined ? { body: input.body } : {}),\n });\n }\n return target.provider.versionControl.createReview({ ...base, event: input.event, body: input.body! });\n },\n }),\n source_control_request_reviewers: createTool({\n id: 'source_control_request_reviewers',\n description:\n 'Request individual or team reviewers on a pull request or merge request. Provider limitations are returned explicitly.',\n inputSchema: changeRequestSchema.extend({\n users: z.array(z.string().trim().min(1)).default([]),\n teams: z.array(z.string().trim().min(1)).default([]),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.requestReviewers({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n users: input.users,\n teams: input.teams,\n });\n },\n }),\n source_control_merge_change_request: createTool({\n id: 'source_control_merge_change_request',\n description: 'Merge a pull request or merge request using the requested provider-supported merge method.',\n inputSchema: changeRequestSchema.extend({\n method: z.enum(['merge', 'squash', 'rebase']).optional(),\n commitTitle: z.string().optional(),\n commitMessage: z.string().optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.mergePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.method !== undefined ? { method: input.method } : {}),\n ...(input.commitTitle !== undefined ? { commitTitle: input.commitTitle } : {}),\n ...(input.commitMessage !== undefined ? { commitMessage: input.commitMessage } : {}),\n });\n },\n }),\n };\n}\n"],"mappings":";;;;;;;AA0CA,SAAS,aAAa,gBAAgC;CACpD,MAAM,OAAO,8BAA8B,cAAc;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AM,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;GACrD,CAAC;GACD,SAAS,OAAM,UAAS;IACtB,MAAM,SAAS,MAAM,WAAW;IAChC,OAAO,OAAO,SAAS,eAAe,iBAAiB;KACrD,GAAI,MAAM,UAAU,MAAM;KAC1B,eAAe,gBAAgB,MAAM,eAAe;KACpD,OAAO,MAAM;KACb,OAAO,MAAM;IACf,CAAC;GACH;EACF,CAAC;EACD,qCAAqC,WAAW;GAC9C,IAAI;GACJ,aAAa;GACb,aAAa,oBAAoB,OAAO;IACtC,QAAQ,EAAE,KAAK;KAAC;KAAS;KAAU;IAAQ,CAAC,CAAC,CAAC,SAAS;IACvD,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;IACjC,eAAe,EAAE,OAAO,CAAC,CAAC,SAAS;GACrC,CAAC;GACD,SAAS,OAAM,UAAS;IACtB,MAAM,SAAS,MAAM,WAAW;IAChC,OAAO,OAAO,SAAS,eAAe,iBAAiB;KACrD,GAAI,MAAM,UAAU,MAAM;KAC1B,eAAe,gBAAgB,MAAM,eAAe;KACpD,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;KAC7D,GAAI,MAAM,gBAAgB,KAAA,IAAY,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;KAC5E,GAAI,MAAM,kBAAkB,KAAA,IAAY,EAAE,eAAe,MAAM,cAAc,IAAI,CAAC;IACpF,CAAC;GACH;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"source-control-tools.js","names":[],"sources":["../../src/session/source-control-tools.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { z } from 'zod';\n\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../auth.js';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { pushRepositoryBranch, refreshMergeRequestCheckout } from '../integrations/github/sandbox.js';\nimport { normalizedVerdictLine } from '../review-verdict.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { resolveSessionWorkdir } from '../sandbox/session-sandbox.js';\nimport type { AuditAgentEmitter } from '../storage/domains/audit/domain.js';\nimport type {\n ProjectRepository,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { mergeRequestNumberFromBranch } from '../work-item-branch.js';\n\ntype RepositorySessionState = {\n factoryProjectId?: string;\n projectRepositoryId?: string;\n};\n\nexport interface SourceControlToolProvider {\n id: string;\n storage: SourceControlStorageHandle;\n versionControl: VersionControl;\n}\n\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n provider: SourceControlToolProvider;\n session: SourceControlSession;\n projectRepository: ProjectRepository;\n repository: SourceControlRepository;\n orgId: string;\n userId: string;\n}\n\ntype ReviewEvent = 'approve' | 'request-changes' | 'comment';\n\n/** Returns why a review's leading `Verdict:` line contradicts the submitted event, if it does. */\nexport function verdictEventMismatch(event: ReviewEvent, body: string | undefined): string | undefined {\n const match = /^verdict: ?(approve|request changes|changes requested)\\b/.exec(normalizedVerdictLine(body) ?? '');\n if (!match) return undefined;\n const verdict = match[1] === 'approve' ? 'approve' : 'request changes';\n // GitLab has no request-changes state, so a blocking verdict is published as a comment review.\n const allowed: ReviewEvent[] = verdict === 'approve' ? ['approve'] : ['request-changes', 'comment'];\n if (allowed.includes(event)) return undefined;\n return `Review body opens with \"Verdict: ${verdict}\" but event is \"${event}\". Nothing was posted. Use event ${allowed\n .map(e => `\"${e}\"`)\n .join(' or ')} for this body, or regenerate the body for the verdict you intend.`;\n}\n\nconst REVIEWED_HEAD_LINE = /^[\\s*_>-]*reviewed head[*_]*:[*_]*\\s*(.*)$/gim;\nconst FULL_SHA = /^`?([0-9a-f]{40}|[0-9a-f]{64})`?(?:\\s|$)/i;\n\n/**\n * Returns the full SHA named by the body's `Reviewed head:` lines, `null` when any line is malformed or the lines\n * disagree, or `undefined` when absent.\n */\nexport function reviewedHeadFromBody(body: string | undefined): string | null | undefined {\n const shas = new Set(\n [...(body ?? '').matchAll(REVIEWED_HEAD_LINE)].map(\n line => FULL_SHA.exec(line[1]!.trim())?.[1]?.toLowerCase() ?? null,\n ),\n );\n if (shas.size === 0) return undefined;\n if (shas.size > 1) return null;\n return [...shas][0];\n}\n\nfunction authIdentity(requestContext: RequestContext) {\n const user = getFactoryAuthUserFromContext(requestContext);\n return { orgId: getFactoryAuthOrgId(user), userId: getFactoryAuthUserId(user) };\n}\n\nasync function resolveSessionTarget(\n requestContext: RequestContext,\n providers: readonly SourceControlToolProvider[],\n): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const { orgId, userId } = authIdentity(requestContext);\n if (!context?.resourceId || !orgId || !userId) {\n throw new Error('Source-control tools require an authenticated repository session.');\n }\n\n const matches = (\n await Promise.all(\n providers.map(async provider => ({\n provider,\n session: await provider.storage.sessions.getBySessionId(context.resourceId),\n })),\n )\n ).filter(\n (match): match is { provider: SourceControlToolProvider; session: SourceControlSession } => match.session !== null,\n );\n if (matches.length !== 1) {\n throw new Error(\n matches.length === 0\n ? 'The active session is not backed by a source-control repository.'\n : 'The active session is ambiguous across source-control providers.',\n );\n }\n\n const { provider, session } = matches[0]!;\n if (session.orgId !== orgId || (session.visibility === 'private' && session.userId !== userId)) {\n throw new Error('The active source-control session is not available to the authenticated user.');\n }\n const projectRepository = await provider.storage.projectRepositories.get({\n orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error('The active project repository was not found.');\n const state = context.getState();\n if (state.projectRepositoryId && state.projectRepositoryId !== projectRepository.id) {\n throw new Error('The active source-control session does not match its controller repository.');\n }\n const connection = await provider.storage.connections.get({ orgId, id: projectRepository.connectionId });\n if (!connection) throw new Error('The active source-control connection was not found.');\n if (state.factoryProjectId && state.factoryProjectId !== connection.factoryProjectId) {\n throw new Error('The active source-control session does not match its Factory project.');\n }\n const repository = await provider.storage.repositories.get({ orgId, id: projectRepository.repositoryId });\n if (!repository) throw new Error('The active source-control repository was not found.');\n return { context, provider, session, projectRepository, repository, orgId, userId };\n}\n\nfunction changeRequestId(value: string | number): string {\n return String(value);\n}\n\nfunction executableSandbox(value: unknown): WorkspaceSandbox & ExecutableSandbox {\n const sandbox = value as Partial<ExecutableSandbox> | undefined;\n if (!sandbox?.executeCommand) throw new Error('The active Factory workspace has no executable sandbox.');\n return sandbox as WorkspaceSandbox & ExecutableSandbox;\n}\n\nasync function emitAgentAudit(\n audit: AuditAgentEmitter,\n requestContext: RequestContext,\n input: Parameters<AuditAgentEmitter['emitAgent']>[0]['input'],\n): Promise<void> {\n try {\n await audit.emitAgent({ requestContext, input });\n } catch (error) {\n console.warn('[Audit] Failed to record brokered source-control action', {\n action: input.action,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nconst changeRequestSchema = z.object({\n changeRequestId: z.union([z.string().trim().min(1), z.number().int().positive()]),\n});\n\nexport function createSourceControlTools({\n requestContext,\n providers,\n audit,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n audit: AuditAgentEmitter;\n}): IntegrationTools {\n if (!requestContext || typeof (requestContext as { get?: unknown }).get !== 'function') return {};\n const controller = requestContext.get('controller') as\n | AgentControllerRequestContext<RepositorySessionState>\n | undefined;\n const identity = authIdentity(requestContext);\n if (!controller?.resourceId || !identity.orgId || !identity.userId || providers.length === 0) return {};\n\n const withTarget = () => resolveSessionTarget(requestContext, providers);\n const reference = async (target: SessionTarget) => ({\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n });\n\n return {\n source_control_refresh_change_request_checkout: createTool({\n id: 'source_control_refresh_change_request_checkout',\n description:\n 'Refresh the active GitLab review session checkout to its current MR head. The MR, repository, branch, and credential are resolved server-side; no provider credentials enter the agent workspace.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const mergeRequestNumber = mergeRequestNumberFromBranch(target.session.branch);\n if (target.provider.id !== 'gitlab' || mergeRequestNumber === undefined) {\n throw new Error('Checkout refresh is only available in a bound GitLab merge-request review session.');\n }\n const ref = await reference(target);\n const mergeRequest = await target.provider.versionControl.getPullRequest({\n ...ref,\n pullRequestId: String(mergeRequestNumber),\n });\n if (!mergeRequest || mergeRequest.state !== 'open' || mergeRequest.merged) {\n throw new Error('The bound GitLab merge request is no longer open.');\n }\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n const result = await refreshMergeRequestCheckout(sandbox, workdir, {\n branch: target.session.branch,\n mergeRequestNumber,\n expectedHeadSha: mergeRequest.headSha,\n access,\n });\n return result;\n },\n }),\n source_control_push_branch: createTool({\n id: 'source_control_push_branch',\n description:\n 'Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, repository, remote, or branch arguments.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n await pushRepositoryBranch(sandbox, workdir, target.session.branch, access, target.repository.slug);\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.push',\n targets: [{ type: 'repository', id: target.repository.slug }],\n metadata: { branch: target.session.branch, provider: target.provider.id },\n });\n return { pushed: true, branch: target.session.branch, repository: target.repository.slug };\n },\n }),\n source_control_get_change_request: createTool({\n id: 'source_control_get_change_request',\n description:\n 'Read a pull request or merge request in the active Factory repository by its numeric repository-local ID.',\n inputSchema: changeRequestSchema,\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n },\n }),\n source_control_list_change_request_reviews: createTool({\n id: 'source_control_list_change_request_reviews',\n description: 'List submitted reviews and approvals on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listReviews({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_change_request: createTool({\n id: 'source_control_create_change_request',\n description:\n 'Open a pull request or merge request from the active Factory session branch into its persisted base branch. Push the branch with source_control_push_branch first.',\n inputSchema: z.object({\n title: z.string().trim().min(1),\n body: z.string().optional(),\n draft: z.boolean().optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n const created = await target.provider.versionControl.createPullRequest({\n ...(await reference(target)),\n title: input.title,\n ...(input.body !== undefined ? { body: input.body } : {}),\n baseBranch: target.session.baseBranch,\n headBranch: target.session.branch,\n ...(input.draft !== undefined ? { draft: input.draft } : {}),\n });\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.pr_opened',\n targets: [\n { type: 'pull_request', id: created.url },\n { type: 'repository', id: target.repository.slug },\n ],\n metadata: { url: created.url, provider: target.provider.id },\n });\n return created;\n },\n }),\n source_control_update_change_request: createTool({\n id: 'source_control_update_change_request',\n description: 'Update the title, body, target branch, or open/closed state of a change request.',\n inputSchema: changeRequestSchema.extend({\n title: z.string().trim().min(1).optional(),\n body: z.string().nullable().optional(),\n baseBranch: z.string().trim().min(1).optional(),\n state: z.enum(['open', 'closed']).optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updatePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.baseBranch !== undefined ? { baseBranch: input.baseBranch } : {}),\n ...(input.state !== undefined ? { state: input.state } : {}),\n });\n },\n }),\n source_control_comment_change_request: createTool({\n id: 'source_control_comment_change_request',\n description: 'Add a top-level comment to a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.createComment({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n });\n },\n }),\n source_control_list_change_request_comments: createTool({\n id: 'source_control_list_change_request_comments',\n description: 'List top-level comments on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_update_change_request_comment: createTool({\n id: 'source_control_update_change_request_comment',\n description: 'Edit a top-level pull-request or merge-request comment in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updateComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_change_request_comment: createTool({\n id: 'source_control_delete_change_request_comment',\n description: 'Delete a top-level pull-request or merge-request comment in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n await target.provider.versionControl.deleteComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_list_diff_comments: createTool({\n id: 'source_control_list_diff_comments',\n description:\n 'List line-anchored review comments and discussion replies on a pull request or merge request in the active repository.',\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.listReviewComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_diff_comment: createTool({\n id: 'source_control_create_diff_comment',\n description:\n 'Create a line-anchored review comment or reply to an existing diff discussion. Use replyToId alone for a reply; otherwise provide commitId, path, line, and side.',\n // A root-level union is not representable as provider function parameters, which must be\n // an object schema, so both modes share one object shape and a refinement.\n inputSchema: changeRequestSchema\n .extend({\n body: z.string().trim().min(1),\n replyToId: z.string().trim().min(1).optional(),\n commitId: z.string().trim().min(1).optional(),\n path: z.string().trim().min(1).optional(),\n line: z.number().int().positive().optional(),\n side: z.enum(['left', 'right']).optional(),\n startLine: z.number().int().positive().optional(),\n startSide: z.enum(['left', 'right']).optional(),\n })\n .refine(\n input => {\n const anchorFields = [input.commitId, input.path, input.line, input.side];\n const anchor = anchorFields.every(field => field !== undefined);\n const reply = input.replyToId !== undefined;\n return (\n (reply ? anchorFields.every(field => field === undefined) : anchor) &&\n (input.startLine === undefined) === (input.startSide === undefined)\n );\n },\n {\n message:\n 'Provide replyToId alone to reply to a diff thread, or commitId, path, line, and side to start one. startLine and startSide must be provided together.',\n },\n ),\n execute: async input => {\n const target = await withTarget();\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n };\n if (input.replyToId !== undefined) {\n return target.provider.versionControl.createReviewComment({ ...base, replyToId: input.replyToId });\n }\n if (\n input.commitId === undefined ||\n input.path === undefined ||\n input.line === undefined ||\n input.side === undefined\n ) {\n throw new Error('commitId, path, line, and side are required to start a new diff thread.');\n }\n return target.provider.versionControl.createReviewComment({\n ...base,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side,\n ...(input.startLine !== undefined && input.startSide !== undefined\n ? { startLine: input.startLine, startSide: input.startSide }\n : {}),\n });\n },\n }),\n source_control_update_diff_comment: createTool({\n id: 'source_control_update_diff_comment',\n description: 'Edit a line-anchored review comment or discussion reply in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.updateReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_diff_comment: createTool({\n id: 'source_control_delete_diff_comment',\n description: 'Delete a line-anchored review comment or discussion reply in the active repository.',\n inputSchema: z.object({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await withTarget();\n await target.provider.versionControl.deleteReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_resolve_diff_thread: createTool({\n id: 'source_control_resolve_diff_thread',\n description:\n 'Resolve or reopen the review thread containing a diff comment. Providers without resolvable threads return an explicit limitation.',\n inputSchema: z.object({\n commentId: z.string().trim().min(1),\n resolved: z.boolean().default(true),\n }),\n execute: async input => {\n const target = await withTarget();\n const resolveReviewThread = target.provider.versionControl.resolveReviewThread;\n if (!resolveReviewThread) {\n throw new Error(`${target.provider.id} does not support resolving review threads.`);\n }\n await resolveReviewThread({\n ...(await reference(target)),\n commentId: input.commentId,\n resolved: input.resolved,\n });\n return { resolved: input.resolved };\n },\n }),\n source_control_review_change_request: createTool({\n id: 'source_control_review_change_request',\n description:\n 'Submit an approve, request-changes, or comment review to a change request. Provider limitations are returned explicitly.',\n inputSchema: changeRequestSchema\n .extend({\n event: z.enum(['approve', 'request-changes', 'comment']),\n body: z.string().optional(),\n commitId: z.string().trim().min(1).optional(),\n })\n .refine(input => input.event === 'approve' || Boolean(input.body?.trim()), {\n path: ['body'],\n message: 'request-changes and comment reviews require a body.',\n })\n .superRefine((input, ctx) => {\n const mismatch = verdictEventMismatch(input.event, input.body);\n if (mismatch) ctx.addIssue({ code: 'custom', path: ['body'], message: mismatch });\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead === null) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Every \"Reviewed head:\" line must name the same full 40- or 64-character commit SHA.',\n });\n } else if (reviewedHead && input.commitId && input.commitId.toLowerCase() !== reviewedHead) {\n ctx.addIssue({\n code: 'custom',\n path: ['commitId'],\n message: `Review body says \"Reviewed head: ${reviewedHead}\" but commitId is ${input.commitId}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n });\n }\n }),\n execute: async input => {\n const target = await withTarget();\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead) {\n const pullRequest = await target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n if (!pullRequest) {\n throw new Error(`Change request ${input.changeRequestId} was not found; nothing was posted.`);\n }\n if (pullRequest.headSha && pullRequest.headSha.toLowerCase() !== reviewedHead) {\n throw new Error(\n `Review body says \"Reviewed head: ${reviewedHead}\" but the current change-request head is ${pullRequest.headSha}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n );\n }\n }\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.commitId !== undefined\n ? { commitId: input.commitId }\n : reviewedHead\n ? { commitId: reviewedHead }\n : {}),\n };\n if (input.event === 'approve') {\n return target.provider.versionControl.createReview({\n ...base,\n event: 'approve',\n ...(input.body !== undefined ? { body: input.body } : {}),\n });\n }\n return target.provider.versionControl.createReview({ ...base, event: input.event, body: input.body! });\n },\n }),\n source_control_request_reviewers: createTool({\n id: 'source_control_request_reviewers',\n description:\n 'Request individual or team reviewers on a pull request or merge request. Provider limitations are returned explicitly.',\n inputSchema: changeRequestSchema.extend({\n users: z.array(z.string().trim().min(1)).default([]),\n teams: z.array(z.string().trim().min(1)).default([]),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.requestReviewers({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n users: input.users,\n teams: input.teams,\n });\n },\n }),\n source_control_merge_change_request: createTool({\n id: 'source_control_merge_change_request',\n description: 'Merge a pull request or merge request using the requested provider-supported merge method.',\n inputSchema: changeRequestSchema.extend({\n method: z.enum(['merge', 'squash', 'rebase']).optional(),\n commitTitle: z.string().optional(),\n commitMessage: z.string().optional(),\n }),\n execute: async input => {\n const target = await withTarget();\n return target.provider.versionControl.mergePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.method !== undefined ? { method: input.method } : {}),\n ...(input.commitTitle !== undefined ? { commitTitle: input.commitTitle } : {}),\n ...(input.commitMessage !== undefined ? { commitMessage: input.commitMessage } : {}),\n });\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;AA8CA,SAAgB,qBAAqB,OAAoB,MAA8C;CACrG,MAAM,QAAQ,2DAA2D,KAAK,sBAAsB,IAAI,KAAK,EAAE;CAC/G,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,OAAO,YAAY,YAAY;CAErD,MAAM,UAAyB,YAAY,YAAY,CAAC,SAAS,IAAI,CAAC,mBAAmB,SAAS;CAClG,IAAI,QAAQ,SAAS,KAAK,GAAG,OAAO,KAAA;CACpC,OAAO,oCAAoC,QAAQ,kBAAkB,MAAM,mCAAmC,QAC3G,KAAI,MAAK,IAAI,EAAE,EAAE,CAAC,CAClB,KAAK,MAAM,EAAE;AAClB;AAEA,MAAM,qBAAqB;AAC3B,MAAM,WAAW;;;;;AAMjB,SAAgB,qBAAqB,MAAqD;CACxF,MAAM,OAAO,IAAI,IACf,CAAC,IAAI,QAAQ,GAAA,CAAI,SAAS,kBAAkB,CAAC,CAAC,CAAC,KAC7C,SAAQ,SAAS,KAAK,KAAK,EAAE,CAAE,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,YAAY,KAAK,IAChE,CACF;CACA,IAAI,KAAK,SAAS,GAAG,OAAO,KAAA;CAC5B,IAA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AI,MAAM,UAAU,MAAM;KAC1B,eAAe,gBAAgB,MAAM,eAAe;KACpD,OAAO,MAAM;KACb,OAAO,MAAM;IACf,CAAC;GACH;EACF,CAAC;EACD,qCAAqC,WAAW;GAC9C,IAAI;GACJ,aAAa;GACb,aAAa,oBAAoB,OAAO;IACtC,QAAQ,EAAE,KAAK;KAAC;KAAS;KAAU;IAAQ,CAAC,CAAC,CAAC,SAAS;IACvD,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;IACjC,eAAe,EAAE,OAAO,CAAC,CAAC,SAAS;GACrC,CAAC;GACD,SAAS,OAAM,UAAS;IACtB,MAAM,SAAS,MAAM,WAAW;IAChC,OAAO,OAAO,SAAS,eAAe,iBAAiB;KACrD,GAAI,MAAM,UAAU,MAAM;KAC1B,eAAe,gBAAgB,MAAM,eAAe;KACpD,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;KAC7D,GAAI,MAAM,gBAAgB,KAAA,IAAY,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;KAC5E,GAAI,MAAM,kBAAkB,KAAA,IAAY,EAAE,eAAe,MAAM,cAAc,IAAI,CAAC;IACpF,CAAC;GACH;EACF,CAAC;CACH;AACF"}
@@ -1,4 +1,4 @@
1
- import { createHmac, randomBytes, timingSafeEqual } from "crypto";
1
+ import { createHmac, timingSafeEqual } from "crypto";
2
2
  //#region src/state-signing.ts
3
3
  /**
4
4
  * Shared OAuth/install `state` signing for web integrations.
@@ -33,7 +33,7 @@ const STATE_MAX_AGE_MS = 600 * 1e3;
33
33
  */
34
34
  function createStateSigner(secret) {
35
35
  const stable = typeof secret === "string" && secret.length > 0;
36
- const key = stable ? secret : randomBytes(32).toString("hex");
36
+ const key = stable ? secret : Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))).toString("hex");
37
37
  return {
38
38
  stable,
39
39
  sign(orgId, userId, context) {
@@ -41,7 +41,7 @@ function createStateSigner(secret) {
41
41
  orgId,
42
42
  userId,
43
43
  ...context?.factoryProjectId ? { factoryProjectId: context.factoryProjectId } : {},
44
- nonce: randomBytes(8).toString("hex"),
44
+ nonce: Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(8))).toString("hex"),
45
45
  issuedAt: Date.now()
46
46
  };
47
47
  const body = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
@@ -1 +1 @@
1
- {"version":3,"file":"state-signing.js","names":[],"sources":["../src/state-signing.ts"],"sourcesContent":["/**\n * Shared OAuth/install `state` signing for web integrations.\n *\n * The GitHub, Linear, and Slack OAuth/OIDC flows each round-trip a signed `state`\n * value\n * through the third party to bind the callback to the `(orgId, userId)` tenant\n * that initiated it (CSRF protection + tenant routing). The signer is a system\n * facility: `MastraFactory` creates ONE signer at boot and hands it to every\n * registered integration through `IntegrationContext` (see\n * `./factory-integration.ts`), so all integrations sign and verify with the\n * same secret.\n *\n * Secret resolution happens in the factory, not here: explicit\n * `config.stateSecret` → the GitHub integration's webhook secret → a\n * per-process random secret. A random secret is NOT stable across replicas —\n * a `state` signed by one replica cannot be verified by another — which is\n * what the `stable` flag reports. The factory fails loud at boot when a\n * registered integration requires a stable signer but only a random one is\n * available.\n *\n * The wire format (base64url JSON payload + `.` + HMAC-SHA256 base64url\n * signature) is unchanged from the previous `github/config.ts` implementation\n * so in-flight OAuth states survive a deploy.\n */\n\nimport { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\n\n/** Verified tenant and optional Factory context carried by a signed `state`. */\nexport interface StateTenant {\n orgId: string;\n userId: string;\n /** Factory that initiated the integration flow, when the caller supplied one. */\n factoryProjectId?: string;\n /**\n * Per-`state` random value. A signed `state` stays valid for its whole\n * lifetime, so a flow that must not run twice off one `state` (account\n * binding, for instance) can key single-use bookkeeping on this.\n */\n nonce: string;\n}\n\n/** Signs and verifies OAuth `state` values bound to a tenant and optional Factory. */\nexport interface StateSigner {\n /** Build a signed `state` bound to the tenant and optional initiating Factory. */\n sign(orgId: string, userId: string, context?: { factoryProjectId?: string }): string;\n /** Verify a signed `state`; returns the bound tenant, or `null` if invalid. */\n verify(state: string | undefined): StateTenant | null;\n /**\n * True when the signer was built from an explicit deployment-stable secret.\n * False means a per-process random secret: fine for single-process/local\n * dev, broken for multi-replica deploys (see module docs).\n */\n readonly stable: boolean;\n}\n\ninterface StatePayload {\n orgId: string;\n userId: string;\n factoryProjectId?: string;\n nonce: string;\n issuedAt: number;\n}\n\n/** Signed `state` values expire after this window to bound the CSRF token. */\nconst STATE_MAX_AGE_MS = 10 * 60 * 1000;\n\n/**\n * Create a state signer. With a `secret`, the signer is deployment-stable\n * (`stable: true`); without one it falls back to a per-process random secret\n * (`stable: false`).\n */\nexport function createStateSigner(secret?: string): StateSigner {\n const stable = typeof secret === 'string' && secret.length > 0;\n const key = stable ? secret : randomBytes(32).toString('hex');\n return {\n stable,\n sign(orgId: string, userId: string, context?: { factoryProjectId?: string }): string {\n const payload: StatePayload = {\n orgId,\n userId,\n ...(context?.factoryProjectId ? { factoryProjectId: context.factoryProjectId } : {}),\n nonce: randomBytes(8).toString('hex'),\n issuedAt: Date.now(),\n };\n const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\n const sig = createHmac('sha256', key).update(body).digest('base64url');\n return `${body}.${sig}`;\n },\n verify(state: string | undefined): StateTenant | null {\n if (!state) return null;\n const dot = state.lastIndexOf('.');\n if (dot <= 0) return null;\n const body = state.slice(0, dot);\n const sig = state.slice(dot + 1);\n const expected = createHmac('sha256', key).update(body).digest('base64url');\n const sigBuf = Buffer.from(sig);\n const expectedBuf = Buffer.from(expected);\n if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {\n return null;\n }\n try {\n const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as StatePayload;\n if (typeof parsed.orgId !== 'string' || typeof parsed.userId !== 'string') return null;\n if (typeof parsed.issuedAt !== 'number' || !Number.isFinite(parsed.issuedAt)) return null;\n if (typeof parsed.nonce !== 'string' || parsed.nonce.length === 0) return null;\n if (\n parsed.factoryProjectId !== undefined &&\n (typeof parsed.factoryProjectId !== 'string' || parsed.factoryProjectId.length === 0)\n ) {\n return null;\n }\n const age = Date.now() - parsed.issuedAt;\n if (age < 0 || age > STATE_MAX_AGE_MS) return null;\n return {\n orgId: parsed.orgId,\n userId: parsed.userId,\n ...(parsed.factoryProjectId ? { factoryProjectId: parsed.factoryProjectId } : {}),\n nonce: parsed.nonce,\n };\n } catch {\n return null;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,mBAAmB,MAAU;;;;;;AAOnC,SAAgB,kBAAkB,QAA8B;CAC9D,MAAM,SAAS,OAAO,WAAW,YAAY,OAAO,SAAS;CAC7D,MAAM,MAAM,SAAS,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC5D,OAAO;EACL;EACA,KAAK,OAAe,QAAgB,SAAiD;GACnF,MAAM,UAAwB;IAC5B;IACA;IACA,GAAI,SAAS,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;IAClF,OAAO,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK;IACpC,UAAU,KAAK,IAAI;GACrB;GACA,MAAM,OAAO,OAAO,KAAK,KAAK,UAAU,OAAO,GAAG,MAAM,CAAC,CAAC,SAAS,WAAW;GAE9E,OAAO,GAAG,KAAK,GADH,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,WACtC;EACtB;EACA,OAAO,OAA+C;GACpD,IAAI,CAAC,OAAO,OAAO;GACnB,MAAM,MAAM,MAAM,YAAY,GAAG;GACjC,IAAI,OAAO,GAAG,OAAO;GACrB,MAAM,OAAO,MAAM,MAAM,GAAG,GAAG;GAC/B,MAAM,MAAM,MAAM,MAAM,MAAM,CAAC;GAC/B,MAAM,WAAW,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,WAAW;GAC1E,MAAM,SAAS,OAAO,KAAK,GAAG;GAC9B,MAAM,cAAc,OAAO,KAAK,QAAQ;GACxC,IAAI,OAAO,WAAW,YAAY,UAAU,CAAC,gBAAgB,QAAQ,WAAW,GAC9E,OAAO;GAET,IAAI;IACF,MAAM,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;IACzE,IAAI,OAAO,OAAO,UAAU,YAAY,OAAO,OAAO,WAAW,UAAU,OAAO;IAClF,IAAI,OAAO,OAAO,aAAa,YAAY,CAAC,OAAO,SAAS,OAAO,QAAQ,GAAG,OAAO;IACrF,IAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,WAAW,GAAG,OAAO;IAC1E,IACE,OAAO,qBAAqB,KAAA,MAC3B,OAAO,OAAO,qBAAqB,YAAY,OAAO,iBAAiB,WAAW,IAEnF,OAAO;IAET,MAAM,MAAM,KAAK,IAAI,IAAI,OAAO;IAChC,IAAI,MAAM,KAAK,MAAM,kBAAkB,OAAO;IAC9C,OAAO;KACL,OAAO,OAAO;KACd,QAAQ,OAAO;KACf,GAAI,OAAO,mBAAmB,EAAE,kBAAkB,OAAO,iBAAiB,IAAI,CAAC;KAC/E,OAAO,OAAO;IAChB;GACF,QAAQ;IACN,OAAO;GACT;EACF;CACF;AACF"}
1
+ {"version":3,"file":"state-signing.js","names":[],"sources":["../src/state-signing.ts"],"sourcesContent":["/**\n * Shared OAuth/install `state` signing for web integrations.\n *\n * The GitHub, Linear, and Slack OAuth/OIDC flows each round-trip a signed `state`\n * value\n * through the third party to bind the callback to the `(orgId, userId)` tenant\n * that initiated it (CSRF protection + tenant routing). The signer is a system\n * facility: `MastraFactory` creates ONE signer at boot and hands it to every\n * registered integration through `IntegrationContext` (see\n * `./factory-integration.ts`), so all integrations sign and verify with the\n * same secret.\n *\n * Secret resolution happens in the factory, not here: explicit\n * `config.stateSecret` → the GitHub integration's webhook secret → a\n * per-process random secret. A random secret is NOT stable across replicas —\n * a `state` signed by one replica cannot be verified by another — which is\n * what the `stable` flag reports. The factory fails loud at boot when a\n * registered integration requires a stable signer but only a random one is\n * available.\n *\n * The wire format (base64url JSON payload + `.` + HMAC-SHA256 base64url\n * signature) is unchanged from the previous `github/config.ts` implementation\n * so in-flight OAuth states survive a deploy.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** Verified tenant and optional Factory context carried by a signed `state`. */\nexport interface StateTenant {\n orgId: string;\n userId: string;\n /** Factory that initiated the integration flow, when the caller supplied one. */\n factoryProjectId?: string;\n /**\n * Per-`state` random value. A signed `state` stays valid for its whole\n * lifetime, so a flow that must not run twice off one `state` (account\n * binding, for instance) can key single-use bookkeeping on this.\n */\n nonce: string;\n}\n\n/** Signs and verifies OAuth `state` values bound to a tenant and optional Factory. */\nexport interface StateSigner {\n /** Build a signed `state` bound to the tenant and optional initiating Factory. */\n sign(orgId: string, userId: string, context?: { factoryProjectId?: string }): string;\n /** Verify a signed `state`; returns the bound tenant, or `null` if invalid. */\n verify(state: string | undefined): StateTenant | null;\n /**\n * True when the signer was built from an explicit deployment-stable secret.\n * False means a per-process random secret: fine for single-process/local\n * dev, broken for multi-replica deploys (see module docs).\n */\n readonly stable: boolean;\n}\n\ninterface StatePayload {\n orgId: string;\n userId: string;\n factoryProjectId?: string;\n nonce: string;\n issuedAt: number;\n}\n\n/** Signed `state` values expire after this window to bound the CSRF token. */\nconst STATE_MAX_AGE_MS = 10 * 60 * 1000;\n\n/**\n * Create a state signer. With a `secret`, the signer is deployment-stable\n * (`stable: true`); without one it falls back to a per-process random secret\n * (`stable: false`).\n */\nexport function createStateSigner(secret?: string): StateSigner {\n const stable = typeof secret === 'string' && secret.length > 0;\n const key = stable ? secret : Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(32))).toString('hex');\n return {\n stable,\n sign(orgId: string, userId: string, context?: { factoryProjectId?: string }): string {\n const payload: StatePayload = {\n orgId,\n userId,\n ...(context?.factoryProjectId ? { factoryProjectId: context.factoryProjectId } : {}),\n nonce: Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(8))).toString('hex'),\n issuedAt: Date.now(),\n };\n const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\n const sig = createHmac('sha256', key).update(body).digest('base64url');\n return `${body}.${sig}`;\n },\n verify(state: string | undefined): StateTenant | null {\n if (!state) return null;\n const dot = state.lastIndexOf('.');\n if (dot <= 0) return null;\n const body = state.slice(0, dot);\n const sig = state.slice(dot + 1);\n const expected = createHmac('sha256', key).update(body).digest('base64url');\n const sigBuf = Buffer.from(sig);\n const expectedBuf = Buffer.from(expected);\n if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {\n return null;\n }\n try {\n const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as StatePayload;\n if (typeof parsed.orgId !== 'string' || typeof parsed.userId !== 'string') return null;\n if (typeof parsed.issuedAt !== 'number' || !Number.isFinite(parsed.issuedAt)) return null;\n if (typeof parsed.nonce !== 'string' || parsed.nonce.length === 0) return null;\n if (\n parsed.factoryProjectId !== undefined &&\n (typeof parsed.factoryProjectId !== 'string' || parsed.factoryProjectId.length === 0)\n ) {\n return null;\n }\n const age = Date.now() - parsed.issuedAt;\n if (age < 0 || age > STATE_MAX_AGE_MS) return null;\n return {\n orgId: parsed.orgId,\n userId: parsed.userId,\n ...(parsed.factoryProjectId ? { factoryProjectId: parsed.factoryProjectId } : {}),\n nonce: parsed.nonce,\n };\n } catch {\n return null;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,mBAAmB,MAAU;;;;;;AAOnC,SAAgB,kBAAkB,QAA8B;CAC9D,MAAM,SAAS,OAAO,WAAW,YAAY,OAAO,SAAS;CAC7D,MAAM,MAAM,SAAS,SAAS,OAAO,KAAK,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,CAAC,CA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ACpF,MAAM,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,aAAa,CAAC;IAK5D,UAAU,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,aAAa,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;IAwCnG,sEAAsE;IAChE,IAAI,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;CA2BjE"}
@@ -1,4 +1,3 @@
1
- import { createHash } from "crypto";
2
1
  import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage";
3
2
  //#region src/storage/domains/audit/base.ts
4
3
  /**
@@ -139,12 +138,12 @@ var AuditStorage = class extends FactoryStorageDomain {
139
138
  }
140
139
  async recordOnce(input) {
141
140
  if (!input.idempotencyKey) throw new Error("An audit idempotency key is required");
142
- const hash = createHash("sha256").update(JSON.stringify([
141
+ const hash = Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
143
142
  input.orgId,
144
143
  input.factoryProjectId ?? null,
145
144
  input.action,
146
145
  input.idempotencyKey
147
- ])).digest("hex");
146
+ ])))).toString("hex");
148
147
  const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-8${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
149
148
  try {
150
149
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#db","#insert"],"sources":["../../../../src/storage/domains/audit/base.ts"],"sourcesContent":["/**\n * Factory audit events domain — the append-only \"who did what, when\" trail\n * behind the software factory.\n *\n * Rows are append-only: there is no update/delete API, and the table is the\n * local source of truth even when the WorkOS Audit Logs mirror is unavailable.\n * Tenancy is org-first, like `work_items`: `actor_id` records who acted but\n * never scopes reads.\n *\n * The actions the trail holds are listed in `./actions.ts`.\n *\n * Agent events carry `actor_type = 'agent'` with `actor_id = 'agent:<threadId>'`\n * and `metadata.startedBy = <userId>` chaining accountability back to the human\n * whose message drove the run. Rule-driven events carry `actor_type = 'system'`.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport type { AuditActorType } from './actors.js';\n\n/** What an audit event acted on (WorkOS Audit Logs target shape). */\nexport interface AuditTarget {\n /** Target kind, e.g. 'work_item', 'worktree', 'issue', 'pull_request'. */\n type: string;\n /** Stable identifier of the target (row id, branch name, issue number...). */\n id: string;\n /** Human-readable label (work-item title, branch name...). */\n name?: string;\n}\n\nexport type { AuditActorType } from './actors.js';\n\n/** Display name and avatar of a human actor, stamped at record time because MastraAuthStudio cannot resolve users by id. */\nexport interface AuditActorProfileInput {\n name?: string;\n avatarUrl?: string;\n}\n\nexport const ACTOR_PROFILE_METADATA_KEY = '__actorProfile';\n\nexport function auditAgentName(modeId: string): string {\n return `${modeId} agent`;\n}\n\nexport function auditActorProfile(\n user: { name?: string; email?: string; avatarUrl?: string } | undefined,\n): AuditActorProfileInput | undefined {\n const name = user?.name?.trim() || user?.email?.trim();\n const avatarUrl = user?.avatarUrl?.trim();\n if (!name && !avatarUrl) return undefined;\n return { ...(name ? { name } : {}), ...(avatarUrl ? { avatarUrl } : {}) };\n}\n\n/** Request context captured alongside the event. */\nexport interface AuditContext {\n /** Client IP (first hop of `x-forwarded-for`) when available. */\n location?: string;\n /** Request `user-agent` header when available. */\n userAgent?: string;\n}\n\n/** One persisted audit event. */\nexport interface AuditEventRow {\n id: string;\n /** Owning WorkOS organization id — the trail is org-wide. */\n orgId: string;\n /** WorkOS user id of whoever performed the action, or `agent:<threadId>`. */\n actorId: string;\n /** Whether a human or an agent (inside a run) performed the action. */\n actorType: AuditActorType;\n /** Dot-namespaced action, e.g. 'factory.work_item.stage_moved'. */\n action: string;\n /** What was acted on. */\n targets: AuditTarget[];\n /** Bounded event summary — never full payloads, never secrets. */\n metadata: Record<string, unknown>;\n /** Factory project the event is scoped to; null for org-level events. */\n factoryProjectId: string | null;\n /** Project-repository link affected by a repository-specific action. */\n projectRepositoryId: string | null;\n /** Request context (`x-forwarded-for` / `user-agent`). */\n context: AuditContext;\n occurredAt: Date;\n}\n\nexport interface RecordAuditEventInput<Action extends string = string> {\n idempotencyKey?: string;\n orgId: string;\n actorId: string;\n /** Who performed the action; defaults to 'human'. */\n actorType?: AuditActorType;\n actorProfile?: AuditActorProfileInput;\n action: Action;\n targets: AuditTarget[];\n metadata?: Record<string, unknown>;\n factoryProjectId?: string;\n projectRepositoryId?: string;\n context?: AuditContext;\n occurredAt?: Date;\n}\n\n/** A fully-normalized event ready to persist (id assigned on insert). */\nexport type AuditEventInsert = Omit<AuditEventRow, 'id'>;\n\nexport interface ListAuditEventsInput {\n orgId: string;\n factoryProjectId?: string;\n /** Restrict to these actions (exact match). */\n actions?: string[];\n actorId?: string;\n /** Opaque cursor from a previous page (`nextCursor`). */\n before?: string;\n limit?: number;\n}\n\nexport interface AuditEventPage {\n events: AuditEventRow[];\n /** Pass back as `before` to fetch the next (older) page; absent at the end. */\n nextCursor?: string;\n}\n\n/** Metadata is a bounded summary — never full payloads, never secrets. */\nconst MAX_METADATA_JSON_LENGTH = 4096;\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst MAX_PAGE_SIZE = 200;\n\n/** Truncate oversized metadata rather than dropping the whole event. */\nexport function boundAuditMetadata(metadata: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!metadata) return {};\n try {\n if (JSON.stringify(metadata).length <= MAX_METADATA_JSON_LENGTH) return metadata;\n } catch {\n return { truncated: true };\n }\n return { truncated: true };\n}\n\n/** Normalize a requested page size to a finite integer in `[1, MAX_PAGE_SIZE]`. */\nexport function clampAuditLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\n/** Encode the `(occurredAt, id)` keyset cursor of a row. */\nexport function encodeAuditCursor(row: AuditEventRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\n/** Decode a cursor back into its `(occurredAt, id)` parts, or `undefined`. */\nexport function decodeAuditCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport const AUDIT_EVENTS_SCHEMA: CollectionSchema = {\n name: 'audit_events',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n actor_id: { type: 'text' },\n actor_type: { type: 'text', default: 'human' },\n action: { type: 'text' },\n targets: { type: 'json' },\n metadata: { type: 'json' },\n factory_project_id: { type: 'text', nullable: true },\n project_repository_id: { type: 'text', nullable: true },\n context: { type: 'json' },\n occurred_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'audit_events_org_occurred_idx', columns: ['org_id', 'occurred_at'] },\n { name: 'audit_events_org_project_occurred_idx', columns: ['org_id', 'factory_project_id', 'occurred_at'] },\n ],\n};\n\n/** Column shape of one `audit_events` row as returned by ops. */\ninterface AuditEventDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n actor_id: string;\n actor_type: AuditActorType;\n action: string;\n targets: AuditTarget[];\n metadata: Record<string, unknown>;\n factory_project_id: string | null;\n project_repository_id: string | null;\n context: AuditContext;\n occurred_at: Date;\n}\n\nfunction toRow(db: AuditEventDbRow): AuditEventRow {\n return {\n id: db.id,\n orgId: db.org_id,\n actorId: db.actor_id,\n actorType: db.actor_type,\n action: db.action,\n targets: db.targets,\n metadata: db.metadata,\n factoryProjectId: db.factory_project_id,\n projectRepositoryId: db.project_repository_id,\n context: db.context,\n occurredAt: db.occurred_at,\n };\n}\n\n/**\n * Audit event storage, written once against the generic `FactoryStorageOps`\n * surface. `record()` normalizes inputs (defaults, metadata bounding);\n * `list()` is keyset-paginated on `(occurred_at, id)` newest-first.\n */\nexport class AuditStorage extends FactoryStorageDomain {\n constructor() {\n super('audit');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([AUDIT_EVENTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('audit_events', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n /** Append one audit event. Throws on failure — swallow-on-failure lives in the caller. */\n async record(input: RecordAuditEventInput): Promise<AuditEventRow> {\n if (input.idempotencyKey) return (await this.recordOnce(input)).event;\n return this.#insert(input);\n }\n\n async recordOnce(input: RecordAuditEventInput): Promise<{ event: AuditEventRow; created: boolean }> {\n if (!input.idempotencyKey) throw new Error('An audit idempotency key is required');\n const hash = createHash('sha256')\n .update(JSON.stringify([input.orgId, input.factoryProjectId ?? null, input.action, input.idempotencyKey]))\n .digest('hex');\n const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-8${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;\n try {\n return { event: await this.#insert(input, id), created: true };\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const existing = await this.#db.findOne<AuditEventDbRow>('audit_events', { id, org_id: input.orgId });\n if (!existing) throw error;\n return { event: toRow(existing), created: false };\n }\n }\n\n async #insert(input: RecordAuditEventInput, id?: string): Promise<AuditEventRow> {\n const inserted = await this.#db.insertOne<AuditEventDbRow>('audit_events', {\n ...(id ? { id } : {}),\n org_id: input.orgId,\n actor_id: input.actorId,\n actor_type: input.actorType ?? 'human',\n action: input.action,\n targets: input.targets,\n metadata: boundAuditMetadata(\n input.actorProfile ? { ...input.metadata, [ACTOR_PROFILE_METADATA_KEY]: input.actorProfile } : input.metadata,\n ),\n factory_project_id: input.factoryProjectId ?? null,\n project_repository_id: input.projectRepositoryId ?? null,\n context: input.context ?? {},\n occurred_at: input.occurredAt ?? new Date(),\n });\n return toRow(inserted);\n }\n\n /** List an org's audit events newest-first with keyset pagination. */\n async list(input: ListAuditEventsInput): Promise<AuditEventPage> {\n const limit = clampAuditLimit(input.limit);\n\n const where: CollectionWhere = { org_id: input.orgId };\n if (input.factoryProjectId) where.factory_project_id = input.factoryProjectId;\n if (input.actions && input.actions.length > 0) where.action = { in: input.actions };\n if (input.actorId) where.actor_id = input.actorId;\n\n const cursor = input.before ? decodeAuditCursor(input.before) : undefined;\n\n const rows = await this.#db.findMany<AuditEventDbRow>('audit_events', where, {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n });\n\n const events = rows.slice(0, limit).map(toRow);\n const hasMore = rows.length > limit;\n const last = events[events.length - 1];\n return {\n events,\n ...(hasMore && last ? { nextCursor: encodeAuditCursor(last) } : {}),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyCA,MAAa,6BAA6B;AAE1C,SAAgB,eAAe,QAAwB;CACrD,OAAO,GAAG,OAAO;AACnB;AAEA,SAAgB,kBACd,MACoC;CACpC,MAAM,OAAO,MAAM,MAAM,KAAK,KAAK,MAAM,OAAO,KAAK;CACrD,MAAM,YAAY,MAAM,WAAW,KAAK;CACxC,IAAI,CAAC,QAAQ,CAAC,WAAW,OAAO,KAAA;CAChC,OAAO;EAAE,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;EAAI,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CAAG;AAC1E;;AAuEA,MAAM,2BAA2B;AAEjC,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;;AAGtB,SAAgB,mBAAmB,UAAwE;CACzG,IAAI,CAAC,UAAU,OAAO,CAAC;CACvB,IAAI;EACF,IAAI,KAAK,UAAU,QAAQ,CAAC,CAAC,UAAU,0BAA0B,OAAO;CAC1E,QAAQ;EACN,OAAO,EAAE,WAAW,KAAK;CAC3B;CACA,OAAO,EAAE,WAAW,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,CAAC,CAAC,IAAI,KAAK;EAC7C,MAAM,UAAU,KAAK,SAAS;EAC9B,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,OAAO;GACL;GACA,GAAI,WAAW,OAAO,EAAE,YAAY,kBAAkB,IAAI,EAAE,IAAI,CAAC;EACnE;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":["#db","#insert"],"sources":["../../../../src/storage/domains/audit/base.ts"],"sourcesContent":["/**\n * Factory audit events domain — the append-only \"who did what, when\" trail\n * behind the software factory.\n *\n * Rows are append-only: there is no update/delete API, and the table is the\n * local source of truth even when the WorkOS Audit Logs mirror is unavailable.\n * Tenancy is org-first, like `work_items`: `actor_id` records who acted but\n * never scopes reads.\n *\n * The actions the trail holds are listed in `./actions.ts`.\n *\n * Agent events carry `actor_type = 'agent'` with `actor_id = 'agent:<threadId>'`\n * and `metadata.startedBy = <userId>` chaining accountability back to the human\n * whose message drove the run. Rule-driven events carry `actor_type = 'system'`.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport type { AuditActorType } from './actors.js';\n\n/** What an audit event acted on (WorkOS Audit Logs target shape). */\nexport interface AuditTarget {\n /** Target kind, e.g. 'work_item', 'worktree', 'issue', 'pull_request'. */\n type: string;\n /** Stable identifier of the target (row id, branch name, issue number...). */\n id: string;\n /** Human-readable label (work-item title, branch name...). */\n name?: string;\n}\n\nexport type { AuditActorType } from './actors.js';\n\n/** Display name and avatar of a human actor, stamped at record time because MastraAuthStudio cannot resolve users by id. */\nexport interface AuditActorProfileInput {\n name?: string;\n avatarUrl?: string;\n}\n\nexport const ACTOR_PROFILE_METADATA_KEY = '__actorProfile';\n\nexport function auditAgentName(modeId: string): string {\n return `${modeId} agent`;\n}\n\nexport function auditActorProfile(\n user: { name?: string; email?: string; avatarUrl?: string } | undefined,\n): AuditActorProfileInput | undefined {\n const name = user?.name?.trim() || user?.email?.trim();\n const avatarUrl = user?.avatarUrl?.trim();\n if (!name && !avatarUrl) return undefined;\n return { ...(name ? { name } : {}), ...(avatarUrl ? { avatarUrl } : {}) };\n}\n\n/** Request context captured alongside the event. */\nexport interface AuditContext {\n /** Client IP (first hop of `x-forwarded-for`) when available. */\n location?: string;\n /** Request `user-agent` header when available. */\n userAgent?: string;\n}\n\n/** One persisted audit event. */\nexport interface AuditEventRow {\n id: string;\n /** Owning WorkOS organization id — the trail is org-wide. */\n orgId: string;\n /** WorkOS user id of whoever performed the action, or `agent:<threadId>`. */\n actorId: string;\n /** Whether a human or an agent (inside a run) performed the action. */\n actorType: AuditActorType;\n /** Dot-namespaced action, e.g. 'factory.work_item.stage_moved'. */\n action: string;\n /** What was acted on. */\n targets: AuditTarget[];\n /** Bounded event summary — never full payloads, never secrets. */\n metadata: Record<string, unknown>;\n /** Factory project the event is scoped to; null for org-level events. */\n factoryProjectId: string | null;\n /** Project-repository link affected by a repository-specific action. */\n projectRepositoryId: string | null;\n /** Request context (`x-forwarded-for` / `user-agent`). */\n context: AuditContext;\n occurredAt: Date;\n}\n\nexport interface RecordAuditEventInput<Action extends string = string> {\n idempotencyKey?: string;\n orgId: string;\n actorId: string;\n /** Who performed the action; defaults to 'human'. */\n actorType?: AuditActorType;\n actorProfile?: AuditActorProfileInput;\n action: Action;\n targets: AuditTarget[];\n metadata?: Record<string, unknown>;\n factoryProjectId?: string;\n projectRepositoryId?: string;\n context?: AuditContext;\n occurredAt?: Date;\n}\n\n/** A fully-normalized event ready to persist (id assigned on insert). */\nexport type AuditEventInsert = Omit<AuditEventRow, 'id'>;\n\nexport interface ListAuditEventsInput {\n orgId: string;\n factoryProjectId?: string;\n /** Restrict to these actions (exact match). */\n actions?: string[];\n actorId?: string;\n /** Opaque cursor from a previous page (`nextCursor`). */\n before?: string;\n limit?: number;\n}\n\nexport interface AuditEventPage {\n events: AuditEventRow[];\n /** Pass back as `before` to fetch the next (older) page; absent at the end. */\n nextCursor?: string;\n}\n\n/** Metadata is a bounded summary — never full payloads, never secrets. */\nconst MAX_METADATA_JSON_LENGTH = 4096;\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst MAX_PAGE_SIZE = 200;\n\n/** Truncate oversized metadata rather than dropping the whole event. */\nexport function boundAuditMetadata(metadata: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!metadata) return {};\n try {\n if (JSON.stringify(metadata).length <= MAX_METADATA_JSON_LENGTH) return metadata;\n } catch {\n return { truncated: true };\n }\n return { truncated: true };\n}\n\n/** Normalize a requested page size to a finite integer in `[1, MAX_PAGE_SIZE]`. */\nexport function clampAuditLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\n/** Encode the `(occurredAt, id)` keyset cursor of a row. */\nexport function encodeAuditCursor(row: AuditEventRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\n/** Decode a cursor back into its `(occurredAt, id)` parts, or `undefined`. */\nexport function decodeAuditCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport const AUDIT_EVENTS_SCHEMA: CollectionSchema = {\n name: 'audit_events',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n actor_id: { type: 'text' },\n actor_type: { type: 'text', default: 'human' },\n action: { type: 'text' },\n targets: { type: 'json' },\n metadata: { type: 'json' },\n factory_project_id: { type: 'text', nullable: true },\n project_repository_id: { type: 'text', nullable: true },\n context: { type: 'json' },\n occurred_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'audit_events_org_occurred_idx', columns: ['org_id', 'occurred_at'] },\n { name: 'audit_events_org_project_occurred_idx', columns: ['org_id', 'factory_project_id', 'occurred_at'] },\n ],\n};\n\n/** Column shape of one `audit_events` row as returned by ops. */\ninterface AuditEventDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n actor_id: string;\n actor_type: AuditActorType;\n action: string;\n targets: AuditTarget[];\n metadata: Record<string, unknown>;\n factory_project_id: string | null;\n project_repository_id: string | null;\n context: AuditContext;\n occurred_at: Date;\n}\n\nfunction toRow(db: AuditEventDbRow): AuditEventRow {\n return {\n id: db.id,\n orgId: db.org_id,\n actorId: db.actor_id,\n actorType: db.actor_type,\n action: db.action,\n targets: db.targets,\n metadata: db.metadata,\n factoryProjectId: db.factory_project_id,\n projectRepositoryId: db.project_repository_id,\n context: db.context,\n occurredAt: db.occurred_at,\n };\n}\n\n/**\n * Audit event storage, written once against the generic `FactoryStorageOps`\n * surface. `record()` normalizes inputs (defaults, metadata bounding);\n * `list()` is keyset-paginated on `(occurred_at, id)` newest-first.\n */\nexport class AuditStorage extends FactoryStorageDomain {\n constructor() {\n super('audit');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([AUDIT_EVENTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('audit_events', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n /** Append one audit event. Throws on failure — swallow-on-failure lives in the caller. */\n async record(input: RecordAuditEventInput): Promise<AuditEventRow> {\n if (input.idempotencyKey) return (await this.recordOnce(input)).event;\n return this.#insert(input);\n }\n\n async recordOnce(input: RecordAuditEventInput): Promise<{ event: AuditEventRow; created: boolean }> {\n if (!input.idempotencyKey) throw new Error('An audit idempotency key is required');\n const hash = Buffer.from(\n await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(\n JSON.stringify([input.orgId, input.factoryProjectId ?? null, input.action, input.idempotencyKey]),\n ),\n ),\n ).toString('hex');\n const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-8${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;\n try {\n return { event: await this.#insert(input, id), created: true };\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const existing = await this.#db.findOne<AuditEventDbRow>('audit_events', { id, org_id: input.orgId });\n if (!existing) throw error;\n return { event: toRow(existing), created: false };\n }\n }\n\n async #insert(input: RecordAuditEventInput, id?: string): Promise<AuditEventRow> {\n const inserted = await this.#db.insertOne<AuditEventDbRow>('audit_events', {\n ...(id ? { id } : {}),\n org_id: input.orgId,\n actor_id: input.actorId,\n actor_type: input.actorType ?? 'human',\n action: input.action,\n targets: input.targets,\n metadata: boundAuditMetadata(\n input.actorProfile ? { ...input.metadata, [ACTOR_PROFILE_METADATA_KEY]: input.actorProfile } : input.metadata,\n ),\n factory_project_id: input.factoryProjectId ?? null,\n project_repository_id: input.projectRepositoryId ?? null,\n context: input.context ?? {},\n occurred_at: input.occurredAt ?? new Date(),\n });\n return toRow(inserted);\n }\n\n /** List an org's audit events newest-first with keyset pagination. */\n async list(input: ListAuditEventsInput): Promise<AuditEventPage> {\n const limit = clampAuditLimit(input.limit);\n\n const where: CollectionWhere = { org_id: input.orgId };\n if (input.factoryProjectId) where.factory_project_id = input.factoryProjectId;\n if (input.actions && input.actions.length > 0) where.action = { in: input.actions };\n if (input.actorId) where.actor_id = input.actorId;\n\n const cursor = input.before ? decodeAuditCursor(input.before) : undefined;\n\n const rows = await this.#db.findMany<AuditEventDbRow>('audit_events', where, {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n });\n\n const events = rows.slice(0, limit).map(toRow);\n const hasMore = rows.length > limit;\n const last = events[events.length - 1];\n return {\n events,\n ...(hasMore && last ? { nextCursor: encodeAuditCursor(last) } : {}),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuCA,MAAa,6BAA6B;AAE1C,SAAgB,eAAe,QAAwB;CACrD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9E;IAEF,QAAQ,CAAC,QAAQ;sDACqC;YAAE,mBAAmB,EAAE,MAAM,CAAC;YAAC,YAAY,EAAE,MAAM,CAAA;SAAE;2DAMhD;YAAE,mBAAmB,EAAE,MAAM,CAAA;SAAE;oCAEtD,MAAM,KAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;uCAM1C;YAAE,SAAS,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,KAAG,OAAO,CAAC,IAAI,CAAC;iEAWtF;YACD,mBAAmB,EAAE,MAAM,CAAC;YAC5B,MAAM,EAAE,MAAM,CAAC;YACf,MAAM,EAAE,MAAM,CAAC;SAChB,KAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;wBAIlB,+BAA+B,KAAG,OAAO,CAAC,oBAAoB,CAAC;yDA2BlF;YACD,EAAE,EAAE,MAAM,CAAC;YACX,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;YACzB,cAAc,EAAE,MAAM,CAAC;SACxB;mCAIgC;YAAE,EAAE,EAAE,MAAM,CAAA;SAAE;0CAIP;YAAE,SAAS,EAAE,MAAM,CAAA;SAAE;iDAId;YAAE,SAAS,EAAE,MAAM,CAAA;SAAE;qBAMjD,MAAM;MAGzB;CACH"}
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "crypto";
2
1
  import { UniqueViolationError } from "@mastra/core/storage";
3
2
  //#region src/storage/domains/source-control/inmemory.ts
4
3
  /** In-memory provider-scoped source-control handle for route tests. */
@@ -28,7 +27,7 @@ var SourceControlStorageInMemory = class {
28
27
  return existing;
29
28
  }
30
29
  const created = {
31
- id: randomUUID(),
30
+ id: globalThis.crypto.randomUUID(),
32
31
  integrationId: this.integrationId,
33
32
  orgId: input.orgId,
34
33
  connectedByUserId: input.connectedByUserId,
@@ -92,7 +91,7 @@ var SourceControlStorageInMemory = class {
92
91
  return existing;
93
92
  }
94
93
  const created = {
95
- id: randomUUID(),
94
+ id: globalThis.crypto.randomUUID(),
96
95
  installationId: input.installationId,
97
96
  externalId: input.externalId,
98
97
  slug: input.slug,
@@ -140,7 +139,7 @@ var SourceControlStorageInMemory = class {
140
139
  const existing = this.connectionsRows.find((row) => row.factoryProjectId === input.factoryProjectId && row.integrationId === this.integrationId && row.installationId === input.installationId);
141
140
  if (existing) return existing;
142
141
  const created = {
143
- id: randomUUID(),
142
+ id: globalThis.crypto.randomUUID(),
144
143
  factoryProjectId: input.factoryProjectId,
145
144
  integrationId: this.integrationId,
146
145
  installationId: input.installationId,
@@ -219,7 +218,7 @@ var SourceControlStorageInMemory = class {
219
218
  if (existing) return existing;
220
219
  const now = /* @__PURE__ */ new Date();
221
220
  const created = {
222
- id: randomUUID(),
221
+ id: globalThis.crypto.randomUUID(),
223
222
  connectionId: input.connectionId,
224
223
  repositoryId: input.repositoryId,
225
224
  createdByUserId: input.createdByUserId,
@@ -274,7 +273,7 @@ var SourceControlStorageInMemory = class {
274
273
  if (this.sessionsRows.some((row) => row.sessionId === input.sessionId)) throw new UniqueViolationError("Source-control session ID already exists");
275
274
  const now = /* @__PURE__ */ new Date();
276
275
  const session = {
277
- id: randomUUID(),
276
+ id: globalThis.crypto.randomUUID(),
278
277
  ...input,
279
278
  title: input.title ?? null,
280
279
  visibility: input.visibility ?? "org",