@mtaap/mcp 0.1.2 → 0.1.3

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.
@@ -1,318 +1,919 @@
1
- import {
2
- dist_exports,
3
- prisma
4
- } from "./chunk-IEQQVLM4.js";
5
- import {
6
- AbandonTaskInputSchema,
7
- AddNoteInputSchema,
8
- ApiKeyPermission,
9
- AssignTaskInputSchema,
10
- CompleteTaskInputSchema,
11
- CreatePersonalProjectInputSchema,
12
- GetProjectContextInputSchema,
13
- GetTaskInputSchema,
14
- ListProjectsInputSchema,
15
- ListTasksInputSchema,
16
- ProjectOrigin,
17
- ProjectType,
18
- ReportErrorInputSchema,
19
- TaskState,
20
- UpdateProgressInputSchema,
21
- UserRole,
22
- z
23
- } from "./chunk-ASNGTDTC.js";
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
24
18
 
25
19
  // src/index.ts
26
20
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
27
21
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
28
22
 
29
- // ../../packages/auth/dist/nextauth.js
30
- import Credentials from "next-auth/providers/credentials";
23
+ // ../../packages/db/dist/index.js
24
+ var dist_exports = {};
25
+ __export(dist_exports, {
26
+ prisma: () => prisma2
27
+ });
31
28
 
32
- // ../../packages/auth/dist/ldap.js
33
- async function authenticateWithLdap(email, password, organizationId) {
34
- const settings = await prisma.organizationSettings.findUnique({
35
- where: { organizationId }
36
- });
37
- if (!settings?.ldapEnabled || !settings.ldapUrl) {
38
- return null;
29
+ // ../../packages/db/dist/client.js
30
+ var client_exports = {};
31
+ __export(client_exports, {
32
+ default: () => client_default,
33
+ prisma: () => prisma
34
+ });
35
+ __reExport(client_exports, client_star);
36
+ import { PrismaClient } from "@prisma/client";
37
+ import { PrismaPg } from "@prisma/adapter-pg";
38
+ import * as client_star from "@prisma/client";
39
+ var adapter = new PrismaPg({
40
+ connectionString: process.env.DATABASE_URL
41
+ });
42
+ var globalForPrisma = globalThis;
43
+ var prisma = globalForPrisma.prisma ?? new PrismaClient({
44
+ adapter
45
+ });
46
+ if (process.env.NODE_ENV !== "production") {
47
+ globalForPrisma.prisma = prisma;
48
+ }
49
+ var client_default = prisma;
50
+
51
+ // ../../packages/core/dist/constants/enums.js
52
+ var TaskState;
53
+ (function(TaskState2) {
54
+ TaskState2["BACKLOG"] = "BACKLOG";
55
+ TaskState2["READY"] = "READY";
56
+ TaskState2["IN_PROGRESS"] = "IN_PROGRESS";
57
+ TaskState2["REVIEW"] = "REVIEW";
58
+ TaskState2["DONE"] = "DONE";
59
+ })(TaskState || (TaskState = {}));
60
+ var UserRole;
61
+ (function(UserRole2) {
62
+ UserRole2["ADMIN"] = "ADMIN";
63
+ UserRole2["MEMBER"] = "MEMBER";
64
+ })(UserRole || (UserRole = {}));
65
+ var ProjectType;
66
+ (function(ProjectType2) {
67
+ ProjectType2["TEAM"] = "TEAM";
68
+ ProjectType2["PERSONAL"] = "PERSONAL";
69
+ })(ProjectType || (ProjectType = {}));
70
+ var ProjectOrigin;
71
+ (function(ProjectOrigin2) {
72
+ ProjectOrigin2["CREATED"] = "CREATED";
73
+ ProjectOrigin2["PROMOTED"] = "PROMOTED";
74
+ })(ProjectOrigin || (ProjectOrigin = {}));
75
+ var TaskPriority;
76
+ (function(TaskPriority2) {
77
+ TaskPriority2["LOW"] = "LOW";
78
+ TaskPriority2["MEDIUM"] = "MEDIUM";
79
+ TaskPriority2["HIGH"] = "HIGH";
80
+ TaskPriority2["CRITICAL"] = "CRITICAL";
81
+ })(TaskPriority || (TaskPriority = {}));
82
+ var DeploymentMode;
83
+ (function(DeploymentMode2) {
84
+ DeploymentMode2["SAAS"] = "saas";
85
+ DeploymentMode2["ONPREM"] = "onprem";
86
+ })(DeploymentMode || (DeploymentMode = {}));
87
+ var ErrorType;
88
+ (function(ErrorType3) {
89
+ ErrorType3["BUILD_FAILURE"] = "BUILD_FAILURE";
90
+ ErrorType3["TEST_FAILURE"] = "TEST_FAILURE";
91
+ ErrorType3["CONFLICT"] = "CONFLICT";
92
+ ErrorType3["AUTH_ERROR"] = "AUTH_ERROR";
93
+ ErrorType3["OTHER"] = "OTHER";
94
+ })(ErrorType || (ErrorType = {}));
95
+ var PRStatus;
96
+ (function(PRStatus2) {
97
+ PRStatus2["OPEN"] = "OPEN";
98
+ PRStatus2["CLOSED"] = "CLOSED";
99
+ PRStatus2["MERGED"] = "MERGED";
100
+ PRStatus2["DELETED"] = "DELETED";
101
+ })(PRStatus || (PRStatus = {}));
102
+ var PricingTier;
103
+ (function(PricingTier2) {
104
+ PricingTier2["FREE"] = "FREE";
105
+ PricingTier2["PRO"] = "PRO";
106
+ PricingTier2["ENTERPRISE"] = "ENTERPRISE";
107
+ })(PricingTier || (PricingTier = {}));
108
+ var ApiKeyPermission;
109
+ (function(ApiKeyPermission2) {
110
+ ApiKeyPermission2["READ"] = "READ";
111
+ ApiKeyPermission2["WRITE"] = "WRITE";
112
+ ApiKeyPermission2["ADMIN"] = "ADMIN";
113
+ })(ApiKeyPermission || (ApiKeyPermission = {}));
114
+ var WebSocketEventType;
115
+ (function(WebSocketEventType2) {
116
+ WebSocketEventType2["TASK_ASSIGNED"] = "task.assigned";
117
+ WebSocketEventType2["TASK_ABANDONED"] = "task.abandoned";
118
+ WebSocketEventType2["TASK_PROGRESS"] = "task.progress";
119
+ WebSocketEventType2["TASK_PR_CREATED"] = "task.pr_created";
120
+ WebSocketEventType2["TASK_REVIEW_REQUESTED"] = "task.review_requested";
121
+ WebSocketEventType2["TASK_COMPLETED"] = "task.completed";
122
+ WebSocketEventType2["TASK_ERROR"] = "task.error";
123
+ WebSocketEventType2["TASK_STATE_CHANGED"] = "task.state_changed";
124
+ WebSocketEventType2["MEMBER_JOINED"] = "member.joined";
125
+ })(WebSocketEventType || (WebSocketEventType = {}));
126
+ var AuthProvider;
127
+ (function(AuthProvider2) {
128
+ AuthProvider2["CREDENTIALS"] = "credentials";
129
+ AuthProvider2["LDAP"] = "ldap";
130
+ AuthProvider2["SSO"] = "sso";
131
+ })(AuthProvider || (AuthProvider = {}));
132
+ var SubscriptionStatus;
133
+ (function(SubscriptionStatus2) {
134
+ SubscriptionStatus2["ACTIVE"] = "ACTIVE";
135
+ SubscriptionStatus2["INACTIVE"] = "INACTIVE";
136
+ SubscriptionStatus2["PAST_DUE"] = "PAST_DUE";
137
+ SubscriptionStatus2["CANCELED"] = "CANCELED";
138
+ SubscriptionStatus2["INCOMPLETE"] = "INCOMPLETE";
139
+ })(SubscriptionStatus || (SubscriptionStatus = {}));
140
+ var EventType;
141
+ (function(EventType2) {
142
+ EventType2["AUTH"] = "AUTH";
143
+ EventType2["AUTHORIZATION"] = "AUTHORIZATION";
144
+ EventType2["ACCESS"] = "ACCESS";
145
+ EventType2["MODIFICATION"] = "MODIFICATION";
146
+ })(EventType || (EventType = {}));
147
+
148
+ // ../../packages/core/dist/constants/state-machine.js
149
+ var VALID_TRANSITIONS = {
150
+ [TaskState.BACKLOG]: [TaskState.READY],
151
+ [TaskState.READY]: [TaskState.BACKLOG, TaskState.IN_PROGRESS],
152
+ [TaskState.IN_PROGRESS]: [
153
+ TaskState.BACKLOG,
154
+ TaskState.READY,
155
+ TaskState.REVIEW
156
+ ],
157
+ [TaskState.REVIEW]: [
158
+ TaskState.BACKLOG,
159
+ TaskState.READY,
160
+ TaskState.IN_PROGRESS,
161
+ TaskState.DONE
162
+ ],
163
+ [TaskState.DONE]: []
164
+ };
165
+
166
+ // ../../packages/core/dist/version.js
167
+ var VERSION = "0.1.0";
168
+
169
+ // ../../packages/core/dist/config/index.js
170
+ var DEPLOYMENT_MODE = process.env.DEPLOYMENT_MODE || "saas";
171
+ var config = {
172
+ version: VERSION,
173
+ deploymentMode: DEPLOYMENT_MODE,
174
+ billing: {
175
+ enabled: DEPLOYMENT_MODE === "saas",
176
+ revenuecat: {
177
+ publicKey: process.env.REVENUECAT_PUBLIC_API_KEY,
178
+ stripeKey: process.env.STRIPE_SECRET_KEY
179
+ // Required by RevenueCat Web Billing
180
+ }
181
+ },
182
+ licensing: {
183
+ enabled: DEPLOYMENT_MODE === "onprem",
184
+ licenseKey: process.env.LICENSE_KEY
185
+ },
186
+ auth: {
187
+ credentials: true,
188
+ ldap: process.env.LDAP_ENABLED === "true"
189
+ },
190
+ git: {
191
+ deleteMergedBranches: process.env.DELETE_MERGED_BRANCHES !== "false",
192
+ enforceConventionalCommits: process.env.ENFORCE_CONVENTIONAL_COMMITS === "true",
193
+ defaultBaseBranch: process.env.DEFAULT_BASE_BRANCH || "develop"
194
+ },
195
+ pricing: {
196
+ maxPersonalProjects: {
197
+ FREE: 2,
198
+ PRO: 5,
199
+ ENTERPRISE: 10
200
+ },
201
+ maxCollaboratorsPerProject: {
202
+ FREE: 3,
203
+ PRO: -1,
204
+ ENTERPRISE: -1
205
+ },
206
+ maxProjectsPerOrg: {
207
+ FREE: 5,
208
+ PRO: -1,
209
+ ENTERPRISE: -1
210
+ },
211
+ maxSeats: {
212
+ FREE: 3,
213
+ PRO: -1,
214
+ ENTERPRISE: -1
215
+ },
216
+ // Default seats when subscription doesn't specify an explicit seat count
217
+ defaultSeats: {
218
+ FREE: 3,
219
+ PRO: 10,
220
+ ENTERPRISE: 999999
221
+ }
222
+ },
223
+ features: {
224
+ stripe: {
225
+ enabled: DEPLOYMENT_MODE === "saas"
226
+ },
227
+ gitlab: {
228
+ enabled: true
229
+ },
230
+ ldap: {
231
+ enabled: process.env.LDAP_ENABLED === "true"
232
+ },
233
+ auditLogs: {
234
+ enabled: process.env.AUDIT_LOGS_ENABLED === "true"
235
+ }
236
+ },
237
+ api: {
238
+ apiKey: {
239
+ defaultExpiryDays: 90,
240
+ prefix: "usr_"
241
+ },
242
+ rateLimit: {
243
+ requestsPerMinute: 100,
244
+ requestsPerHour: 1e3
245
+ }
246
+ },
247
+ limits: {
248
+ projectNameMaxLength: 100,
249
+ taskDescriptionMaxLength: 5e3,
250
+ notesMaxLength: 500,
251
+ conventionsNotesMaxLength: 500,
252
+ recentCompletedTasksLimit: 10
39
253
  }
40
- const config = {
41
- url: settings.ldapUrl,
42
- bindDN: settings.ldapBindDN || "",
43
- searchBase: settings.ldapSearchBase || ""
44
- };
45
- return performLdapAuth(email, password, config);
254
+ };
255
+ var DEFAULT_SEAT_LIMITS = {
256
+ [PricingTier.FREE]: config.pricing.defaultSeats.FREE,
257
+ [PricingTier.PRO]: config.pricing.defaultSeats.PRO,
258
+ [PricingTier.ENTERPRISE]: config.pricing.defaultSeats.ENTERPRISE
259
+ };
260
+
261
+ // ../../packages/core/dist/types/index.js
262
+ import { z } from "zod";
263
+ var UserIdSchema = z.string().regex(/^usr_[a-zA-Z0-9]+$/);
264
+ var UserSchema = z.object({
265
+ id: UserIdSchema,
266
+ email: z.string().email(),
267
+ name: z.string().min(1).max(255),
268
+ role: z.nativeEnum(UserRole),
269
+ organizationId: z.string().optional(),
270
+ lastActiveAt: z.coerce.date().optional(),
271
+ createdAt: z.coerce.date()
272
+ });
273
+ var OrganizationUserSchema = z.object({
274
+ id: z.number().int(),
275
+ userId: UserIdSchema,
276
+ organizationId: z.string(),
277
+ roleId: z.nativeEnum(UserRole).optional(),
278
+ user: UserSchema.pick({ id: true, email: true, name: true, role: true }),
279
+ createdAt: z.coerce.date()
280
+ });
281
+ var OrganizationIdSchema = z.string().regex(/^org_[a-zA-Z0-9]+$/);
282
+ var OrganizationSchema = z.object({
283
+ id: OrganizationIdSchema,
284
+ name: z.string().min(1).max(255),
285
+ slug: z.string().min(1).max(100).regex(/^[a-z0-9-]+$/),
286
+ logoUrl: z.string().url().nullable(),
287
+ accentColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/).nullable(),
288
+ tenantName: z.string().nullable(),
289
+ pricingTier: z.nativeEnum(PricingTier),
290
+ createdAt: z.coerce.date()
291
+ });
292
+ var OrganizationSettingsSchema = z.object({
293
+ organizationId: OrganizationIdSchema,
294
+ ldapEnabled: z.boolean(),
295
+ ldapUrl: z.string().url().nullable(),
296
+ ldapBindDN: z.string().nullable(),
297
+ ldapSearchBase: z.string().nullable(),
298
+ deleteMergedBranches: z.boolean(),
299
+ enforceConventionalCommits: z.boolean(),
300
+ maxPersonalProjectsPerUser: z.number().int().min(0)
301
+ });
302
+ var TagSchema = z.object({
303
+ id: z.string(),
304
+ name: z.string().min(1).max(50),
305
+ organizationId: OrganizationIdSchema,
306
+ createdAt: z.coerce.date()
307
+ });
308
+ var ProjectIdSchema = z.string().regex(/^prj_[a-zA-Z0-9]+$/);
309
+ var ProjectSchema = z.object({
310
+ id: ProjectIdSchema,
311
+ name: z.string().min(1).max(100),
312
+ description: z.string().max(500).nullable(),
313
+ type: z.nativeEnum(ProjectType),
314
+ origin: z.nativeEnum(ProjectOrigin),
315
+ organizationId: OrganizationIdSchema,
316
+ ownerId: UserIdSchema.nullable(),
317
+ repositoryUrl: z.string().url(),
318
+ baseBranch: z.string().default("develop"),
319
+ tags: z.array(z.string()),
320
+ createdAt: z.coerce.date(),
321
+ updatedAt: z.coerce.date()
322
+ });
323
+ var EpicIdSchema = z.string().regex(/^epc_[a-zA-Z0-9]+$/);
324
+ var EpicSchema = z.object({
325
+ id: EpicIdSchema,
326
+ projectId: ProjectIdSchema,
327
+ name: z.string().min(1).max(200),
328
+ description: z.string().nullable(),
329
+ createdAt: z.coerce.date(),
330
+ updatedAt: z.coerce.date()
331
+ });
332
+ var TaskIdSchema = z.string().regex(/^tsk_[a-zA-Z0-9]+$/);
333
+ var TaskSchema = z.object({
334
+ id: TaskIdSchema,
335
+ projectId: ProjectIdSchema,
336
+ epicId: EpicIdSchema.nullable(),
337
+ title: z.string().min(1).max(200),
338
+ description: z.string().max(5e3),
339
+ state: z.nativeEnum(TaskState),
340
+ priority: z.nativeEnum(TaskPriority),
341
+ assigneeId: UserIdSchema.nullable(),
342
+ createdBy: UserIdSchema.nullable(),
343
+ assignedAt: z.coerce.date().nullable(),
344
+ startedAt: z.coerce.date().nullable(),
345
+ completedAt: z.coerce.date().nullable(),
346
+ branchName: z.string().nullable(),
347
+ pullRequestUrl: z.string().url().nullable(),
348
+ pullRequestNumber: z.number().int().nullable(),
349
+ pullRequestStatus: z.nativeEnum(PRStatus).nullable(),
350
+ errorType: z.nativeEnum(ErrorType).nullable(),
351
+ errorMessage: z.string().max(1e3).nullable(),
352
+ createdAt: z.coerce.date(),
353
+ updatedAt: z.coerce.date()
354
+ });
355
+ var AcceptanceCriterionSchema = z.object({
356
+ id: z.string(),
357
+ taskId: TaskIdSchema,
358
+ description: z.string().min(1).max(500),
359
+ completed: z.boolean(),
360
+ completedAt: z.coerce.date().nullable(),
361
+ order: z.number().int(),
362
+ createdAt: z.coerce.date()
363
+ });
364
+ var ProgressUpdateSchema = z.object({
365
+ id: z.string(),
366
+ taskId: TaskIdSchema,
367
+ userId: UserIdSchema,
368
+ message: z.string().max(2e3),
369
+ checkpoints: z.array(z.string()).optional(),
370
+ createdAt: z.coerce.date()
371
+ });
372
+ var TaskNoteSchema = z.object({
373
+ id: z.string(),
374
+ taskId: TaskIdSchema,
375
+ userId: UserIdSchema,
376
+ content: z.string().max(500),
377
+ createdAt: z.coerce.date()
378
+ });
379
+ var ApiKeyIdSchema = z.string().regex(/^key_[a-zA-Z0-9]+$/);
380
+ var ApiKeySchema = z.object({
381
+ id: ApiKeyIdSchema,
382
+ userId: UserIdSchema,
383
+ name: z.string().min(1).max(100),
384
+ keyHash: z.string(),
385
+ permissions: z.nativeEnum(ApiKeyPermission),
386
+ lastUsedAt: z.coerce.date().nullable(),
387
+ expiresAt: z.coerce.date().nullable(),
388
+ revoked: z.boolean(),
389
+ createdAt: z.coerce.date()
390
+ });
391
+ var SubscriptionIdSchema = z.string();
392
+ var SubscriptionSchema = z.object({
393
+ id: SubscriptionIdSchema,
394
+ organizationId: OrganizationIdSchema,
395
+ pricingTier: z.nativeEnum(PricingTier),
396
+ seats: z.number().int().min(0),
397
+ stripeSubscriptionId: z.string().nullable(),
398
+ stripeCustomerId: z.string().nullable(),
399
+ status: z.enum(["active", "past_due", "canceled", "incomplete"]),
400
+ currentPeriodStart: z.coerce.date(),
401
+ currentPeriodEnd: z.coerce.date(),
402
+ createdAt: z.coerce.date()
403
+ });
404
+ var ProjectCollaboratorSchema = z.object({
405
+ id: z.string(),
406
+ projectId: ProjectIdSchema,
407
+ userId: UserIdSchema,
408
+ addedBy: UserIdSchema,
409
+ createdAt: z.coerce.date()
410
+ });
411
+
412
+ // ../../packages/core/dist/validation/index.js
413
+ import { z as z2 } from "zod";
414
+ var ListProjectsInputSchema = z2.object({
415
+ workspaceType: z2.preprocess((val) => typeof val === "string" ? val.toUpperCase() : val, z2.enum(["TEAM", "PERSONAL", "ALL"]).optional())
416
+ });
417
+ var ListTasksInputSchema = z2.object({
418
+ projectId: z2.string().optional(),
419
+ state: z2.nativeEnum(TaskState).optional(),
420
+ assigneeId: z2.string().optional()
421
+ });
422
+ var GetTaskInputSchema = z2.object({
423
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/)
424
+ });
425
+ var AssignTaskInputSchema = z2.object({
426
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
427
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
428
+ expectedState: z2.nativeEnum(TaskState).default(TaskState.READY)
429
+ });
430
+ var UpdateProgressInputSchema = z2.object({
431
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
432
+ statusMessage: z2.string().max(1e3).optional(),
433
+ completedCheckpointIds: z2.array(z2.string()).optional(),
434
+ currentCheckpointIndex: z2.number().int().optional()
435
+ });
436
+ var CompleteTaskInputSchema = z2.object({
437
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
438
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
439
+ pullRequestTitle: z2.string().min(1).max(300).optional(),
440
+ pullRequestBody: z2.string().max(1e4).optional()
441
+ });
442
+ var ReportErrorInputSchema = z2.object({
443
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
444
+ errorType: z2.nativeEnum(ErrorType),
445
+ errorMessage: z2.string().min(1).max(1e3),
446
+ context: z2.string().max(2e3).optional()
447
+ });
448
+ var GetProjectContextInputSchema = z2.object({
449
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/)
450
+ });
451
+ var AddNoteInputSchema = z2.object({
452
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
453
+ content: z2.string().min(1).max(500)
454
+ });
455
+ var AbandonTaskInputSchema = z2.object({
456
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
457
+ taskId: z2.string().regex(/^tsk_[a-zA-Z0-9]+$/),
458
+ deleteBranch: z2.boolean().optional()
459
+ });
460
+ var CreatePersonalProjectInputSchema = z2.object({
461
+ name: z2.string().min(1).max(100),
462
+ description: z2.string().max(500).optional(),
463
+ repositoryUrl: z2.string().url()
464
+ });
465
+ var CheckActiveTaskInputSchema = z2.object({});
466
+ var CreateOrganizationInputSchema = z2.object({
467
+ name: z2.string().min(1).max(255),
468
+ slug: z2.string().min(1).max(100).regex(/^[a-z0-9-]+$/).optional()
469
+ });
470
+ var UpdateOrganizationInputSchema = z2.object({
471
+ organizationId: z2.string().regex(/^org_[a-zA-Z0-9]+$/),
472
+ name: z2.string().min(1).max(255).optional(),
473
+ logoUrl: z2.string().url().nullable().optional(),
474
+ accentColor: z2.string().regex(/^#[0-9A-Fa-f]{6}$/, "Invalid hex color format. Expected #RRGGBB").nullable().optional(),
475
+ tenantName: z2.string().max(255).nullable().optional()
476
+ });
477
+ var CreateProjectInputSchema = z2.object({
478
+ name: z2.string().min(1).max(100),
479
+ description: z2.string().max(500).optional(),
480
+ type: z2.nativeEnum(ProjectType),
481
+ repositoryUrl: z2.string().url(),
482
+ baseBranch: z2.string().default("develop").optional(),
483
+ tags: z2.array(z2.string()).default([])
484
+ });
485
+ var UpdateProjectInputSchema = z2.object({
486
+ projectId: z2.string().min(1).optional(),
487
+ name: z2.string().min(1).max(100).optional(),
488
+ description: z2.string().max(500).optional(),
489
+ repositoryUrl: z2.string().url().optional(),
490
+ baseBranch: z2.string().optional(),
491
+ tags: z2.array(z2.string()).optional()
492
+ });
493
+ var CreateEpicInputSchema = z2.object({
494
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
495
+ name: z2.string().min(1).max(200),
496
+ description: z2.string().max(2e3).optional()
497
+ });
498
+ var CreateTaskInputSchema = z2.object({
499
+ projectId: z2.string().min(1),
500
+ epicId: z2.string().min(1).nullable().optional(),
501
+ title: z2.string().min(1).max(200),
502
+ description: z2.string().max(5e3),
503
+ priority: z2.nativeEnum(TaskPriority).default(TaskPriority.MEDIUM),
504
+ acceptanceCriteria: z2.array(z2.object({
505
+ description: z2.string().min(1).max(500)
506
+ })).min(1)
507
+ });
508
+ var UpdateTaskInputSchema = z2.object({
509
+ taskId: z2.string().min(1),
510
+ title: z2.string().min(1).max(200).optional(),
511
+ description: z2.string().max(5e3).optional(),
512
+ priority: z2.nativeEnum(TaskPriority).optional(),
513
+ state: z2.nativeEnum(TaskState).optional(),
514
+ assigneeId: z2.string().nullable().optional(),
515
+ acceptanceCriteria: z2.array(z2.object({
516
+ id: z2.string().optional(),
517
+ description: z2.string().min(1).max(500),
518
+ completed: z2.boolean().optional()
519
+ })).optional()
520
+ });
521
+ var AssignTaskWebappInputSchema = z2.object({
522
+ taskId: z2.string().min(1),
523
+ userId: z2.string().min(1)
524
+ });
525
+ var CreateTagInputSchema = z2.object({
526
+ organizationId: z2.string().regex(/^org_[a-zA-Z0-9]+$/),
527
+ name: z2.string().min(1).max(50).regex(/^[a-zA-Z0-9\s-]+$/)
528
+ });
529
+ var UpdateTagInputSchema = z2.object({
530
+ name: z2.string().min(1).max(50).regex(/^[a-zA-Z0-9\s-]+$/)
531
+ });
532
+ var UpdateOrganizationSettingsInputSchema = z2.object({
533
+ organizationId: z2.string().regex(/^org_[a-zA-Z0-9]+$/),
534
+ ldapEnabled: z2.boolean().optional(),
535
+ ldapUrl: z2.string().url().nullable().optional(),
536
+ ldapBindDN: z2.string().nullable().optional(),
537
+ ldapSearchBase: z2.string().nullable().optional(),
538
+ deleteMergedBranches: z2.boolean().optional(),
539
+ enforceConventionalCommits: z2.boolean().optional(),
540
+ maxPersonalProjectsPerUser: z2.number().int().min(0).optional(),
541
+ logoUrl: z2.string().url().nullable().optional(),
542
+ accentColor: z2.string().regex(/^#[0-9A-Fa-f]{6}$/, "Invalid hex color format. Expected #RRGGBB").nullable().optional(),
543
+ tenantName: z2.string().max(255).nullable().optional()
544
+ });
545
+ var InviteUserInputSchema = z2.object({
546
+ organizationId: z2.string().regex(/^org_[a-zA-Z0-9]+$/),
547
+ email: z2.string().email(),
548
+ role: z2.nativeEnum(UserRole).default(UserRole.MEMBER),
549
+ tags: z2.array(z2.string()).default([])
550
+ });
551
+ var AssignUserTagsInputSchema = z2.object({
552
+ userId: z2.string().regex(/^usr_[a-zA-Z0-9]+$/),
553
+ tags: z2.array(z2.string()).min(0)
554
+ });
555
+ var InviteCollaboratorInputSchema = z2.object({
556
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
557
+ email: z2.string().email()
558
+ });
559
+ var PublishProjectInputSchema = z2.object({
560
+ projectId: z2.string().regex(/^prj_[a-zA-Z0-9]+$/),
561
+ transferOwnership: z2.boolean().default(false),
562
+ tags: z2.array(z2.string()).min(1)
563
+ });
564
+ var GenerateApiKeyInputSchema = z2.object({
565
+ name: z2.string().min(1).max(100),
566
+ expiresInDays: z2.number().int().min(1).max(365).default(90),
567
+ permissions: z2.nativeEnum(ApiKeyPermission).default(ApiKeyPermission.WRITE)
568
+ });
569
+ var RevokeApiKeyInputSchema = z2.object({
570
+ keyId: z2.string().regex(/^key_[a-zA-Z0-9]+$/)
571
+ });
572
+ var LoginInputSchema = z2.object({
573
+ email: z2.string().email(),
574
+ password: z2.string().min(8).max(255)
575
+ });
576
+ var RegisterInputSchema = z2.object({
577
+ email: z2.string().email(),
578
+ password: z2.string().min(8).max(255),
579
+ name: z2.string().min(1).max(255),
580
+ organizationSlug: z2.string().min(1).max(100).regex(/^[a-z0-9-]+$/).optional()
581
+ });
582
+
583
+ // ../../packages/core/dist/logging/metrics.js
584
+ var metrics = /* @__PURE__ */ new Map();
585
+ function labelsToKey(labels) {
586
+ if (!labels || Object.keys(labels).length === 0)
587
+ return "";
588
+ return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}="${v}"`).join(",");
46
589
  }
47
- async function performLdapAuth(email, password, config) {
48
- const ldapjs = await import("ldapjs");
49
- return new Promise((resolve) => {
50
- const client = ldapjs.createClient({
51
- url: config.url,
52
- timeout: 5e3,
53
- connectTimeout: 1e4
54
- });
55
- client.on("error", (err) => {
56
- console.error("LDAP connection error:", err.message);
57
- resolve(null);
58
- });
59
- const usernameAttr = "mail";
60
- const searchFilter = `(${usernameAttr}=${ldapEscape(email)})`;
61
- const searchOptions = {
62
- filter: searchFilter,
63
- scope: "sub",
64
- attributes: ["dn", "mail", "cn", "displayName", "givenName", "sn"]
65
- };
66
- if (config.bindDN) {
67
- client.bind(config.bindDN, "", (bindErr) => {
68
- if (bindErr) {
69
- console.error("LDAP service bind failed:", bindErr.message);
70
- client.unbind();
71
- resolve(null);
72
- return;
73
- }
74
- searchAndBind(client, config.searchBase, searchOptions, password, resolve);
75
- });
76
- } else {
77
- searchAndBind(client, config.searchBase, searchOptions, password, resolve);
590
+ function createCounter(name, help) {
591
+ const data = {
592
+ name,
593
+ type: "counter",
594
+ help,
595
+ values: /* @__PURE__ */ new Map()
596
+ };
597
+ metrics.set(name, data);
598
+ return {
599
+ inc(labels, value = 1) {
600
+ const key = labelsToKey(labels);
601
+ const current = data.values.get(key) || 0;
602
+ data.values.set(key, current + value);
78
603
  }
79
- });
604
+ };
80
605
  }
81
- function searchAndBind(client, searchBase, searchOptions, password, resolve) {
82
- client.search(searchBase, searchOptions, (searchErr, searchRes) => {
83
- if (searchErr) {
84
- console.error("LDAP search error:", searchErr.message);
85
- client.unbind();
86
- resolve(null);
87
- return;
606
+ function createGauge(name, help) {
607
+ const data = {
608
+ name,
609
+ type: "gauge",
610
+ help,
611
+ values: /* @__PURE__ */ new Map()
612
+ };
613
+ metrics.set(name, data);
614
+ return {
615
+ set(labels, value) {
616
+ const key = labelsToKey(labels);
617
+ data.values.set(key, value);
618
+ },
619
+ inc(labels, value = 1) {
620
+ const key = labelsToKey(labels);
621
+ const current = data.values.get(key) || 0;
622
+ data.values.set(key, current + value);
623
+ },
624
+ dec(labels, value = 1) {
625
+ const key = labelsToKey(labels);
626
+ const current = data.values.get(key) || 0;
627
+ data.values.set(key, current - value);
88
628
  }
89
- let userEntry = null;
90
- searchRes.on("searchEntry", (entry) => {
91
- const dn = entry.dn.toString();
92
- const attrs = entry.attributes;
93
- const mail = getAttrValue(attrs, "mail");
94
- const displayName = getAttrValue(attrs, "displayName");
95
- const cn = getAttrValue(attrs, "cn");
96
- const givenName = getAttrValue(attrs, "givenName");
97
- const sn = getAttrValue(attrs, "sn");
98
- const name = displayName || cn || [givenName, sn].filter(Boolean).join(" ") || mail;
99
- userEntry = {
100
- email: mail || "",
101
- name: name || "",
102
- dn
103
- };
104
- });
105
- searchRes.on("error", (err) => {
106
- console.error("LDAP search result error:", err.message);
107
- client.unbind();
108
- resolve(null);
109
- });
110
- searchRes.on("end", () => {
111
- if (!userEntry) {
112
- client.unbind();
113
- resolve(null);
114
- return;
115
- }
116
- const userDn = userEntry.dn;
117
- const foundUser = userEntry;
118
- client.bind(userDn, password, (authErr) => {
119
- client.unbind();
120
- if (authErr) {
121
- console.error("LDAP user bind failed:", authErr.message);
122
- resolve(null);
123
- return;
629
+ };
630
+ }
631
+ function createHistogram(name, help, buckets = [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]) {
632
+ const data = {
633
+ name,
634
+ type: "histogram",
635
+ help,
636
+ values: /* @__PURE__ */ new Map(),
637
+ buckets
638
+ };
639
+ metrics.set(name, data);
640
+ return {
641
+ observe(labels, value) {
642
+ const baseKey = labelsToKey(labels);
643
+ const sumKey = `${baseKey}|sum`;
644
+ const countKey = `${baseKey}|count`;
645
+ data.values.set(sumKey, (data.values.get(sumKey) || 0) + value);
646
+ data.values.set(countKey, (data.values.get(countKey) || 0) + 1);
647
+ for (const bucket of buckets) {
648
+ const bucketKey = `${baseKey}|le="${bucket}"`;
649
+ if (value <= bucket) {
650
+ data.values.set(bucketKey, (data.values.get(bucketKey) || 0) + 1);
124
651
  }
125
- resolve(foundUser);
126
- });
127
- });
128
- });
652
+ }
653
+ const infKey = `${baseKey}|le="+Inf"`;
654
+ data.values.set(infKey, (data.values.get(infKey) || 0) + 1);
655
+ }
656
+ };
129
657
  }
130
- function getAttrValue(attrs, name) {
131
- const attr = attrs.find((a) => a.type.toLowerCase() === name.toLowerCase());
132
- if (!attr || !attr.values || attr.values.length === 0) {
133
- return void 0;
134
- }
135
- const val = attr.values[0];
136
- if (typeof val === "string")
137
- return val;
138
- if (val && typeof val === "object" && "toString" in val) {
139
- return val.toString();
658
+ var httpRequestsTotal = createCounter("mtaap_http_requests_total", "Total number of HTTP requests");
659
+ var httpRequestDuration = createHistogram("mtaap_http_request_duration_seconds", "HTTP request duration in seconds");
660
+ var activeUsers = createGauge("mtaap_active_users", "Number of active users");
661
+ var tasksTotal = createCounter("mtaap_tasks_total", "Total number of tasks by state");
662
+ var taskStateChanges = createCounter("mtaap_task_state_changes_total", "Total number of task state changes");
663
+ var httpErrorsTotal = createCounter("mtaap_http_errors_total", "Total number of HTTP errors");
664
+ var httpActiveConnections = createGauge("mtaap_http_active_connections", "Number of active HTTP connections");
665
+ var newSignupsTotal = createCounter("mtaap_new_signups_total", "Total number of new user signups");
666
+ var loginSuccessTotal = createCounter("mtaap_login_success_total", "Total number of successful logins");
667
+ var loginFailureTotal = createCounter("mtaap_login_failure_total", "Total number of failed logins");
668
+ var dbConnectionPoolActive = createGauge("mtaap_db_connection_pool_active", "Number of active database connections");
669
+ var dbConnectionPoolIdle = createGauge("mtaap_db_connection_pool_idle", "Number of idle database connections");
670
+ var dbConnectionPoolMax = createGauge("mtaap_db_connection_pool_max", "Maximum number of database connections");
671
+ var dbQueryDuration = createHistogram("mtaap_db_query_duration_seconds", "Database query duration in seconds");
672
+ var dbSlowQueriesTotal = createCounter("mtaap_db_slow_queries_total", "Total number of slow database queries (>1s)");
673
+ var dbErrorsTotal = createCounter("mtaap_db_errors_total", "Total number of database errors");
674
+ var tasksCreatedTotal = createCounter("mtaap_tasks_created_total", "Total number of tasks created");
675
+ var tasksAssignedTotal = createCounter("mtaap_tasks_assigned_total", "Total number of tasks assigned");
676
+ var tasksCompletedTotal = createCounter("mtaap_tasks_completed_total", "Total number of tasks completed");
677
+ var tasksByState = createGauge("mtaap_tasks_by_state", "Number of tasks by state");
678
+
679
+ // ../../packages/core/dist/logging/performance-monitor.js
680
+ var MAX_SAMPLES = 1e3;
681
+ var ALERT_COOLDOWN_MS = 5 * 60 * 1e3;
682
+ var DEFAULT_THRESHOLDS = {
683
+ api: {
684
+ p50: 100,
685
+ p95: 500,
686
+ p99: 1e3
687
+ },
688
+ db: {
689
+ p95: 100,
690
+ p99: 500
691
+ },
692
+ webvitals: {
693
+ FCP: 2e3,
694
+ LCP: 2500,
695
+ FID: 100,
696
+ CLS: 0.1
140
697
  }
141
- return void 0;
698
+ };
699
+ function cloneThresholds() {
700
+ return Object.fromEntries(Object.entries(DEFAULT_THRESHOLDS).map(([category, metrics2]) => [
701
+ category,
702
+ { ...metrics2 }
703
+ ]));
142
704
  }
143
- function ldapEscape(str) {
144
- return str.replace(/[\\*()]/g, (char) => `\\${char.charCodeAt(0).toString(16)}`);
705
+ function labelsToKey2(labels) {
706
+ if (!labels || Object.keys(labels).length === 0)
707
+ return "";
708
+ return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}="${value}"`).join(",");
145
709
  }
146
- async function getOrganizationLdapConfig(organizationSlug) {
147
- const org = await prisma.organization.findUnique({
148
- where: { slug: organizationSlug },
149
- include: { settings: true }
150
- });
151
- if (!org) {
152
- return null;
153
- }
154
- return {
155
- enabled: org.settings?.ldapEnabled ?? false,
156
- organizationId: org.id
157
- };
710
+ function percentile(sortedValues, percentileValue) {
711
+ if (sortedValues.length === 0)
712
+ return 0;
713
+ const rank = Math.ceil(percentileValue / 100 * sortedValues.length);
714
+ const index = Math.min(Math.max(rank - 1, 0), sortedValues.length - 1);
715
+ return sortedValues[index];
158
716
  }
159
- async function findOrCreateLdapUser(ldapUser, organizationId) {
160
- let user = await prisma.user.findUnique({
161
- where: { email: ldapUser.email }
162
- });
163
- if (!user) {
164
- const crypto = await import("crypto");
165
- const randomPassword = crypto.randomBytes(32).toString("hex");
166
- const bcrypt = await import("bcryptjs");
167
- const passwordHash = await bcrypt.hash(randomPassword, 10);
168
- user = await prisma.user.create({
169
- data: {
170
- email: ldapUser.email,
171
- name: ldapUser.name,
172
- passwordHash,
173
- role: UserRole.MEMBER
174
- }
175
- });
717
+ var CircularBuffer = class {
718
+ capacity;
719
+ values = [];
720
+ index = 0;
721
+ size = 0;
722
+ constructor(capacity) {
723
+ this.capacity = capacity;
176
724
  }
177
- const membership = await prisma.organizationUser.findFirst({
178
- where: {
179
- userId: user.id,
180
- organizationId
725
+ add(value) {
726
+ if (this.size < this.capacity) {
727
+ this.values.push(value);
728
+ this.size += 1;
729
+ this.index = this.size % this.capacity;
730
+ return;
181
731
  }
182
- });
183
- if (!membership) {
184
- const subscription = await prisma.subscription.findUnique({
185
- where: { organizationId }
186
- });
187
- if (subscription && subscription.seats > 0) {
188
- const currentSeats = await prisma.organizationUser.count({
189
- where: { organizationId }
190
- });
191
- if (currentSeats >= subscription.seats) {
192
- throw new Error("No available seats in organization subscription");
193
- }
732
+ this.values[this.index] = value;
733
+ this.index = (this.index + 1) % this.capacity;
734
+ }
735
+ getValues() {
736
+ if (this.size < this.capacity) {
737
+ return this.values.slice(0, this.size);
194
738
  }
195
- await prisma.organizationUser.create({
196
- data: {
197
- userId: user.id,
198
- organizationId,
199
- roleId: UserRole.MEMBER
200
- }
201
- });
739
+ return this.values.slice();
202
740
  }
203
- return {
204
- id: user.id,
205
- email: user.email,
206
- name: user.name
207
- };
208
- }
209
-
210
- // ../../packages/auth/dist/nextauth.js
211
- var THIRTY_DAYS_IN_SECONDS = 30 * 24 * 60 * 60;
212
- var authConfig = {
213
- providers: [
214
- Credentials({
215
- name: "credentials",
216
- credentials: {
217
- email: { label: "Email", type: "email" },
218
- password: { label: "Password", type: "password" },
219
- organizationSlug: { label: "Organization", type: "text" }
220
- },
221
- async authorize(credentials) {
222
- const parsed = z.object({
223
- email: z.string().email(),
224
- password: z.string().min(8),
225
- organizationSlug: z.string().optional()
226
- }).safeParse(credentials);
227
- if (!parsed.success) {
228
- return null;
229
- }
230
- const { email, password, organizationSlug } = parsed.data;
231
- if (organizationSlug) {
232
- const ldapConfig = await getOrganizationLdapConfig(organizationSlug);
233
- if (ldapConfig?.enabled) {
234
- const ldapUser = await authenticateWithLdap(email, password, ldapConfig.organizationId);
235
- if (ldapUser) {
236
- const user2 = await findOrCreateLdapUser(ldapUser, ldapConfig.organizationId);
237
- return {
238
- id: user2.id,
239
- email: user2.email,
240
- name: user2.name,
241
- role: UserRole.MEMBER,
242
- organizationId: ldapConfig.organizationId
243
- };
244
- }
245
- return null;
246
- }
247
- }
248
- const whereClause = {};
249
- if (organizationSlug) {
250
- whereClause.organization = {
251
- slug: organizationSlug
741
+ };
742
+ var PerformanceMonitor = class {
743
+ samples = /* @__PURE__ */ new Map();
744
+ thresholds = cloneThresholds();
745
+ alertCallback;
746
+ lastAlertTimestamps = /* @__PURE__ */ new Map();
747
+ recordTiming(category, name, durationMs, labels) {
748
+ if (!Number.isFinite(durationMs))
749
+ return;
750
+ const categoryMap = this.getCategoryMap(category);
751
+ const nameMap = this.getNameMap(categoryMap, name);
752
+ const labelKey = labelsToKey2(labels);
753
+ const buffer = nameMap.get(labelKey) ?? new CircularBuffer(MAX_SAMPLES);
754
+ buffer.add(durationMs);
755
+ nameMap.set(labelKey, buffer);
756
+ }
757
+ getPercentiles(category, name) {
758
+ const samples = this.collectSamples(category, name);
759
+ if (samples.length === 0) {
760
+ return { p50: 0, p95: 0, p99: 0 };
761
+ }
762
+ const sorted = [...samples].sort((a, b) => a - b);
763
+ return {
764
+ p50: percentile(sorted, 50),
765
+ p95: percentile(sorted, 95),
766
+ p99: percentile(sorted, 99)
767
+ };
768
+ }
769
+ checkThresholds() {
770
+ const alerts = [];
771
+ const now = Date.now();
772
+ const callbackAlerts = [];
773
+ for (const [category, nameMap] of this.samples) {
774
+ const thresholds = this.thresholds[category];
775
+ if (!thresholds)
776
+ continue;
777
+ for (const name of nameMap.keys()) {
778
+ const percentiles = this.getPercentiles(category, name);
779
+ for (const [metric, threshold] of Object.entries(thresholds)) {
780
+ const value = this.resolveMetricValue(metric, name, percentiles);
781
+ if (value === void 0 || value <= threshold)
782
+ continue;
783
+ const alert = {
784
+ category,
785
+ name,
786
+ metric,
787
+ value,
788
+ threshold
252
789
  };
253
- }
254
- const user = await prisma.user.findUnique({
255
- where: { email },
256
- include: {
257
- organizations: {
258
- where: whereClause,
259
- take: 1
260
- }
790
+ alerts.push(alert);
791
+ const alertKey = `${category}|${name}|${metric}`;
792
+ const lastAlertTime = this.lastAlertTimestamps.get(alertKey);
793
+ if (!lastAlertTime || now - lastAlertTime >= ALERT_COOLDOWN_MS) {
794
+ this.lastAlertTimestamps.set(alertKey, now);
795
+ callbackAlerts.push(alert);
261
796
  }
262
- });
263
- if (!user) {
264
- return null;
265
- }
266
- const bcrypt = await import("bcryptjs");
267
- const isValid = await bcrypt.compare(password, user.passwordHash);
268
- if (!isValid) {
269
- return null;
270
797
  }
271
- const orgUser = user.organizations?.[0];
272
- const role = orgUser ? orgUser.roleId : UserRole.MEMBER;
273
- return {
274
- id: user.id,
275
- email: user.email,
276
- name: user.name,
277
- role,
278
- organizationId: orgUser?.organizationId
279
- };
280
798
  }
281
- })
282
- ],
283
- session: {
284
- strategy: "jwt",
285
- maxAge: THIRTY_DAYS_IN_SECONDS
286
- },
287
- pages: {
288
- signIn: "/auth/signin",
289
- error: "/auth/error"
290
- },
291
- callbacks: {
292
- async jwt({ token, user }) {
293
- if (user) {
294
- token.id = user.id;
295
- token.role = user.role;
296
- token.organizationId = user.organizationId;
799
+ }
800
+ if (callbackAlerts.length > 0 && this.alertCallback) {
801
+ this.alertCallback(callbackAlerts);
802
+ }
803
+ return alerts;
804
+ }
805
+ setAlertCallback(callback) {
806
+ this.alertCallback = callback;
807
+ }
808
+ setThreshold(category, metric, value) {
809
+ if (!this.thresholds[category]) {
810
+ this.thresholds[category] = {};
811
+ }
812
+ this.thresholds[category][metric] = value;
813
+ }
814
+ collectSamples(category, name) {
815
+ const categoryMap = this.samples.get(category);
816
+ if (!categoryMap)
817
+ return [];
818
+ const entries = name ? [[name, categoryMap.get(name)]] : Array.from(categoryMap.entries());
819
+ const samples = [];
820
+ for (const [, labelMap] of entries) {
821
+ if (!labelMap)
822
+ continue;
823
+ for (const buffer of labelMap.values()) {
824
+ samples.push(...buffer.getValues());
297
825
  }
298
- return token;
299
- },
300
- async session({ session, token }) {
301
- if (token) {
302
- session.user = {
303
- ...session.user,
304
- id: token.id,
305
- role: token.role,
306
- organizationId: token.organizationId
307
- };
826
+ }
827
+ return samples;
828
+ }
829
+ resolveMetricValue(metric, name, percentiles) {
830
+ if (metric === "p50")
831
+ return percentiles.p50;
832
+ if (metric === "p95")
833
+ return percentiles.p95;
834
+ if (metric === "p99")
835
+ return percentiles.p99;
836
+ if (metric === name)
837
+ return percentiles.p95;
838
+ return void 0;
839
+ }
840
+ getCategoryMap(category) {
841
+ const existing = this.samples.get(category);
842
+ if (existing)
843
+ return existing;
844
+ const created = /* @__PURE__ */ new Map();
845
+ this.samples.set(category, created);
846
+ return created;
847
+ }
848
+ getNameMap(categoryMap, name) {
849
+ const existing = categoryMap.get(name);
850
+ if (existing)
851
+ return existing;
852
+ const created = /* @__PURE__ */ new Map();
853
+ categoryMap.set(name, created);
854
+ return created;
855
+ }
856
+ };
857
+ var defaultMonitor = new PerformanceMonitor();
858
+ function recordTiming(category, name, durationMs, labels) {
859
+ defaultMonitor.recordTiming(category, name, durationMs, labels);
860
+ }
861
+
862
+ // ../../packages/core/dist/logging/error-tracker.js
863
+ var NoOpErrorTracker = class {
864
+ captureError(error, context) {
865
+ console.error("Error captured:", error.message, context);
866
+ }
867
+ captureException(error, context) {
868
+ console.error("Exception captured:", error, context);
869
+ }
870
+ captureMessage(message, level, context) {
871
+ console[level === "warning" ? "warn" : level](`Message captured [${level}]:`, message, context);
872
+ }
873
+ setUser(user) {
874
+ console.log("User set:", user);
875
+ }
876
+ clearUser() {
877
+ console.log("User cleared");
878
+ }
879
+ };
880
+ var errorTrackerInstance = new NoOpErrorTracker();
881
+
882
+ // ../../packages/db/dist/index.js
883
+ __reExport(dist_exports, client_star2);
884
+ import * as client_star2 from "@prisma/client";
885
+ var prisma2 = client_default.$extends({
886
+ query: {
887
+ async $allOperations({ args, model, operation, query }) {
888
+ const start = Date.now();
889
+ try {
890
+ return await query(args);
891
+ } finally {
892
+ const durationMs = Date.now() - start;
893
+ const modelLabel = model ?? "raw";
894
+ recordTiming("db", operation, durationMs, { model: modelLabel });
895
+ dbQueryDuration.observe({ operation }, durationMs / 1e3);
896
+ if (durationMs > 1e3) {
897
+ dbSlowQueriesTotal.inc({ operation });
898
+ }
308
899
  }
309
- return session;
310
900
  }
311
901
  }
902
+ });
903
+
904
+ // ../../packages/auth/dist/api-key.js
905
+ var API_KEY_PERMISSION_RANK = {
906
+ [ApiKeyPermission.READ]: 1,
907
+ [ApiKeyPermission.WRITE]: 2,
908
+ [ApiKeyPermission.ADMIN]: 3
312
909
  };
910
+ async function hashApiKey(apiKey) {
911
+ const crypto = await import("crypto");
912
+ return crypto.createHash("sha256").update(apiKey).digest("hex");
913
+ }
313
914
  async function validateApiKey(apiKey) {
314
915
  const keyHash = await hashApiKey(apiKey);
315
- const keyRecord = await prisma.apiKey.findFirst({
916
+ const keyRecord = await prisma2.apiKey.findFirst({
316
917
  where: {
317
918
  keyHash,
318
919
  revoked: false
@@ -333,7 +934,7 @@ async function validateApiKey(apiKey) {
333
934
  if (!keyRecord || keyRecord.expiresAt && keyRecord.expiresAt < /* @__PURE__ */ new Date()) {
334
935
  return null;
335
936
  }
336
- await prisma.apiKey.update({
937
+ await prisma2.apiKey.update({
337
938
  where: { id: keyRecord.id },
338
939
  data: { lastUsedAt: /* @__PURE__ */ new Date() }
339
940
  });
@@ -341,30 +942,19 @@ async function validateApiKey(apiKey) {
341
942
  return {
342
943
  user: keyRecord.user,
343
944
  organization: orgUser?.organization,
344
- apiKey: keyRecord
945
+ apiKey: {
946
+ id: keyRecord.id,
947
+ name: keyRecord.name,
948
+ // Cast Prisma enum to @mtaap/core enum (same values, different types)
949
+ permissions: keyRecord.permissions,
950
+ expiresAt: keyRecord.expiresAt,
951
+ lastUsedAt: keyRecord.lastUsedAt
952
+ }
345
953
  };
346
954
  }
347
- var API_KEY_PERMISSION_RANK = {
348
- [ApiKeyPermission.READ]: 1,
349
- [ApiKeyPermission.WRITE]: 2,
350
- [ApiKeyPermission.ADMIN]: 3
351
- };
352
- async function hashApiKey(apiKey) {
353
- const crypto = await import("crypto");
354
- return crypto.createHash("sha256").update(apiKey).digest("hex");
355
- }
356
-
357
- // ../../packages/auth/dist/stateMachine.js
358
- var VALID_TRANSITIONS = {
359
- [TaskState.BACKLOG]: [TaskState.READY],
360
- [TaskState.READY]: [TaskState.IN_PROGRESS],
361
- [TaskState.IN_PROGRESS]: [TaskState.REVIEW],
362
- [TaskState.REVIEW]: [TaskState.DONE, TaskState.IN_PROGRESS],
363
- [TaskState.DONE]: []
364
- };
365
955
 
366
956
  // src/version.ts
367
- var VERSION = "0.1.2";
957
+ var VERSION2 = "0.1.3";
368
958
 
369
959
  // ../../packages/git/dist/github.js
370
960
  import { Octokit } from "octokit";
@@ -665,7 +1255,7 @@ async function getAuthenticatedUser(apiKey) {
665
1255
  }
666
1256
  async function ensureAccessControl(projectId, userId, organizationId) {
667
1257
  if (!organizationId) {
668
- const project = await prisma.project.findUnique({
1258
+ const project = await prisma2.project.findUnique({
669
1259
  where: { id: projectId },
670
1260
  include: { owner: true }
671
1261
  });
@@ -675,7 +1265,7 @@ async function ensureAccessControl(projectId, userId, organizationId) {
675
1265
  );
676
1266
  }
677
1267
  } else {
678
- const project = await prisma.project.findUnique({
1268
+ const project = await prisma2.project.findUnique({
679
1269
  where: { id: projectId },
680
1270
  include: { organization: true }
681
1271
  });
@@ -684,11 +1274,11 @@ async function ensureAccessControl(projectId, userId, organizationId) {
684
1274
  "Access denied: You do not have permission to access this project"
685
1275
  );
686
1276
  }
687
- const userTags = await prisma.userTag.findMany({
1277
+ const userTags = await prisma2.userTag.findMany({
688
1278
  where: { userId },
689
1279
  include: { tag: true }
690
1280
  });
691
- const projectTags = await prisma.projectTag.findMany({
1281
+ const projectTags = await prisma2.projectTag.findMany({
692
1282
  where: { projectId },
693
1283
  include: { tag: true }
694
1284
  });
@@ -719,7 +1309,7 @@ function slugify(text, maxLength = 50) {
719
1309
  async function createMCPServer() {
720
1310
  const server = new McpServer({
721
1311
  name: "mtaap",
722
- version: VERSION
1312
+ version: VERSION2
723
1313
  });
724
1314
  const apiKey = process.env.MTAAP_API_KEY;
725
1315
  if (!apiKey) {
@@ -1072,7 +1662,7 @@ async function createMCPServer() {
1072
1662
  type: "text",
1073
1663
  text: JSON.stringify(
1074
1664
  {
1075
- version: VERSION,
1665
+ version: VERSION2,
1076
1666
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
1077
1667
  },
1078
1668
  null,
@@ -1103,7 +1693,7 @@ async function listProjects(userId, organizationId, workspaceType = "ALL") {
1103
1693
  include: { tag: true }
1104
1694
  };
1105
1695
  }
1106
- const projects = await prisma.project.findMany({
1696
+ const projects = await prisma2.project.findMany({
1107
1697
  where,
1108
1698
  include,
1109
1699
  orderBy: { updatedAt: "desc" }
@@ -1137,7 +1727,7 @@ async function listTasks(userId, organizationId, projectId, state, assigneeId) {
1137
1727
  if (assigneeId) {
1138
1728
  where.assigneeId = assigneeId;
1139
1729
  }
1140
- const tasks = await prisma.task.findMany({
1730
+ const tasks = await prisma2.task.findMany({
1141
1731
  where,
1142
1732
  include: {
1143
1733
  project: true,
@@ -1149,7 +1739,7 @@ async function listTasks(userId, organizationId, projectId, state, assigneeId) {
1149
1739
  });
1150
1740
  const formattedTasks = await Promise.all(
1151
1741
  tasks.map(async (task) => {
1152
- const acceptanceCriteria = await prisma.acceptanceCriterion.findMany({
1742
+ const acceptanceCriteria = await prisma2.acceptanceCriterion.findMany({
1153
1743
  where: { taskId: task.id },
1154
1744
  orderBy: { order: "asc" }
1155
1745
  });
@@ -1191,7 +1781,7 @@ async function listTasks(userId, organizationId, projectId, state, assigneeId) {
1191
1781
  return formattedTasks;
1192
1782
  }
1193
1783
  async function getTaskWithChecks(taskId, userId, organizationId) {
1194
- const task = await prisma.task.findUnique({
1784
+ const task = await prisma2.task.findUnique({
1195
1785
  where: { id: taskId },
1196
1786
  include: {
1197
1787
  project: {
@@ -1222,7 +1812,7 @@ async function getTaskWithChecks(taskId, userId, organizationId) {
1222
1812
  throw new Error("Task not found");
1223
1813
  }
1224
1814
  if (organizationId && task.project?.organizationId !== organizationId) {
1225
- const userTags = await prisma.userTag.findMany({
1815
+ const userTags = await prisma2.userTag.findMany({
1226
1816
  where: { userId },
1227
1817
  include: { tag: true }
1228
1818
  });
@@ -1295,7 +1885,7 @@ async function getTaskWithChecks(taskId, userId, organizationId) {
1295
1885
  }
1296
1886
  async function assignTask(projectId, taskId, userId, organizationId, expectedState = TaskState.READY) {
1297
1887
  await ensureAccessControl(projectId, userId, organizationId);
1298
- const task = await prisma.task.findUnique({
1888
+ const task = await prisma2.task.findUnique({
1299
1889
  where: { id: taskId },
1300
1890
  include: { project: true }
1301
1891
  });
@@ -1328,7 +1918,7 @@ async function assignTask(projectId, taskId, userId, organizationId, expectedSta
1328
1918
  if (!createResult.success) {
1329
1919
  throw new Error(`Failed to create branch: ${createResult.error}`);
1330
1920
  }
1331
- const updatedTask = await prisma.task.update({
1921
+ const updatedTask = await prisma2.task.update({
1332
1922
  where: { id: taskId },
1333
1923
  data: {
1334
1924
  state: TaskState.IN_PROGRESS,
@@ -1345,7 +1935,7 @@ async function assignTask(projectId, taskId, userId, organizationId, expectedSta
1345
1935
  };
1346
1936
  }
1347
1937
  async function updateProgress(taskId, userId, statusMessage, completedCheckpointIds, _currentCheckpointIndex) {
1348
- const task = await prisma.task.findUnique({
1938
+ const task = await prisma2.task.findUnique({
1349
1939
  where: { id: taskId }
1350
1940
  });
1351
1941
  if (!task) {
@@ -1355,7 +1945,7 @@ async function updateProgress(taskId, userId, statusMessage, completedCheckpoint
1355
1945
  throw new Error("You are not assigned to this task");
1356
1946
  }
1357
1947
  if (completedCheckpointIds && completedCheckpointIds.length > 0) {
1358
- await prisma.acceptanceCriterion.updateMany({
1948
+ await prisma2.acceptanceCriterion.updateMany({
1359
1949
  where: {
1360
1950
  id: { in: completedCheckpointIds }
1361
1951
  },
@@ -1366,7 +1956,7 @@ async function updateProgress(taskId, userId, statusMessage, completedCheckpoint
1366
1956
  });
1367
1957
  }
1368
1958
  if (statusMessage) {
1369
- await prisma.progressUpdate.create({
1959
+ await prisma2.progressUpdate.create({
1370
1960
  data: {
1371
1961
  taskId,
1372
1962
  userId,
@@ -1375,7 +1965,7 @@ async function updateProgress(taskId, userId, statusMessage, completedCheckpoint
1375
1965
  }
1376
1966
  });
1377
1967
  }
1378
- const updatedTask = await prisma.task.update({
1968
+ const updatedTask = await prisma2.task.update({
1379
1969
  where: { id: taskId },
1380
1970
  data: {
1381
1971
  updatedAt: /* @__PURE__ */ new Date()
@@ -1388,7 +1978,7 @@ async function updateProgress(taskId, userId, statusMessage, completedCheckpoint
1388
1978
  }
1389
1979
  async function completeTask(projectId, taskId, userId, organizationId, pullRequestTitle, pullRequestBody) {
1390
1980
  await ensureAccessControl(projectId, userId, organizationId);
1391
- const task = await prisma.task.findUnique({
1981
+ const task = await prisma2.task.findUnique({
1392
1982
  where: { id: taskId },
1393
1983
  include: { project: true }
1394
1984
  });
@@ -1411,7 +2001,7 @@ async function completeTask(projectId, taskId, userId, organizationId, pullReque
1411
2001
  throw new Error("Invalid repository URL");
1412
2002
  }
1413
2003
  const github = getGitHubClient(task.project?.organizationId || "");
1414
- const acceptanceCriteria = await prisma.acceptanceCriterion.findMany({
2004
+ const acceptanceCriteria = await prisma2.acceptanceCriterion.findMany({
1415
2005
  where: { taskId },
1416
2006
  orderBy: { order: "asc" }
1417
2007
  });
@@ -1435,7 +2025,7 @@ ${acceptanceChecklist}`;
1435
2025
  if (!createResult.success) {
1436
2026
  throw new Error(`Failed to create PR: ${createResult.error}`);
1437
2027
  }
1438
- const updatedTask = await prisma.task.update({
2028
+ const updatedTask = await prisma2.task.update({
1439
2029
  where: { id: taskId },
1440
2030
  data: {
1441
2031
  state: TaskState.REVIEW,
@@ -1469,7 +2059,7 @@ async function checkActiveTask() {
1469
2059
  };
1470
2060
  }
1471
2061
  async function reportTaskError(taskId, userId, errorType, errorMessage, _context) {
1472
- const task = await prisma.task.findUnique({
2062
+ const task = await prisma2.task.findUnique({
1473
2063
  where: { id: taskId }
1474
2064
  });
1475
2065
  if (!task) {
@@ -1478,7 +2068,7 @@ async function reportTaskError(taskId, userId, errorType, errorMessage, _context
1478
2068
  if (task.assigneeId !== userId) {
1479
2069
  throw new Error("You are not assigned to this task");
1480
2070
  }
1481
- const updatedTask = await prisma.task.update({
2071
+ const updatedTask = await prisma2.task.update({
1482
2072
  where: { id: taskId },
1483
2073
  data: {
1484
2074
  errorType,
@@ -1491,7 +2081,7 @@ async function reportTaskError(taskId, userId, errorType, errorMessage, _context
1491
2081
  };
1492
2082
  }
1493
2083
  async function getProjectContext(projectId) {
1494
- const project = await prisma.project.findUnique({
2084
+ const project = await prisma2.project.findUnique({
1495
2085
  where: { id: projectId },
1496
2086
  include: {
1497
2087
  organization: {
@@ -1525,7 +2115,7 @@ async function getProjectContext(projectId) {
1525
2115
  stack = Object.keys(deps).slice(0, 20);
1526
2116
  }
1527
2117
  }
1528
- const recentCompletedTasks = await prisma.task.findMany({
2118
+ const recentCompletedTasks = await prisma2.task.findMany({
1529
2119
  where: {
1530
2120
  project: {
1531
2121
  id: projectId
@@ -1561,7 +2151,7 @@ async function getProjectContext(projectId) {
1561
2151
  };
1562
2152
  }
1563
2153
  async function addTaskNote(taskId, userId, content) {
1564
- const task = await prisma.task.findUnique({
2154
+ const task = await prisma2.task.findUnique({
1565
2155
  where: { id: taskId }
1566
2156
  });
1567
2157
  if (!task) {
@@ -1570,7 +2160,7 @@ async function addTaskNote(taskId, userId, content) {
1570
2160
  if (task.assigneeId !== userId) {
1571
2161
  throw new Error("You are not assigned to this task");
1572
2162
  }
1573
- const note = await prisma.taskNote.create({
2163
+ const note = await prisma2.taskNote.create({
1574
2164
  data: {
1575
2165
  taskId,
1576
2166
  userId,
@@ -1583,7 +2173,7 @@ async function addTaskNote(taskId, userId, content) {
1583
2173
  };
1584
2174
  }
1585
2175
  async function abandonTask(taskId, projectId, userId, deleteBranch) {
1586
- const task = await prisma.task.findUnique({
2176
+ const task = await prisma2.task.findUnique({
1587
2177
  where: { id: taskId },
1588
2178
  include: { project: true }
1589
2179
  });
@@ -1616,7 +2206,7 @@ async function abandonTask(taskId, projectId, userId, deleteBranch) {
1616
2206
  }
1617
2207
  }
1618
2208
  const newState = task.state === TaskState.IN_PROGRESS ? TaskState.READY : task.state;
1619
- const updatedTask = await prisma.task.update({
2209
+ const updatedTask = await prisma2.task.update({
1620
2210
  where: { id: taskId },
1621
2211
  data: {
1622
2212
  state: newState,
@@ -1634,7 +2224,7 @@ async function abandonTask(taskId, projectId, userId, deleteBranch) {
1634
2224
  };
1635
2225
  }
1636
2226
  async function createPersonalProject(userId, name, description, repositoryUrl) {
1637
- const user = await prisma.user.findUnique({
2227
+ const user = await prisma2.user.findUnique({
1638
2228
  where: { id: userId },
1639
2229
  include: { organizations: true }
1640
2230
  });
@@ -1654,7 +2244,7 @@ async function createPersonalProject(userId, name, description, repositoryUrl) {
1654
2244
  if (!branchInfo) {
1655
2245
  throw new Error("Could not get repository branch info");
1656
2246
  }
1657
- const project = await prisma.project.create({
2247
+ const project = await prisma2.project.create({
1658
2248
  data: {
1659
2249
  name,
1660
2250
  description,
@@ -1675,4 +2265,4 @@ async function createPersonalProject(userId, name, description, repositoryUrl) {
1675
2265
  export {
1676
2266
  createMCPServer
1677
2267
  };
1678
- //# sourceMappingURL=chunk-4ILBJI7A.js.map
2268
+ //# sourceMappingURL=chunk-7YL3QGGO.js.map