@snapback/cli 3.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node --no-warnings=ExperimentalWarning
2
- import { isRedisAvailable, getCache, setCache, deleteCache } from './chunk-GQ73B37K.js';
3
- import { snapshots, snapshotFiles, agentSuggestions, quarantineEvents, postAcceptOutcomes, policyEvaluations, loops, feedback, telemetryEvents, telemetryIdempotencyKeys, combinedSchema, user, aiChat, organization, member, invitation, purchase, session, account, verification, passkey, db, userAttributions, subscriptions, trials, pioneers, usageLimits, creditsLedger, mcpObservations, mcpToolInvocations, extensionSyncState, pioneerActions, sagas, apiKeys, TIER_STALENESS_THRESHOLD_MS, WORKSPACE_LINK_TTL_MS, patterns, closeDatabaseConnection, checkDatabaseConnection } from './chunk-LIBBDBW5.js';
2
+ import { snapshots, snapshotFiles, agentSuggestions, quarantineEvents, postAcceptOutcomes, policyEvaluations, loops, feedback, telemetryEvents, telemetryIdempotencyKeys, combinedSchema, user, aiChat, organization, member, invitation, purchase, session, account, verification, passkey, db, userAttributions, subscriptions, trials, usageLimits, creditsLedger, mcpObservations, mcpToolInvocations, extensionSyncState, sagas, apiKeys, TIER_STALENESS_THRESHOLD_MS, WORKSPACE_LINK_TTL_MS, patterns, closeDatabaseConnection, checkDatabaseConnection } from './chunk-BWWPGNZ5.js';
3
+ import { isRedisAvailable, getCache, setCache, deleteCache } from './chunk-YVZXPBSV.js';
4
4
  import { logger } from './chunk-PL4HF4M2.js';
5
- import { shouldMergeAttribution, createLogger, LogLevel, isFeatureAvailableAtTier, getTierFeatures, getTierLimit, EventBus, generateIdempotencyKey, getActionPoints, calculatePioneerTier, PIONEER_TIER_THRESHOLDS, isFirstTimeAction, TIER_UPGRADE_SAGA } from './chunk-WS36HDEU.js';
5
+ import { shouldMergeAttribution, createLogger, LogLevel, isFeatureAvailableAtTier, getTierFeatures, getTierLimit, TIER_UPGRADE_SAGA } from './chunk-NOWJBG6X.js';
6
6
  import { __name } from './chunk-7ADPL4Q3.js';
7
7
  import { eq, desc, and, gte, lte, sum, gt, sql, inArray } from 'drizzle-orm';
8
8
  import { z } from 'zod';
@@ -780,7 +780,7 @@ async function getCapabilities(userId, options = {}) {
780
780
  throw new Error("Database not available");
781
781
  }
782
782
  let capabilities = await db.query.userDetectionCapabilities.findFirst({
783
- where: /* @__PURE__ */ __name((cap, { eq: eq16 }) => eq16(cap.userId, validatedUserId), "where")
783
+ where: /* @__PURE__ */ __name((cap, { eq: eq15 }) => eq15(cap.userId, validatedUserId), "where")
784
784
  });
785
785
  if (!capabilities) {
786
786
  const [created] = await db.insert(userDetectionCapabilities).values({
@@ -1003,7 +1003,7 @@ async function getCapabilityAuditHistory(userId, limit = 50) {
1003
1003
  return [];
1004
1004
  }
1005
1005
  return await db.query.capabilityAudit.findMany({
1006
- where: /* @__PURE__ */ __name((audit, { eq: eq16 }) => eq16(audit.userId, userId), "where"),
1006
+ where: /* @__PURE__ */ __name((audit, { eq: eq15 }) => eq15(audit.userId, userId), "where"),
1007
1007
  orderBy: /* @__PURE__ */ __name((audit, { desc: desc4 }) => desc4(audit.createdAt), "orderBy"),
1008
1008
  limit
1009
1009
  });
@@ -1170,7 +1170,7 @@ async function getOrganizationById(id) {
1170
1170
  throw new Error("Database not available");
1171
1171
  }
1172
1172
  return await db.query.organization.findFirst({
1173
- where: /* @__PURE__ */ __name((org, { eq: eq16 }) => eq16(org.id, id), "where"),
1173
+ where: /* @__PURE__ */ __name((org, { eq: eq15 }) => eq15(org.id, id), "where"),
1174
1174
  with: {
1175
1175
  members: true,
1176
1176
  invitations: true
@@ -1185,7 +1185,7 @@ async function getOrganizationsWithMembers(userId) {
1185
1185
  return await db.query.organization.findMany({
1186
1186
  with: {
1187
1187
  members: {
1188
- where: /* @__PURE__ */ __name((member3, { eq: eq16 }) => eq16(member3.userId, userId), "where"),
1188
+ where: /* @__PURE__ */ __name((member3, { eq: eq15 }) => eq15(member3.userId, userId), "where"),
1189
1189
  with: {
1190
1190
  user: true
1191
1191
  }
@@ -1199,7 +1199,7 @@ async function getInvitationById(id) {
1199
1199
  throw new Error("Database not available");
1200
1200
  }
1201
1201
  return await db.query.invitation.findFirst({
1202
- where: /* @__PURE__ */ __name((invitation2, { eq: eq16 }) => eq16(invitation2.id, id), "where"),
1202
+ where: /* @__PURE__ */ __name((invitation2, { eq: eq15 }) => eq15(invitation2.id, id), "where"),
1203
1203
  with: {
1204
1204
  organization: true
1205
1205
  }
@@ -1211,7 +1211,7 @@ async function getOrganizationBySlug(slug) {
1211
1211
  throw new Error("Database not available");
1212
1212
  }
1213
1213
  return await db.query.organization.findFirst({
1214
- where: /* @__PURE__ */ __name((org, { eq: eq16 }) => eq16(org.slug, slug), "where")
1214
+ where: /* @__PURE__ */ __name((org, { eq: eq15 }) => eq15(org.slug, slug), "where")
1215
1215
  });
1216
1216
  }
1217
1217
  __name(getOrganizationBySlug, "getOrganizationBySlug");
@@ -1220,7 +1220,7 @@ async function getOrganizationMembership(organizationId, userId) {
1220
1220
  throw new Error("Database not available");
1221
1221
  }
1222
1222
  return await db.query.member.findFirst({
1223
- where: /* @__PURE__ */ __name((member3, { and: and6, eq: eq16 }) => and6(eq16(member3.organizationId, organizationId), eq16(member3.userId, userId)), "where"),
1223
+ where: /* @__PURE__ */ __name((member3, { and: and5, eq: eq15 }) => and5(eq15(member3.organizationId, organizationId), eq15(member3.userId, userId)), "where"),
1224
1224
  with: {
1225
1225
  organization: true
1226
1226
  }
@@ -1232,7 +1232,7 @@ async function getOrganizationWithPurchasesAndMembersCount(organizationId) {
1232
1232
  throw new Error("Database not available");
1233
1233
  }
1234
1234
  return await db.query.organization.findFirst({
1235
- where: /* @__PURE__ */ __name((org, { eq: eq16 }) => eq16(org.id, organizationId), "where"),
1235
+ where: /* @__PURE__ */ __name((org, { eq: eq15 }) => eq15(org.id, organizationId), "where"),
1236
1236
  with: {
1237
1237
  purchases: true
1238
1238
  },
@@ -1247,7 +1247,7 @@ async function getPendingInvitationByEmail(email) {
1247
1247
  throw new Error("Database not available");
1248
1248
  }
1249
1249
  return await db.query.invitation.findFirst({
1250
- where: /* @__PURE__ */ __name((invitation2, { and: and6, eq: eq16 }) => and6(eq16(invitation2.email, email), eq16(invitation2.status, "pending")), "where")
1250
+ where: /* @__PURE__ */ __name((invitation2, { and: and5, eq: eq15 }) => and5(eq15(invitation2.email, email), eq15(invitation2.status, "pending")), "where")
1251
1251
  });
1252
1252
  }
1253
1253
  __name(getPendingInvitationByEmail, "getPendingInvitationByEmail");
@@ -1508,7 +1508,7 @@ async function getPurchasesByOrganizationId(organizationId) {
1508
1508
  throw new Error("Database not available");
1509
1509
  }
1510
1510
  return db.query.purchase.findMany({
1511
- where: /* @__PURE__ */ __name((purchase3, { eq: eq16 }) => eq16(purchase3.organizationId, organizationId), "where")
1511
+ where: /* @__PURE__ */ __name((purchase3, { eq: eq15 }) => eq15(purchase3.organizationId, organizationId), "where")
1512
1512
  });
1513
1513
  }
1514
1514
  __name(getPurchasesByOrganizationId, "getPurchasesByOrganizationId");
@@ -1517,7 +1517,7 @@ async function getPurchasesByUserId(userId) {
1517
1517
  throw new Error("Database not available");
1518
1518
  }
1519
1519
  return db.query.purchase.findMany({
1520
- where: /* @__PURE__ */ __name((purchase3, { eq: eq16 }) => eq16(purchase3.userId, userId), "where")
1520
+ where: /* @__PURE__ */ __name((purchase3, { eq: eq15 }) => eq15(purchase3.userId, userId), "where")
1521
1521
  });
1522
1522
  }
1523
1523
  __name(getPurchasesByUserId, "getPurchasesByUserId");
@@ -1526,7 +1526,7 @@ async function getPurchaseById(id) {
1526
1526
  throw new Error("Database not available");
1527
1527
  }
1528
1528
  return db.query.purchase.findFirst({
1529
- where: /* @__PURE__ */ __name((purchase3, { eq: eq16 }) => eq16(purchase3.id, id), "where")
1529
+ where: /* @__PURE__ */ __name((purchase3, { eq: eq15 }) => eq15(purchase3.id, id), "where")
1530
1530
  });
1531
1531
  }
1532
1532
  __name(getPurchaseById, "getPurchaseById");
@@ -1535,7 +1535,7 @@ async function getPurchaseBySubscriptionId(subscriptionId) {
1535
1535
  throw new Error("Database not available");
1536
1536
  }
1537
1537
  return db.query.purchase.findFirst({
1538
- where: /* @__PURE__ */ __name((purchase3, { eq: eq16 }) => eq16(purchase3.subscriptionId, subscriptionId), "where")
1538
+ where: /* @__PURE__ */ __name((purchase3, { eq: eq15 }) => eq15(purchase3.subscriptionId, subscriptionId), "where")
1539
1539
  });
1540
1540
  }
1541
1541
  __name(getPurchaseBySubscriptionId, "getPurchaseBySubscriptionId");
@@ -1611,7 +1611,7 @@ async function getUserById(id) {
1611
1611
  throw new Error("Database not available");
1612
1612
  }
1613
1613
  return await db.query.user.findFirst({
1614
- where: /* @__PURE__ */ __name((user3, { eq: eq16 }) => eq16(user3.id, id), "where")
1614
+ where: /* @__PURE__ */ __name((user3, { eq: eq15 }) => eq15(user3.id, id), "where")
1615
1615
  });
1616
1616
  }
1617
1617
  __name(getUserById, "getUserById");
@@ -1620,7 +1620,7 @@ async function getUserByEmail(email) {
1620
1620
  throw new Error("Database not available");
1621
1621
  }
1622
1622
  return await db.query.user.findFirst({
1623
- where: /* @__PURE__ */ __name((user3, { eq: eq16 }) => eq16(user3.email, email), "where")
1623
+ where: /* @__PURE__ */ __name((user3, { eq: eq15 }) => eq15(user3.email, email), "where")
1624
1624
  });
1625
1625
  }
1626
1626
  __name(getUserByEmail, "getUserByEmail");
@@ -1653,7 +1653,7 @@ async function getAccountById(id) {
1653
1653
  throw new Error("Database not available");
1654
1654
  }
1655
1655
  return await db.query.account.findFirst({
1656
- where: /* @__PURE__ */ __name((account3, { eq: eq16 }) => eq16(account3.id, id), "where")
1656
+ where: /* @__PURE__ */ __name((account3, { eq: eq15 }) => eq15(account3.id, id), "where")
1657
1657
  });
1658
1658
  }
1659
1659
  __name(getAccountById, "getAccountById");
@@ -1714,7 +1714,7 @@ async function getWorkspaceLinkById(workspaceId) {
1714
1714
  }
1715
1715
  const validatedId = workspaceIdSchema.parse(workspaceId);
1716
1716
  return await db.query.workspaceLinks.findFirst({
1717
- where: /* @__PURE__ */ __name((link, { eq: eq16 }) => eq16(link.workspaceId, validatedId), "where")
1717
+ where: /* @__PURE__ */ __name((link, { eq: eq15 }) => eq15(link.workspaceId, validatedId), "where")
1718
1718
  });
1719
1719
  }
1720
1720
  __name(getWorkspaceLinkById, "getWorkspaceLinkById");
@@ -1728,7 +1728,7 @@ async function resolveTierByWorkspaceId(workspaceId) {
1728
1728
  try {
1729
1729
  const validatedId = workspaceIdSchema.parse(workspaceId);
1730
1730
  const link = await db.query.workspaceLinks.findFirst({
1731
- where: /* @__PURE__ */ __name((link2, { eq: eq16 }) => eq16(link2.workspaceId, validatedId), "where")
1731
+ where: /* @__PURE__ */ __name((link2, { eq: eq15 }) => eq15(link2.workspaceId, validatedId), "where")
1732
1732
  });
1733
1733
  if (!link) {
1734
1734
  return {
@@ -1854,7 +1854,7 @@ async function getWorkspaceLinksByUserId(userId) {
1854
1854
  throw new Error("Database not available");
1855
1855
  }
1856
1856
  return await db.query.workspaceLinks.findMany({
1857
- where: /* @__PURE__ */ __name((link, { eq: eq16 }) => eq16(link.userId, userId), "where"),
1857
+ where: /* @__PURE__ */ __name((link, { eq: eq15 }) => eq15(link.userId, userId), "where"),
1858
1858
  orderBy: /* @__PURE__ */ __name((link, { desc: desc4 }) => desc4(link.lastSeenAt), "orderBy")
1859
1859
  });
1860
1860
  }
@@ -2047,7 +2047,7 @@ var extensionSessions = pgTable("extension_sessions", {
2047
2047
  // ../../packages/platform/dist/db/test-utils.js
2048
2048
  var testInTransaction = /* @__PURE__ */ __name((testName, testFn) => {
2049
2049
  return async () => {
2050
- const module = await import('./client-62E3L6DW.js');
2050
+ const module = await import('./client-RHDS6NOB.js');
2051
2051
  const db2 = module.db;
2052
2052
  try {
2053
2053
  await testFn(db2);
@@ -2071,7 +2071,7 @@ var truncateAllTables = /* @__PURE__ */ __name(async () => {
2071
2071
  console.warn("truncateAllTables is not implemented - tests may have side effects");
2072
2072
  }, "truncateAllTables");
2073
2073
  var getTestDb = /* @__PURE__ */ __name(async () => {
2074
- const module = await import('./client-62E3L6DW.js');
2074
+ const module = await import('./client-RHDS6NOB.js');
2075
2075
  return module.db;
2076
2076
  }, "getTestDb");
2077
2077
  var closeTestDb = /* @__PURE__ */ __name(async () => {
@@ -2757,16 +2757,12 @@ var EntitlementsServiceImpl = class {
2757
2757
  try {
2758
2758
  const [subscription] = await db.select().from(subscriptions).where(eq(subscriptions.userId, userId)).limit(1);
2759
2759
  const [trial] = await db.select().from(trials).where(and(eq(trials.userId, userId), eq(trials.status, "active"))).limit(1);
2760
- const [pioneer] = await db.select().from(pioneers).where(eq(pioneers.userId, userId)).limit(1);
2761
- let tier = subscription?.plan || "free";
2762
- if (pioneer?.tier === "founding_pioneer" && (tier === "free" || tier === "pro")) {
2763
- tier = "pro";
2764
- }
2760
+ const tier = subscription?.plan || "free";
2765
2761
  const [usageData] = subscription ? await db.select().from(usageLimits).where(eq(usageLimits.subscriptionId, subscription.id)).orderBy(desc(usageLimits.month)).limit(1) : [
2766
2762
  null
2767
2763
  ];
2768
2764
  const creditBalance = await this.calculateCreditBalance(userId, tier, subscription);
2769
- const entitlements = this.buildEntitlements(userId, tier, trial || null, pioneer || null, subscription || null, usageData || null, creditBalance);
2765
+ const entitlements = this.buildEntitlements(userId, tier, trial || null, null, subscription || null, usageData || null, creditBalance);
2770
2766
  if (isRedisAvailable()) {
2771
2767
  await setCache(`entitlements:${userId}`, entitlements, 60);
2772
2768
  }
@@ -2994,7 +2990,7 @@ var EntitlementsServiceImpl = class {
2994
2990
  * Calculate points needed to reach next tier
2995
2991
  */
2996
2992
  calculatePointsToNext(currentTier, totalPoints) {
2997
- const PIONEER_TIER_THRESHOLDS2 = {
2993
+ const PIONEER_TIER_THRESHOLDS = {
2998
2994
  pioneer: 0,
2999
2995
  active_pioneer: 1,
3000
2996
  contributing_pioneer: 2,
@@ -3014,7 +3010,7 @@ var EntitlementsServiceImpl = class {
3014
3010
  if (!nextTier) {
3015
3011
  return 0;
3016
3012
  }
3017
- const threshold = PIONEER_TIER_THRESHOLDS2[nextTier];
3013
+ const threshold = PIONEER_TIER_THRESHOLDS[nextTier];
3018
3014
  return threshold !== void 0 ? threshold - totalPoints : 0;
3019
3015
  }
3020
3016
  /**
@@ -3317,359 +3313,6 @@ function getMCPService() {
3317
3313
  return instance;
3318
3314
  }
3319
3315
  __name(getMCPService, "getMCPService");
3320
- var PioneerServiceImpl = class {
3321
- static {
3322
- __name(this, "PioneerServiceImpl");
3323
- }
3324
- idempotencyCache = /* @__PURE__ */ new Map();
3325
- IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1e3;
3326
- eventBus;
3327
- // In-memory user points storage (stub - will be replaced with database)
3328
- userPoints = /* @__PURE__ */ new Map();
3329
- actionHistory = /* @__PURE__ */ new Map();
3330
- constructor(eventBus) {
3331
- this.eventBus = eventBus || new EventBus();
3332
- }
3333
- /**
3334
- * Record a Pioneer action and award points with idempotency guarantee
3335
- * Uses Redis for distributed idempotency across multiple instances
3336
- */
3337
- async recordAction(userId, action, metadata, idempotencyKey) {
3338
- const key = idempotencyKey || generateIdempotencyKey(userId, action, metadata);
3339
- const redisKey = `pioneer:idempotency:${key}`;
3340
- if (isRedisAvailable()) {
3341
- const cached = await getCache(redisKey);
3342
- if (cached) {
3343
- return {
3344
- ...cached,
3345
- message: "Action already recorded (idempotent response from Redis)",
3346
- originalTimestamp: cached.timestamp
3347
- };
3348
- }
3349
- }
3350
- const memoryCached = this.idempotencyCache.get(key);
3351
- if (memoryCached && Date.now() - memoryCached.timestamp < this.IDEMPOTENCY_TTL_MS) {
3352
- return {
3353
- ...memoryCached.result,
3354
- message: "Action already recorded (idempotent response from memory)",
3355
- originalTimestamp: memoryCached.result.timestamp
3356
- };
3357
- }
3358
- if (!db) {
3359
- return this.recordActionInMemory(userId, action, metadata, key);
3360
- }
3361
- try {
3362
- const [existingAction] = await db.select().from(pioneerActions).where(and(eq(pioneerActions.actionType, action), eq(pioneerActions.metadata, {
3363
- idempotencyKey: key
3364
- }))).limit(1);
3365
- if (existingAction) {
3366
- const [pioneer2] = await db.select().from(pioneers).where(eq(pioneers.userId, userId)).limit(1);
3367
- const result2 = {
3368
- success: true,
3369
- action,
3370
- pointsAwarded: 0,
3371
- newTotalPoints: pioneer2?.totalPoints || 0,
3372
- tierChanged: false,
3373
- newTier: null,
3374
- benefitsUnlocked: [],
3375
- timestamp: existingAction.createdAt,
3376
- message: "Action already recorded (idempotent response)",
3377
- idempotencyKey: key,
3378
- originalTimestamp: existingAction.createdAt
3379
- };
3380
- this.idempotencyCache.set(key, {
3381
- result: result2,
3382
- timestamp: Date.now()
3383
- });
3384
- return result2;
3385
- }
3386
- const eligibilityCheck = await this.checkActionEligibility(userId, action, metadata);
3387
- if (!eligibilityCheck.eligible) {
3388
- const [pioneer2] = await db.select().from(pioneers).where(eq(pioneers.userId, userId)).limit(1);
3389
- return {
3390
- success: false,
3391
- action,
3392
- pointsAwarded: 0,
3393
- newTotalPoints: pioneer2?.totalPoints || 0,
3394
- tierChanged: false,
3395
- newTier: null,
3396
- benefitsUnlocked: [],
3397
- timestamp: /* @__PURE__ */ new Date(),
3398
- message: eligibilityCheck.reason
3399
- };
3400
- }
3401
- const [pioneer] = await db.select().from(pioneers).where(eq(pioneers.userId, userId)).limit(1);
3402
- const pointsToAward = getActionPoints(action);
3403
- const currentPoints = pioneer?.totalPoints || 0;
3404
- const newTotalPoints = currentPoints + pointsToAward;
3405
- const oldTier = calculatePioneerTier(currentPoints);
3406
- const newTier = calculatePioneerTier(newTotalPoints);
3407
- const tierChanged = oldTier !== newTier;
3408
- if (!pioneer) {
3409
- throw new Error(`Pioneer profile not found for user ${userId}`);
3410
- }
3411
- await db.update(pioneers).set({
3412
- totalPoints: newTotalPoints,
3413
- tier: newTier,
3414
- updatedAt: /* @__PURE__ */ new Date()
3415
- }).where(eq(pioneers.id, pioneer.id));
3416
- await db.insert(pioneerActions).values({
3417
- pioneerId: pioneer.id,
3418
- actionType: action,
3419
- points: pointsToAward,
3420
- verified: true,
3421
- metadata: {
3422
- ...metadata,
3423
- idempotencyKey: key
3424
- },
3425
- createdAt: /* @__PURE__ */ new Date()
3426
- });
3427
- const benefitsUnlocked = [];
3428
- if (tierChanged) {
3429
- benefitsUnlocked.push(`Pioneer ${newTier} tier reached`);
3430
- if (newTier === "founding_pioneer") {
3431
- benefitsUnlocked.push("Lifetime Pro access unlocked");
3432
- }
3433
- }
3434
- const result = {
3435
- success: true,
3436
- action,
3437
- pointsAwarded: pointsToAward,
3438
- newTotalPoints,
3439
- tierChanged,
3440
- newTier: tierChanged ? newTier : null,
3441
- benefitsUnlocked,
3442
- timestamp: /* @__PURE__ */ new Date(),
3443
- idempotencyKey: key
3444
- };
3445
- if (isRedisAvailable()) {
3446
- await setCache(redisKey, result, 86400);
3447
- }
3448
- this.idempotencyCache.set(key, {
3449
- result,
3450
- timestamp: Date.now()
3451
- });
3452
- this.eventBus.emit("pioneer:action_recorded", {
3453
- userId,
3454
- action,
3455
- points: pointsToAward,
3456
- totalPoints: newTotalPoints,
3457
- idempotencyKey: key
3458
- });
3459
- if (tierChanged) {
3460
- this.eventBus.emit("pioneer:tier_changed", {
3461
- userId,
3462
- oldTier,
3463
- newTier,
3464
- totalPoints: newTotalPoints,
3465
- benefitsUnlocked
3466
- });
3467
- }
3468
- return result;
3469
- } catch (error) {
3470
- console.error(`[Pioneer] Error recording action for user ${userId}:`, error);
3471
- return this.recordActionInMemory(userId, action, metadata, key);
3472
- }
3473
- }
3474
- /**
3475
- * Check if user has achieved a milestone
3476
- */
3477
- async checkMilestone(userId, milestone) {
3478
- const currentPoints = this.getUserPoints(userId);
3479
- const milestones = {
3480
- first_10_snapshots: {
3481
- points: 100,
3482
- description: "Create 10 snapshots",
3483
- reward: "Explorer badge"
3484
- },
3485
- reach_active_pioneer: {
3486
- points: PIONEER_TIER_THRESHOLDS.active_pioneer,
3487
- description: "Reach Active Pioneer tier",
3488
- reward: "50% discount on Pro plan"
3489
- },
3490
- reach_founding_pioneer: {
3491
- points: PIONEER_TIER_THRESHOLDS.founding_pioneer,
3492
- description: "Reach Founding Pioneer tier",
3493
- reward: "Lifetime Pro access"
3494
- }
3495
- };
3496
- const milestoneData = milestones[milestone];
3497
- if (!milestoneData) {
3498
- return {
3499
- milestone,
3500
- achieved: false,
3501
- progress: 0,
3502
- description: "Unknown milestone"
3503
- };
3504
- }
3505
- const achieved = currentPoints >= milestoneData.points;
3506
- const progress = Math.min(currentPoints / milestoneData.points, 1);
3507
- return {
3508
- milestone,
3509
- achieved,
3510
- progress,
3511
- description: milestoneData.description,
3512
- reward: milestoneData.reward,
3513
- achievedAt: achieved ? /* @__PURE__ */ new Date() : void 0
3514
- };
3515
- }
3516
- /**
3517
- * Apply a Pioneer benefit to user's account
3518
- */
3519
- async applyBenefit(_userId, benefit) {
3520
- return {
3521
- success: true,
3522
- benefit,
3523
- message: `Benefit ${benefit.id} applied successfully`,
3524
- appliedAt: /* @__PURE__ */ new Date()
3525
- };
3526
- }
3527
- /**
3528
- * Get user's Pioneer status including points and tier
3529
- */
3530
- async getPioneerStatus(userId) {
3531
- const totalPoints = this.getUserPoints(userId);
3532
- if (totalPoints === 0) {
3533
- return null;
3534
- }
3535
- const tier = calculatePioneerTier(totalPoints);
3536
- const tierThresholds = Object.entries(PIONEER_TIER_THRESHOLDS).sort(([, a], [, b]) => a - b);
3537
- const currentTierIndex = tierThresholds.findIndex(([t]) => t === tier);
3538
- const nextTierEntry = tierThresholds[currentTierIndex + 1];
3539
- const nextTier = nextTierEntry ? nextTierEntry[0] : null;
3540
- const pointsToNext = nextTier ? PIONEER_TIER_THRESHOLDS[nextTier] - totalPoints : 0;
3541
- const discountPercent = tier === "founding_pioneer" ? 100 : tier === "contributing_pioneer" ? 75 : tier === "active_pioneer" ? 50 : 0;
3542
- return {
3543
- tier,
3544
- totalPoints,
3545
- pointsToNext,
3546
- nextTier,
3547
- discountPercent,
3548
- benefits: this.getTierBenefits(tier)
3549
- };
3550
- }
3551
- /**
3552
- * Get action history for a user
3553
- */
3554
- async getActionHistory(userId, limit = 50) {
3555
- const history = this.actionHistory.get(userId) || [];
3556
- return history.slice(-limit).reverse();
3557
- }
3558
- /**
3559
- * Check if user is eligible for an action
3560
- */
3561
- async checkActionEligibility(userId, action, _metadata) {
3562
- if (isFirstTimeAction(action)) {
3563
- const history = this.actionHistory.get(userId) || [];
3564
- const alreadyDone = history.some((record) => record.action === action);
3565
- if (alreadyDone) {
3566
- return {
3567
- eligible: false,
3568
- reason: `Action '${action}' not allowed: user has already completed this action`
3569
- };
3570
- }
3571
- }
3572
- if (action === "daily_snapshot") {
3573
- const history = this.actionHistory.get(userId) || [];
3574
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3575
- const doneToday = history.some((record) => {
3576
- const recordDate = record.recordedAt.toISOString().split("T")[0];
3577
- return record.action === action && recordDate === today;
3578
- });
3579
- if (doneToday) {
3580
- return {
3581
- eligible: false,
3582
- reason: "Daily snapshot already recorded for today"
3583
- };
3584
- }
3585
- }
3586
- return {
3587
- eligible: true
3588
- };
3589
- }
3590
- /**
3591
- * Get user's total points (stub - will query database)
3592
- */
3593
- getUserPoints(userId) {
3594
- return this.userPoints.get(userId) || 0;
3595
- }
3596
- /**
3597
- * Get benefits available at a tier
3598
- */
3599
- getTierBenefits(tier) {
3600
- const benefits = {
3601
- pioneer: [
3602
- "Pioneer badge",
3603
- "Community access"
3604
- ],
3605
- active_pioneer: [
3606
- "Pioneer badge",
3607
- "Community access",
3608
- "50% discount on Pro plan"
3609
- ],
3610
- contributing_pioneer: [
3611
- "Pioneer badge",
3612
- "Community access",
3613
- "75% discount on Pro plan",
3614
- "Priority support"
3615
- ],
3616
- founding_pioneer: [
3617
- "Pioneer badge",
3618
- "Community access",
3619
- "Lifetime Pro access",
3620
- "Priority support",
3621
- "Founding member recognition"
3622
- ]
3623
- };
3624
- return benefits[tier] || [];
3625
- }
3626
- /**
3627
- * Fallback: Record action in-memory (for graceful degradation)
3628
- */
3629
- recordActionInMemory(userId, action, metadata, key) {
3630
- const pointsToAward = getActionPoints(action);
3631
- const currentPoints = this.getUserPoints(userId);
3632
- const newTotalPoints = currentPoints + pointsToAward;
3633
- this.userPoints.set(userId, newTotalPoints);
3634
- const oldTier = calculatePioneerTier(currentPoints);
3635
- const newTier = calculatePioneerTier(newTotalPoints);
3636
- const tierChanged = oldTier !== newTier;
3637
- const actionRecord = {
3638
- action,
3639
- points: pointsToAward,
3640
- recordedAt: /* @__PURE__ */ new Date(),
3641
- metadata,
3642
- idempotencyKey: key
3643
- };
3644
- const history = this.actionHistory.get(userId) || [];
3645
- history.push(actionRecord);
3646
- this.actionHistory.set(userId, history);
3647
- const benefitsUnlocked = [];
3648
- if (tierChanged) {
3649
- benefitsUnlocked.push(`Pioneer ${newTier} tier reached`);
3650
- if (newTier === "founding_pioneer") {
3651
- benefitsUnlocked.push("Lifetime Pro access unlocked");
3652
- }
3653
- }
3654
- const result = {
3655
- success: true,
3656
- action,
3657
- pointsAwarded: pointsToAward,
3658
- newTotalPoints,
3659
- tierChanged,
3660
- newTier: tierChanged ? newTier : null,
3661
- benefitsUnlocked,
3662
- timestamp: /* @__PURE__ */ new Date(),
3663
- idempotencyKey: key
3664
- };
3665
- this.idempotencyCache.set(key, {
3666
- result,
3667
- timestamp: Date.now()
3668
- });
3669
- return result;
3670
- }
3671
- };
3672
- new PioneerServiceImpl();
3673
3316
  var SagaOrchestratorImpl = class {
3674
3317
  static {
3675
3318
  __name(this, "SagaOrchestratorImpl");
@@ -4429,4 +4072,4 @@ function createTierUpgradeSagaWithDeps(deps) {
4429
4072
  }
4430
4073
  __name(createTierUpgradeSagaWithDeps, "createTierUpgradeSagaWithDeps");
4431
4074
 
4432
- export { AccountSchema, AiChatSchema, AttributionServiceImpl, ENABLE_CAPTCHA, ENABLE_ENHANCED_2FA, ENABLE_MULTI_SESSION, ENABLE_SSO, EntitlementsServiceImpl, InvitationSchema, MCPService, MemberSchema, OrganizationSchema, OrganizationUpdateSchema, PasskeySchema, PioneerServiceImpl, PurchaseInsertSchema, PurchaseSchema, PurchaseUpdateSchema, SagaOrchestratorImpl, SessionSchema, SnapshotStoreDb, TelemetrySinkDb, TelemetrySinkDbAdapter, UserSchema, UserUpdateSchema, VerificationSchema, anonymizeEmail, anonymizeUserData, anonymizeUserId, appendFalsePositivePatterns, calculateDecayedWeight, cleanupExpiredData, clearCapabilityCache, closeTestDb, config, countAllOrganizations, countAllUsers, createPurchase, createTestUser, createTierUpgradeSagaWithDeps, createUser, createUserAccount, databaseService, deletePurchaseBySubscriptionId, deleteUserApiKeys, deleteUserData, exportUserData, extensionLinkTokens, extensionSessions, findSimilarPatterns, generateOrganizationSlug, getAccountById, getBaseUrl, getCacheMetrics, getCapabilities, getCapabilityAuditHistory, getInvitationById, getMCPService, getOrganizationById, getOrganizationBySlug, getOrganizationMembership, getOrganizationWithPurchasesAndMembersCount, getOrganizations, getOrganizationsWithMembers, getPendingInvitationByEmail, getPurchaseById, getPurchaseBySubscriptionId, getPurchasesByOrganizationId, getPurchasesByUserId, getTestDb, getUserByEmail, getUserById, getUserPrivacyPreferences, getUsers, getVectorStats, getWorkspaceLinkById, getWorkspaceLinksByUserId, handleTierDowngrade, handleTierUpgrade, healthCheck, incrementDetectionsAnalyzed, insertPatternWithEmbedding, invalidateCapabilityCache, isPgvectorEnabled, linkWorkspace, logAnonymizedEvent, logCapabilityAudit, mergeSignalIntoPattern, recordFalsePositiveSignal, resetCacheMetrics, resetCapabilities, resolveTierByWorkspaceId, sagaPersistence, sanitizeForLogging, searchSimilarPatterns, shouldRetainData, signalToPattern, testInTransaction, truncateAllTables, unlinkAllWorkspacesForUser, unlinkWorkspace, updateCapabilities, updateOrganization, updatePatternEmbedding, updatePurchase, updateUser, updateWorkspaceTier };
4075
+ export { AccountSchema, AiChatSchema, AttributionServiceImpl, ENABLE_CAPTCHA, ENABLE_ENHANCED_2FA, ENABLE_MULTI_SESSION, ENABLE_SSO, EntitlementsServiceImpl, InvitationSchema, MCPService, MemberSchema, OrganizationSchema, OrganizationUpdateSchema, PasskeySchema, PurchaseInsertSchema, PurchaseSchema, PurchaseUpdateSchema, SagaOrchestratorImpl, SessionSchema, SnapshotStoreDb, TelemetrySinkDb, TelemetrySinkDbAdapter, UserSchema, UserUpdateSchema, VerificationSchema, anonymizeEmail, anonymizeUserData, anonymizeUserId, appendFalsePositivePatterns, calculateDecayedWeight, cleanupExpiredData, clearCapabilityCache, closeTestDb, config, countAllOrganizations, countAllUsers, createPurchase, createTestUser, createTierUpgradeSagaWithDeps, createUser, createUserAccount, databaseService, deletePurchaseBySubscriptionId, deleteUserApiKeys, deleteUserData, exportUserData, extensionLinkTokens, extensionSessions, findSimilarPatterns, generateOrganizationSlug, getAccountById, getBaseUrl, getCacheMetrics, getCapabilities, getCapabilityAuditHistory, getInvitationById, getMCPService, getOrganizationById, getOrganizationBySlug, getOrganizationMembership, getOrganizationWithPurchasesAndMembersCount, getOrganizations, getOrganizationsWithMembers, getPendingInvitationByEmail, getPurchaseById, getPurchaseBySubscriptionId, getPurchasesByOrganizationId, getPurchasesByUserId, getTestDb, getUserByEmail, getUserById, getUserPrivacyPreferences, getUsers, getVectorStats, getWorkspaceLinkById, getWorkspaceLinksByUserId, handleTierDowngrade, handleTierUpgrade, healthCheck, incrementDetectionsAnalyzed, insertPatternWithEmbedding, invalidateCapabilityCache, isPgvectorEnabled, linkWorkspace, logAnonymizedEvent, logCapabilityAudit, mergeSignalIntoPattern, recordFalsePositiveSignal, resetCacheMetrics, resetCapabilities, resolveTierByWorkspaceId, sagaPersistence, sanitizeForLogging, searchSimilarPatterns, shouldRetainData, signalToPattern, testInTransaction, truncateAllTables, unlinkAllWorkspacesForUser, unlinkWorkspace, updateCapabilities, updateOrganization, updatePatternEmbedding, updatePurchase, updateUser, updateWorkspaceTier };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node --no-warnings=ExperimentalWarning
2
- import { createLogger, LogLevel } from './chunk-WS36HDEU.js';
2
+ import { createLogger, LogLevel } from './chunk-NOWJBG6X.js';
3
3
  import { __name } from './chunk-7ADPL4Q3.js';
4
4
  import { createClient } from 'redis';
5
5
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node --no-warnings=ExperimentalWarning
2
- export { checkDatabaseConnection, closeDatabaseConnection, combinedSchema, db, pool } from './chunk-LIBBDBW5.js';
3
- import './chunk-WS36HDEU.js';
2
+ export { checkDatabaseConnection, closeDatabaseConnection, combinedSchema, db, pool } from './chunk-BWWPGNZ5.js';
3
+ import './chunk-NOWJBG6X.js';
4
4
  import './chunk-5EOPYJ4Y.js';
5
5
  import './chunk-CBGOC6RV.js';
6
6
  import './chunk-7ADPL4Q3.js';
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node --no-warnings=ExperimentalWarning
2
+ export { AccountSchema, AiChatSchema, AttributionServiceImpl, EntitlementsServiceImpl, InvitationSchema, MCPService, MemberSchema, OrganizationSchema, OrganizationUpdateSchema, PasskeySchema, PurchaseInsertSchema, PurchaseSchema, PurchaseUpdateSchema, SagaOrchestratorImpl, SessionSchema, SnapshotStoreDb, TelemetrySinkDb, TelemetrySinkDbAdapter, UserSchema, UserUpdateSchema, VerificationSchema, anonymizeEmail, anonymizeUserData, anonymizeUserId, appendFalsePositivePatterns, calculateDecayedWeight, cleanupExpiredData, clearCapabilityCache, closeTestDb, countAllOrganizations, countAllUsers, createPurchase, createTestUser, createTierUpgradeSagaWithDeps, createUser, createUserAccount, databaseService, deletePurchaseBySubscriptionId, deleteUserApiKeys, deleteUserData, exportUserData, extensionLinkTokens, extensionSessions as extensionSessionsAuth, findSimilarPatterns, generateOrganizationSlug, getAccountById, getCacheMetrics, getCapabilities, getCapabilityAuditHistory, getInvitationById, getMCPService, getOrganizationById, getOrganizationBySlug, getOrganizationMembership, getOrganizationWithPurchasesAndMembersCount, getOrganizations, getOrganizationsWithMembers, getPendingInvitationByEmail, getPurchaseById, getPurchaseBySubscriptionId, getPurchasesByOrganizationId, getPurchasesByUserId, getTestDb, getUserByEmail, getUserById, getUserPrivacyPreferences, getUsers, getVectorStats, getWorkspaceLinkById, getWorkspaceLinksByUserId, handleTierDowngrade, handleTierUpgrade, healthCheck, incrementDetectionsAnalyzed, insertPatternWithEmbedding, invalidateCapabilityCache, isPgvectorEnabled, linkWorkspace, logAnonymizedEvent, logCapabilityAudit, mergeSignalIntoPattern, recordFalsePositiveSignal, resetCacheMetrics, resetCapabilities, resolveTierByWorkspaceId, sagaPersistence, sanitizeForLogging, searchSimilarPatterns, shouldRetainData, signalToPattern, testInTransaction, truncateAllTables, unlinkAllWorkspacesForUser, unlinkWorkspace, updateCapabilities, updateOrganization, updatePatternEmbedding, updatePurchase, updateUser, updateWorkspaceTier } from './chunk-V7B37PPD.js';
3
+ export { TOPUP_PACKS, account, activationCodeRedemptions, activationCodes, adminAuditLog, agentSuggestions, analysisEvents, apiKeyMetadata, apiKeyUsage, apiKeys, apiUsage, apiUsageLogs, burnInviteCode, checkDatabaseConnection, clientTokens, combinedSchema, creditJobTypeEnum, creditTopups, creditTransactionStatusEnum, creditTransactionTypeEnum, creditsLedger, db, deviceTrials, emailDeliveries, emailPreferences, extensionSessions, featureUsage, feedback, fileSnapshotSessions, fingerprints, getTopupPackDetails, inviteCodes, isValidPackSize, loops, mcpActivityEvents, mcpAggregatedLearnings, mcpSessions, member, newsletterSubscribers, orgDailyMetrics, organization, pendingApiKeys, policyEvaluations, pool, postAcceptOutcomes, purchase, rateLimitViolations, responseCache, retentionConfig, rollbackEvents, ruleViolations, postgres_exports as schema, securityEvents, snapbackSchema, snapshotFiles, snapshots, subscriptions, superAdmins, telemetryDailyStats, telemetryEvents, telemetryIdempotencyKeys, telemetryOutbox, topupStatusEnum, usageLimits, user, userProductMetrics, userSafetyProfiles, waitlist, waitlistAuditLogs, waitlistReferrals, waitlistTasks } from './chunk-BWWPGNZ5.js';
4
+ export { closeRedis, getRedisClient, initializeRedis, isRedisAvailable } from './chunk-YVZXPBSV.js';
5
+ import './chunk-BE3HNVSV.js';
6
+ import './chunk-PL4HF4M2.js';
7
+ import './chunk-NOWJBG6X.js';
8
+ import './chunk-5EOPYJ4Y.js';
9
+ import './chunk-CBGOC6RV.js';
10
+ import './chunk-7ADPL4Q3.js';
11
+
12
+ process.env.SNAPBACK_CLI='true';
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node --no-warnings=ExperimentalWarning
2
- export { AnalyticsEvents, CORRELATION_ANALYSES, CORRELATION_COHORTS, KEY_METRIC_ALERTS, OTelInstrumentationProvider, RETENTION_COHORTS, TelemetryClient, addSentryBreadcrumb, captureError, captureMessage, checkDatabaseConnection, checkErrorBudget, checkHttpService, checkRedisConnection, clearSentryUser, createAlert, createCohort, createGracefulShutdown, createHealthCheck, createSentryMiddleware, deleteAlert, deleteCohort, detectSurface, drainAndCloseServer, flushSentry, getAlerts, getAnalyticsEnv, getAnalyticsSuperProperties, getCohort, getCohortMembers, getCohorts, getCorrelationAnalysis, getDeploymentEnv, getEnvironmentInfo, getErrorRate, getMetrics, initSentry, isDevelopment, isProduction, neon_exports as neon, performCorrelationAnalysis, preStopDelay, prometheus_exports as prometheus, recordError, recordSuccess, registerKeyMetricAlerts, resetMetrics, setSentryUser, startSentryTransaction, toggleAlert, updateCohort } from './chunk-Q4VC7GND.js';
2
+ export { AnalyticsEvents, CORRELATION_ANALYSES, CORRELATION_COHORTS, KEY_METRIC_ALERTS, OTelInstrumentationProvider, RETENTION_COHORTS, TelemetryClient, addSentryBreadcrumb, captureError, captureMessage, checkDatabaseConnection, checkErrorBudget, checkHttpService, checkRedisConnection, clearSentryUser, createAlert, createCohort, createGracefulShutdown, createHealthCheck, createSentryMiddleware, deleteAlert, deleteCohort, detectSurface, drainAndCloseServer, flushSentry, getAlerts, getAnalyticsEnv, getAnalyticsSuperProperties, getCohort, getCohortMembers, getCohorts, getCorrelationAnalysis, getDeploymentEnv, getEnvironmentInfo, getErrorRate, getMetrics, initSentry, isDevelopment, isProduction, neon_exports as neon, performCorrelationAnalysis, preStopDelay, prometheus_exports as prometheus, recordError, recordSuccess, registerKeyMetricAlerts, resetMetrics, setSentryUser, startSentryTransaction, toggleAlert, updateCohort } from './chunk-BE3HNVSV.js';
3
3
  export { cache_exports as cache, logger, makeWatcher, resiliency_exports as resiliency } from './chunk-PL4HF4M2.js';
4
- export { LogLevel, NoOpInstrumentationProvider } from './chunk-WS36HDEU.js';
4
+ export { LogLevel, NoOpInstrumentationProvider } from './chunk-NOWJBG6X.js';
5
5
  import './chunk-5EOPYJ4Y.js';
6
6
  import './chunk-CBGOC6RV.js';
7
7
  import './chunk-7ADPL4Q3.js';