@vreko/cli 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.
Files changed (98) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +45 -0
  3. package/dist/CeremonyView-LQS7FTMK.js +134 -0
  4. package/dist/CeremonyView-LQS7FTMK.js.map +1 -0
  5. package/dist/InitApp-7K5DTYSW.js +1479 -0
  6. package/dist/InitApp-7K5DTYSW.js.map +1 -0
  7. package/dist/SkippedTestDetector-PJSKSOZR.js +7 -0
  8. package/dist/SkippedTestDetector-PJSKSOZR.js.map +1 -0
  9. package/dist/TuiApp-FX23XQBK.js +8 -0
  10. package/dist/TuiApp-FX23XQBK.js.map +1 -0
  11. package/dist/analysis-ABEO6RTN.js +8 -0
  12. package/dist/analysis-ABEO6RTN.js.map +1 -0
  13. package/dist/auth-XNBEBNPY.js +7669 -0
  14. package/dist/auth-XNBEBNPY.js.map +1 -0
  15. package/dist/ceremony-M7CXVBVA.js +45 -0
  16. package/dist/ceremony-M7CXVBVA.js.map +1 -0
  17. package/dist/chunk-A3QSZJPD.js +3147 -0
  18. package/dist/chunk-A3QSZJPD.js.map +1 -0
  19. package/dist/chunk-ASGZ5B6C.js +3969 -0
  20. package/dist/chunk-ASGZ5B6C.js.map +1 -0
  21. package/dist/chunk-DMXC2JTC.js +58 -0
  22. package/dist/chunk-DMXC2JTC.js.map +1 -0
  23. package/dist/chunk-EEBSK2IH.js +161 -0
  24. package/dist/chunk-EEBSK2IH.js.map +1 -0
  25. package/dist/chunk-EWOJGXRX.js +22 -0
  26. package/dist/chunk-EWOJGXRX.js.map +1 -0
  27. package/dist/chunk-F7GEJLP7.js +2389 -0
  28. package/dist/chunk-F7GEJLP7.js.map +1 -0
  29. package/dist/chunk-GOYL3F4T.js +605 -0
  30. package/dist/chunk-GOYL3F4T.js.map +1 -0
  31. package/dist/chunk-GRMRYWYS.js +17 -0
  32. package/dist/chunk-GRMRYWYS.js.map +1 -0
  33. package/dist/chunk-GSUGROXB.js +1951 -0
  34. package/dist/chunk-GSUGROXB.js.map +1 -0
  35. package/dist/chunk-H7773ONB.js +50 -0
  36. package/dist/chunk-H7773ONB.js.map +1 -0
  37. package/dist/chunk-HFQHU5LC.js +445 -0
  38. package/dist/chunk-HFQHU5LC.js.map +1 -0
  39. package/dist/chunk-IVHUBLJD.js +318 -0
  40. package/dist/chunk-IVHUBLJD.js.map +1 -0
  41. package/dist/chunk-KJWKY4L4.js +14 -0
  42. package/dist/chunk-KJWKY4L4.js.map +1 -0
  43. package/dist/chunk-MJVY2XUN.js +1793 -0
  44. package/dist/chunk-MJVY2XUN.js.map +1 -0
  45. package/dist/chunk-QWZVCJII.js +1797 -0
  46. package/dist/chunk-QWZVCJII.js.map +1 -0
  47. package/dist/chunk-VTSNRV3V.js +3237 -0
  48. package/dist/chunk-VTSNRV3V.js.map +1 -0
  49. package/dist/chunk-W5B4GTXR.js +1466 -0
  50. package/dist/chunk-W5B4GTXR.js.map +1 -0
  51. package/dist/chunk-WZEZLVOW.js +4995 -0
  52. package/dist/chunk-WZEZLVOW.js.map +1 -0
  53. package/dist/chunk-YPTTIXKC.js +199 -0
  54. package/dist/chunk-YPTTIXKC.js.map +1 -0
  55. package/dist/chunk-Z55UGM6X.js +6360 -0
  56. package/dist/chunk-Z55UGM6X.js.map +1 -0
  57. package/dist/chunk-ZIIRQODJ.js +110 -0
  58. package/dist/chunk-ZIIRQODJ.js.map +1 -0
  59. package/dist/chunk-ZSUQ4FMB.js +77 -0
  60. package/dist/chunk-ZSUQ4FMB.js.map +1 -0
  61. package/dist/client-JMTSZS3V.js +10 -0
  62. package/dist/client-JMTSZS3V.js.map +1 -0
  63. package/dist/deprecated-snap.js +19 -0
  64. package/dist/deprecated-snap.js.map +1 -0
  65. package/dist/dist-2KWBZFLA.js +14 -0
  66. package/dist/dist-2KWBZFLA.js.map +1 -0
  67. package/dist/dist-5ZYKNNU3.js +7 -0
  68. package/dist/dist-5ZYKNNU3.js.map +1 -0
  69. package/dist/dist-CP3RFHPI.js +11 -0
  70. package/dist/dist-CP3RFHPI.js.map +1 -0
  71. package/dist/gecko-53ITAGG6.js +56 -0
  72. package/dist/gecko-53ITAGG6.js.map +1 -0
  73. package/dist/guards-QAFC64NO.js +7 -0
  74. package/dist/guards-QAFC64NO.js.map +1 -0
  75. package/dist/index.js +57785 -0
  76. package/dist/index.js.map +1 -0
  77. package/dist/init-command-246JIVXM.js +7 -0
  78. package/dist/init-command-246JIVXM.js.map +1 -0
  79. package/dist/init-core-KAI7LCXZ.js +12 -0
  80. package/dist/init-core-KAI7LCXZ.js.map +1 -0
  81. package/dist/init-scan-RZNYDTUV.js +1919 -0
  82. package/dist/init-scan-RZNYDTUV.js.map +1 -0
  83. package/dist/local-service-adapter-6KNN6WQL.js +8 -0
  84. package/dist/local-service-adapter-6KNN6WQL.js.map +1 -0
  85. package/dist/secure-credentials-JXWAQLS2.js +306 -0
  86. package/dist/secure-credentials-JXWAQLS2.js.map +1 -0
  87. package/dist/tui-TPJPUS2R.js +111 -0
  88. package/dist/tui-TPJPUS2R.js.map +1 -0
  89. package/dist/vreko-dir-O3RLG7PI.js +8 -0
  90. package/dist/vreko-dir-O3RLG7PI.js.map +1 -0
  91. package/package.json +132 -0
  92. package/scripts/check-banned-words.ts +152 -0
  93. package/scripts/hooks/posttooluse-file-notify.sh +108 -0
  94. package/scripts/hooks/pretooluse-fragile-guard.sh +82 -0
  95. package/scripts/post-install-notice.js +24 -0
  96. package/scripts/postinstall.mjs +84 -0
  97. package/scripts/preuninstall.mjs +34 -0
  98. package/scripts/verify-jsx-transform.mjs +55 -0
@@ -0,0 +1,4995 @@
1
+ #!/usr/bin/env node
2
+ import { JsonRpcMessageSchema } from './chunk-VTSNRV3V.js';
3
+ import { __name } from './chunk-EWOJGXRX.js';
4
+ import { z } from 'zod';
5
+ import 'neverthrow';
6
+ import 'crypto';
7
+ import 'eventemitter2';
8
+ import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
9
+ import 'ts-pattern';
10
+
11
+ process.env.VREKO_CLI='true';process.env.NODE_NO_WARNINGS='1';
12
+
13
+ // ../../packages/contracts/dist/logger.js
14
+ var _loggerFactory = null;
15
+ function getLoggerFactory() {
16
+ return _loggerFactory;
17
+ }
18
+ __name(getLoggerFactory, "getLoggerFactory");
19
+ var LogLevel;
20
+ (function(LogLevel2) {
21
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
22
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
23
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
24
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
25
+ LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
26
+ })(LogLevel || (LogLevel = {}));
27
+ function createLogger(options) {
28
+ const { name, level = LogLevel.INFO, timestamps = false } = options;
29
+ return {
30
+ debug(messageOrObj, metaOrMsg) {
31
+ if (level <= LogLevel.DEBUG) ;
32
+ },
33
+ info(messageOrObj, metaOrMsg) {
34
+ if (level <= LogLevel.INFO) ;
35
+ },
36
+ warn(messageOrObj, metaOrMsg) {
37
+ if (level <= LogLevel.WARN) ;
38
+ },
39
+ error(messageOrObj, metaOrMsg) {
40
+ if (level <= LogLevel.ERROR) ;
41
+ }
42
+ };
43
+ }
44
+ __name(createLogger, "createLogger");
45
+
46
+ // ../../packages/contracts/dist/observability/InstrumentationProvider.js
47
+ var NoOpInstrumentationProvider = class _NoOpInstrumentationProvider {
48
+ static {
49
+ __name(this, "NoOpInstrumentationProvider");
50
+ }
51
+ static noopSpan = {
52
+ setAttribute: /* @__PURE__ */ __name(() => {
53
+ }, "setAttribute"),
54
+ setAttributes: /* @__PURE__ */ __name(() => {
55
+ }, "setAttributes"),
56
+ addEvent: /* @__PURE__ */ __name(() => {
57
+ }, "addEvent"),
58
+ setStatus: /* @__PURE__ */ __name(() => {
59
+ }, "setStatus"),
60
+ recordException: /* @__PURE__ */ __name(() => {
61
+ }, "recordException"),
62
+ end: /* @__PURE__ */ __name(() => {
63
+ }, "end"),
64
+ isRecording: /* @__PURE__ */ __name(() => false, "isRecording")
65
+ };
66
+ startSpan(_name, _options) {
67
+ return _NoOpInstrumentationProvider.noopSpan;
68
+ }
69
+ async withSpan(_name, fn, _options) {
70
+ return await fn(_NoOpInstrumentationProvider.noopSpan);
71
+ }
72
+ injectContext(_carrier) {
73
+ }
74
+ extractContext(_carrier) {
75
+ return null;
76
+ }
77
+ recordMetric(_name, _value, _attributes) {
78
+ }
79
+ recordEvent(_name, _attributes) {
80
+ }
81
+ async shutdown() {
82
+ }
83
+ };
84
+
85
+ // ../../packages/contracts/dist/constants/sensitive-patterns.js
86
+ var SENSITIVE_PATTERNS = [
87
+ // Environment / secrets
88
+ /\.env$/i,
89
+ /\.pem$/i,
90
+ /\.key$/i,
91
+ /secret/i,
92
+ /password/i,
93
+ /credential/i,
94
+ /private/i,
95
+ // Auth / access control
96
+ /auth/i,
97
+ // Configuration files
98
+ /config\.json$/i,
99
+ /package\.json$/i,
100
+ // Financial / business-critical (from MCP)
101
+ /payment/i,
102
+ // Infrastructure / data (from MCP)
103
+ /security/i,
104
+ /database/i
105
+ ];
106
+ var ImplicitRollbackBucketSchema = z.object({
107
+ count: z.number().int().min(0),
108
+ weightedSum: z.number().min(0)
109
+ }).strict();
110
+ var RollbackRateTraceSchema = z.object({
111
+ /** Explicit rollbacks (user-initiated restore). */
112
+ explicit: z.number().int().min(0),
113
+ /** Implicit rollbacks attributed to AI-generated code. */
114
+ implicitAIAttributed: ImplicitRollbackBucketSchema,
115
+ /** Implicit rollbacks not attributed to AI-generated code. */
116
+ implicitUnattributed: ImplicitRollbackBucketSchema,
117
+ /** Total file modifications in the observation window. */
118
+ totalModifications: z.number().int().min(0),
119
+ /** Computed rate: (explicit + weighted implicit) / totalModifications. */
120
+ computedRate: z.number().min(0).max(1)
121
+ }).strict();
122
+ var FragilityPillarTraceSchema = z.object({
123
+ pillar: z.enum([
124
+ "churn",
125
+ "rollback",
126
+ "ai_fraction",
127
+ "time_since_commit",
128
+ "file_count"
129
+ ]),
130
+ weight: z.number().min(0).max(1),
131
+ rawValue: z.number(),
132
+ contribution: z.number().min(0).max(1)
133
+ }).strict();
134
+ var FragilityTraceSchema = z.object({
135
+ pillars: z.array(FragilityPillarTraceSchema).min(1),
136
+ /** Weighted sum across all pillars before clamping. */
137
+ rawScore: z.number(),
138
+ /** Final fragility score after clamping to [0, 1]. */
139
+ computedScore: z.number().min(0).max(1)
140
+ }).strict();
141
+ var TrustScoreTraceSchema = z.object({
142
+ /** Agent rollback rate for this workspace. */
143
+ agentRollbackRate: z.number().min(0).max(1),
144
+ /** Fleet-wide average rollback rate for comparison. */
145
+ workspaceAvgRollbackRate: z.number().min(0).max(1),
146
+ /** Number of observations used to compute the rate. */
147
+ observationCount: z.number().int().min(0),
148
+ /** Bayesian prior weight (lower = more observations = less prior pull). */
149
+ priorWeight: z.number().min(0).max(1),
150
+ /** Final trust score after Bayesian smoothing. */
151
+ computedScore: z.number().min(0).max(1)
152
+ }).strict();
153
+ z.object({
154
+ /** ISO 8601 timestamp of the calculation. */
155
+ calculatedAt: z.string().datetime(),
156
+ /** Opaque workspace identifier (sha256-derived, never raw path). */
157
+ workspaceId: z.string(),
158
+ /** Fragility pillar breakdown. */
159
+ fragility: FragilityTraceSchema,
160
+ /** Rollback rate decomposition - the novel AI-attribution signal. */
161
+ rollbackRate: RollbackRateTraceSchema,
162
+ /** Trust score Bayesian trace. */
163
+ trustScore: TrustScoreTraceSchema
164
+ }).strict();
165
+ var DaemonTierSchema = z.enum([
166
+ "free",
167
+ "pro",
168
+ "team",
169
+ "enterprise"
170
+ ]);
171
+ z.object({
172
+ userId: z.string().nullable(),
173
+ email: z.string().email().nullable(),
174
+ tier: DaemonTierSchema.default("free"),
175
+ pioneer: z.boolean().default(false),
176
+ cohort: z.number().int().nullable(),
177
+ keyPreview: z.string().nullable(),
178
+ // NOTE: 'cli-token' covers device auth flow; 'api-key' is raw key from env
179
+ authenticatedVia: z.enum([
180
+ "github",
181
+ "google",
182
+ "api-key",
183
+ "cli-token"
184
+ ]).nullable(),
185
+ tokenExpiresAt: z.coerce.date().nullable(),
186
+ lastValidatedAt: z.coerce.date().nullable(),
187
+ isStale: z.boolean()
188
+ });
189
+ z.object({
190
+ version: z.literal("1").default("1"),
191
+ lastIdentityValidatedAt: z.coerce.date().nullable().default(null),
192
+ startCount: z.number().int().default(0),
193
+ lastStartedAt: z.coerce.date().nullable().default(null)
194
+ });
195
+ var WorkspaceRegistrationSchema = z.object({
196
+ id: z.string(),
197
+ path: z.string(),
198
+ alias: z.string().optional(),
199
+ ownership: z.enum([
200
+ "personal",
201
+ "team"
202
+ ]),
203
+ teamId: z.string().optional(),
204
+ createdAt: z.coerce.date(),
205
+ lastSeenAt: z.coerce.date(),
206
+ stackSummary: z.string().optional()
207
+ });
208
+ z.object({
209
+ version: z.literal("1").default("1"),
210
+ detectedAt: z.coerce.date(),
211
+ repoType: z.enum([
212
+ "monorepo",
213
+ "single",
214
+ "multi-package",
215
+ "unknown"
216
+ ]),
217
+ primaryLanguage: z.string(),
218
+ buildSystem: z.enum([
219
+ "turborepo",
220
+ "nx",
221
+ "lerna",
222
+ "none",
223
+ "unknown"
224
+ ]),
225
+ packageManager: z.enum([
226
+ "pnpm",
227
+ "npm",
228
+ "yarn",
229
+ "bun",
230
+ "unknown"
231
+ ]),
232
+ detectedAiTools: z.array(z.enum([
233
+ "cursor",
234
+ "copilot",
235
+ "claude-code",
236
+ "windsurf",
237
+ "unknown"
238
+ ])),
239
+ estimatedFileCount: z.number().int(),
240
+ estimatedContributors: z.number().int(),
241
+ hasCI: z.boolean(),
242
+ hasTests: z.boolean(),
243
+ // SEMANTIC DISTINCTION:
244
+ // - null = CTI has not run yet (default, unanalyzed)
245
+ // - [] = CTI ran, no critical paths found (analysis complete, no results)
246
+ // This distinction drives onboarding flow and CTI scheduling decisions.
247
+ criticalPaths: z.array(z.string()).nullable().default(null),
248
+ detectionFailed: z.boolean().default(false),
249
+ detectionError: z.string().optional()
250
+ });
251
+
252
+ // ../../packages/contracts/dist/api/attribution.js
253
+ function shouldMergeAttribution(existing, incoming) {
254
+ if (existing.source === incoming.source && existing.campaignId === incoming.campaignId) {
255
+ return true;
256
+ }
257
+ return false;
258
+ }
259
+ __name(shouldMergeAttribution, "shouldMergeAttribution");
260
+ var ApiErrorCodeSchema = z.enum([
261
+ // Authentication (401)
262
+ "AUTH_REQUIRED",
263
+ "AUTH_INVALID_TOKEN",
264
+ "AUTH_EXPIRED_TOKEN",
265
+ "AUTH_INVALID_API_KEY",
266
+ "AUTH_REVOKED_KEY",
267
+ // Authorization (403)
268
+ "FORBIDDEN",
269
+ "PERMISSION_DENIED",
270
+ "PLAN_LIMIT_EXCEEDED",
271
+ "FEATURE_NOT_AVAILABLE",
272
+ "TRIAL_EXPIRED",
273
+ // Validation (400)
274
+ "VALIDATION_ERROR",
275
+ "VALIDATION_MISSING_FIELD",
276
+ "VALIDATION_INVALID_FORMAT",
277
+ "VALIDATION_CONSTRAINT_VIOLATION",
278
+ // Resource Errors (404, 409, 410)
279
+ "RESOURCE_NOT_FOUND",
280
+ "RESOURCE_ALREADY_EXISTS",
281
+ "RESOURCE_DELETED",
282
+ "RESOURCE_CONFLICT",
283
+ "RESOURCE_LOCKED",
284
+ // Rate Limiting (429)
285
+ "RATE_LIMIT_EXCEEDED",
286
+ "RATE_LIMIT_API_KEY",
287
+ "RATE_LIMIT_USER",
288
+ "RATE_LIMIT_IP",
289
+ // Payment/Billing (402)
290
+ "PAYMENT_REQUIRED",
291
+ "PAYMENT_FAILED",
292
+ "SUBSCRIPTION_EXPIRED",
293
+ "SUBSCRIPTION_CANCELLED",
294
+ // External Integration Errors (502, 503)
295
+ "INTEGRATION_UNAVAILABLE",
296
+ "INTEGRATION_TIMEOUT",
297
+ "INTEGRATION_ERROR",
298
+ // Security (400, 403)
299
+ "SECURITY_CSRF_INVALID",
300
+ "SECURITY_CAPTCHA_REQUIRED",
301
+ "SECURITY_CAPTCHA_FAILED",
302
+ "SECURITY_PRIVACY_VIOLATION",
303
+ // Server Errors (500, 503)
304
+ "INTERNAL_ERROR",
305
+ "SERVICE_UNAVAILABLE",
306
+ "DATABASE_ERROR",
307
+ "CONFIGURATION_ERROR",
308
+ // Request Errors (400, 413, 415)
309
+ "BAD_REQUEST",
310
+ "PAYLOAD_TOO_LARGE",
311
+ "UNSUPPORTED_MEDIA_TYPE",
312
+ "METHOD_NOT_ALLOWED"
313
+ ]);
314
+ var ValidationErrorDetailSchema = z.object({
315
+ field: z.string().describe("The field path that failed validation"),
316
+ message: z.string().describe("Human-readable error message"),
317
+ code: z.string().optional().describe("Zod error code")
318
+ });
319
+ z.object({
320
+ /** Human-readable error message (safe to display to users) */
321
+ error: z.string(),
322
+ /** Machine-readable error code for programmatic handling */
323
+ code: ApiErrorCodeSchema,
324
+ /** Optional detailed error information */
325
+ details: z.union([
326
+ z.array(ValidationErrorDetailSchema),
327
+ z.record(z.string(), z.unknown())
328
+ ]).optional(),
329
+ /** Request ID for support correlation (from X-Request-Id header) */
330
+ requestId: z.string().optional(),
331
+ /** Timestamp when error occurred */
332
+ timestamp: z.string().datetime().optional()
333
+ });
334
+ var ApiTierSchema = z.enum([
335
+ "api_free",
336
+ "api_starter",
337
+ "api_pro",
338
+ "api_enterprise"
339
+ ]);
340
+ var ApiFeatureSchema = z.enum([
341
+ // Core analysis features
342
+ "risk_scoring",
343
+ "ai_detection",
344
+ "session_grouping",
345
+ "rollback_validation",
346
+ // Advanced features
347
+ "batch_analysis",
348
+ "webhook_notifications",
349
+ "custom_thresholds",
350
+ "priority_queue",
351
+ // Enterprise features
352
+ "dedicated_instance",
353
+ "sla_guarantee",
354
+ "audit_logs",
355
+ "sso_integration"
356
+ ]);
357
+ var RateLimitConfigSchema = z.object({
358
+ requestsPerMinute: z.number().int().positive(),
359
+ requestsPerDay: z.number().int().positive(),
360
+ maxBatchSize: z.number().int().positive(),
361
+ maxPayloadBytes: z.number().int().positive()
362
+ });
363
+ z.object({
364
+ tier: ApiTierSchema,
365
+ name: z.string(),
366
+ description: z.string(),
367
+ features: z.array(ApiFeatureSchema),
368
+ rateLimits: RateLimitConfigSchema,
369
+ priceMonthly: z.number().nonnegative(),
370
+ priceYearly: z.number().nonnegative()
371
+ });
372
+ z.object({
373
+ id: z.string().uuid(),
374
+ key: z.string().regex(/^sb_live_[a-zA-Z0-9]{32}$/, "Invalid API key format"),
375
+ tier: ApiTierSchema,
376
+ organizationId: z.string().uuid().optional(),
377
+ name: z.string().max(100).optional(),
378
+ createdAt: z.coerce.date(),
379
+ expiresAt: z.coerce.date().optional(),
380
+ lastUsedAt: z.coerce.date().optional(),
381
+ isActive: z.boolean().default(true)
382
+ });
383
+ z.object({
384
+ keyId: z.string().uuid(),
385
+ endpoint: z.string(),
386
+ requestCount: z.number().int().nonnegative(),
387
+ bytesProcessed: z.number().int().nonnegative(),
388
+ period: z.enum([
389
+ "minute",
390
+ "hour",
391
+ "day",
392
+ "month"
393
+ ]),
394
+ timestamp: z.coerce.date()
395
+ });
396
+ z.object({
397
+ name: z.string().max(100).optional(),
398
+ expiresAt: z.coerce.date().optional()
399
+ });
400
+ var AuthErrorCodeSchema = z.enum([
401
+ "INVALID_CREDENTIALS",
402
+ "USER_NOT_FOUND",
403
+ "EMAIL_NOT_VERIFIED",
404
+ "SESSION_EXPIRED",
405
+ "UNAUTHORIZED",
406
+ "RATE_LIMITED",
407
+ "INVALID_TOKEN",
408
+ "USER_ALREADY_EXISTS",
409
+ "WEAK_PASSWORD",
410
+ "INVALID_EMAIL",
411
+ "OAUTH_ERROR",
412
+ "NETWORK_ERROR",
413
+ "UNKNOWN_ERROR"
414
+ ]);
415
+ var AuthErrorSchema = z.object({
416
+ code: AuthErrorCodeSchema,
417
+ message: z.string(),
418
+ details: z.record(z.string(), z.unknown()).optional()
419
+ });
420
+ var UserRoleSchema = z.enum([
421
+ "admin",
422
+ "user",
423
+ "viewer"
424
+ ]).nullable();
425
+ var AuthUserSchema = z.object({
426
+ id: z.string(),
427
+ email: z.string().email(),
428
+ name: z.string().nullable(),
429
+ image: z.string().url().nullable().optional(),
430
+ emailVerified: z.boolean(),
431
+ createdAt: z.coerce.date(),
432
+ updatedAt: z.coerce.date(),
433
+ // Role field from database - nullable as not all users have a role assigned
434
+ role: UserRoleSchema.optional()
435
+ });
436
+ var SessionSchema = z.object({
437
+ id: z.string(),
438
+ userId: z.string(),
439
+ expiresAt: z.coerce.date(),
440
+ createdAt: z.coerce.date(),
441
+ updatedAt: z.coerce.date(),
442
+ // Better Auth session metadata
443
+ userAgent: z.string().nullable().optional(),
444
+ ipAddress: z.string().nullable().optional()
445
+ });
446
+ var SessionWithUserSchema = z.object({
447
+ session: SessionSchema,
448
+ user: AuthUserSchema
449
+ });
450
+ z.discriminatedUnion("status", [
451
+ z.object({
452
+ status: z.literal("authenticated"),
453
+ user: AuthUserSchema,
454
+ session: SessionSchema
455
+ }),
456
+ z.object({
457
+ status: z.literal("unauthenticated")
458
+ }),
459
+ z.object({
460
+ status: z.literal("loading")
461
+ })
462
+ ]);
463
+
464
+ // ../../packages/contracts/dist/auth/api.js
465
+ var PasswordSchema = z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number");
466
+ var EmailSchema = z.string().email("Invalid email address").toLowerCase().trim();
467
+ z.object({
468
+ email: EmailSchema,
469
+ password: PasswordSchema,
470
+ name: z.string().min(1, "Name is required").max(100, "Name is too long").trim()
471
+ });
472
+ z.discriminatedUnion("success", [
473
+ z.object({
474
+ success: z.literal(true),
475
+ user: AuthUserSchema
476
+ }),
477
+ z.object({
478
+ success: z.literal(false),
479
+ error: AuthErrorSchema
480
+ })
481
+ ]);
482
+ z.object({
483
+ email: EmailSchema,
484
+ password: z.string().min(1, "Password is required"),
485
+ rememberMe: z.boolean().optional().default(false)
486
+ });
487
+ z.discriminatedUnion("success", [
488
+ z.object({
489
+ success: z.literal(true),
490
+ user: AuthUserSchema,
491
+ session: z.object({
492
+ id: z.string(),
493
+ expiresAt: z.coerce.date()
494
+ })
495
+ }),
496
+ z.object({
497
+ success: z.literal(false),
498
+ error: AuthErrorSchema
499
+ })
500
+ ]);
501
+ z.union([
502
+ SessionWithUserSchema,
503
+ z.null()
504
+ ]);
505
+ z.discriminatedUnion("success", [
506
+ z.object({
507
+ success: z.literal(true)
508
+ }),
509
+ z.object({
510
+ success: z.literal(false),
511
+ error: AuthErrorSchema
512
+ })
513
+ ]);
514
+ z.object({
515
+ name: z.string().min(1).max(100).trim().optional(),
516
+ image: z.string().url().optional()
517
+ });
518
+ z.discriminatedUnion("success", [
519
+ z.object({
520
+ success: z.literal(true),
521
+ user: AuthUserSchema
522
+ }),
523
+ z.object({
524
+ success: z.literal(false),
525
+ error: AuthErrorSchema
526
+ })
527
+ ]);
528
+ z.object({
529
+ currentPassword: z.string().min(1, "Current password is required"),
530
+ newPassword: PasswordSchema
531
+ });
532
+ z.discriminatedUnion("success", [
533
+ z.object({
534
+ success: z.literal(true)
535
+ }),
536
+ z.object({
537
+ success: z.literal(false),
538
+ error: AuthErrorSchema
539
+ })
540
+ ]);
541
+ z.object({
542
+ provider: z.enum([
543
+ "github",
544
+ "google"
545
+ ]),
546
+ callbackURL: z.string().url().optional()
547
+ });
548
+ var AuthScope = z.enum([
549
+ "console",
550
+ "api"
551
+ ]);
552
+
553
+ // ../../packages/contracts/dist/auth/identity.js
554
+ z.object({
555
+ pioneer: z.boolean().default(false),
556
+ pioneerCohort: z.number().int().optional(),
557
+ referralCode: z.string().optional(),
558
+ invitedBy: z.string().nullable().optional()
559
+ });
560
+ var OrgType = z.enum([
561
+ "personal",
562
+ "team"
563
+ ]);
564
+ var OrgRole = z.enum([
565
+ "owner",
566
+ "admin",
567
+ "member"
568
+ ]);
569
+ z.object({
570
+ id: z.string().uuid(),
571
+ name: z.string(),
572
+ type: OrgType,
573
+ tier: z.enum([
574
+ "free",
575
+ "pro",
576
+ "team",
577
+ "enterprise"
578
+ ]),
579
+ stripeCustomerId: z.string().nullable(),
580
+ stripeSubscriptionId: z.string().nullable(),
581
+ metadata: z.object({
582
+ saml: z.object({
583
+ entryPoint: z.string().url(),
584
+ issuer: z.string(),
585
+ cert: z.string()
586
+ }).optional()
587
+ }).optional(),
588
+ createdAt: z.string().datetime()
589
+ });
590
+ z.object({
591
+ id: z.string().uuid(),
592
+ keyPreview: z.string(),
593
+ name: z.string(),
594
+ orgId: z.string().uuid(),
595
+ createdBy: z.string().uuid(),
596
+ scopes: z.array(AuthScope).default([
597
+ "api"
598
+ ]),
599
+ createdAt: z.string().datetime(),
600
+ lastUsedAt: z.string().datetime().nullable(),
601
+ revokedAt: z.string().datetime().nullable()
602
+ });
603
+ z.object({
604
+ userId: z.string().uuid(),
605
+ orgId: z.string().uuid(),
606
+ role: OrgRole,
607
+ tier: z.enum([
608
+ "free",
609
+ "pro",
610
+ "team",
611
+ "enterprise"
612
+ ]),
613
+ scopes: z.array(AuthScope),
614
+ pioneer: z.boolean(),
615
+ authenticatedVia: z.enum([
616
+ "session",
617
+ "api_key",
618
+ "device_token"
619
+ ])
620
+ });
621
+ z.object({
622
+ deviceCode: z.string(),
623
+ userCode: z.string(),
624
+ verificationUri: z.string().url(),
625
+ expiresIn: z.number().int(),
626
+ interval: z.number().int()
627
+ });
628
+ z.discriminatedUnion("status", [
629
+ z.object({
630
+ status: z.literal("pending"),
631
+ error: z.literal("authorization_pending")
632
+ }),
633
+ z.object({
634
+ status: z.literal("success"),
635
+ accessToken: z.string(),
636
+ refreshToken: z.string(),
637
+ expiresIn: z.number().int(),
638
+ orgId: z.string().uuid()
639
+ }),
640
+ z.object({
641
+ status: z.literal("denied"),
642
+ error: z.literal("access_denied")
643
+ }),
644
+ z.object({
645
+ status: z.literal("expired"),
646
+ error: z.literal("expired_token")
647
+ })
648
+ ]);
649
+ z.object({
650
+ version: z.string(),
651
+ riskClasses: z.record(z.enum([
652
+ "safe",
653
+ "low",
654
+ "medium",
655
+ "high",
656
+ "critical"
657
+ ]), z.object({
658
+ description: z.string(),
659
+ defaultSandbox: z.enum([
660
+ "none",
661
+ "basic",
662
+ "strict",
663
+ "isolated"
664
+ ]),
665
+ requiresAuth: z.boolean(),
666
+ requiresSnapshot: z.boolean(),
667
+ maxConcurrent: z.number().positive(),
668
+ timeoutMs: z.number().positive(),
669
+ requiresApproval: z.boolean().optional()
670
+ })),
671
+ categories: z.record(z.string(), z.object({
672
+ description: z.string(),
673
+ namespace: z.string(),
674
+ defaultRiskClass: z.enum([
675
+ "safe",
676
+ "low",
677
+ "medium",
678
+ "high",
679
+ "critical"
680
+ ])
681
+ })),
682
+ tools: z.array(z.object({
683
+ urn: z.string(),
684
+ name: z.string(),
685
+ description: z.string(),
686
+ category: z.string(),
687
+ riskClass: z.enum([
688
+ "safe",
689
+ "low",
690
+ "medium",
691
+ "high",
692
+ "critical"
693
+ ]),
694
+ caps: z.array(z.string()),
695
+ requiredPermissions: z.array(z.string()),
696
+ requiredFeatures: z.array(z.string()),
697
+ minTier: z.enum([
698
+ "free",
699
+ "pro",
700
+ "team",
701
+ "enterprise"
702
+ ]).optional(),
703
+ inputSchema: z.object({
704
+ type: z.literal("object"),
705
+ properties: z.record(z.string(), z.any()).optional(),
706
+ required: z.array(z.string()).optional()
707
+ })
708
+ })),
709
+ permissions: z.array(z.object({
710
+ id: z.string(),
711
+ description: z.string(),
712
+ scope: z.enum([
713
+ "workspace",
714
+ "channel",
715
+ "admin"
716
+ ]),
717
+ requiresTier: z.enum([
718
+ "free",
719
+ "pro",
720
+ "team",
721
+ "enterprise"
722
+ ]).optional()
723
+ })),
724
+ sandboxes: z.record(z.enum([
725
+ "none",
726
+ "basic",
727
+ "strict",
728
+ "isolated"
729
+ ]), z.object({
730
+ description: z.string(),
731
+ capabilities: z.array(z.string()),
732
+ restrictions: z.array(z.string()),
733
+ implementation: z.enum([
734
+ "container",
735
+ "vm",
736
+ "process"
737
+ ]).optional()
738
+ }))
739
+ });
740
+
741
+ // ../../packages/contracts/dist/tiers.js
742
+ function isTierBypassEnabled() {
743
+ return process.env.VREKO_BYPASS_TIER_RESTRICTIONS === "true";
744
+ }
745
+ __name(isTierBypassEnabled, "isTierBypassEnabled");
746
+ function getEffectiveTier(actualTier) {
747
+ if (isTierBypassEnabled()) {
748
+ return "pro";
749
+ }
750
+ return actualTier;
751
+ }
752
+ __name(getEffectiveTier, "getEffectiveTier");
753
+
754
+ // ../../packages/contracts/dist/entitlements.js
755
+ var TIER_FEATURES = {
756
+ free: [
757
+ "api_access"
758
+ ],
759
+ pro: [
760
+ "cloud_backup",
761
+ "api_access",
762
+ "advanced_analytics",
763
+ "unlimited_workspaces",
764
+ "cli_full_features"
765
+ ],
766
+ team: [
767
+ "cloud_backup",
768
+ "api_access",
769
+ "advanced_analytics",
770
+ "unlimited_workspaces",
771
+ "cli_full_features",
772
+ "team_dashboard",
773
+ "multi_workspace",
774
+ "priority_support"
775
+ ],
776
+ enterprise: [
777
+ "cloud_backup",
778
+ "api_access",
779
+ "advanced_analytics",
780
+ "unlimited_workspaces",
781
+ "cli_full_features",
782
+ "team_dashboard",
783
+ "multi_workspace",
784
+ "sso_authentication",
785
+ "audit_logs",
786
+ "priority_support",
787
+ "custom_retention"
788
+ ]
789
+ };
790
+ var TIER_LIMITS = {
791
+ free: {
792
+ cloud_backup: 0,
793
+ api_access: 100,
794
+ unlimited_workspaces: 1
795
+ },
796
+ pro: {
797
+ cloud_backup: 100 * 1024,
798
+ api_access: 1e5,
799
+ unlimited_workspaces: null
800
+ },
801
+ team: {
802
+ cloud_backup: 500 * 1024,
803
+ api_access: 1e6,
804
+ unlimited_workspaces: null
805
+ },
806
+ enterprise: {
807
+ cloud_backup: null,
808
+ api_access: null,
809
+ unlimited_workspaces: null
810
+ }
811
+ };
812
+ function getTierFeatures(tier) {
813
+ const effectiveTier = getEffectiveTier(tier);
814
+ return TIER_FEATURES[effectiveTier] || [];
815
+ }
816
+ __name(getTierFeatures, "getTierFeatures");
817
+ function isFeatureAvailableAtTier(feature, tier) {
818
+ const effectiveTier = getEffectiveTier(tier);
819
+ return TIER_FEATURES[effectiveTier]?.includes(feature) || false;
820
+ }
821
+ __name(isFeatureAvailableAtTier, "isFeatureAvailableAtTier");
822
+ function getTierLimit(tier, feature) {
823
+ const effectiveTier = getEffectiveTier(tier);
824
+ return TIER_LIMITS[effectiveTier]?.[feature] ?? null;
825
+ }
826
+ __name(getTierLimit, "getTierLimit");
827
+
828
+ // ../../packages/contracts/dist/errors/base.js
829
+ function extractErrorCode(error) {
830
+ if (error.code) {
831
+ return error.code;
832
+ }
833
+ if (error.name && error.name !== "Error") {
834
+ return error.name.toUpperCase().replace(/ERROR$/, "").replace(/\s+/g, "_");
835
+ }
836
+ return void 0;
837
+ }
838
+ __name(extractErrorCode, "extractErrorCode");
839
+
840
+ // ../../packages/contracts/dist/errors/domain/base.js
841
+ var ErrorCategory;
842
+ (function(ErrorCategory2) {
843
+ ErrorCategory2["NOT_FOUND"] = "NOT_FOUND";
844
+ ErrorCategory2["VALIDATION"] = "VALIDATION";
845
+ ErrorCategory2["PERMISSION"] = "PERMISSION";
846
+ ErrorCategory2["CONFLICT"] = "CONFLICT";
847
+ ErrorCategory2["EXTERNAL"] = "EXTERNAL";
848
+ ErrorCategory2["INTERNAL"] = "INTERNAL";
849
+ })(ErrorCategory || (ErrorCategory = {}));
850
+ var VrekoEvent;
851
+ (function(VrekoEvent2) {
852
+ VrekoEvent2["SNAPSHOT_CREATED"] = "snapshot:created";
853
+ VrekoEvent2["SNAPSHOT_DELETED"] = "snapshot:deleted";
854
+ VrekoEvent2["SNAPSHOT_RESTORED"] = "snapshot:restored";
855
+ VrekoEvent2["RESTORE_STARTED"] = "snapshot:restore_started";
856
+ VrekoEvent2["PROTECTION_CHANGED"] = "protection:changed";
857
+ VrekoEvent2["FILE_PROTECTED"] = "file:protected";
858
+ VrekoEvent2["FILE_UNPROTECTED"] = "file:unprotected";
859
+ VrekoEvent2["ANALYSIS_REQUESTED"] = "analysis:requested";
860
+ VrekoEvent2["ANALYSIS_COMPLETED"] = "analysis:completed";
861
+ })(VrekoEvent || (VrekoEvent = {}));
862
+ var QoSLevel;
863
+ (function(QoSLevel2) {
864
+ QoSLevel2[QoSLevel2["BEST_EFFORT"] = 0] = "BEST_EFFORT";
865
+ QoSLevel2[QoSLevel2["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE";
866
+ QoSLevel2[QoSLevel2["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE";
867
+ })(QoSLevel || (QoSLevel = {}));
868
+ process.env.MCP_QUIET === "1" || process.env.MCP_QUIET === "true";
869
+
870
+ // ../../packages/contracts/dist/telemetry/events.js
871
+ var TELEMETRY_EVENTS = {
872
+ EXTENSION_ACTIVATED: "extension.activated",
873
+ EXTENSION_DEACTIVATED: "extension.deactivated",
874
+ COMMAND_EXECUTION: "command.execution",
875
+ SNAPSHOT_CREATED: "snapshot.created",
876
+ VREKO_USED: "vreko.used",
877
+ SNAPBACK_USED: "snapback.used",
878
+ RISK_DETECTED: "risk.detected",
879
+ VIEW_ACTIVATED: "view.activated",
880
+ NOTIFICATION_SHOWN: "notification.shown",
881
+ FEATURE_USED: "feature.used",
882
+ ERROR: "error",
883
+ WALKTHROUGH_STEP_COMPLETED: "walkthrough.step.completed",
884
+ ONBOARDING_PROTECTION_ASSIGNED: "onboarding.protection.assigned",
885
+ ONBOARDING_PHASE_PROGRESSED: "onboarding.phase.progressed",
886
+ ONBOARDING_CONTEXTUAL_PROMPT_SHOWN: "onboarding.contextualPrompt.shown",
887
+ SIGNATURE_VERIFICATION_SUCCESS: "signature.verification.success",
888
+ SIGNATURE_VERIFICATION_FAILED: "signature.verification.failed",
889
+ RULES_CACHED_FALLBACK: "rules.cached.fallback",
890
+ // Vitals Events
891
+ VITALS_TRAJECTORY_CHANGED: "vitals_trajectory_changed",
892
+ VITALS_CRITICAL_STATE: "vitals_critical_state",
893
+ VITALS_AUTO_SNAPSHOT: "vitals_auto_snapshot",
894
+ VITALS_NUDGE_SHOWN: "vitals_nudge_shown"
895
+ };
896
+ function validateTelemetryEvent(event) {
897
+ switch (event.event) {
898
+ case TELEMETRY_EVENTS.EXTENSION_ACTIVATED:
899
+ return validateExtensionActivatedEvent(event);
900
+ case TELEMETRY_EVENTS.EXTENSION_DEACTIVATED:
901
+ return validateExtensionDeactivatedEvent(event);
902
+ case TELEMETRY_EVENTS.COMMAND_EXECUTION:
903
+ return validateCommandExecutionEvent(event);
904
+ case TELEMETRY_EVENTS.SNAPSHOT_CREATED:
905
+ return validateSnapshotCreatedEvent(event);
906
+ case TELEMETRY_EVENTS.VREKO_USED:
907
+ return validateVrekoUsedEvent(event);
908
+ case TELEMETRY_EVENTS.SNAPBACK_USED:
909
+ return validateSnapBackUsedEvent(event);
910
+ case TELEMETRY_EVENTS.RISK_DETECTED:
911
+ return validateRiskDetectedEvent(event);
912
+ case TELEMETRY_EVENTS.VIEW_ACTIVATED:
913
+ return validateViewActivatedEvent(event);
914
+ case TELEMETRY_EVENTS.NOTIFICATION_SHOWN:
915
+ return validateNotificationShownEvent(event);
916
+ case TELEMETRY_EVENTS.FEATURE_USED:
917
+ return validateFeatureUsedEvent(event);
918
+ case TELEMETRY_EVENTS.ERROR:
919
+ return validateErrorEvent(event);
920
+ case TELEMETRY_EVENTS.WALKTHROUGH_STEP_COMPLETED:
921
+ return validateWalkthroughStepCompletedEvent(event);
922
+ case TELEMETRY_EVENTS.ONBOARDING_PROTECTION_ASSIGNED:
923
+ return validateOnboardingProtectionAssignedEvent(event);
924
+ case TELEMETRY_EVENTS.ONBOARDING_PHASE_PROGRESSED:
925
+ return validateOnboardingPhaseProgressedEvent(event);
926
+ case TELEMETRY_EVENTS.ONBOARDING_CONTEXTUAL_PROMPT_SHOWN:
927
+ return validateOnboardingContextualPromptShownEvent(event);
928
+ case TELEMETRY_EVENTS.SIGNATURE_VERIFICATION_SUCCESS:
929
+ return validateSignatureVerificationSuccessEvent(event);
930
+ case TELEMETRY_EVENTS.SIGNATURE_VERIFICATION_FAILED:
931
+ return validateSignatureVerificationFailedEvent(event);
932
+ case TELEMETRY_EVENTS.RULES_CACHED_FALLBACK:
933
+ return validateRulesCachedFallbackEvent(event);
934
+ case TELEMETRY_EVENTS.VITALS_TRAJECTORY_CHANGED:
935
+ return validateVitalsTrajectoryChangedEvent(event);
936
+ case TELEMETRY_EVENTS.VITALS_CRITICAL_STATE:
937
+ return validateVitalsCriticalStateEvent(event);
938
+ case TELEMETRY_EVENTS.VITALS_AUTO_SNAPSHOT:
939
+ return validateVitalsAutoSnapshotEvent(event);
940
+ case TELEMETRY_EVENTS.VITALS_NUDGE_SHOWN:
941
+ return validateVitalsNudgeShownEvent(event);
942
+ default:
943
+ return false;
944
+ }
945
+ }
946
+ __name(validateTelemetryEvent, "validateTelemetryEvent");
947
+ function validateExtensionActivatedEvent(event) {
948
+ return typeof event.properties.version === "string" && typeof event.properties.vscodeVersion === "string";
949
+ }
950
+ __name(validateExtensionActivatedEvent, "validateExtensionActivatedEvent");
951
+ function validateExtensionDeactivatedEvent(event) {
952
+ return Object.keys(event.properties).length === 0;
953
+ }
954
+ __name(validateExtensionDeactivatedEvent, "validateExtensionDeactivatedEvent");
955
+ function validateCommandExecutionEvent(event) {
956
+ return typeof event.properties.command === "string" && typeof event.properties.duration === "number" && typeof event.properties.success === "boolean";
957
+ }
958
+ __name(validateCommandExecutionEvent, "validateCommandExecutionEvent");
959
+ function validateSnapshotCreatedEvent(event) {
960
+ return typeof event.properties.method === "string" && typeof event.properties.filesCount === "number";
961
+ }
962
+ __name(validateSnapshotCreatedEvent, "validateSnapshotCreatedEvent");
963
+ function validateVrekoUsedEvent(event) {
964
+ return typeof event.properties.filesRestored === "number" && typeof event.properties.duration === "number" && typeof event.properties.success === "boolean";
965
+ }
966
+ __name(validateVrekoUsedEvent, "validateVrekoUsedEvent");
967
+ function validateSnapBackUsedEvent(event) {
968
+ return typeof event.properties.filesRestored === "number" && typeof event.properties.duration === "number" && typeof event.properties.success === "boolean";
969
+ }
970
+ __name(validateSnapBackUsedEvent, "validateSnapBackUsedEvent");
971
+ function validateRiskDetectedEvent(event) {
972
+ return typeof event.properties.riskLevel === "string" && Array.isArray(event.properties.patterns) && typeof event.properties.confidence === "number";
973
+ }
974
+ __name(validateRiskDetectedEvent, "validateRiskDetectedEvent");
975
+ function validateViewActivatedEvent(event) {
976
+ return typeof event.properties.viewId === "string";
977
+ }
978
+ __name(validateViewActivatedEvent, "validateViewActivatedEvent");
979
+ function validateNotificationShownEvent(event) {
980
+ return typeof event.properties.notificationType === "string" && (event.properties.actionTaken === null || typeof event.properties.actionTaken === "string");
981
+ }
982
+ __name(validateNotificationShownEvent, "validateNotificationShownEvent");
983
+ function validateFeatureUsedEvent(event) {
984
+ return typeof event.properties.feature === "string";
985
+ }
986
+ __name(validateFeatureUsedEvent, "validateFeatureUsedEvent");
987
+ function validateErrorEvent(event) {
988
+ return typeof event.properties.errorType === "string" && typeof event.properties.errorMessage === "string";
989
+ }
990
+ __name(validateErrorEvent, "validateErrorEvent");
991
+ function validateWalkthroughStepCompletedEvent(event) {
992
+ return typeof event.properties.stepId === "string" && typeof event.properties.stepTitle === "string";
993
+ }
994
+ __name(validateWalkthroughStepCompletedEvent, "validateWalkthroughStepCompletedEvent");
995
+ function validateOnboardingProtectionAssignedEvent(event) {
996
+ return typeof event.properties.level === "string" && typeof event.properties.trigger === "string" && typeof event.properties.fileType === "string" && typeof event.properties.isFirstProtection === "boolean";
997
+ }
998
+ __name(validateOnboardingProtectionAssignedEvent, "validateOnboardingProtectionAssignedEvent");
999
+ function validateOnboardingPhaseProgressedEvent(event) {
1000
+ return typeof event.properties.phase === "number" && typeof event.properties.trigger === "string" && Array.isArray(event.properties.unlockedFeatures);
1001
+ }
1002
+ __name(validateOnboardingPhaseProgressedEvent, "validateOnboardingPhaseProgressedEvent");
1003
+ function validateOnboardingContextualPromptShownEvent(event) {
1004
+ return typeof event.properties.promptType === "string" && (event.properties.actionTaken === null || typeof event.properties.actionTaken === "string");
1005
+ }
1006
+ __name(validateOnboardingContextualPromptShownEvent, "validateOnboardingContextualPromptShownEvent");
1007
+ function validateSignatureVerificationSuccessEvent(event) {
1008
+ return Object.keys(event.properties).length === 0;
1009
+ }
1010
+ __name(validateSignatureVerificationSuccessEvent, "validateSignatureVerificationSuccessEvent");
1011
+ function validateSignatureVerificationFailedEvent(event) {
1012
+ return Object.keys(event.properties).length === 0;
1013
+ }
1014
+ __name(validateSignatureVerificationFailedEvent, "validateSignatureVerificationFailedEvent");
1015
+ function validateRulesCachedFallbackEvent(event) {
1016
+ return Object.keys(event.properties).length === 0;
1017
+ }
1018
+ __name(validateRulesCachedFallbackEvent, "validateRulesCachedFallbackEvent");
1019
+ var VALID_TRAJECTORIES = [
1020
+ "stable",
1021
+ "escalating",
1022
+ "critical",
1023
+ "recovering"
1024
+ ];
1025
+ var VALID_TEMP_LEVELS = [
1026
+ "cold",
1027
+ "warm",
1028
+ "hot",
1029
+ "burning"
1030
+ ];
1031
+ function validateVitalsTrajectoryChangedEvent(event) {
1032
+ return VALID_TRAJECTORIES.includes(event.properties.previousTrajectory) && VALID_TRAJECTORIES.includes(event.properties.newTrajectory) && typeof event.properties.pressure === "number" && typeof event.properties.oxygen === "number" && VALID_TEMP_LEVELS.includes(event.properties.tempLevel);
1033
+ }
1034
+ __name(validateVitalsTrajectoryChangedEvent, "validateVitalsTrajectoryChangedEvent");
1035
+ function validateVitalsCriticalStateEvent(event) {
1036
+ return typeof event.properties.pressure === "number" && typeof event.properties.oxygen === "number" && VALID_TEMP_LEVELS.includes(event.properties.tempLevel) && typeof event.properties.unsnapshotedChanges === "number";
1037
+ }
1038
+ __name(validateVitalsCriticalStateEvent, "validateVitalsCriticalStateEvent");
1039
+ function validateVitalsAutoSnapshotEvent(event) {
1040
+ return VALID_TRAJECTORIES.includes(event.properties.trajectory) && typeof event.properties.pressure === "number" && typeof event.properties.oxygen === "number" && typeof event.properties.filesCount === "number";
1041
+ }
1042
+ __name(validateVitalsAutoSnapshotEvent, "validateVitalsAutoSnapshotEvent");
1043
+ function validateVitalsNudgeShownEvent(event) {
1044
+ return VALID_TRAJECTORIES.includes(event.properties.trajectory) && typeof event.properties.suggestion === "string" && (event.properties.actionTaken === null || typeof event.properties.actionTaken === "string");
1045
+ }
1046
+ __name(validateVitalsNudgeShownEvent, "validateVitalsNudgeShownEvent");
1047
+ var SeveritySchema = z.enum([
1048
+ "critical",
1049
+ "high",
1050
+ "medium",
1051
+ "low",
1052
+ "info"
1053
+ ]);
1054
+ var RiskSeveritySchema = z.enum([
1055
+ "critical",
1056
+ "high",
1057
+ "medium",
1058
+ "low"
1059
+ ]);
1060
+ var ValidationSeveritySchema = z.enum([
1061
+ "critical",
1062
+ "warning",
1063
+ "info"
1064
+ ]);
1065
+ var BaseIssueSchema = z.object({
1066
+ /** Severity level */
1067
+ severity: z.union([
1068
+ SeveritySchema,
1069
+ ValidationSeveritySchema
1070
+ ]),
1071
+ /** Issue type code (e.g., UNSAFE_EVAL, PATH_TRAVERSAL) */
1072
+ type: z.string(),
1073
+ /** Human-readable message */
1074
+ message: z.string(),
1075
+ /** Line number (1-indexed) */
1076
+ line: z.number().optional(),
1077
+ /** Suggested fix */
1078
+ fix: z.string().optional()
1079
+ });
1080
+ BaseIssueSchema.extend({
1081
+ severity: ValidationSeveritySchema
1082
+ });
1083
+ BaseIssueSchema.extend({
1084
+ /** Unique identifier for deduplication: analyzer/type/file/line */
1085
+ id: z.string(),
1086
+ /** Severity level */
1087
+ severity: SeveritySchema,
1088
+ /** File path where issue was found */
1089
+ file: z.string().optional(),
1090
+ /** Column number (1-indexed) */
1091
+ column: z.number().optional(),
1092
+ /** Code snippet showing the issue */
1093
+ snippet: z.string().optional(),
1094
+ /** Rule ID if from a lint tool */
1095
+ rule: z.string().optional()
1096
+ });
1097
+ z.object({
1098
+ /** Whether validation passed */
1099
+ passed: z.boolean(),
1100
+ /** Issues found */
1101
+ issues: z.array(BaseIssueSchema),
1102
+ /** Duration in milliseconds */
1103
+ duration: z.number().optional()
1104
+ });
1105
+ var CircuitBreakerStateEnumSchema = z.enum([
1106
+ "closed",
1107
+ "open",
1108
+ "half-open"
1109
+ ]);
1110
+ z.object({
1111
+ /** Current state */
1112
+ state: CircuitBreakerStateEnumSchema,
1113
+ /** Failure count */
1114
+ failures: z.number(),
1115
+ /** Failure threshold */
1116
+ threshold: z.number(),
1117
+ /** Last failure timestamp */
1118
+ lastFailure: z.number().optional(),
1119
+ /** Cooldown period in ms */
1120
+ cooldownMs: z.number()
1121
+ });
1122
+
1123
+ // ../../packages/contracts/dist/events/core.js
1124
+ extendZodWithOpenApi(z);
1125
+ var EVENT_VERSION = "1.0.0";
1126
+ var BaseEventSchema = z.object({
1127
+ event_version: z.string().default(EVENT_VERSION).openapi({
1128
+ example: "1.0.0"
1129
+ }),
1130
+ timestamp: z.number().default(() => Date.now()).openapi({
1131
+ example: 162e10
1132
+ })
1133
+ });
1134
+ var SaveAttemptSchema = BaseEventSchema.extend({
1135
+ event: z.literal("save_attempt"),
1136
+ properties: z.object({
1137
+ protection: z.enum([
1138
+ "watch",
1139
+ "warn",
1140
+ "block"
1141
+ ]).openapi({
1142
+ description: "Protection level applied to the file"
1143
+ }),
1144
+ severity: z.enum([
1145
+ "low",
1146
+ "medium",
1147
+ "high",
1148
+ "critical"
1149
+ ]).openapi({
1150
+ description: "Severity of the risk detected"
1151
+ }),
1152
+ file_kind: z.string().openapi({
1153
+ description: "Type of file being protected",
1154
+ example: "typescript"
1155
+ }),
1156
+ reason: z.string().openapi({
1157
+ description: "Reason for the save attempt",
1158
+ example: "User tried to save a file with a secret"
1159
+ }),
1160
+ ai_present: z.boolean().openapi({
1161
+ description: "Whether AI was involved in the decision"
1162
+ }),
1163
+ ai_burst: z.boolean().openapi({
1164
+ description: "Whether this was part of an AI burst operation"
1165
+ }),
1166
+ outcome: z.enum([
1167
+ "saved",
1168
+ "canceled",
1169
+ "blocked"
1170
+ ]).openapi({
1171
+ description: "Outcome of the save attempt"
1172
+ })
1173
+ })
1174
+ }).openapi("SaveAttemptEvent");
1175
+ var SnapshotCreatedSchema = BaseEventSchema.extend({
1176
+ event: z.literal("snapshot_created"),
1177
+ properties: z.object({
1178
+ session_id: z.string().openapi({
1179
+ description: "Unique identifier for the session",
1180
+ example: "sess_12345"
1181
+ }),
1182
+ snapshot_id: z.string().openapi({
1183
+ description: "Unique identifier for the snapshot",
1184
+ example: "snap_67890"
1185
+ }),
1186
+ bytes_original: z.number().openapi({
1187
+ description: "Original size of the file in bytes",
1188
+ example: 1024
1189
+ }),
1190
+ bytes_stored: z.number().openapi({
1191
+ description: "Size of the stored snapshot in bytes",
1192
+ example: 512
1193
+ }),
1194
+ dedup_hit: z.boolean().openapi({
1195
+ description: "Whether deduplication was applied"
1196
+ }),
1197
+ latency_ms: z.number().openapi({
1198
+ description: "Time taken to create the snapshot in milliseconds",
1199
+ example: 45
1200
+ })
1201
+ })
1202
+ }).openapi("SnapshotCreatedEvent");
1203
+ var SessionFinalizedSchema = BaseEventSchema.extend({
1204
+ event: z.literal("session_finalized"),
1205
+ properties: z.object({
1206
+ session_id: z.string().openapi({
1207
+ description: "Unique identifier for the session",
1208
+ example: "sess_12345"
1209
+ }),
1210
+ files: z.array(z.string()).openapi({
1211
+ description: "List of files in the session",
1212
+ example: [
1213
+ "src/index.ts",
1214
+ "package.json"
1215
+ ]
1216
+ }),
1217
+ triggers: z.array(z.string()).openapi({
1218
+ description: "List of triggers that activated during the session",
1219
+ example: [
1220
+ "save_attempt",
1221
+ "risk_detected"
1222
+ ]
1223
+ }),
1224
+ duration_ms: z.number().openapi({
1225
+ description: "Duration of the session in milliseconds",
1226
+ example: 12e4
1227
+ }),
1228
+ ai_present: z.boolean().openapi({
1229
+ description: "Whether AI was involved in the session"
1230
+ }),
1231
+ ai_burst: z.boolean().openapi({
1232
+ description: "Whether this was part of an AI burst operation"
1233
+ }),
1234
+ highest_severity: z.enum([
1235
+ "info",
1236
+ "low",
1237
+ "medium",
1238
+ "high",
1239
+ "critical"
1240
+ ]).openapi({
1241
+ description: "Highest severity of issues in the session"
1242
+ }),
1243
+ // AI detection v1 fields
1244
+ ai_assist_level: z.enum([
1245
+ "none",
1246
+ "light",
1247
+ "medium",
1248
+ "heavy",
1249
+ "unknown"
1250
+ ]).optional().openapi({
1251
+ description: "AI assistance level inferred from change patterns",
1252
+ example: "medium"
1253
+ }),
1254
+ ai_confidence_score: z.number().min(0).max(10).optional().openapi({
1255
+ description: "Confidence score for AI detection (0-10)",
1256
+ example: 7.5
1257
+ }),
1258
+ ai_provider: z.enum([
1259
+ "cursor",
1260
+ "claude",
1261
+ "unknown",
1262
+ "none"
1263
+ ]).optional().openapi({
1264
+ description: "Detected AI tool/provider",
1265
+ example: "cursor"
1266
+ }),
1267
+ ai_large_insert_count: z.number().int().min(0).optional().openapi({
1268
+ description: "Count of large insertions detected",
1269
+ example: 5
1270
+ }),
1271
+ ai_total_chars: z.number().int().min(0).optional().openapi({
1272
+ description: "Total characters in large insertions",
1273
+ example: 2e3
1274
+ }),
1275
+ context: z.record(z.string(), z.any()).optional().openapi({
1276
+ description: "Additional context for the session"
1277
+ })
1278
+ })
1279
+ }).openapi("SessionFinalizedEvent");
1280
+ var IssueCreatedSchema = BaseEventSchema.extend({
1281
+ event: z.literal("issue_created"),
1282
+ properties: z.object({
1283
+ issue_id: z.string().openapi({
1284
+ description: "Unique identifier for the issue",
1285
+ example: "issue_12345"
1286
+ }),
1287
+ session_id: z.string().openapi({
1288
+ description: "Unique identifier for the session",
1289
+ example: "sess_12345"
1290
+ }),
1291
+ file_kind: z.string().openapi({
1292
+ description: "Type of file where the issue was detected",
1293
+ example: "typescript"
1294
+ }),
1295
+ type: z.enum([
1296
+ "secret",
1297
+ "mock",
1298
+ "phantom"
1299
+ ]).openapi({
1300
+ description: "Type of issue detected"
1301
+ }),
1302
+ severity: RiskSeveritySchema.openapi({
1303
+ description: "Severity of the issue"
1304
+ }),
1305
+ recommendation: z.string().openapi({
1306
+ description: "Recommendation for resolving the issue",
1307
+ example: "Remove the secret from the file"
1308
+ }),
1309
+ context: z.record(z.string(), z.any()).optional().openapi({
1310
+ description: "Additional context for the issue"
1311
+ })
1312
+ })
1313
+ }).openapi("IssueCreatedEvent");
1314
+ var IssueResolvedSchema = BaseEventSchema.extend({
1315
+ event: z.literal("issue_resolved"),
1316
+ properties: z.object({
1317
+ issue_id: z.string().openapi({
1318
+ description: "Unique identifier for the issue",
1319
+ example: "issue_12345"
1320
+ }),
1321
+ resolution: z.enum([
1322
+ "fixed",
1323
+ "ignored",
1324
+ "allowlisted"
1325
+ ]).openapi({
1326
+ description: "How the issue was resolved"
1327
+ })
1328
+ })
1329
+ }).openapi("IssueResolvedEvent");
1330
+ var SessionRestoredSchema = BaseEventSchema.extend({
1331
+ event: z.literal("session_restored"),
1332
+ properties: z.object({
1333
+ session_id: z.string().openapi({
1334
+ description: "Unique identifier for the session",
1335
+ example: "sess_12345"
1336
+ }),
1337
+ files_restored: z.array(z.string()).openapi({
1338
+ description: "List of files that were restored",
1339
+ example: [
1340
+ "src/index.ts",
1341
+ "package.json"
1342
+ ]
1343
+ }),
1344
+ time_to_restore_ms: z.number().openapi({
1345
+ description: "Time taken to restore the session in milliseconds",
1346
+ example: 2500
1347
+ }),
1348
+ reason: z.string().openapi({
1349
+ description: "Reason for the session restoration",
1350
+ example: "User requested rollback"
1351
+ })
1352
+ })
1353
+ }).openapi("SessionRestoredEvent");
1354
+ var PolicyChangedSchema = BaseEventSchema.extend({
1355
+ event: z.literal("policy_changed"),
1356
+ properties: z.object({
1357
+ pattern: z.string().openapi({
1358
+ description: "File pattern that the policy applies to",
1359
+ example: "*.env"
1360
+ }),
1361
+ from: z.enum([
1362
+ "watch",
1363
+ "warn",
1364
+ "block",
1365
+ "unprotected",
1366
+ "unauthenticated",
1367
+ "unaware"
1368
+ ]).openapi({
1369
+ description: "Previous protection level"
1370
+ }),
1371
+ to: z.enum([
1372
+ "watch",
1373
+ "warn",
1374
+ "block",
1375
+ "unprotected",
1376
+ "authenticated",
1377
+ "aware"
1378
+ ]).openapi({
1379
+ description: "New protection level"
1380
+ }),
1381
+ source: z.string().openapi({
1382
+ description: "Source of the policy change",
1383
+ example: "cli"
1384
+ }),
1385
+ context: z.record(z.string(), z.any()).optional().openapi({
1386
+ description: "Additional context for the policy change"
1387
+ })
1388
+ })
1389
+ }).openapi("PolicyChangedEvent");
1390
+ var AuthProviderSelectedSchema = BaseEventSchema.extend({
1391
+ event: z.literal("auth.provider.selected"),
1392
+ properties: z.object({
1393
+ provider: z.enum([
1394
+ "oauth",
1395
+ "device_flow"
1396
+ ]).openapi({
1397
+ description: "Authentication provider selected"
1398
+ }),
1399
+ trigger: z.enum([
1400
+ "user_selected",
1401
+ "fallback",
1402
+ "auto"
1403
+ ]).openapi({
1404
+ description: "How the provider was selected"
1405
+ })
1406
+ })
1407
+ }).openapi("AuthProviderSelectedEvent");
1408
+ var AuthBrowserOpenedSchema = BaseEventSchema.extend({
1409
+ event: z.literal("auth.browser.opened"),
1410
+ properties: z.object({
1411
+ method: z.enum([
1412
+ "external_command",
1413
+ "clipboard",
1414
+ "error"
1415
+ ]).openapi({
1416
+ description: "Method used to open browser"
1417
+ }),
1418
+ success: z.boolean().openapi({
1419
+ description: "Whether browser was successfully opened"
1420
+ }),
1421
+ error: z.string().optional().openapi({
1422
+ description: "Error message if browser opening failed"
1423
+ })
1424
+ })
1425
+ }).openapi("AuthBrowserOpenedEvent");
1426
+ var AuthCodeEntrySchema = BaseEventSchema.extend({
1427
+ event: z.literal("auth.code.entry"),
1428
+ properties: z.object({
1429
+ code_format: z.enum([
1430
+ "valid",
1431
+ "invalid_chars",
1432
+ "wrong_length"
1433
+ ]).openapi({
1434
+ description: "Validity of the entered code format"
1435
+ }),
1436
+ time_to_enter_ms: z.number().openapi({
1437
+ description: "Time taken to enter the code in milliseconds"
1438
+ }),
1439
+ attempts: z.number().int().min(1).openapi({
1440
+ description: "Number of attempts to enter the code correctly"
1441
+ }),
1442
+ code_length: z.number().int().optional().openapi({
1443
+ description: "Length of the entered code"
1444
+ })
1445
+ })
1446
+ }).openapi("AuthCodeEntryEvent");
1447
+ var AuthApprovalReceivedSchema = BaseEventSchema.extend({
1448
+ event: z.literal("auth.approval.received"),
1449
+ properties: z.object({
1450
+ polling_attempts: z.number().int().min(1).openapi({
1451
+ description: "Number of polling attempts before approval"
1452
+ }),
1453
+ total_wait_ms: z.number().openapi({
1454
+ description: "Total time waited for approval in milliseconds"
1455
+ }),
1456
+ device_code_expired: z.boolean().openapi({
1457
+ description: "Whether the device code had expired"
1458
+ })
1459
+ })
1460
+ }).openapi("AuthApprovalReceivedEvent");
1461
+ var WelcomeFeatureViewedSchema = BaseEventSchema.extend({
1462
+ event: z.literal("welcome.feature.viewed"),
1463
+ properties: z.object({
1464
+ feature: z.string().openapi({
1465
+ description: "Feature name shown in welcome panel",
1466
+ example: "ai_detection"
1467
+ }),
1468
+ position: z.number().int().min(0).openapi({
1469
+ description: "Position in feature carousel",
1470
+ example: 0
1471
+ }),
1472
+ trigger: z.enum([
1473
+ "onboarding",
1474
+ "nudge",
1475
+ "manual"
1476
+ ]).openapi({
1477
+ description: "How the welcome panel was triggered"
1478
+ })
1479
+ })
1480
+ }).openapi("WelcomeFeatureViewedEvent");
1481
+ var WelcomeActionTriggeredSchema = BaseEventSchema.extend({
1482
+ event: z.literal("welcome.action.triggered"),
1483
+ properties: z.object({
1484
+ action: z.string().openapi({
1485
+ description: "Action triggered by user",
1486
+ example: "try_now"
1487
+ }),
1488
+ feature: z.string().openapi({
1489
+ description: "Feature associated with the action",
1490
+ example: "ai_detection"
1491
+ }),
1492
+ time_viewed_ms: z.number().openapi({
1493
+ description: "How long the feature was viewed before action",
1494
+ example: 2500
1495
+ })
1496
+ })
1497
+ }).openapi("WelcomeActionTriggeredEvent");
1498
+ z.discriminatedUnion("event", [
1499
+ SaveAttemptSchema,
1500
+ SnapshotCreatedSchema,
1501
+ SessionFinalizedSchema,
1502
+ IssueCreatedSchema,
1503
+ IssueResolvedSchema,
1504
+ SessionRestoredSchema,
1505
+ PolicyChangedSchema,
1506
+ AuthProviderSelectedSchema,
1507
+ AuthBrowserOpenedSchema,
1508
+ AuthCodeEntrySchema,
1509
+ AuthApprovalReceivedSchema,
1510
+ WelcomeFeatureViewedSchema,
1511
+ WelcomeActionTriggeredSchema
1512
+ ]);
1513
+
1514
+ // ../../packages/contracts/dist/events/accountability.js
1515
+ extendZodWithOpenApi(z);
1516
+ var PerceivedHelpSchema = z.enum([
1517
+ "significantly",
1518
+ "somewhat",
1519
+ "not_really",
1520
+ "blocked"
1521
+ ]).openapi({
1522
+ description: "User's perception of how much SnapBack helped"
1523
+ });
1524
+ var ActualChangesSchema = z.object({
1525
+ files_modified: z.number().int().min(0).openapi({
1526
+ description: "Number of files modified during session",
1527
+ example: 5
1528
+ }),
1529
+ lines_added: z.number().int().min(0).openapi({
1530
+ description: "Total lines added",
1531
+ example: 150
1532
+ }),
1533
+ lines_removed: z.number().int().min(0).openapi({
1534
+ description: "Total lines removed",
1535
+ example: 30
1536
+ }),
1537
+ snapshots_used: z.number().int().min(0).openapi({
1538
+ description: "Number of snapshots created or restored",
1539
+ example: 2
1540
+ })
1541
+ }).openapi("ActualChanges");
1542
+ var PreventedIssuesSchema = z.object({
1543
+ rollbacks_avoided: z.number().int().min(0).openapi({
1544
+ description: "Rollbacks avoided due to snapshots",
1545
+ example: 1
1546
+ }),
1547
+ pattern_violations_caught: z.number().int().min(0).openapi({
1548
+ description: "Pattern violations caught before commit",
1549
+ example: 3
1550
+ }),
1551
+ skipped_tests_flagged: z.number().int().min(0).openapi({
1552
+ description: "Skipped tests flagged for attention",
1553
+ example: 2
1554
+ })
1555
+ }).openapi("PreventedIssues");
1556
+ var TierSchema = z.enum([
1557
+ "free",
1558
+ "pro",
1559
+ "team",
1560
+ "enterprise"
1561
+ ]).openapi({
1562
+ description: "User's subscription tier"
1563
+ });
1564
+ BaseEventSchema.extend({
1565
+ event: z.literal("session:feedback_submitted"),
1566
+ properties: z.object({
1567
+ // Session identification
1568
+ session_id: z.string().openapi({
1569
+ description: "Unique session identifier",
1570
+ example: "sess_12345"
1571
+ }),
1572
+ session_duration_ms: z.number().int().min(0).openapi({
1573
+ description: "Session duration in milliseconds",
1574
+ example: 36e5
1575
+ }),
1576
+ // User perception
1577
+ perceived_help: PerceivedHelpSchema,
1578
+ // Reality metrics (counts only, no PII)
1579
+ actual_changes: ActualChangesSchema,
1580
+ prevented_issues: PreventedIssuesSchema,
1581
+ // Tier for consent checking
1582
+ tier: TierSchema
1583
+ })
1584
+ }).openapi("AccountabilityEffectEvent");
1585
+ var ClaimSubjectKind = z.enum([
1586
+ "pr",
1587
+ "spec",
1588
+ "session",
1589
+ "commit",
1590
+ "file",
1591
+ "phase",
1592
+ "workspace",
1593
+ "claim"
1594
+ ]);
1595
+ var ClaimantUrn = z.string().regex(/^urn:claimant:[a-z0-9.-]+$/);
1596
+ z.enum([
1597
+ "immediate",
1598
+ "deferred-manual",
1599
+ "deferred-observational"
1600
+ ]);
1601
+ var EvidenceGate = z.object({
1602
+ name: z.string(),
1603
+ passed: z.boolean(),
1604
+ output: z.string().optional()
1605
+ });
1606
+ var BaseClaim = z.object({
1607
+ // Identity
1608
+ claimId: z.string().uuid(),
1609
+ claimedAt: z.number().int().positive(),
1610
+ // Attribution
1611
+ claimant: ClaimantUrn,
1612
+ claimType: z.string(),
1613
+ claimFamily: z.enum([
1614
+ "completion",
1615
+ "verdict",
1616
+ "attribution",
1617
+ "prediction"
1618
+ ]),
1619
+ // Subject (what the claim is about)
1620
+ subject: z.object({
1621
+ kind: ClaimSubjectKind,
1622
+ ref: z.string().min(1)
1623
+ }),
1624
+ // Confidence (null for mechanical claims, [0,1] for predictive/attribution)
1625
+ confidence: z.number().min(0).max(1).nullable(),
1626
+ // Evidence supporting the claim
1627
+ evidence: z.object({
1628
+ gates: z.array(EvidenceGate).default([]),
1629
+ referenced: z.array(z.string()).default([])
1630
+ })
1631
+ });
1632
+ var OutcomeType = z.enum([
1633
+ "verified",
1634
+ "refuted",
1635
+ "ambiguous",
1636
+ "expired"
1637
+ ]);
1638
+ var Outcome = z.object({
1639
+ // Identity
1640
+ outcomeId: z.string().uuid(),
1641
+ claimId: z.string().uuid(),
1642
+ observedAt: z.number().int().positive(),
1643
+ // Outcome classification
1644
+ outcomeType: OutcomeType,
1645
+ // Evidence for the outcome
1646
+ evidence: z.record(z.unknown()),
1647
+ // For predictive claims: comparison between predicted and actual
1648
+ delta: z.object({
1649
+ predicted: z.unknown(),
1650
+ actual: z.unknown()
1651
+ }).optional()
1652
+ });
1653
+ BaseClaim.extend({
1654
+ outcome: Outcome.optional()
1655
+ });
1656
+ var AttributionSource = z.enum([
1657
+ "ai-tool",
1658
+ "human",
1659
+ "automation",
1660
+ "import",
1661
+ "unknown"
1662
+ ]);
1663
+ BaseClaim.extend({
1664
+ claimFamily: z.literal("attribution"),
1665
+ // Attribution requires confidence per spec
1666
+ confidence: z.number().min(0).max(1),
1667
+ // Attribution-specific payload
1668
+ claim: z.object({
1669
+ source: AttributionSource,
1670
+ toolUrn: z.string().optional(),
1671
+ confidenceRationale: z.string().optional(),
1672
+ indicators: z.array(z.string()).default([])
1673
+ })
1674
+ });
1675
+ var CompletionStatus = z.enum([
1676
+ "complete",
1677
+ "partial",
1678
+ "failed"
1679
+ ]);
1680
+ BaseClaim.extend({
1681
+ claimFamily: z.literal("completion"),
1682
+ // Completion-specific payload
1683
+ claim: z.object({
1684
+ status: CompletionStatus,
1685
+ completedGates: z.number().int().min(0),
1686
+ totalGates: z.number().int().positive(),
1687
+ phase: z.string().optional()
1688
+ })
1689
+ });
1690
+ var PredictedOutcomeType = z.enum([
1691
+ "rollback",
1692
+ "bug-introduced",
1693
+ "performance-degradation",
1694
+ "security-issue",
1695
+ "drift",
1696
+ "failure",
1697
+ "success"
1698
+ ]);
1699
+ var PredictionWindow = z.object({
1700
+ days: z.number().int().positive(),
1701
+ since: z.number().int().positive().optional()
1702
+ });
1703
+ BaseClaim.extend({
1704
+ claimFamily: z.literal("prediction"),
1705
+ // Predictions require confidence per spec
1706
+ confidence: z.number().min(0).max(1),
1707
+ // Prediction-specific payload
1708
+ claim: z.object({
1709
+ outcomeType: PredictedOutcomeType,
1710
+ window: PredictionWindow,
1711
+ rationale: z.string().optional(),
1712
+ modelVersion: z.string().optional()
1713
+ })
1714
+ });
1715
+ var VerdictStatus = z.enum([
1716
+ "pass",
1717
+ "fail",
1718
+ "needs-review",
1719
+ "drift-detected",
1720
+ "clean",
1721
+ "suspect"
1722
+ ]);
1723
+ BaseClaim.extend({
1724
+ claimFamily: z.literal("verdict"),
1725
+ // Verdict-specific payload
1726
+ claim: z.object({
1727
+ status: VerdictStatus,
1728
+ details: z.string().optional(),
1729
+ criteria: z.array(z.string()).default([]),
1730
+ severity: z.enum([
1731
+ "info",
1732
+ "low",
1733
+ "medium",
1734
+ "high",
1735
+ "critical"
1736
+ ]).optional()
1737
+ })
1738
+ });
1739
+ var REGISTERED_CLAIMANTS = [
1740
+ "urn:claimant:subagent-stop-hook",
1741
+ "urn:claimant:drift-detector",
1742
+ "urn:claimant:tool-identity",
1743
+ "urn:claimant:spec-writer",
1744
+ "urn:claimant:intelligence.risk-scorer",
1745
+ "urn:claimant:intelligence.fragility-detector",
1746
+ "urn:claimant:intelligence.pattern-detector"
1747
+ ];
1748
+ z.enum(REGISTERED_CLAIMANTS);
1749
+
1750
+ // ../../packages/contracts/dist/events/claims.js
1751
+ extendZodWithOpenApi(z);
1752
+ var CLAIMS_EVENT_VERSION = "1.0.0";
1753
+ z.object({
1754
+ event_version: z.string().default(CLAIMS_EVENT_VERSION).openapi({
1755
+ example: "1.0.0"
1756
+ }),
1757
+ timestamp: z.number().default(() => Date.now()).openapi({
1758
+ example: 162e10
1759
+ }),
1760
+ event: z.literal("claim.recorded"),
1761
+ payload: z.object({
1762
+ claim: BaseClaim.openapi({
1763
+ description: "The claim that was recorded"
1764
+ }),
1765
+ workspaceHash: z.string().openapi({
1766
+ description: "SHA-256 hash of workspace path",
1767
+ example: "a1b2c3d4..."
1768
+ })
1769
+ })
1770
+ });
1771
+ z.object({
1772
+ event_version: z.string().default(CLAIMS_EVENT_VERSION).openapi({
1773
+ example: "1.0.0"
1774
+ }),
1775
+ timestamp: z.number().default(() => Date.now()).openapi({
1776
+ example: 162e10
1777
+ }),
1778
+ event: z.literal("claim.resolved"),
1779
+ payload: z.object({
1780
+ claimId: z.string().uuid().openapi({
1781
+ description: "ID of the resolved claim"
1782
+ }),
1783
+ outcome: Outcome.openapi({
1784
+ description: "The outcome record"
1785
+ }),
1786
+ workspaceHash: z.string().openapi({
1787
+ description: "SHA-256 hash of workspace path",
1788
+ example: "a1b2c3d4..."
1789
+ })
1790
+ })
1791
+ });
1792
+ z.object({
1793
+ event_version: z.string().default(CLAIMS_EVENT_VERSION).openapi({
1794
+ example: "1.0.0"
1795
+ }),
1796
+ timestamp: z.number().default(() => Date.now()).openapi({
1797
+ example: 162e10
1798
+ }),
1799
+ event: z.literal("claim.expired"),
1800
+ payload: z.object({
1801
+ claimId: z.string().uuid().openapi({
1802
+ description: "ID of the expired claim"
1803
+ }),
1804
+ outcomeId: z.string().uuid().openapi({
1805
+ description: "ID of the expiration outcome"
1806
+ }),
1807
+ expiredAt: z.number().openapi({
1808
+ description: "Timestamp when expiry was recorded"
1809
+ }),
1810
+ workspaceHash: z.string().openapi({
1811
+ description: "SHA-256 hash of workspace path",
1812
+ example: "a1b2c3d4..."
1813
+ })
1814
+ })
1815
+ });
1816
+ var toolUrnPattern = /^urn:ai-tool:[a-z0-9-]+:\d+\.\d+$/;
1817
+ var toolUrnSchema = z.string().regex(toolUrnPattern, "Invalid tool URN format. Expected: urn:ai-tool:<vendor>:<version>").max(64, "Tool URN must be \u226464 characters");
1818
+ var attributionSourceSchema = z.enum([
1819
+ "fingerprint",
1820
+ "session-correlation",
1821
+ "temporal",
1822
+ "mcp-direct"
1823
+ ]);
1824
+ var toolAttributionSchema = z.object({
1825
+ kind: z.literal("tool"),
1826
+ /** Tool URN (e.g., urn:ai-tool:claude-code:1.0) */
1827
+ toolUrn: toolUrnSchema,
1828
+ /** Confidence score 0.0-1.0 */
1829
+ confidence: z.number().min(0).max(1),
1830
+ /** Attribution source method */
1831
+ source: attributionSourceSchema
1832
+ });
1833
+ var userAttributionSchema = z.object({
1834
+ kind: z.literal("user"),
1835
+ /** User authored the change without AI mediation */
1836
+ description: z.literal("user authored the change without AI mediation").optional()
1837
+ });
1838
+ var systemAttributionSchema = z.object({
1839
+ kind: z.literal("system"),
1840
+ /** System operation source */
1841
+ source: z.enum([
1842
+ "scheduled",
1843
+ "startup",
1844
+ "shutdown",
1845
+ "gc"
1846
+ ])
1847
+ });
1848
+ var unknownAttributionSchema = z.object({
1849
+ kind: z.literal("unknown"),
1850
+ /** Signal was insufficient to attribute; emitted rather than dropped */
1851
+ description: z.literal("signal was insufficient to attribute").optional()
1852
+ });
1853
+ var attributionSchema = z.discriminatedUnion("kind", [
1854
+ toolAttributionSchema,
1855
+ userAttributionSchema,
1856
+ systemAttributionSchema,
1857
+ unknownAttributionSchema
1858
+ ]);
1859
+
1860
+ // ../../packages/contracts/dist/events/spine/envelope.js
1861
+ var uuidv7Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1862
+ var uuidv7Schema = z.string().regex(uuidv7Pattern, "Invalid UUIDv7 format. Expected: xxxxxxxx-xxxx-7xxx-8xxx-xxxxxxxxxxxx");
1863
+ var sha256Pattern = /^[0-9a-f]{64}$/i;
1864
+ var sha256Schema = z.string().regex(sha256Pattern, "Invalid SHA-256 hash format. Expected: 64 hex characters");
1865
+ var eventTypePattern = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
1866
+ var eventTypeSchema = z.string().regex(eventTypePattern, "Invalid event type format. Expected: domain.entity.action (e.g., snapshot.blob.created)").max(64, "Event type must be \u226464 characters");
1867
+ z.enum([
1868
+ "immediate",
1869
+ "normal",
1870
+ "batch"
1871
+ ]);
1872
+ var spineEnvelopeSchema = z.object({
1873
+ /** UUIDv7 for ordering + deduplication */
1874
+ eventId: uuidv7Schema,
1875
+ /** Integer schema version; increments on breaking change (M9) */
1876
+ schemaVersion: z.number().int().positive(),
1877
+ /** Domain.Entity.Action naming convention (§3.3) */
1878
+ eventType: eventTypeSchema,
1879
+ /** Unix timestamp in milliseconds (daemon-local clock) */
1880
+ occurredAt: z.number().int().positive(),
1881
+ /** SHA-256 of workspace path (M7) */
1882
+ workspaceHash: sha256Schema,
1883
+ /** Attribution discriminated union (§3.2) */
1884
+ attribution: attributionSchema
1885
+ });
1886
+ var spineOptionalFieldsSchema = z.object({
1887
+ /** Session identifier when operation is session-bound (S1) */
1888
+ sessionId: z.string().uuid().optional(),
1889
+ /** SHA-256 of userId; present only for Pro+ (M7) */
1890
+ userHash: sha256Schema.optional(),
1891
+ /** SHA-256 of orgId; present only for Team+ (M7) */
1892
+ orgHash: sha256Schema.optional(),
1893
+ /** SHA-256 of file path; never raw path (M7, N3) */
1894
+ filePathHash: sha256Schema.optional()
1895
+ });
1896
+ function createSpineEventSchema(dataSchema) {
1897
+ return spineEnvelopeSchema.merge(spineOptionalFieldsSchema).merge(z.object({
1898
+ data: dataSchema
1899
+ }));
1900
+ }
1901
+ __name(createSpineEventSchema, "createSpineEventSchema");
1902
+ var snapshotTriggerSchema = z.enum([
1903
+ "manual",
1904
+ "auto-save",
1905
+ "pre-command",
1906
+ "session-end",
1907
+ "shutdown"
1908
+ ]);
1909
+ var riskLevelSchema = z.enum([
1910
+ "low",
1911
+ "medium",
1912
+ "high",
1913
+ "critical"
1914
+ ]);
1915
+ var snapshotRiskSchema = z.object({
1916
+ score: z.number().min(0),
1917
+ level: riskLevelSchema
1918
+ });
1919
+ var snapshotBlobCreatedDataSchema = z.object({
1920
+ /** Unique snapshot identifier */
1921
+ snapshotId: z.string().uuid(),
1922
+ /** SHA-256 hash of file content (never raw content) */
1923
+ contentHash: z.string().regex(/^[0-9a-f]{64}$/i),
1924
+ /** Size of snapshot in bytes */
1925
+ sizeBytes: z.number().int().nonnegative(),
1926
+ /** What triggered the snapshot creation */
1927
+ trigger: snapshotTriggerSchema,
1928
+ /** Risk assessment at time of snapshot */
1929
+ risk: snapshotRiskSchema.optional(),
1930
+ /** AI tool attribution confidence if detected */
1931
+ toolConfidence: z.number().min(0).max(1).optional()
1932
+ });
1933
+ var snapshotBlobCreatedSchema = createSpineEventSchema(snapshotBlobCreatedDataSchema);
1934
+ var SNAPSHOT_BLOB_CREATED = "snapshot.blob.created";
1935
+ var snapshotBlobRestoredDataSchema = z.object({
1936
+ /** Snapshot identifier that was restored */
1937
+ snapshotId: z.string().uuid(),
1938
+ /** Time when snapshot was originally created */
1939
+ originalCreatedAt: z.number().int().positive(),
1940
+ /** Trigger for the restore operation */
1941
+ trigger: z.enum([
1942
+ "manual",
1943
+ "rollback",
1944
+ "undo",
1945
+ "system"
1946
+ ]),
1947
+ /** Time taken to restore in milliseconds */
1948
+ durationMs: z.number().int().nonnegative()
1949
+ });
1950
+ var snapshotBlobRestoredSchema = createSpineEventSchema(snapshotBlobRestoredDataSchema);
1951
+ var SNAPSHOT_BLOB_RESTORED = "snapshot.blob.restored";
1952
+ var snapshotBlobDeletedDataSchema = z.object({
1953
+ /** Array of snapshot identifiers that were deleted */
1954
+ snapshotIds: z.array(z.string().uuid()),
1955
+ /** Reason for deletion */
1956
+ reason: z.enum([
1957
+ "retention-policy",
1958
+ "user-request",
1959
+ "corrupted",
1960
+ "gc"
1961
+ ]),
1962
+ /** Number of bytes freed */
1963
+ bytesFreed: z.number().int().nonnegative()
1964
+ });
1965
+ var snapshotBlobDeletedSchema = createSpineEventSchema(snapshotBlobDeletedDataSchema);
1966
+ var SNAPSHOT_BLOB_DELETED = "snapshot.blob.deleted";
1967
+ var snapshotMetadataUpdatedDataSchema = z.object({
1968
+ /** Snapshot identifier */
1969
+ snapshotId: z.string().uuid(),
1970
+ /** Fields that were updated */
1971
+ updatedFields: z.array(z.enum([
1972
+ "tags",
1973
+ "risk",
1974
+ "annotation",
1975
+ "protection"
1976
+ ])),
1977
+ /** Previous risk level if risk was updated */
1978
+ previousRisk: riskLevelSchema.optional(),
1979
+ /** New risk level if risk was updated */
1980
+ newRisk: riskLevelSchema.optional()
1981
+ });
1982
+ var snapshotMetadataUpdatedSchema = createSpineEventSchema(snapshotMetadataUpdatedDataSchema);
1983
+ var SNAPSHOT_METADATA_UPDATED = "snapshot.metadata.updated";
1984
+ var SNAPSHOT_EVENT_SCHEMAS = {
1985
+ [SNAPSHOT_BLOB_CREATED]: snapshotBlobCreatedSchema,
1986
+ [SNAPSHOT_BLOB_RESTORED]: snapshotBlobRestoredSchema,
1987
+ [SNAPSHOT_BLOB_DELETED]: snapshotBlobDeletedSchema,
1988
+ [SNAPSHOT_METADATA_UPDATED]: snapshotMetadataUpdatedSchema
1989
+ };
1990
+ var coherenceAssessmentSchema = z.enum([
1991
+ "focused",
1992
+ "moderate",
1993
+ "scattered",
1994
+ "chaotic"
1995
+ ]);
1996
+ var sessionOutcomeSchema = z.enum([
1997
+ "completed",
1998
+ "interrupted",
1999
+ "abandoned",
2000
+ "timeout",
2001
+ "rolled-back"
2002
+ ]);
2003
+ var sessionLifecycleStartedDataSchema = z.object({
2004
+ /** Session identifier */
2005
+ sessionId: z.string().uuid(),
2006
+ /** Task description provided by user or inferred */
2007
+ task: z.string().min(1).max(500),
2008
+ /** Session start timestamp */
2009
+ startedAt: z.number().int().positive(),
2010
+ /** Initial coherence score */
2011
+ initialCoherence: z.number().min(0).max(1).optional(),
2012
+ /** Client that initiated the session */
2013
+ clientType: z.enum([
2014
+ "vscode",
2015
+ "jetbrains",
2016
+ "cli",
2017
+ "mcp",
2018
+ "unknown"
2019
+ ])
2020
+ });
2021
+ var sessionLifecycleStartedSchema = createSpineEventSchema(sessionLifecycleStartedDataSchema);
2022
+ var SESSION_LIFECYCLE_STARTED = "session.lifecycle.started";
2023
+ var sessionLifecycleEndedDataSchema = z.object({
2024
+ /** Session identifier */
2025
+ sessionId: z.string().uuid(),
2026
+ /** Session end timestamp */
2027
+ endedAt: z.number().int().positive(),
2028
+ /** Duration in milliseconds */
2029
+ durationMs: z.number().int().nonnegative(),
2030
+ /** Session outcome */
2031
+ outcome: sessionOutcomeSchema,
2032
+ /** Final coherence score */
2033
+ finalCoherence: z.number().min(0).max(1),
2034
+ /** Number of snapshots created during session */
2035
+ snapshotCount: z.number().int().nonnegative(),
2036
+ /** Number of rollbacks performed */
2037
+ rollbackCount: z.number().int().nonnegative()
2038
+ });
2039
+ var sessionLifecycleEndedSchema = createSpineEventSchema(sessionLifecycleEndedDataSchema);
2040
+ var SESSION_LIFECYCLE_ENDED = "session.lifecycle.ended";
2041
+ var sessionCoherenceUpdatedDataSchema = z.object({
2042
+ /** Session identifier */
2043
+ sessionId: z.string().uuid(),
2044
+ /** Updated coherence score 0.0-1.0 */
2045
+ score: z.number().min(0).max(1),
2046
+ /** Assessment category */
2047
+ assessment: coherenceAssessmentSchema,
2048
+ /** Number of detected context clusters */
2049
+ clusterCount: z.number().int().nonnegative(),
2050
+ /** Time since session start in milliseconds */
2051
+ elapsedMs: z.number().int().nonnegative()
2052
+ });
2053
+ var sessionCoherenceUpdatedSchema = createSpineEventSchema(sessionCoherenceUpdatedDataSchema);
2054
+ var SESSION_COHERENCE_UPDATED = "session.coherence.updated";
2055
+ var sessionCheckpointCreatedDataSchema = z.object({
2056
+ /** Session identifier */
2057
+ sessionId: z.string().uuid(),
2058
+ /** Checkpoint identifier */
2059
+ checkpointId: z.string().uuid(),
2060
+ /** Description of checkpoint state */
2061
+ description: z.string().min(1).max(500),
2062
+ /** Coherence score at checkpoint time */
2063
+ coherenceAtCheckpoint: z.number().min(0).max(1),
2064
+ /** Number of changes since session start */
2065
+ changeCount: z.number().int().nonnegative()
2066
+ });
2067
+ var sessionCheckpointCreatedSchema = createSpineEventSchema(sessionCheckpointCreatedDataSchema);
2068
+ var SESSION_CHECKPOINT_CREATED = "session.checkpoint.created";
2069
+ var SESSION_EVENT_SCHEMAS = {
2070
+ [SESSION_LIFECYCLE_STARTED]: sessionLifecycleStartedSchema,
2071
+ [SESSION_LIFECYCLE_ENDED]: sessionLifecycleEndedSchema,
2072
+ [SESSION_COHERENCE_UPDATED]: sessionCoherenceUpdatedSchema,
2073
+ [SESSION_CHECKPOINT_CREATED]: sessionCheckpointCreatedSchema
2074
+ };
2075
+ var riskLevelSchema2 = z.enum([
2076
+ "low",
2077
+ "medium",
2078
+ "high",
2079
+ "critical"
2080
+ ]);
2081
+ var riskScoreSchema = z.number().min(0);
2082
+ var riskSignalFatigueDetectedDataSchema = z.object({
2083
+ /** Workspace hash (from envelope, but also referenced in data for clarity) */
2084
+ workspaceHash: z.string().regex(/^[0-9a-f]{64}$/i),
2085
+ /** Fatigue level assessment */
2086
+ level: z.enum([
2087
+ "rested",
2088
+ "normal",
2089
+ "elevated",
2090
+ "fatigued"
2091
+ ]),
2092
+ /** Risk score boost factor from fatigue */
2093
+ riskBoost: z.number().min(0),
2094
+ /** Ratio of rapid accepts to total suggestions */
2095
+ rapidAcceptRatio: z.number().min(0).max(1),
2096
+ /** Time window for fatigue detection in milliseconds */
2097
+ windowMs: z.number().int().positive(),
2098
+ /** Number of suggestions in detection window */
2099
+ suggestionCount: z.number().int().nonnegative(),
2100
+ /** Session ID if part of tracked session */
2101
+ sessionId: z.string().uuid().optional()
2102
+ });
2103
+ var riskSignalFatigueDetectedSchema = createSpineEventSchema(riskSignalFatigueDetectedDataSchema);
2104
+ var RISK_SIGNAL_FATIGUE_DETECTED = "risk.signal.fatigue-detected";
2105
+ var riskSignalFragileDetectedDataSchema = z.object({
2106
+ /** Fragility score 0.0-1.0 */
2107
+ fragilityScore: z.number().min(0).max(1),
2108
+ /** Severity assessment */
2109
+ severity: z.enum([
2110
+ "moderate",
2111
+ "high",
2112
+ "critical"
2113
+ ]),
2114
+ /** Detection reason code */
2115
+ reason: z.enum([
2116
+ "rapid-changes",
2117
+ "incomplete-pattern",
2118
+ "dependency-risk",
2119
+ "complexity-spike",
2120
+ "unknown-tool"
2121
+ ]),
2122
+ /** Confidence in fragility assessment */
2123
+ confidence: z.number().min(0).max(1),
2124
+ /** Related snapshot hash if applicable */
2125
+ snapshotHash: z.string().regex(/^[0-9a-f]{64}$/i).optional()
2126
+ });
2127
+ var riskSignalFragileDetectedSchema = createSpineEventSchema(riskSignalFragileDetectedDataSchema);
2128
+ var RISK_SIGNAL_FRAGILE_DETECTED = "risk.signal.fragile-detected";
2129
+ var riskSignalPoisoningDetectedDataSchema = z.object({
2130
+ /** Unique fingerprint of poisoning pattern */
2131
+ fingerprint: z.string().regex(/^[0-9a-f]{64}$/i),
2132
+ /** Number of distinct sessions showing this pattern */
2133
+ distinctSessions: z.number().int().positive(),
2134
+ /** Tools involved in poisoning pattern */
2135
+ toolFingerprints: z.array(z.string().regex(/^[0-9a-f]{64}$/i)).max(10),
2136
+ /** Detection confidence */
2137
+ confidence: z.number().min(0).max(1),
2138
+ /** Pattern category */
2139
+ category: z.enum([
2140
+ "repeated-error",
2141
+ "anti-pattern",
2142
+ "degraded-quality",
2143
+ "attribution-drift"
2144
+ ])
2145
+ });
2146
+ var riskSignalPoisoningDetectedSchema = createSpineEventSchema(riskSignalPoisoningDetectedDataSchema);
2147
+ var RISK_SIGNAL_POISONING_DETECTED = "risk.signal.poisoning-detected";
2148
+ var riskScoreUpdatedDataSchema = z.object({
2149
+ /** New risk score */
2150
+ score: riskScoreSchema,
2151
+ /** New risk level */
2152
+ level: riskLevelSchema2,
2153
+ /** Previous score */
2154
+ previousScore: riskScoreSchema,
2155
+ /** Previous level */
2156
+ previousLevel: riskLevelSchema2,
2157
+ /** Contributing factors to score change */
2158
+ factors: z.array(z.object({
2159
+ name: z.string().min(1).max(100),
2160
+ impact: z.enum([
2161
+ "positive",
2162
+ "negative",
2163
+ "neutral"
2164
+ ]),
2165
+ weight: z.number().min(0).max(1)
2166
+ })).max(10),
2167
+ /** Risk change trigger */
2168
+ trigger: z.enum([
2169
+ "snapshot-created",
2170
+ "snapshot-restored",
2171
+ "session-changed",
2172
+ "manual-adjustment",
2173
+ "auto-recalculation"
2174
+ ])
2175
+ });
2176
+ var riskScoreUpdatedSchema = createSpineEventSchema(riskScoreUpdatedDataSchema);
2177
+ var RISK_SCORE_UPDATED = "risk.score.updated";
2178
+ var RISK_EVENT_SCHEMAS = {
2179
+ [RISK_SIGNAL_FATIGUE_DETECTED]: riskSignalFatigueDetectedSchema,
2180
+ [RISK_SIGNAL_FRAGILE_DETECTED]: riskSignalFragileDetectedSchema,
2181
+ [RISK_SIGNAL_POISONING_DETECTED]: riskSignalPoisoningDetectedSchema,
2182
+ [RISK_SCORE_UPDATED]: riskScoreUpdatedSchema
2183
+ };
2184
+ var learningTypeSchema = z.enum([
2185
+ "recovery",
2186
+ "workflow",
2187
+ "risk",
2188
+ "attribution",
2189
+ "tool-preference"
2190
+ ]);
2191
+ var learningConfidenceSchema = z.enum([
2192
+ "hypothesis",
2193
+ "emerging",
2194
+ "established",
2195
+ "validated"
2196
+ ]);
2197
+ var learningPatternRecordedDataSchema = z.object({
2198
+ /** Pattern identifier */
2199
+ patternId: z.string().uuid(),
2200
+ /** Pattern type category */
2201
+ type: learningTypeSchema,
2202
+ /** Human-readable pattern description */
2203
+ description: z.string().min(1).max(1e3),
2204
+ /** Pattern confidence level */
2205
+ confidence: learningConfidenceSchema,
2206
+ /** Occurrence count for this pattern */
2207
+ occurrenceCount: z.number().int().nonnegative(),
2208
+ /** First observed timestamp */
2209
+ firstObservedAt: z.number().int().positive(),
2210
+ /** Pattern features (hashed/anonymized) */
2211
+ featureHash: z.string().regex(/^[0-9a-f]{64}$/i),
2212
+ /** Whether pattern has been validated through outcomes */
2213
+ isValidated: z.boolean()
2214
+ });
2215
+ var learningPatternRecordedSchema = createSpineEventSchema(learningPatternRecordedDataSchema);
2216
+ var LEARNING_PATTERN_RECORDED = "learning.pattern.recorded";
2217
+ var learningPatternPromotedDataSchema = z.object({
2218
+ /** Pattern identifier */
2219
+ patternId: z.string().uuid(),
2220
+ /** Previous confidence level */
2221
+ previousConfidence: learningConfidenceSchema,
2222
+ /** New confidence level */
2223
+ newConfidence: learningConfidenceSchema,
2224
+ /** Number of occurrences at promotion time */
2225
+ occurrenceCount: z.number().int().positive(),
2226
+ /** Outcome ratio (successes / total) */
2227
+ outcomeRatio: z.number().min(0).max(1),
2228
+ /** Promotion timestamp */
2229
+ promotedAt: z.number().int().positive()
2230
+ });
2231
+ var learningPatternPromotedSchema = createSpineEventSchema(learningPatternPromotedDataSchema);
2232
+ var LEARNING_PATTERN_PROMOTED = "learning.pattern.promoted";
2233
+ var learningPatternPrunedDataSchema = z.object({
2234
+ /** Number of patterns pruned */
2235
+ count: z.number().int().nonnegative(),
2236
+ /** Pruning reason */
2237
+ reason: z.enum([
2238
+ "stale",
2239
+ "low-confidence",
2240
+ "invalidated",
2241
+ "redundant"
2242
+ ]),
2243
+ /** Oldest pattern age at pruning in milliseconds */
2244
+ oldestPatternAgeMs: z.number().int().nonnegative(),
2245
+ /** Pruning timestamp */
2246
+ prunedAt: z.number().int().positive()
2247
+ });
2248
+ var learningPatternPrunedSchema = createSpineEventSchema(learningPatternPrunedDataSchema);
2249
+ var LEARNING_PATTERN_PRUNED = "learning.pattern.pruned";
2250
+ var learningAnnotationAddedDataSchema = z.object({
2251
+ /** Annotation identifier */
2252
+ annotationId: z.string().uuid(),
2253
+ /** Tag/category for the annotation */
2254
+ tag: z.string().min(1).max(100),
2255
+ /** Risk signal direction */
2256
+ riskSignal: z.object({
2257
+ direction: z.enum([
2258
+ "increasing",
2259
+ "decreasing",
2260
+ "stable"
2261
+ ]),
2262
+ magnitude: z.number().min(0).max(1)
2263
+ }),
2264
+ /** Related snapshot hash */
2265
+ snapshotHash: z.string().regex(/^[0-9a-f]{64}$/i),
2266
+ /** Annotation timestamp */
2267
+ annotatedAt: z.number().int().positive(),
2268
+ /** Session ID if part of tracked session */
2269
+ sessionId: z.string().uuid().optional()
2270
+ });
2271
+ var learningAnnotationAddedSchema = createSpineEventSchema(learningAnnotationAddedDataSchema);
2272
+ var LEARNING_ANNOTATION_ADDED = "learning.annotation.added";
2273
+ var LEARNING_EVENT_SCHEMAS = {
2274
+ [LEARNING_PATTERN_RECORDED]: learningPatternRecordedSchema,
2275
+ [LEARNING_PATTERN_PROMOTED]: learningPatternPromotedSchema,
2276
+ [LEARNING_PATTERN_PRUNED]: learningPatternPrunedSchema,
2277
+ [LEARNING_ANNOTATION_ADDED]: learningAnnotationAddedSchema
2278
+ };
2279
+ var fileOperationSchema = z.enum([
2280
+ "create",
2281
+ "modify",
2282
+ "delete",
2283
+ "rename"
2284
+ ]);
2285
+ var fileCategorySchema = z.enum([
2286
+ "source-code",
2287
+ "configuration",
2288
+ "documentation",
2289
+ "test",
2290
+ "asset",
2291
+ "other"
2292
+ ]);
2293
+ var fileWatchModifiedDataSchema = z.object({
2294
+ /** SHA-256 hash of file path (never raw path per M7, N3) */
2295
+ filePathHash: z.string().regex(/^[0-9a-f]{64}$/i),
2296
+ /** File extension category */
2297
+ category: fileCategorySchema,
2298
+ /** Operation type */
2299
+ operation: fileOperationSchema,
2300
+ /** Size change in bytes (positive for growth, negative for shrinkage) */
2301
+ sizeChangeBytes: z.number().int(),
2302
+ /** Lines changed (if applicable) */
2303
+ linesChanged: z.number().int().optional(),
2304
+ /** Whether change is attributed to AI tool */
2305
+ aiAttributed: z.boolean(),
2306
+ /** Tool confidence if AI attributed */
2307
+ toolConfidence: z.number().min(0).max(1).optional(),
2308
+ /** Time since last modification in milliseconds */
2309
+ timeSinceLastModifyMs: z.number().int().nonnegative().optional()
2310
+ });
2311
+ var fileWatchModifiedSchema = createSpineEventSchema(fileWatchModifiedDataSchema);
2312
+ var FILE_WATCH_MODIFIED = "file.watch.modified";
2313
+ var fileWatchBatchDataSchema = z.object({
2314
+ /** Number of files in batch */
2315
+ fileCount: z.number().int().positive().max(100),
2316
+ /** Operations summary */
2317
+ operations: z.object({
2318
+ create: z.number().int().nonnegative(),
2319
+ modify: z.number().int().nonnegative(),
2320
+ delete: z.number().int().nonnegative(),
2321
+ rename: z.number().int().nonnegative()
2322
+ }),
2323
+ /** Categories summary */
2324
+ categories: z.object({
2325
+ "source-code": z.number().int().nonnegative(),
2326
+ configuration: z.number().int().nonnegative(),
2327
+ documentation: z.number().int().nonnegative(),
2328
+ test: z.number().int().nonnegative(),
2329
+ asset: z.number().int().nonnegative(),
2330
+ other: z.number().int().nonnegative()
2331
+ }),
2332
+ /** Batch time window in milliseconds */
2333
+ windowMs: z.number().int().positive(),
2334
+ /** Whether any changes are AI attributed */
2335
+ aiAttributed: z.boolean()
2336
+ });
2337
+ var fileWatchBatchSchema = createSpineEventSchema(fileWatchBatchDataSchema);
2338
+ var FILE_WATCH_BATCH = "file.watch.batch";
2339
+ var fileProtectionChangedDataSchema = z.object({
2340
+ /** SHA-256 hash of file path */
2341
+ filePathHash: z.string().regex(/^[0-9a-f]{64}$/i),
2342
+ /** New protection level */
2343
+ newLevel: z.enum([
2344
+ "watch",
2345
+ "warn",
2346
+ "block"
2347
+ ]),
2348
+ /** Previous protection level */
2349
+ previousLevel: z.enum([
2350
+ "watch",
2351
+ "warn",
2352
+ "block"
2353
+ ]).optional(),
2354
+ /** Source of protection change */
2355
+ source: z.enum([
2356
+ "auto-risk",
2357
+ "manual-user",
2358
+ "config-rule",
2359
+ "session-context"
2360
+ ]),
2361
+ /** Risk score at time of change */
2362
+ riskScore: z.number().min(0).optional(),
2363
+ /** Session ID if part of tracked session */
2364
+ sessionId: z.string().uuid().optional()
2365
+ });
2366
+ var fileProtectionChangedSchema = createSpineEventSchema(fileProtectionChangedDataSchema);
2367
+ var FILE_PROTECTION_CHANGED = "file.protection.changed";
2368
+ var FILE_EVENT_SCHEMAS = {
2369
+ [FILE_WATCH_MODIFIED]: fileWatchModifiedSchema,
2370
+ [FILE_WATCH_BATCH]: fileWatchBatchSchema,
2371
+ [FILE_PROTECTION_CHANGED]: fileProtectionChangedSchema
2372
+ };
2373
+
2374
+ // ../../packages/contracts/dist/events/spine/index.js
2375
+ [
2376
+ ...Object.keys(SNAPSHOT_EVENT_SCHEMAS),
2377
+ ...Object.keys(SESSION_EVENT_SCHEMAS),
2378
+ ...Object.keys(RISK_EVENT_SCHEMAS),
2379
+ ...Object.keys(LEARNING_EVENT_SCHEMAS),
2380
+ ...Object.keys(FILE_EVENT_SCHEMAS)
2381
+ ];
2382
+
2383
+ // ../../packages/contracts/dist/features.js
2384
+ var FEATURE_FLAGS = {
2385
+ // Core protection features
2386
+ "protection.enabled": true,
2387
+ "protection.auto_checkpoint": true,
2388
+ "protection.pre_save_hook": true,
2389
+ // Risk analysis
2390
+ "risk.guardian_v2": false,
2391
+ "risk.dependency_analysis": true,
2392
+ "risk.deep_analysis": false,
2393
+ "risk.ai_detection": true,
2394
+ // Storage
2395
+ "storage.compression": true,
2396
+ "storage.deduplication": false,
2397
+ "storage.encryption": false,
2398
+ // UI/UX
2399
+ "ui.chat_participant": true,
2400
+ "ui.status_bar": true,
2401
+ "ui.timeline_view": true,
2402
+ // Telemetry
2403
+ "telemetry.detailed_events": false,
2404
+ "telemetry.performance_metrics": true,
2405
+ "telemetry.sampling_rate": 1,
2406
+ // Experimental
2407
+ "experimental.mcp_tools": false,
2408
+ "experimental.recovery_mode": false,
2409
+ // Intelligence Layer (WU-4.1b)
2410
+ "intelligence.layer": false,
2411
+ "intelligence.trust_calibration": false,
2412
+ "intelligence.pattern_library": false,
2413
+ // A/B Testing - DeepScan
2414
+ "deepscan.v2_algorithm": false,
2415
+ "deepscan.enhanced_analysis": false,
2416
+ "deepscan.real_time_processing": false,
2417
+ // Event System Migration
2418
+ "events.eventemitter2": false
2419
+ };
2420
+
2421
+ // ../../packages/contracts/dist/feature-manager.js
2422
+ var logger = createLogger({
2423
+ name: "feature-manager",
2424
+ level: LogLevel.INFO
2425
+ });
2426
+ var FeatureManager = class _FeatureManager {
2427
+ static {
2428
+ __name(this, "FeatureManager");
2429
+ }
2430
+ static instance;
2431
+ flags = /* @__PURE__ */ new Map();
2432
+ posthogClient = null;
2433
+ constructor() {
2434
+ for (const [key, value] of Object.entries(FEATURE_FLAGS)) {
2435
+ this.flags.set(key, value);
2436
+ }
2437
+ this.loadEnvironmentOverrides();
2438
+ }
2439
+ static getInstance() {
2440
+ if (!_FeatureManager.instance) {
2441
+ _FeatureManager.instance = new _FeatureManager();
2442
+ }
2443
+ return _FeatureManager.instance;
2444
+ }
2445
+ isEnabled(flag) {
2446
+ const value = this.flags.get(flag) ?? FEATURE_FLAGS[flag];
2447
+ if (flag === "telemetry.sampling_rate" && typeof value === "number") {
2448
+ return Math.random() < value;
2449
+ }
2450
+ return Boolean(value);
2451
+ }
2452
+ getValue(flag) {
2453
+ return this.flags.get(flag);
2454
+ }
2455
+ setFlag(flag, value) {
2456
+ this.flags.set(flag, value);
2457
+ }
2458
+ /**
2459
+ * Set PostHog client for dynamic feature flag evaluation
2460
+ */
2461
+ setPostHogClient(client) {
2462
+ this.posthogClient = client;
2463
+ if (client) {
2464
+ logger.info("PostHog client configured");
2465
+ } else {
2466
+ logger.info("PostHog client cleared, falling back to static config");
2467
+ }
2468
+ }
2469
+ /**
2470
+ * Get configured PostHog client
2471
+ */
2472
+ getPostHogClient() {
2473
+ return this.posthogClient;
2474
+ }
2475
+ /**
2476
+ * Asynchronously check if feature is enabled (with PostHog fallback)
2477
+ * @param flag - Feature flag name
2478
+ * @param userId - User ID for targeting rules (optional)
2479
+ * @param context - Additional context for PostHog targeting (optional)
2480
+ * @returns Promise<boolean> - True if feature is enabled
2481
+ */
2482
+ async isEnabledAsync(flag, userId, context) {
2483
+ if (this.posthogClient && userId) {
2484
+ try {
2485
+ const defaultSubscriptionTier = process.env.VREKO_DEFAULT_SUBSCRIPTION_TIER || "free";
2486
+ const posthogContext = {
2487
+ subscriptionTier: defaultSubscriptionTier,
2488
+ ...context
2489
+ };
2490
+ const result = await this.posthogClient.isFeatureEnabled(flag, userId, posthogContext);
2491
+ if (result !== null && result !== void 0) {
2492
+ logger.info("Feature flag evaluated via PostHog", {
2493
+ flag,
2494
+ userId,
2495
+ enabled: result
2496
+ });
2497
+ return result;
2498
+ }
2499
+ } catch (error) {
2500
+ logger.warn("PostHog feature flag check failed, falling back to static config", {
2501
+ flag,
2502
+ userId,
2503
+ error: error instanceof Error ? error.message : String(error)
2504
+ });
2505
+ }
2506
+ }
2507
+ return this.isEnabled(flag);
2508
+ }
2509
+ loadEnvironmentOverrides() {
2510
+ for (const flag of Object.keys(FEATURE_FLAGS)) {
2511
+ const envVar = `VREKO_${flag.replace(/\./g, "_").toUpperCase()}`;
2512
+ const envValue = process.env[envVar];
2513
+ if (envValue !== void 0) {
2514
+ if (envValue === "true" || envValue === "false") {
2515
+ this.flags.set(flag, envValue === "true");
2516
+ } else if (!Number.isNaN(Number(envValue))) {
2517
+ this.flags.set(flag, Number(envValue));
2518
+ }
2519
+ }
2520
+ }
2521
+ }
2522
+ reset() {
2523
+ this.flags.clear();
2524
+ this.posthogClient = null;
2525
+ for (const [key, value] of Object.entries(FEATURE_FLAGS)) {
2526
+ this.flags.set(key, value);
2527
+ }
2528
+ this.loadEnvironmentOverrides();
2529
+ }
2530
+ };
2531
+ z.object({
2532
+ /** Internal ingest record ID */
2533
+ ingestId: z.string().uuid(),
2534
+ /** User ID (for scope resolution) */
2535
+ userId: z.string(),
2536
+ /** Organization ID (null for personal sessions) */
2537
+ organizationId: z.string().uuid().nullable(),
2538
+ /** Session payload (JSONB content) */
2539
+ payload: z.record(z.unknown()),
2540
+ /** Feature flag state for this session */
2541
+ enabledFeatures: z.array(z.string()),
2542
+ /** Tier-based limits */
2543
+ maxReflectionTokens: z.number().int().positive()
2544
+ });
2545
+ z.object({
2546
+ /** Internal ingest record ID */
2547
+ ingestId: z.string().uuid(),
2548
+ /** User ID */
2549
+ userId: z.string(),
2550
+ /** Organization ID */
2551
+ organizationId: z.string().uuid().nullable(),
2552
+ /** Session payload (for pattern analysis) */
2553
+ payload: z.record(z.unknown()),
2554
+ /** User's outcome assessment (optional - can be computed) */
2555
+ userOutcome: z.object({
2556
+ /** Was the session successful? */
2557
+ success: z.boolean(),
2558
+ /** User's description of outcome */
2559
+ description: z.string().max(500).optional()
2560
+ }).optional()
2561
+ });
2562
+ var MissingContextCategorySchema = z.enum([
2563
+ "eventual_consistency_contract",
2564
+ "shared_dependency",
2565
+ "test_coverage_gap",
2566
+ "implicit_ownership",
2567
+ "prior_breakage_history",
2568
+ "async_message_contract",
2569
+ "environment_coupling",
2570
+ "undocumented_invariant",
2571
+ "other"
2572
+ ]);
2573
+ var MissingContextItemSchema = z.object({
2574
+ category: MissingContextCategorySchema,
2575
+ description: z.string().max(200),
2576
+ affectedFiles: z.array(z.string()).optional(),
2577
+ severity: z.enum([
2578
+ "high",
2579
+ "medium",
2580
+ "low"
2581
+ ])
2582
+ });
2583
+ var ConfidenceGapItemSchema = z.object({
2584
+ filePath: z.string().min(1),
2585
+ reason: z.string().max(150),
2586
+ confidenceScore: z.number().min(0).max(1)
2587
+ });
2588
+ var ContributingFactorSchema = z.enum([
2589
+ "multi_service_change",
2590
+ "high_churn_file",
2591
+ "ai_generated_without_tests",
2592
+ "dependency_boundary_crossed",
2593
+ "config_file_modified",
2594
+ "auth_middleware_touched",
2595
+ "database_schema_changed"
2596
+ ]);
2597
+ z.object({
2598
+ schemaVersion: z.literal("sb.reflection.v1"),
2599
+ missingContext: z.array(MissingContextItemSchema),
2600
+ confidenceGaps: z.array(ConfidenceGapItemSchema),
2601
+ wouldHaveChangedApproach: z.boolean(),
2602
+ contributingFactors: z.array(ContributingFactorSchema),
2603
+ rawSummary: z.string().max(600),
2604
+ generatedBy: z.enum([
2605
+ "llm",
2606
+ "heuristic"
2607
+ ])
2608
+ });
2609
+ var OrgModeSchema = z.enum([
2610
+ "none",
2611
+ "shared",
2612
+ "ring_fenced"
2613
+ ]);
2614
+ z.object({
2615
+ personal: z.boolean(),
2616
+ global: z.boolean(),
2617
+ org: z.object({
2618
+ orgId: z.string(),
2619
+ mode: OrgModeSchema
2620
+ }).nullable()
2621
+ });
2622
+
2623
+ // ../../packages/contracts/dist/observability/types.js
2624
+ var SpanStatusCode;
2625
+ (function(SpanStatusCode2) {
2626
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
2627
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
2628
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
2629
+ })(SpanStatusCode || (SpanStatusCode = {}));
2630
+ var SpanKind;
2631
+ (function(SpanKind2) {
2632
+ SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
2633
+ SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER";
2634
+ SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT";
2635
+ SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER";
2636
+ SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
2637
+ })(SpanKind || (SpanKind = {}));
2638
+
2639
+ // ../../packages/contracts/dist/pioneer/events.js
2640
+ var PIONEER_EVENTS = {
2641
+ INVITE_CODE_REDEEMED: "invite_code_redeemed",
2642
+ CLI_INSTALLED: "cli_installed",
2643
+ EXTENSION_INSTALLED: "extension_installed",
2644
+ FIRST_SESSION: "first_session",
2645
+ FIRST_SNAPSHOT: "first_snapshot",
2646
+ FIRST_CEREMONY: "first_ceremony",
2647
+ FIRST_INTELLIGENCE_FILE_CARD: "first_intelligence_file_card",
2648
+ FIRST_RECOVERY: "first_recovery"
2649
+ };
2650
+ var IDE_VALUES = [
2651
+ "vscode",
2652
+ "cursor",
2653
+ "windsurf",
2654
+ "qoder",
2655
+ "jetbrains",
2656
+ "neovim",
2657
+ "other"
2658
+ ];
2659
+ var AI_TOOL_VALUES = [
2660
+ "github-copilot",
2661
+ "cursor-ai",
2662
+ "claude-code",
2663
+ "claude-chat",
2664
+ "chatgpt",
2665
+ "codeium",
2666
+ "amazon-q",
2667
+ "gemini",
2668
+ "morph",
2669
+ "other"
2670
+ ];
2671
+ z.object({
2672
+ email: z.string().email().max(254).transform((e) => e.toLowerCase().trim()),
2673
+ // Optional enrichment branches downstream sequences without gating the capture.
2674
+ intent: z.enum([
2675
+ "solo",
2676
+ "team"
2677
+ ]).optional(),
2678
+ referralCode: z.string().max(64).optional(),
2679
+ // Turnstile token is OPTIONAL at the schema level. Whether it is REQUIRED is
2680
+ // decided at runtime by whether a server secret is configured (see route).
2681
+ turnstileToken: z.string().optional()
2682
+ });
2683
+ var codeRegex = /^[23456789A-HJ-NP-Z]{8}$/;
2684
+ z.object({
2685
+ code: z.string().regex(codeRegex, "invalid_format"),
2686
+ primaryIde: z.enum(IDE_VALUES),
2687
+ aiTools: z.array(z.enum(AI_TOOL_VALUES)).min(1).max(AI_TOOL_VALUES.length)
2688
+ });
2689
+ z.object({
2690
+ id: z.string().min(1),
2691
+ source: z.string().min(1),
2692
+ specversion: z.literal("1.0"),
2693
+ type: z.string().min(1),
2694
+ datacontenttype: z.string().optional(),
2695
+ dataschema: z.string().url().optional(),
2696
+ subject: z.string().optional(),
2697
+ time: z.string().datetime().optional(),
2698
+ data: z.unknown().optional(),
2699
+ // Vreko extensions
2700
+ traceid: z.string().optional(),
2701
+ workspaceid: z.string().optional(),
2702
+ userid: z.string().optional(),
2703
+ sessionid: z.string().optional(),
2704
+ toolurn: z.string().optional(),
2705
+ riskclass: z.enum([
2706
+ "safe",
2707
+ "low",
2708
+ "medium",
2709
+ "high",
2710
+ "critical"
2711
+ ]).optional(),
2712
+ sandboxed: z.boolean().optional(),
2713
+ privacysig: z.string().optional()
2714
+ });
2715
+ z.string().regex(/^\d+\.\d+\.\d+(?:-[\w.]+)?$/, "Invalid semver format. Expected: MAJOR.MINOR.PATCH[-prerelease]");
2716
+ var ToolURNSchema = z.string().regex(/^urn:(vreko|openclaw|community|enterprise):[\w-]+:[\w-]+:\d+\.\d+\.\d+(?:-[\w.]+)?$/, "Invalid URN format. Expected: urn:{namespace}:{pluginId}:{capability}:{semver}").brand();
2717
+
2718
+ // ../../packages/contracts/dist/primitives/tool-invocation.js
2719
+ var AGENT_RUNTIMES = [
2720
+ "claude-code",
2721
+ "cursor",
2722
+ "copilot",
2723
+ "openclaw",
2724
+ "windsurf",
2725
+ "cline",
2726
+ "aider",
2727
+ "continue",
2728
+ "unknown"
2729
+ ];
2730
+ var SANDBOX_LEVELS = [
2731
+ "none",
2732
+ "basic",
2733
+ "strict",
2734
+ "isolated"
2735
+ ];
2736
+ var RISK_CLASSES = [
2737
+ "safe",
2738
+ "low",
2739
+ "medium",
2740
+ "high",
2741
+ "critical"
2742
+ ];
2743
+ var CHANNELS = [
2744
+ "api",
2745
+ "mcp",
2746
+ "vscode",
2747
+ "cli",
2748
+ "web",
2749
+ "whatsapp",
2750
+ "telegram",
2751
+ "discord",
2752
+ "slack",
2753
+ "teams",
2754
+ "matrix"
2755
+ ];
2756
+ var SessionContextSchema = z.object({
2757
+ /** Channel through which request was made */
2758
+ channel: z.enum(CHANNELS),
2759
+ /** Workspace identifier (local path hash or cloud workspace ID) */
2760
+ workspaceId: z.string().min(1),
2761
+ /** Session ID for request correlation */
2762
+ sessionId: z.string().uuid(),
2763
+ /** OpenClaw session ID if bridged */
2764
+ openclawSessionId: z.string().optional(),
2765
+ /** Channel-specific user identifier */
2766
+ channelUserId: z.string().optional()
2767
+ });
2768
+ var IdentityContextSchema = z.object({
2769
+ /** User ID (authenticated) */
2770
+ userId: z.string().uuid().optional(),
2771
+ /** Anonymous identifier for unauthenticated requests */
2772
+ anonymousId: z.string().optional(),
2773
+ /** Current subscription tier */
2774
+ tier: z.enum([
2775
+ "free",
2776
+ "pro",
2777
+ "team",
2778
+ "enterprise"
2779
+ ]).default("free"),
2780
+ /** Enabled features for this user */
2781
+ features: z.array(z.string()).default([]),
2782
+ /** Pre-resolved entitlements (optional, can be fetched) */
2783
+ entitlements: z.object({
2784
+ tier: z.enum([
2785
+ "free",
2786
+ "pro",
2787
+ "team",
2788
+ "enterprise"
2789
+ ]),
2790
+ features: z.array(z.string()),
2791
+ limits: z.record(z.string(), z.number().nullable())
2792
+ }).optional(),
2793
+ /** API key identifier (if using API key auth) */
2794
+ apiKeyId: z.string().optional()
2795
+ });
2796
+ var ToolSpecSchema = z.object({
2797
+ /** Tool URN (canonical identifier) */
2798
+ urn: ToolURNSchema,
2799
+ /** Tool risk classification */
2800
+ riskClass: z.enum(RISK_CLASSES),
2801
+ /** Required permissions to invoke this tool */
2802
+ requiredPermissions: z.array(z.string()).default([]),
2803
+ /** Required features (entitlement check) */
2804
+ requiredFeatures: z.array(z.string()).default([]),
2805
+ /** Minimum tier required */
2806
+ minTier: z.enum([
2807
+ "free",
2808
+ "pro",
2809
+ "team",
2810
+ "enterprise"
2811
+ ]).optional()
2812
+ });
2813
+ var ExecutionContextSchema = z.object({
2814
+ /** Agent runtime that initiated the call */
2815
+ agentRuntime: z.enum(AGENT_RUNTIMES).default("unknown"),
2816
+ /** Required sandbox level */
2817
+ sandboxLevel: z.enum(SANDBOX_LEVELS).default("basic"),
2818
+ /** Timeout in milliseconds */
2819
+ timeoutMs: z.number().positive().default(3e4),
2820
+ /** Whether to auto-snapshot before execution */
2821
+ snapshotBefore: z.boolean().default(false),
2822
+ /** Maximum concurrent executions allowed */
2823
+ maxConcurrent: z.number().positive().default(1),
2824
+ /** Retry configuration */
2825
+ retry: z.object({
2826
+ maxAttempts: z.number().min(1).max(5).default(1),
2827
+ backoffMs: z.number().min(100).max(3e4).default(1e3)
2828
+ }).optional()
2829
+ });
2830
+ z.object({
2831
+ /** Unique trace ID for request correlation and audit */
2832
+ traceId: z.string().uuid(),
2833
+ /** Timestamp when invocation was created */
2834
+ createdAt: z.coerce.date().default(() => /* @__PURE__ */ new Date()),
2835
+ /** Session context - channel and workspace */
2836
+ session: SessionContextSchema,
2837
+ /** Identity context - who and what permissions */
2838
+ identity: IdentityContextSchema,
2839
+ /** Tool specification - what tool and risk class */
2840
+ tool: ToolSpecSchema,
2841
+ /** Tool arguments (validated against tool's input schema) */
2842
+ args: z.record(z.string(), z.unknown()).default({}),
2843
+ /** Execution context - how to execute */
2844
+ context: ExecutionContextSchema,
2845
+ /**
2846
+ * Metadata for observability and debugging
2847
+ * Not used in execution logic, only for tracing
2848
+ */
2849
+ metadata: z.object({
2850
+ /** Source surface that created this invocation */
2851
+ source: z.string().optional(),
2852
+ /** Parent trace ID for nested calls */
2853
+ parentTraceId: z.string().uuid().optional(),
2854
+ /** Custom labels for filtering */
2855
+ labels: z.record(z.string(), z.string()).optional(),
2856
+ /** Original request payload hash (for audit) */
2857
+ requestHash: z.string().optional()
2858
+ }).optional()
2859
+ });
2860
+ var PipelineStepResultSchema = z.object({
2861
+ /** Step name */
2862
+ step: z.string(),
2863
+ /** Whether step passed */
2864
+ passed: z.boolean(),
2865
+ /** Duration in milliseconds */
2866
+ durationMs: z.number(),
2867
+ /** Error if step failed */
2868
+ error: z.object({
2869
+ code: z.string(),
2870
+ message: z.string(),
2871
+ details: z.unknown().optional()
2872
+ }).optional(),
2873
+ /** Step-specific data */
2874
+ data: z.unknown().optional()
2875
+ });
2876
+ z.object({
2877
+ /** Trace ID from invocation */
2878
+ traceId: z.string().uuid(),
2879
+ /** Whether execution succeeded */
2880
+ success: z.boolean(),
2881
+ /** Result data (if successful) */
2882
+ result: z.unknown().optional(),
2883
+ /** Error details (if failed) */
2884
+ error: z.object({
2885
+ code: z.string(),
2886
+ message: z.string(),
2887
+ step: z.string().optional(),
2888
+ details: z.unknown().optional()
2889
+ }).optional(),
2890
+ /** Pipeline step results */
2891
+ steps: z.array(PipelineStepResultSchema),
2892
+ /** Total execution duration */
2893
+ durationMs: z.number(),
2894
+ /** Snapshot ID if created */
2895
+ snapshotId: z.string().optional(),
2896
+ /** Audit log ID */
2897
+ auditId: z.string().optional()
2898
+ });
2899
+
2900
+ // ../../packages/contracts/dist/primitives/execution-pipeline.js
2901
+ var PIPELINE_STEPS = [
2902
+ "validate",
2903
+ "authenticate",
2904
+ "authorize",
2905
+ "rate_limit",
2906
+ "pre_scan",
2907
+ "lease",
2908
+ "snapshot",
2909
+ "execute",
2910
+ "post_scan",
2911
+ "egress",
2912
+ "audit",
2913
+ "finalize"
2914
+ ];
2915
+ z.object({
2916
+ skipSteps: z.array(z.enum(PIPELINE_STEPS)).optional(),
2917
+ timeoutMs: z.number().positive().optional(),
2918
+ continueOnNonCriticalFailure: z.boolean().optional()
2919
+ });
2920
+ z.object({
2921
+ /** Whether the lease was acquired */
2922
+ acquired: z.boolean(),
2923
+ /** Lease ID if acquired */
2924
+ leaseId: z.string().optional(),
2925
+ /** Reason if not acquired */
2926
+ reason: z.string().optional(),
2927
+ /** Conflicting leases if acquisition failed */
2928
+ conflicts: z.array(z.object({
2929
+ leaseId: z.string(),
2930
+ files: z.array(z.string()),
2931
+ heldBy: z.object({
2932
+ agentRuntime: z.enum(AGENT_RUNTIMES),
2933
+ sessionId: z.string()
2934
+ }),
2935
+ expiresAt: z.coerce.date()
2936
+ })).optional()
2937
+ });
2938
+ z.object({
2939
+ /** Whether there are conflicts */
2940
+ hasConflicts: z.boolean(),
2941
+ /** Conflicting files grouped by lease */
2942
+ conflicts: z.array(z.object({
2943
+ leaseId: z.string(),
2944
+ files: z.array(z.string()),
2945
+ heldBy: z.object({
2946
+ agentRuntime: z.enum(AGENT_RUNTIMES),
2947
+ sessionId: z.string()
2948
+ }),
2949
+ expiresAt: z.coerce.date(),
2950
+ /** Whether this conflict is blocking (cannot proceed) */
2951
+ blocking: z.boolean()
2952
+ })),
2953
+ /** Files that are safe to modify */
2954
+ safeFiles: z.array(z.string()),
2955
+ /** Files that are blocked */
2956
+ blockedFiles: z.array(z.string())
2957
+ });
2958
+ z.object({
2959
+ /** Unique lease identifier */
2960
+ leaseId: z.string(),
2961
+ /** Workspace this lease belongs to */
2962
+ workspaceId: z.string(),
2963
+ /** Files covered by this lease */
2964
+ files: z.array(z.string()),
2965
+ /** Agent that holds this lease */
2966
+ agentRuntime: z.enum(AGENT_RUNTIMES),
2967
+ /** Session that holds this lease */
2968
+ sessionId: z.string(),
2969
+ /** Trace ID for correlation */
2970
+ traceId: z.string().optional(),
2971
+ /** When the lease was acquired */
2972
+ acquiredAt: z.coerce.date(),
2973
+ /** When the lease expires */
2974
+ expiresAt: z.coerce.date(),
2975
+ /** Time-to-live in milliseconds */
2976
+ ttlMs: z.number().positive(),
2977
+ /** Whether the lease is still active */
2978
+ active: z.boolean().default(true),
2979
+ /** Number of times the lease has been extended */
2980
+ extensionCount: z.number().default(0)
2981
+ });
2982
+
2983
+ // ../../packages/contracts/dist/saga/tier-upgrade-saga.js
2984
+ var TIER_UPGRADE_SAGA = {
2985
+ sagaType: "tier_upgrade",
2986
+ maxRetries: 3,
2987
+ persistenceInterval: 1e3,
2988
+ steps: [
2989
+ {
2990
+ stepId: "update_subscription",
2991
+ stepName: "Update Subscription in Payment Provider",
2992
+ execute: /* @__PURE__ */ __name(async (_input) => {
2993
+ throw new Error("Not implemented - to be injected");
2994
+ }, "execute"),
2995
+ compensate: /* @__PURE__ */ __name(async (_input, output) => {
2996
+ const typedOutput = output;
2997
+ if (typedOutput?.subscriptionId) ;
2998
+ }, "compensate"),
2999
+ retryable: true,
3000
+ timeout: 3e4
3001
+ },
3002
+ {
3003
+ stepId: "update_user_tier",
3004
+ stepName: "Update User Tier in Database",
3005
+ execute: /* @__PURE__ */ __name(async (_input) => {
3006
+ throw new Error("Not implemented - to be injected");
3007
+ }, "execute"),
3008
+ compensate: /* @__PURE__ */ __name(async (_input, output) => {
3009
+ const typedOutput = output;
3010
+ if (typedOutput?.previousTier) ;
3011
+ }, "compensate"),
3012
+ retryable: true,
3013
+ timeout: 5e3
3014
+ },
3015
+ {
3016
+ stepId: "update_entitlements",
3017
+ stepName: "Update Entitlements with New Tier Features",
3018
+ execute: /* @__PURE__ */ __name(async (_input) => {
3019
+ throw new Error("Not implemented - to be injected");
3020
+ }, "execute"),
3021
+ compensate: /* @__PURE__ */ __name(async (_input, output) => {
3022
+ const typedOutput = output;
3023
+ if (typedOutput?.previousVersion !== void 0) ;
3024
+ }, "compensate"),
3025
+ retryable: true,
3026
+ timeout: 5e3
3027
+ },
3028
+ {
3029
+ stepId: "send_confirmation",
3030
+ stepName: "Send Upgrade Confirmation Email",
3031
+ execute: /* @__PURE__ */ __name(async (_input) => {
3032
+ throw new Error("Not implemented - to be injected");
3033
+ }, "execute"),
3034
+ compensate: /* @__PURE__ */ __name(async (_input, output) => {
3035
+ const typedOutput = output;
3036
+ if (typedOutput?.emailJobId) ;
3037
+ }, "compensate"),
3038
+ retryable: true,
3039
+ timeout: 1e4
3040
+ },
3041
+ {
3042
+ stepId: "emit_event",
3043
+ stepName: "Emit Tier Upgraded Event",
3044
+ execute: /* @__PURE__ */ __name(async (_input) => {
3045
+ throw new Error("Not implemented - to be injected");
3046
+ }, "execute"),
3047
+ // No compensation needed for events (idempotent)
3048
+ retryable: false,
3049
+ timeout: 3e3
3050
+ }
3051
+ ]
3052
+ };
3053
+ var DiffChangeSchema = z.object({
3054
+ added: z.boolean().optional().default(false),
3055
+ removed: z.boolean().optional().default(false),
3056
+ value: z.string(),
3057
+ count: z.number().optional()
3058
+ });
3059
+ var RiskScoreDetailSchema = z.object({
3060
+ score: z.number().min(0).max(10),
3061
+ factors: z.array(z.string()),
3062
+ severity: RiskSeveritySchema
3063
+ });
3064
+ z.object({
3065
+ metrics: z.record(z.string(), z.number()),
3066
+ trends: z.record(z.string(), z.array(z.number())),
3067
+ insights: z.array(z.string()),
3068
+ timestamp: z.number(),
3069
+ snapshotRecommendations: z.object({
3070
+ shouldCreateSnapshot: z.boolean(),
3071
+ reason: z.string(),
3072
+ urgency: RiskSeveritySchema,
3073
+ suggestedTiming: z.string()
3074
+ }).optional()
3075
+ });
3076
+ z.object({
3077
+ trigger: z.string().default("manual"),
3078
+ risk: z.number().min(0).max(10).optional(),
3079
+ content: z.string().optional(),
3080
+ files: z.array(z.string()).optional()
3081
+ });
3082
+ z.object({
3083
+ trigger: z.string().default("manual"),
3084
+ risk: z.number().min(0).max(10).optional(),
3085
+ content: z.string().optional()
3086
+ });
3087
+ z.object({
3088
+ id: z.string(),
3089
+ timestamp: z.number(),
3090
+ meta: z.object({
3091
+ trigger: z.string().optional(),
3092
+ risk: z.number().optional()
3093
+ }).optional()
3094
+ });
3095
+ z.object({
3096
+ changes: z.array(DiffChangeSchema)
3097
+ });
3098
+ z.object({
3099
+ before: z.record(z.string(), z.any()),
3100
+ after: z.record(z.string(), z.any())
3101
+ });
3102
+ z.object({
3103
+ message: z.string(),
3104
+ code: z.string().optional(),
3105
+ details: z.any().optional()
3106
+ });
3107
+ var RetrySchema = z.object({
3108
+ retries: z.number().int().min(0).default(2),
3109
+ factor: z.number().min(1).default(2),
3110
+ min: z.number().int().default(250),
3111
+ max: z.number().int().default(1500),
3112
+ jitter: z.boolean().default(true)
3113
+ });
3114
+ var CircuitSchema = z.object({
3115
+ enabled: z.boolean().default(true),
3116
+ errorThresholdPercentage: z.number().int().min(1).max(100).default(50),
3117
+ volumeThreshold: z.number().int().min(1).default(10),
3118
+ timeoutMs: z.number().int().default(5e3),
3119
+ resetMs: z.number().int().default(3e4),
3120
+ rollingCountMs: z.number().int().default(6e4),
3121
+ rollingCountBuckets: z.number().int().default(6)
3122
+ });
3123
+ z.object({
3124
+ timeoutMs: z.number().int().default(5e3),
3125
+ maxConcurrent: z.number().int().min(1).default(4),
3126
+ retry: RetrySchema,
3127
+ circuit: CircuitSchema,
3128
+ batch: z.object({
3129
+ size: z.number().int().min(1).default(5),
3130
+ maxWaitMs: z.number().int().default(150)
3131
+ })
3132
+ });
3133
+ z.object({
3134
+ debounceMs: z.number().int().default(120),
3135
+ awaitWriteFinish: z.object({
3136
+ stabilityThreshold: z.number().int().default(200),
3137
+ pollInterval: z.number().int().default(50)
3138
+ }),
3139
+ ignored: z.array(z.string()).default([
3140
+ "**/{node_modules,.git,.vscode,dist,.next,.nuxt,coverage}/**"
3141
+ ])
3142
+ });
3143
+ var SessionSchemaVersion = "sb.session.v1";
3144
+ var ChangeOpSchema = z.enum([
3145
+ "created",
3146
+ "modified",
3147
+ "deleted",
3148
+ "renamed"
3149
+ ]);
3150
+ var EOLTypeSchema = z.enum([
3151
+ "lf",
3152
+ "crlf"
3153
+ ]);
3154
+ var SessionTriggerSchema = z.enum([
3155
+ "filewatch",
3156
+ "pre-commit",
3157
+ "manual",
3158
+ "idle-finalize"
3159
+ ]);
3160
+ var SessionChangeSchema = z.object({
3161
+ /** Relative POSIX path from workspace root */
3162
+ p: z.string(),
3163
+ /** Operation type */
3164
+ op: ChangeOpSchema,
3165
+ /** Prior relative path (for rename operations only) */
3166
+ from: z.string().optional(),
3167
+ /** SHA-256 hash before change (CAS reference) - computed on finalize */
3168
+ hOld: z.string().optional(),
3169
+ /** SHA-256 hash after change (CAS reference) - computed on finalize */
3170
+ hNew: z.string().optional(),
3171
+ /** File size before change (bytes) */
3172
+ sizeBefore: z.number().int().nonnegative().optional(),
3173
+ /** File size after change (bytes) */
3174
+ sizeAfter: z.number().int().nonnegative().optional(),
3175
+ /** Modification time before change (Unix epoch ms) */
3176
+ mtimeBefore: z.number().int().nonnegative().optional(),
3177
+ /** Modification time after change (Unix epoch ms) */
3178
+ mtimeAfter: z.number().int().nonnegative().optional(),
3179
+ /** File permissions before change (Unix mode) */
3180
+ modeBefore: z.number().int().nonnegative().optional(),
3181
+ /** File permissions after change (Unix mode) */
3182
+ modeAfter: z.number().int().nonnegative().optional(),
3183
+ /** Line ending style before change */
3184
+ eolBefore: EOLTypeSchema.optional(),
3185
+ /** Line ending style after change */
3186
+ eolAfter: EOLTypeSchema.optional()
3187
+ });
3188
+ z.object({
3189
+ /** Schema version for backward compatibility */
3190
+ schema: z.literal(SessionSchemaVersion),
3191
+ /** Unique session identifier (CUID) */
3192
+ sessionId: z.string(),
3193
+ /** Session start timestamp (ISO 8601) */
3194
+ startedAt: z.string().datetime(),
3195
+ /** Session end timestamp (ISO 8601) - undefined if active */
3196
+ endedAt: z.string().datetime().optional(),
3197
+ /** VS Code workspace folder URI (multi-root workspace safe) */
3198
+ workspaceUri: z.string(),
3199
+ /** Offline-generated semantic label (never transmitted) */
3200
+ name: z.string().optional(),
3201
+ /** Trigger sources for this session */
3202
+ triggers: z.array(SessionTriggerSchema),
3203
+ /** Total number of file changes in this session */
3204
+ changeCount: z.number().int().nonnegative(),
3205
+ /** Chronological list of file changes */
3206
+ filesChanged: z.array(SessionChangeSchema),
3207
+ /** Array of snapshot IDs created during this session */
3208
+ snapshots: z.array(z.string()).optional()
3209
+ });
3210
+ z.object({
3211
+ sessionId: z.string(),
3212
+ startedAt: z.string().datetime(),
3213
+ endedAt: z.string().datetime().optional(),
3214
+ name: z.string().optional(),
3215
+ changeCount: z.number().int().nonnegative(),
3216
+ triggers: z.array(SessionTriggerSchema)
3217
+ });
3218
+ z.object({
3219
+ /** Only return sessions for this workspace URI */
3220
+ workspaceUri: z.string().optional(),
3221
+ /** Only return active sessions (endedAt is null) */
3222
+ activeOnly: z.boolean().optional(),
3223
+ /** Only return finalized sessions (endedAt is not null) */
3224
+ finalizedOnly: z.boolean().optional(),
3225
+ /** Return sessions that started after this timestamp */
3226
+ after: z.date().optional(),
3227
+ /** Return sessions that started before this timestamp */
3228
+ before: z.date().optional(),
3229
+ /** Maximum number of results */
3230
+ limit: z.number().int().positive().optional(),
3231
+ /** Offset for pagination */
3232
+ offset: z.number().int().nonnegative().optional()
3233
+ });
3234
+ z.object({
3235
+ /** VS Code workspace folder URI */
3236
+ workspaceUri: z.string(),
3237
+ /** Initial trigger sources */
3238
+ triggers: z.array(SessionTriggerSchema).default([
3239
+ "filewatch"
3240
+ ]),
3241
+ /** Optional semantic name (generated offline) */
3242
+ name: z.string().optional()
3243
+ });
3244
+ z.object({
3245
+ /** VS Code workspace folder URI (multi-root safe) */
3246
+ workspaceUri: z.string(),
3247
+ /** Idle timeout in milliseconds (default: 15 minutes) */
3248
+ idleMs: z.number().int().positive().default(15 * 6e4),
3249
+ /** Batch size for flushing changes to database (default: 50) */
3250
+ flushBatchSize: z.number().int().positive().default(50),
3251
+ /** Flush interval in milliseconds (default: 5 seconds) */
3252
+ flushIntervalMs: z.number().int().positive().default(5e3),
3253
+ /** Use VS Code file system watcher (default: true) */
3254
+ useVSCodeWatcher: z.boolean().default(true),
3255
+ /** Patterns to ignore (.vrekoignore) */
3256
+ ignorePatterns: z.array(z.string()).default([
3257
+ "node_modules/**",
3258
+ ".next/**",
3259
+ "dist/**",
3260
+ "build/**",
3261
+ "coverage/**",
3262
+ ".git/**",
3263
+ "*.log",
3264
+ "*.tmp",
3265
+ "*.swp",
3266
+ ".DS_Store"
3267
+ ]),
3268
+ /** @enterprise User tier (for analytics) */
3269
+ tier: z.enum([
3270
+ "free",
3271
+ "pro"
3272
+ ]).default("free"),
3273
+ /** @enterprise Analytics consent (Pro tier only) */
3274
+ consent: z.boolean().default(false)
3275
+ });
3276
+ var SessionFileSummarySchema = z.object({
3277
+ path: z.string().min(1),
3278
+ operation: z.enum([
3279
+ "create",
3280
+ "modify",
3281
+ "delete",
3282
+ "rename"
3283
+ ]),
3284
+ riskScore: z.number().min(0).max(10),
3285
+ aiAttributed: z.boolean(),
3286
+ aiTool: z.string().optional(),
3287
+ aiConfidence: z.number().min(0).max(1).optional(),
3288
+ serviceTag: z.string().optional()
3289
+ });
3290
+ var RiskTimelineEntrySchema = z.object({
3291
+ timestamp: z.string().datetime(),
3292
+ riskScore: z.number().min(0).max(10),
3293
+ trigger: z.enum([
3294
+ "file_change",
3295
+ "ai_detection",
3296
+ "pattern_match"
3297
+ ]),
3298
+ fileCount: z.number().int().nonnegative()
3299
+ });
3300
+ var RollbackEventSummarySchema = z.object({
3301
+ timestamp: z.string().datetime(),
3302
+ snapshotId: z.string().min(1),
3303
+ triggerReason: z.enum([
3304
+ "user_initiated",
3305
+ "auto_threshold",
3306
+ "policy_rule"
3307
+ ]),
3308
+ filesRestored: z.number().int().nonnegative(),
3309
+ filesAffected: z.array(z.string()),
3310
+ riskScoreAtTrigger: z.number().min(0).max(10)
3311
+ });
3312
+ var AIToolAttributionSchema = z.object({
3313
+ tool: z.enum([
3314
+ "cursor",
3315
+ "copilot",
3316
+ "windsurf",
3317
+ "claude",
3318
+ "unknown"
3319
+ ]),
3320
+ confidence: z.number().min(0).max(1),
3321
+ changesAttributed: z.number().int().nonnegative()
3322
+ });
3323
+ var ConsentSnapshotSchema = z.object({
3324
+ personalSyncEnabled: z.boolean(),
3325
+ sharedLearningEnabled: z.boolean(),
3326
+ consentedAt: z.string().datetime(),
3327
+ promptVersion: z.string().min(1)
3328
+ });
3329
+ z.object({
3330
+ externalSessionId: z.string().min(1),
3331
+ workspaceId: z.string().min(1),
3332
+ schemaVersion: z.literal("sb.base.v1"),
3333
+ startedAt: z.string().datetime(),
3334
+ endedAt: z.string().datetime(),
3335
+ durationMs: z.number().int().nonnegative(),
3336
+ consentSnapshot: ConsentSnapshotSchema,
3337
+ filesTouched: z.array(SessionFileSummarySchema),
3338
+ serviceBoundariesCrossed: z.number().int().nonnegative(),
3339
+ peakRiskScore: z.number().min(0).max(10),
3340
+ riskScoreTimeline: z.array(RiskTimelineEntrySchema),
3341
+ riskEventCount: z.number().int().nonnegative(),
3342
+ rollbackEvents: z.array(RollbackEventSummarySchema),
3343
+ aiToolsActive: z.array(AIToolAttributionSchema),
3344
+ aiAttributedChangeRatio: z.number().min(0).max(1)
3345
+ });
3346
+ var ModificationSourceSchema = z.enum([
3347
+ "extension",
3348
+ "mcp",
3349
+ "daemon",
3350
+ "cli"
3351
+ ]);
3352
+ var ModificationTypeSchema = z.enum([
3353
+ "create",
3354
+ "update",
3355
+ "delete"
3356
+ ]);
3357
+ z.object({
3358
+ /** Absolute path to the modified file */
3359
+ path: z.string().min(1, "Path cannot be empty"),
3360
+ /** Modification timestamp (ms since epoch) */
3361
+ timestamp: z.number().positive("Timestamp must be positive"),
3362
+ /** Type of modification */
3363
+ type: ModificationTypeSchema,
3364
+ /** Lines changed (0 if unknown or delete) */
3365
+ linesChanged: z.number().int().nonnegative().default(0),
3366
+ /** Whether this change was AI-attributed (detected by AIPresenceDetector) */
3367
+ aiAttributed: z.boolean().default(false),
3368
+ /** Which AI tool made the change, if detected (e.g., 'copilot', 'cursor', 'claude') */
3369
+ aiTool: z.string().nullable().default(null),
3370
+ /** Source surface that recorded this modification */
3371
+ source: ModificationSourceSchema
3372
+ });
3373
+ z.object({
3374
+ /** Active extension IDs in the IDE environment */
3375
+ extensionIds: z.array(z.string()).default([]),
3376
+ /** Optional file content to analyze for AI signatures */
3377
+ content: z.string().optional(),
3378
+ /** Character velocity (chars/ms) from burst detection */
3379
+ velocity: z.number().nonnegative().optional(),
3380
+ /** Total characters changed in the operation */
3381
+ charCount: z.number().int().nonnegative().optional()
3382
+ });
3383
+ var AiDetectionOutputSchema = z.object({
3384
+ /** Detected AI tool name, or null if none detected */
3385
+ tool: z.string().nullable(),
3386
+ /** Confidence score (0-1) */
3387
+ confidence: z.number().min(0).max(1),
3388
+ /** Detection method that triggered */
3389
+ method: z.enum([
3390
+ "extension",
3391
+ "velocity",
3392
+ "pattern",
3393
+ "combined"
3394
+ ]).nullable(),
3395
+ /** Indicators that contributed to detection */
3396
+ indicators: z.array(z.string()).optional()
3397
+ });
3398
+ z.object({
3399
+ /** Code content to scan for threats */
3400
+ content: z.string()
3401
+ });
3402
+ var ThreatPatternSchema = z.object({
3403
+ /** Description of the threat pattern */
3404
+ description: z.string(),
3405
+ /** Severity score (0-1), where 1 is most critical */
3406
+ severity: z.number().min(0).max(1)
3407
+ });
3408
+ var ThreatDetectionOutputSchema = z.object({
3409
+ /** Total number of threats detected */
3410
+ threatCount: z.number().int().nonnegative(),
3411
+ /** List of detected threat patterns */
3412
+ patterns: z.array(ThreatPatternSchema),
3413
+ /** Overall severity level */
3414
+ severity: z.enum([
3415
+ "none",
3416
+ "low",
3417
+ "medium",
3418
+ "high",
3419
+ "critical"
3420
+ ]),
3421
+ /** Aggregated threat score (0-10) */
3422
+ score: z.number().min(0).max(10)
3423
+ });
3424
+ z.object({
3425
+ /** File path being analyzed */
3426
+ filePath: z.string(),
3427
+ /** Number of characters changed */
3428
+ charCount: z.number().int().nonnegative(),
3429
+ /** Timestamp of the change (ms since epoch) */
3430
+ timestamp: z.number().int().positive().optional()
3431
+ });
3432
+ var BurstDetectionOutputSchema = z.object({
3433
+ /** Whether a burst was detected */
3434
+ isBurst: z.boolean(),
3435
+ /** Character velocity (chars/ms) */
3436
+ velocity: z.number().nonnegative(),
3437
+ /** File path analyzed */
3438
+ filePath: z.string(),
3439
+ /** Total characters in the change */
3440
+ charCount: z.number().int().nonnegative(),
3441
+ /** Timestamp of detection */
3442
+ timestamp: z.number().int().positive()
3443
+ });
3444
+ var ComplexityFileInputSchema = z.object({
3445
+ /** File path */
3446
+ path: z.string(),
3447
+ /** File content */
3448
+ content: z.string(),
3449
+ /** Line count of the file */
3450
+ lineCount: z.number().int().nonnegative()
3451
+ });
3452
+ z.object({
3453
+ /** Files to analyze */
3454
+ files: z.array(ComplexityFileInputSchema)
3455
+ });
3456
+ var ComplexityAnalysisOutputSchema = z.object({
3457
+ /** Average complexity score across all files (0-1) */
3458
+ avgComplexity: z.number().min(0).max(1),
3459
+ /** Maximum complexity score of any single file (0-1) */
3460
+ maxComplexity: z.number().min(0).max(1),
3461
+ /** List of files with complexity > 0.7 */
3462
+ highComplexityFiles: z.array(z.string()),
3463
+ /** Number of files analyzed */
3464
+ fileCount: z.number().int().nonnegative(),
3465
+ /** Overall complexity value (same as avgComplexity) */
3466
+ value: z.number().min(0).max(1)
3467
+ });
3468
+ z.object({
3469
+ /** Extension IDs for AI detection */
3470
+ extensionIds: z.array(z.string()).default([]),
3471
+ /** Content to analyze (for threats, AI patterns, complexity) */
3472
+ content: z.string(),
3473
+ /** File path being analyzed */
3474
+ filePath: z.string(),
3475
+ /** Line count (for complexity calculation) */
3476
+ lineCount: z.number().int().nonnegative().optional(),
3477
+ /** Character count (for burst detection) */
3478
+ charCount: z.number().int().nonnegative().optional(),
3479
+ /** Velocity (for AI detection) */
3480
+ velocity: z.number().nonnegative().optional(),
3481
+ /** Timestamp (for burst detection) */
3482
+ timestamp: z.number().int().positive().optional()
3483
+ });
3484
+ z.object({
3485
+ /** Signal name */
3486
+ signal: z.enum([
3487
+ "ai",
3488
+ "threats",
3489
+ "burst",
3490
+ "complexity"
3491
+ ]),
3492
+ /** Signal-specific score/value */
3493
+ value: z.number(),
3494
+ /** Whether this signal is considered "triggered" */
3495
+ triggered: z.boolean()
3496
+ });
3497
+ z.object({
3498
+ /** Individual signal results */
3499
+ signals: z.object({
3500
+ ai: AiDetectionOutputSchema,
3501
+ threats: ThreatDetectionOutputSchema,
3502
+ burst: BurstDetectionOutputSchema.optional(),
3503
+ complexity: ComplexityAnalysisOutputSchema
3504
+ }),
3505
+ /** Overall risk score (0-1), weighted combination of all signals */
3506
+ overallRisk: z.number().min(0).max(1),
3507
+ /** Risk level classification */
3508
+ riskLevel: z.enum([
3509
+ "low",
3510
+ "medium",
3511
+ "high",
3512
+ "critical"
3513
+ ]),
3514
+ /** Summary of triggered signals */
3515
+ triggeredSignals: z.array(z.enum([
3516
+ "ai",
3517
+ "threats",
3518
+ "burst",
3519
+ "complexity"
3520
+ ])),
3521
+ /** Processing time in milliseconds */
3522
+ processingTimeMs: z.number().nonnegative()
3523
+ });
3524
+ var SignalTypeSchema = z.enum([
3525
+ "ai",
3526
+ "threats",
3527
+ "burst",
3528
+ "complexity",
3529
+ "comprehensive"
3530
+ ]);
3531
+ z.object({
3532
+ /** Error code */
3533
+ code: z.string(),
3534
+ /** Human-readable error message */
3535
+ message: z.string(),
3536
+ /** Signal type that failed */
3537
+ signal: SignalTypeSchema.optional()
3538
+ });
3539
+ z.object({
3540
+ sessionId: z.string().uuid(),
3541
+ workspaceId: z.string(),
3542
+ startedAt: z.number(),
3543
+ endedAt: z.number().nullable(),
3544
+ durationMs: z.number().nullable(),
3545
+ clientType: z.string(),
3546
+ snapshotCount: z.number().int().min(0),
3547
+ learningCount: z.number().int().min(0),
3548
+ touchedFileCount: z.number().int().min(0),
3549
+ riskScores: z.array(z.number().min(0).max(1))
3550
+ }).strict();
3551
+ var TaskStatusSchema = z.enum([
3552
+ "created",
3553
+ "active",
3554
+ "completed",
3555
+ "abandoned",
3556
+ "failed",
3557
+ "auto-ended",
3558
+ "ceremony_blocked"
3559
+ ]);
3560
+ var TaskOutcomeSchema = z.enum([
3561
+ "completed",
3562
+ "abandoned",
3563
+ "failed"
3564
+ ]);
3565
+ z.object({
3566
+ /** Monotonic integer ID for system tracking */
3567
+ id: z.number().int().positive(),
3568
+ /** Deterministic kebab-case identifier generated from name */
3569
+ slug: z.string().min(1).max(64),
3570
+ /** Human-readable task name provided by LLM */
3571
+ name: z.string().min(1).max(256),
3572
+ /** Current status of the task */
3573
+ status: TaskStatusSchema,
3574
+ /** Outcome when task was closed (null if active) */
3575
+ outcome: TaskOutcomeSchema.nullable(),
3576
+ /** ISO 8601 timestamp when task was created */
3577
+ createdAt: z.string().datetime(),
3578
+ /** ISO 8601 timestamp when task was last updated */
3579
+ updatedAt: z.string().datetime(),
3580
+ /** ISO 8601 timestamp when task was closed (null if active) */
3581
+ closedAt: z.string().datetime().nullable(),
3582
+ /** JSON-serialized ceremony object (null until task closes) */
3583
+ ceremonyJson: z.string().nullable(),
3584
+ /** Task ID this task explicitly continues from (lineage) */
3585
+ continuesFrom: z.number().int().positive().nullable(),
3586
+ /** Source of migration for legacy sessions */
3587
+ migrationSource: z.enum([
3588
+ "active_session",
3589
+ "completed_session"
3590
+ ]).nullable()
3591
+ });
3592
+ var TaskEventTypeSchema = z.enum([
3593
+ "task_created",
3594
+ "task_resumed",
3595
+ "task_ended",
3596
+ "learning_captured",
3597
+ "pulse_recorded",
3598
+ "file_changed",
3599
+ "session_connected",
3600
+ "session_disconnected",
3601
+ "ceremony_blocked",
3602
+ "ceremony_completed"
3603
+ ]);
3604
+ z.object({
3605
+ /** Monotonic integer ID */
3606
+ id: z.number().int().positive(),
3607
+ /** Task this event belongs to */
3608
+ taskId: z.number().int().positive(),
3609
+ /** Sequence number within task (monotonically increasing) */
3610
+ seq: z.number().int().nonnegative(),
3611
+ /** Type of event */
3612
+ type: TaskEventTypeSchema,
3613
+ /** JSON-serialized event payload */
3614
+ payloadJson: z.string().nullable(),
3615
+ /** ISO 8601 timestamp when event occurred */
3616
+ timestamp: z.string().datetime()
3617
+ });
3618
+ var FileActionSchema = z.enum([
3619
+ "added",
3620
+ "modified",
3621
+ "deleted"
3622
+ ]);
3623
+ var TaskFileSchema = z.object({
3624
+ /** Monotonic integer ID */
3625
+ id: z.number().int().positive(),
3626
+ /** Task this file change belongs to */
3627
+ taskId: z.number().int().positive(),
3628
+ /** Relative POSIX path from workspace root */
3629
+ path: z.string().min(1),
3630
+ /** Type of file operation */
3631
+ action: FileActionSchema,
3632
+ /** SHA-256 hash before change (null for added files) */
3633
+ hashBefore: z.string().nullable(),
3634
+ /** SHA-256 hash after change (null for deleted files) */
3635
+ hashAfter: z.string().nullable(),
3636
+ /** ISO 8601 timestamp when change was detected */
3637
+ timestamp: z.string().datetime()
3638
+ });
3639
+ var LearningCategorySchema = z.enum([
3640
+ "pattern",
3641
+ "gotcha",
3642
+ "decision",
3643
+ "convention",
3644
+ "discovery"
3645
+ ]);
3646
+ var LearningConfidenceSchema = z.enum([
3647
+ "low",
3648
+ "medium",
3649
+ "high"
3650
+ ]);
3651
+ var TaskLearningSchema = z.object({
3652
+ /** Monotonic integer ID */
3653
+ id: z.number().int().positive(),
3654
+ /** Task this learning belongs to */
3655
+ taskId: z.number().int().positive(),
3656
+ /** SHA-256 hash of content for deduplication */
3657
+ contentHash: z.string().min(1),
3658
+ /** The actual learning content */
3659
+ content: z.string().min(1),
3660
+ /** Where this learning came from */
3661
+ source: z.string().nullable(),
3662
+ /** Confidence level of the insight */
3663
+ confidence: LearningConfidenceSchema,
3664
+ /** ISO 8601 timestamp when learning was captured */
3665
+ timestamp: z.string().datetime()
3666
+ });
3667
+ z.object({
3668
+ /** Monotonic integer ID */
3669
+ id: z.number().int().positive(),
3670
+ /** Task this session belongs to */
3671
+ taskId: z.number().int().positive(),
3672
+ /** Unique session identifier (UUID) */
3673
+ sessionId: z.string().min(1),
3674
+ /** ISO 8601 timestamp when session connected */
3675
+ connectedAt: z.string().datetime(),
3676
+ /** ISO 8601 timestamp when session disconnected (null if active) */
3677
+ disconnectedAt: z.string().datetime().nullable()
3678
+ });
3679
+ var CeremonyMetricsSchema = z.object({
3680
+ /** Number of unique files modified */
3681
+ filesModified: z.number().int().nonnegative(),
3682
+ /** Number of unique files created */
3683
+ filesCreated: z.number().int().nonnegative(),
3684
+ /** Number of files deleted */
3685
+ filesDeleted: z.number().int().nonnegative(),
3686
+ /** Number of learnings captured */
3687
+ learningsCaptured: z.number().int().nonnegative(),
3688
+ /** Number of pulse snapshots recorded */
3689
+ pulsesRecorded: z.number().int().nonnegative(),
3690
+ /** Number of sessions that connected to this task */
3691
+ sessionsCount: z.number().int().nonnegative(),
3692
+ /** Total file operations (sum of all actions) */
3693
+ totalFileOperations: z.number().int().nonnegative()
3694
+ });
3695
+ var CeremonyDurationSchema = z.object({
3696
+ /** ISO 8601 timestamp of first session start */
3697
+ firstSessionStart: z.string().datetime(),
3698
+ /** ISO 8601 timestamp of last session end */
3699
+ lastSessionEnd: z.string().datetime().nullable(),
3700
+ /** Total active time in milliseconds */
3701
+ totalActiveTimeMs: z.number().int().nonnegative()
3702
+ });
3703
+ var QualityGateStatusSchema = z.object({
3704
+ /** Whether all required gates passed */
3705
+ allPassed: z.boolean(),
3706
+ /** Whether audit passed */
3707
+ auditPassed: z.boolean().nullable(),
3708
+ /** Whether lint is clean */
3709
+ lintClean: z.boolean().nullable(),
3710
+ /** Whether tests pass */
3711
+ testsPass: z.boolean().nullable()
3712
+ });
3713
+ var CeremonySchema = z.object({
3714
+ /** Task ID */
3715
+ taskId: z.number().int().positive(),
3716
+ /** Human-readable task name */
3717
+ taskName: z.string().min(1),
3718
+ /** Deterministic slug */
3719
+ slug: z.string().min(1),
3720
+ /** How the task ended */
3721
+ outcome: TaskOutcomeSchema,
3722
+ /** Duration information */
3723
+ duration: CeremonyDurationSchema,
3724
+ /** Derived metrics from accumulated state */
3725
+ metrics: CeremonyMetricsSchema,
3726
+ /** All learnings captured during this task */
3727
+ learnings: z.array(TaskLearningSchema),
3728
+ /** Complete file change log */
3729
+ fileChanges: z.array(TaskFileSchema),
3730
+ /** Quality gate results from most recent pulse */
3731
+ qualityGates: QualityGateStatusSchema,
3732
+ /** LLM-generated summary for context injection into future tasks */
3733
+ briefingForNextTask: z.string().nullable()
3734
+ });
3735
+ var BriefingModeSchema = z.enum([
3736
+ "standard",
3737
+ "comprehensive"
3738
+ ]);
3739
+ var BriefingSchema = z.object({
3740
+ /** Summary of most recent completed task's ceremony (1-2 paragraphs) */
3741
+ recentCeremonySummary: z.string().nullable(),
3742
+ /** Top 5 most recent learnings from across all tasks */
3743
+ recentLearnings: z.array(TaskLearningSchema).max(5),
3744
+ /** Any active warnings or known issues from the project */
3745
+ activeWarnings: z.array(z.string()),
3746
+ /** Full ceremony from continued task (if continues parameter provided) */
3747
+ continuedCeremony: CeremonySchema.nullable(),
3748
+ /** Lineage chain (task IDs this task continues from) */
3749
+ lineageChain: z.array(z.number().int().positive())
3750
+ });
3751
+ z.object({
3752
+ /** Human-readable task name from LLM */
3753
+ taskName: z.string().min(1).max(256)
3754
+ });
3755
+ z.object({
3756
+ /** Generated kebab-case slug */
3757
+ slug: z.string().min(1).max(64),
3758
+ /** Whether a counter suffix was added for uniqueness */
3759
+ hasCounterSuffix: z.boolean(),
3760
+ /** Counter value if suffix was added (null otherwise) */
3761
+ counterValue: z.number().int().positive().nullable()
3762
+ });
3763
+ z.object({
3764
+ /** Human-readable task name. Vreko generates a deterministic slug for matching. */
3765
+ task: z.string().min(1).max(256),
3766
+ /** Task ID or slug of a completed task that this new task continues. */
3767
+ continues: z.string().optional(),
3768
+ /** Level of context to include in the briefing. Default "standard". */
3769
+ mode: BriefingModeSchema.default("standard")
3770
+ });
3771
+ z.object({
3772
+ /** Task ID */
3773
+ taskId: z.number().int().positive(),
3774
+ /** Deterministic slug */
3775
+ slug: z.string().min(1),
3776
+ /** Human-readable task name */
3777
+ name: z.string().min(1),
3778
+ /** Current status */
3779
+ status: TaskStatusSchema,
3780
+ /** Whether this was a resume of an existing task */
3781
+ resumed: z.boolean(),
3782
+ /** Slug of auto-ended task (if any) */
3783
+ autoEnded: z.string().nullable(),
3784
+ /** Contextual briefing from recent work history */
3785
+ briefing: BriefingSchema,
3786
+ /** Number of sessions that have connected to this task */
3787
+ sessionsCount: z.number().int().nonnegative()
3788
+ });
3789
+ var PulseFocusSchema = z.enum([
3790
+ "vitals",
3791
+ "advice"
3792
+ ]);
3793
+ var PulseEnrichmentSchema = z.object({
3794
+ /** Patterns, concerns the LLM noticed */
3795
+ observations: z.array(z.string()).optional(),
3796
+ /** Confidence in observations */
3797
+ confidence: LearningConfidenceSchema.optional()
3798
+ });
3799
+ z.object({
3800
+ /** What to focus on. "vitals" returns workspace health diagnostics.
3801
+ * "advice" returns proactive recommendations based on current task context. */
3802
+ focus: PulseFocusSchema.default("vitals"),
3803
+ /** When focus is "advice", a specific question or area.
3804
+ * When focus is "vitals", optional hint about what to prioritize. */
3805
+ query: z.string().optional(),
3806
+ /** LLM-observed context to attach. Additive, not replacing. */
3807
+ enrichment: PulseEnrichmentSchema.optional()
3808
+ });
3809
+ var WorkspaceVitalsSchema = z.object({
3810
+ /** Whether configured tests pass */
3811
+ testsPass: z.boolean().nullable(),
3812
+ /** Whether lint is clean */
3813
+ lintClean: z.boolean().nullable(),
3814
+ /** Whether typecheck passes */
3815
+ typecheckPass: z.boolean().nullable(),
3816
+ /** Git branch name */
3817
+ gitBranch: z.string().nullable(),
3818
+ /** Whether there are uncommitted changes */
3819
+ hasUncommittedChanges: z.boolean(),
3820
+ /** Number of modified files (from git status) */
3821
+ modifiedFilesCount: z.number().int().nonnegative(),
3822
+ /** Error details if any check failed */
3823
+ errorDetails: z.string().nullable()
3824
+ });
3825
+ z.object({
3826
+ /** Whether there is an active task */
3827
+ hasActiveTask: z.boolean(),
3828
+ /** Task ID if active */
3829
+ taskId: z.number().int().positive().nullable(),
3830
+ /** Daemon-collected workspace vitals */
3831
+ vitals: WorkspaceVitalsSchema,
3832
+ /** Whether task is flagged as stale (inactivity timeout exceeded) */
3833
+ isStale: z.boolean(),
3834
+ /** Proactive recommendations (when focus is "advice") */
3835
+ recommendations: z.array(z.string()).optional(),
3836
+ /** Pulse sequence number for this task */
3837
+ pulseSeq: z.number().int().nonnegative()
3838
+ });
3839
+ z.object({
3840
+ /** The learning to capture. Should be a concrete, actionable insight. */
3841
+ insight: z.string().min(1),
3842
+ /** Classification of the learning. Default: inferred by the daemon. */
3843
+ category: LearningCategorySchema.optional(),
3844
+ /** Where this learning came from. Default: "llm-observation". */
3845
+ source: z.string().optional(),
3846
+ /** How confident the LLM is in this insight. Default: "medium". */
3847
+ confidence: LearningConfidenceSchema.default("medium")
3848
+ });
3849
+ z.object({
3850
+ /** Learning ID */
3851
+ learningId: z.number().int().positive(),
3852
+ /** Content hash for deduplication */
3853
+ contentHash: z.string().min(1),
3854
+ /** Whether this was a new learning or duplicate */
3855
+ isNew: z.boolean(),
3856
+ /** Total learnings count for this task */
3857
+ taskLearningsCount: z.number().int().nonnegative()
3858
+ });
3859
+ var VrekoEndFeedbackSchema = z.object({
3860
+ /** Rating 1-5 */
3861
+ rating: z.number().int().min(1).max(5),
3862
+ /** Optional notes */
3863
+ notes: z.string().optional()
3864
+ });
3865
+ z.object({
3866
+ /** How the task ended */
3867
+ outcome: TaskOutcomeSchema,
3868
+ /** LLM's summary of what was accomplished. Included in ceremony. */
3869
+ summary: z.string().optional(),
3870
+ /** Bypass quality gate blocks. Not recommended. */
3871
+ force: z.boolean().default(false),
3872
+ /** User/LLM feedback on the task experience */
3873
+ feedback: VrekoEndFeedbackSchema.optional()
3874
+ });
3875
+ z.object({
3876
+ /** Whether the ceremony was blocked by quality gates */
3877
+ blocked: z.boolean(),
3878
+ /** The produced ceremony (null if blocked and force=false) */
3879
+ ceremony: CeremonySchema.nullable(),
3880
+ /** Quality gate failures if blocked */
3881
+ gateFailures: z.object({
3882
+ testsPass: z.boolean().optional(),
3883
+ lintClean: z.boolean().optional(),
3884
+ auditPassed: z.boolean().optional()
3885
+ }).nullable(),
3886
+ /** Instructions to resolve blockage */
3887
+ resolution: z.string().nullable()
3888
+ });
3889
+ var PurchaseTypeEnum = z.enum([
3890
+ "ONE_TIME",
3891
+ "SUBSCRIPTION",
3892
+ "addon"
3893
+ ]);
3894
+ z.object({
3895
+ id: z.string(),
3896
+ organizationId: z.string().nullable().optional(),
3897
+ userId: z.string().nullable().optional(),
3898
+ type: PurchaseTypeEnum,
3899
+ customerId: z.string(),
3900
+ subscriptionId: z.string().nullable().optional(),
3901
+ productId: z.string(),
3902
+ status: z.string().nullable().optional(),
3903
+ createdAt: z.date(),
3904
+ updatedAt: z.date().nullable().optional()
3905
+ });
3906
+ var ConfigFileTypeSchema = z.enum([
3907
+ "package",
3908
+ "typescript",
3909
+ "linting",
3910
+ "build",
3911
+ "environment",
3912
+ "testing",
3913
+ "framework",
3914
+ "database",
3915
+ "ci"
3916
+ ]);
3917
+ var SupportedLanguageSchema = z.enum([
3918
+ "javascript",
3919
+ "typescript",
3920
+ "python",
3921
+ "universal"
3922
+ ]);
3923
+ var FileBaselineSchema = z.object({
3924
+ path: z.string(),
3925
+ hash: z.string(),
3926
+ timestamp: z.number(),
3927
+ size: z.number()
3928
+ });
3929
+ z.object({
3930
+ path: z.string(),
3931
+ type: ConfigFileTypeSchema,
3932
+ language: SupportedLanguageSchema,
3933
+ critical: z.boolean().default(false),
3934
+ baseline: FileBaselineSchema.optional()
3935
+ });
3936
+ z.object({
3937
+ type: z.string(),
3938
+ path: z.string(),
3939
+ name: z.string(),
3940
+ critical: z.boolean().default(false)
3941
+ });
3942
+ z.object({
3943
+ content: z.any(),
3944
+ valid: z.boolean(),
3945
+ error: z.string().optional(),
3946
+ metadata: z.record(z.string(), z.any()).optional()
3947
+ });
3948
+ z.object({
3949
+ valid: z.boolean(),
3950
+ errors: z.array(z.string()).default([]),
3951
+ warnings: z.array(z.string()).default([])
3952
+ });
3953
+ z.object({
3954
+ type: z.enum([
3955
+ "added",
3956
+ "modified",
3957
+ "deleted"
3958
+ ]),
3959
+ file: z.string(),
3960
+ timestamp: z.number(),
3961
+ baseline: FileBaselineSchema.optional()
3962
+ });
3963
+ z.object({
3964
+ autoDetect: z.boolean().default(true),
3965
+ watchChanges: z.boolean().default(true),
3966
+ autoProtect: z.boolean().default(true),
3967
+ customPatterns: z.array(z.any()).optional()
3968
+ });
3969
+ z.object({
3970
+ enabled: z.boolean(),
3971
+ patterns: z.array(z.string()).optional(),
3972
+ threshold: z.number().optional(),
3973
+ includePatterns: z.array(z.string()).optional(),
3974
+ excludePatterns: z.array(z.string()).optional()
3975
+ });
3976
+ var ProtectionLevelSchema = z.enum([
3977
+ "watch",
3978
+ "warn",
3979
+ "block"
3980
+ ]);
3981
+ z.object({
3982
+ level: ProtectionLevelSchema,
3983
+ icon: z.string(),
3984
+ label: z.string(),
3985
+ description: z.string(),
3986
+ color: z.string(),
3987
+ themeColor: z.string().optional()
3988
+ });
3989
+ var ProtectedFileSchema = z.object({
3990
+ path: z.string(),
3991
+ level: ProtectionLevelSchema,
3992
+ reason: z.string().optional(),
3993
+ addedAt: z.date(),
3994
+ pattern: z.string().optional()
3995
+ });
3996
+ var PatternRuleSchema = z.object({
3997
+ pattern: z.string(),
3998
+ level: ProtectionLevelSchema,
3999
+ reason: z.string().optional(),
4000
+ enabled: z.boolean().default(true)
4001
+ });
4002
+ var ProtectionConfigSchema = z.object({
4003
+ patterns: z.array(PatternRuleSchema).default([]),
4004
+ defaultLevel: ProtectionLevelSchema.default("watch"),
4005
+ enabled: z.boolean().default(true),
4006
+ autoProtectConfigs: z.boolean().default(true)
4007
+ });
4008
+ z.object({
4009
+ config: ProtectionConfigSchema.optional(),
4010
+ persistRegistry: z.boolean().default(true),
4011
+ registryPath: z.string().optional()
4012
+ });
4013
+ z.object({
4014
+ isProtected: z.boolean(),
4015
+ level: ProtectionLevelSchema.optional(),
4016
+ reason: z.string().optional(),
4017
+ file: ProtectedFileSchema.optional()
4018
+ });
4019
+ var DEFAULT_CRITICAL_PATTERNS = Object.freeze([
4020
+ // Dependency locks - wrong versions break builds
4021
+ {
4022
+ pattern: "**/package-lock.json",
4023
+ level: "block",
4024
+ reason: "Lock file - wrong version breaks reproducible Node.js builds"
4025
+ },
4026
+ {
4027
+ pattern: "**/yarn.lock",
4028
+ level: "block",
4029
+ reason: "Lock file - ensures reproducible Yarn installs"
4030
+ },
4031
+ {
4032
+ pattern: "**/pnpm-lock.yaml",
4033
+ level: "block",
4034
+ reason: "Lock file - critical for pnpm monorepos"
4035
+ },
4036
+ {
4037
+ pattern: "**/poetry.lock",
4038
+ level: "block",
4039
+ reason: "Lock file - Python dependency lock"
4040
+ },
4041
+ {
4042
+ pattern: "**/Cargo.lock",
4043
+ level: "block",
4044
+ reason: "Lock file - Rust dependency lock"
4045
+ },
4046
+ {
4047
+ pattern: "**/go.sum",
4048
+ level: "block",
4049
+ reason: "Lock file - Go module checksums"
4050
+ },
4051
+ {
4052
+ pattern: "**/Gemfile.lock",
4053
+ level: "block",
4054
+ reason: "Lock file - Ruby gem dependencies"
4055
+ },
4056
+ {
4057
+ pattern: "**/composer.lock",
4058
+ level: "block",
4059
+ reason: "Lock file - PHP composer dependencies"
4060
+ },
4061
+ // Environment & Secrets - exposing causes immediate security breaches
4062
+ {
4063
+ pattern: "**/.env*",
4064
+ level: "block",
4065
+ reason: "Sensitive environment variables and secrets"
4066
+ },
4067
+ // Core configuration files - wrong changes break builds
4068
+ {
4069
+ pattern: "package.json",
4070
+ level: "warn",
4071
+ reason: "Core Node.js configuration - dependencies and scripts"
4072
+ },
4073
+ {
4074
+ pattern: "tsconfig.json",
4075
+ level: "warn",
4076
+ reason: "TypeScript compiler configuration"
4077
+ },
4078
+ // Infrastructure - controls deployment and infrastructure
4079
+ {
4080
+ pattern: "Dockerfile",
4081
+ level: "warn",
4082
+ reason: "Container image definition"
4083
+ },
4084
+ {
4085
+ pattern: "docker-compose.yml",
4086
+ level: "warn",
4087
+ reason: "Multi-container orchestration"
4088
+ },
4089
+ {
4090
+ pattern: "**/docker-compose.yaml",
4091
+ level: "warn",
4092
+ reason: "Multi-container orchestration (yaml variant)"
4093
+ },
4094
+ {
4095
+ pattern: "**/*.tf",
4096
+ level: "warn",
4097
+ reason: "Terraform infrastructure definitions"
4098
+ },
4099
+ {
4100
+ pattern: ".github/workflows/*.yml",
4101
+ level: "warn",
4102
+ reason: "GitHub Actions CI/CD workflows"
4103
+ },
4104
+ {
4105
+ pattern: ".github/workflows/*.yaml",
4106
+ level: "warn",
4107
+ reason: "GitHub Actions CI/CD workflows (yaml variant)"
4108
+ }
4109
+ ]);
4110
+ var EXTENDED_PATTERNS = Object.freeze([
4111
+ // Documentation - passive watching
4112
+ {
4113
+ pattern: "*.md",
4114
+ level: "watch",
4115
+ reason: "Documentation files"
4116
+ },
4117
+ {
4118
+ pattern: "*.txt",
4119
+ level: "watch",
4120
+ reason: "Text files"
4121
+ },
4122
+ {
4123
+ pattern: "README*",
4124
+ level: "watch",
4125
+ reason: "README documentation"
4126
+ },
4127
+ // General configuration files
4128
+ {
4129
+ pattern: "*.json",
4130
+ level: "watch",
4131
+ reason: "JSON configuration files"
4132
+ },
4133
+ {
4134
+ pattern: ".editorconfig",
4135
+ level: "watch",
4136
+ reason: "Editor configuration"
4137
+ },
4138
+ {
4139
+ pattern: ".prettierrc*",
4140
+ level: "watch",
4141
+ reason: "Prettier formatting configuration"
4142
+ },
4143
+ {
4144
+ pattern: ".eslintrc*",
4145
+ level: "watch",
4146
+ reason: "ESLint configuration"
4147
+ },
4148
+ {
4149
+ pattern: ".babelrc",
4150
+ level: "watch",
4151
+ reason: "Babel transpiler configuration"
4152
+ },
4153
+ {
4154
+ pattern: ".gitignore",
4155
+ level: "warn",
4156
+ reason: "Git ignore rules"
4157
+ },
4158
+ // IDE and editor settings
4159
+ {
4160
+ pattern: ".vscode/settings.json",
4161
+ level: "watch",
4162
+ reason: "VS Code settings"
4163
+ },
4164
+ {
4165
+ pattern: ".idea/**",
4166
+ level: "watch",
4167
+ reason: "IDE configuration directory"
4168
+ },
4169
+ // Build tool configurations
4170
+ {
4171
+ pattern: "vite.config.*",
4172
+ level: "warn",
4173
+ reason: "Vite bundler configuration"
4174
+ },
4175
+ {
4176
+ pattern: "webpack.config.*",
4177
+ level: "warn",
4178
+ reason: "Webpack bundler configuration"
4179
+ },
4180
+ {
4181
+ pattern: "rollup.config.*",
4182
+ level: "warn",
4183
+ reason: "Rollup bundler configuration"
4184
+ },
4185
+ {
4186
+ pattern: "esbuild.config.*",
4187
+ level: "warn",
4188
+ reason: "esbuild bundler configuration"
4189
+ },
4190
+ {
4191
+ pattern: "Makefile",
4192
+ level: "watch",
4193
+ reason: "Make build configuration"
4194
+ },
4195
+ {
4196
+ pattern: "CMakeLists.txt",
4197
+ level: "watch",
4198
+ reason: "CMake build configuration"
4199
+ },
4200
+ // Language-specific package managers and configs
4201
+ {
4202
+ pattern: "requirements.txt",
4203
+ level: "watch",
4204
+ reason: "Python dependencies"
4205
+ },
4206
+ {
4207
+ pattern: "Gemfile",
4208
+ level: "warn",
4209
+ reason: "Ruby gem configuration"
4210
+ },
4211
+ {
4212
+ pattern: "composer.json",
4213
+ level: "warn",
4214
+ reason: "PHP composer configuration"
4215
+ },
4216
+ {
4217
+ pattern: "setup.py",
4218
+ level: "warn",
4219
+ reason: "Python package setup"
4220
+ },
4221
+ {
4222
+ pattern: "pyproject.toml",
4223
+ level: "warn",
4224
+ reason: "Python project configuration"
4225
+ },
4226
+ {
4227
+ pattern: "pom.xml",
4228
+ level: "warn",
4229
+ reason: "Maven Java build configuration"
4230
+ },
4231
+ {
4232
+ pattern: "build.gradle*",
4233
+ level: "warn",
4234
+ reason: "Gradle Java build configuration"
4235
+ },
4236
+ {
4237
+ pattern: "*.csproj",
4238
+ level: "warn",
4239
+ reason: ".NET C# project file"
4240
+ },
4241
+ {
4242
+ pattern: "go.mod",
4243
+ level: "warn",
4244
+ reason: "Go module definition"
4245
+ },
4246
+ {
4247
+ pattern: "Cargo.toml",
4248
+ level: "warn",
4249
+ reason: "Rust package configuration"
4250
+ },
4251
+ {
4252
+ pattern: "bunfig.toml",
4253
+ level: "warn",
4254
+ reason: "Bun runtime configuration"
4255
+ },
4256
+ {
4257
+ pattern: "*.sln",
4258
+ level: "watch",
4259
+ reason: "Visual Studio solution file"
4260
+ },
4261
+ // Kubernetes and container orchestration
4262
+ {
4263
+ pattern: "kubernetes/*.yaml",
4264
+ level: "warn",
4265
+ reason: "Kubernetes manifests"
4266
+ }
4267
+ ]);
4268
+ Object.freeze([
4269
+ ...DEFAULT_CRITICAL_PATTERNS,
4270
+ ...EXTENDED_PATTERNS
4271
+ ]);
4272
+ var SnapshotTriggerSchema = z.enum([
4273
+ "manual",
4274
+ "auto",
4275
+ "auto_save",
4276
+ "ai_detected",
4277
+ "ai-detected",
4278
+ "pre_save",
4279
+ "pre-save",
4280
+ "session_start",
4281
+ "session_end",
4282
+ "mcp_snap_start",
4283
+ "cli_protect",
4284
+ "api_request",
4285
+ "engine_internal",
4286
+ "recovery"
4287
+ ]);
4288
+ var SnapshotOriginSchema = z.enum([
4289
+ "manual",
4290
+ "auto",
4291
+ "ai-detected",
4292
+ "recovery",
4293
+ "INTERACTIVE",
4294
+ "AUTOMATED"
4295
+ ]);
4296
+ var SnapshotReasonCodeSchema = z.enum([
4297
+ // AI detection
4298
+ "AI_DETECTED",
4299
+ // Manual operations
4300
+ "MANUAL_CHECKPOINT",
4301
+ "MANUAL_SAVE",
4302
+ // Risk-based triggers
4303
+ "CRITICAL_FILE",
4304
+ "HIGH_RISK",
4305
+ "RISK_BURST_START",
4306
+ "RISK_LARGE_DELETE",
4307
+ "RISK_MULTI_FILE",
4308
+ // Session lifecycle
4309
+ "SESSION_START",
4310
+ "SESSION_END",
4311
+ "IDLE_FINALIZE",
4312
+ // Rollback operations
4313
+ "PRE_ROLLBACK",
4314
+ // Optimization modes
4315
+ "BURST_MODE"
4316
+ ]);
4317
+ var CheckpointTypeSchema = z.enum([
4318
+ "PRE",
4319
+ "POST",
4320
+ "PRE_ROLLBACK"
4321
+ ]);
4322
+ var SnapshotSchema = z.object({
4323
+ id: z.string(),
4324
+ timestamp: z.number(),
4325
+ version: z.string().optional().default("1.0"),
4326
+ meta: z.record(z.string(), z.any()).optional(),
4327
+ files: z.array(z.string()).optional(),
4328
+ fileContents: z.record(z.string(), z.string()).optional()
4329
+ });
4330
+ var FileStateSchema = z.object({
4331
+ path: z.string(),
4332
+ content: z.string(),
4333
+ /** SHA-256 hash of content (optional, computed for dedup) */
4334
+ hash: z.string().optional(),
4335
+ /** File size in bytes */
4336
+ size: z.number().optional(),
4337
+ /** Encrypted data (for sensitive files - VSCode format) */
4338
+ encrypted: z.object({
4339
+ /** Initialization vector */
4340
+ iv: z.string(),
4341
+ /** Authentication tag */
4342
+ tag: z.string(),
4343
+ /** Optional: algorithm used (default: aes-256-gcm) */
4344
+ algorithm: z.string().optional()
4345
+ }).optional()
4346
+ });
4347
+ var CompressionCodecSchema = z.enum([
4348
+ "zstd",
4349
+ "gzip",
4350
+ "none"
4351
+ ]);
4352
+ var SnapshotFileRefV2Schema = z.object({
4353
+ /** SHA-256 hash of file content (CAS reference) */
4354
+ blobHash: z.string(),
4355
+ /** File size in bytes */
4356
+ size: z.number(),
4357
+ /** Compression codec used (optional, defaults to 'none') */
4358
+ codec: CompressionCodecSchema.optional()
4359
+ });
4360
+ z.object({
4361
+ id: z.string(),
4362
+ timestamp: z.number(),
4363
+ files: z.array(FileStateSchema)
4364
+ });
4365
+ z.enum([
4366
+ "pending",
4367
+ "complete",
4368
+ "failed",
4369
+ "deleted"
4370
+ ]);
4371
+ SnapshotSchema.extend({
4372
+ name: z.string(),
4373
+ fileStates: z.array(FileStateSchema).optional(),
4374
+ isProtected: z.boolean(),
4375
+ icon: z.string().optional(),
4376
+ iconColor: z.string().optional()
4377
+ });
4378
+ z.object({
4379
+ id: z.string(),
4380
+ name: z.string(),
4381
+ timestamp: z.number(),
4382
+ fileCount: z.number(),
4383
+ origin: SnapshotOriginSchema.optional(),
4384
+ isProtected: z.boolean(),
4385
+ label: z.string().optional()
4386
+ });
4387
+ z.object({
4388
+ path: z.string(),
4389
+ content: z.string(),
4390
+ action: z.enum([
4391
+ "add",
4392
+ "modify",
4393
+ "delete"
4394
+ ])
4395
+ });
4396
+ z.object({
4397
+ /** Description/reason for the snapshot */
4398
+ description: z.string().optional(),
4399
+ /** Whether to protect from auto-deletion */
4400
+ protected: z.boolean().optional(),
4401
+ /** What triggered the snapshot */
4402
+ trigger: SnapshotTriggerSchema.optional(),
4403
+ /** Origin classification for DORA metrics */
4404
+ origin: SnapshotOriginSchema.optional(),
4405
+ /** Time since last file change in ms (DORA lead time metric) */
4406
+ timeSinceLastChangeMs: z.number().optional()
4407
+ });
4408
+ z.object({
4409
+ filePath: z.string().optional(),
4410
+ before: z.date().optional(),
4411
+ after: z.date().optional(),
4412
+ protected: z.boolean().optional(),
4413
+ limit: z.number().int().positive().optional(),
4414
+ offset: z.number().int().nonnegative().optional()
4415
+ });
4416
+ var FileDiffSchema = z.object({
4417
+ path: z.string(),
4418
+ operation: z.enum([
4419
+ "create",
4420
+ "modify",
4421
+ "delete"
4422
+ ]),
4423
+ linesAdded: z.number(),
4424
+ linesRemoved: z.number(),
4425
+ preview: z.string(),
4426
+ currentChecksum: z.string().optional(),
4427
+ snapshotChecksum: z.string().optional()
4428
+ });
4429
+ var DiffPreviewSchema = z.object({
4430
+ totalFiles: z.number(),
4431
+ filesCreated: z.number(),
4432
+ filesModified: z.number(),
4433
+ filesDeleted: z.number(),
4434
+ totalLinesAdded: z.number(),
4435
+ totalLinesRemoved: z.number(),
4436
+ diffs: z.array(FileDiffSchema)
4437
+ });
4438
+ var ConflictReportSchema = z.object({
4439
+ path: z.string(),
4440
+ reason: z.string(),
4441
+ currentChecksum: z.string(),
4442
+ snapshotChecksum: z.string()
4443
+ });
4444
+ z.object({
4445
+ success: z.boolean(),
4446
+ restoredFiles: z.array(z.string()),
4447
+ errors: z.array(z.string()).optional(),
4448
+ diffPreview: DiffPreviewSchema.optional(),
4449
+ conflicts: z.array(ConflictReportSchema).optional(),
4450
+ verification: z.object({
4451
+ allVerified: z.boolean(),
4452
+ results: z.array(z.object({
4453
+ path: z.string(),
4454
+ verified: z.boolean(),
4455
+ checksum: z.string(),
4456
+ expected: z.string()
4457
+ }))
4458
+ }).optional()
4459
+ });
4460
+ z.object({
4461
+ enableDeduplication: z.boolean().default(true),
4462
+ namingStrategy: z.enum([
4463
+ "git",
4464
+ "semantic",
4465
+ "timestamp",
4466
+ "custom"
4467
+ ]).default("semantic"),
4468
+ autoProtect: z.boolean().default(false),
4469
+ maxSnapshots: z.number().int().positive().optional()
4470
+ });
4471
+ z.object({
4472
+ id: z.string(),
4473
+ path: z.string(),
4474
+ hash: z.string().optional(),
4475
+ size: z.number().optional(),
4476
+ language: z.string().optional(),
4477
+ risk: RiskScoreDetailSchema.optional(),
4478
+ lastModified: z.number().optional(),
4479
+ createdAt: z.number().optional()
4480
+ });
4481
+ z.object({
4482
+ // Core fields (required)
4483
+ id: z.string(),
4484
+ timestamp: z.number(),
4485
+ fileCount: z.number(),
4486
+ // Analytics fields (optional)
4487
+ totalSize: z.number().optional(),
4488
+ riskScore: RiskScoreDetailSchema.optional(),
4489
+ tags: z.array(z.string()).optional(),
4490
+ // V2 Hierarchy fields (from VSCode ManifestV2)
4491
+ /** Sequential snapshot number (1-based, monotonic) */
4492
+ seq: z.number().int().positive().optional(),
4493
+ /** Parent snapshot seq (null for root) */
4494
+ parentSeq: z.number().int().positive().nullable().optional(),
4495
+ /** Parent snapshot ID */
4496
+ parentId: z.string().nullable().optional(),
4497
+ /** Checkpoint type */
4498
+ type: CheckpointTypeSchema.optional(),
4499
+ /** Main file that triggered this snapshot */
4500
+ anchorFile: z.string().optional(),
4501
+ // DORA Metrics fields
4502
+ /** Time since last file change in ms (for lead time metric) */
4503
+ timeSinceLastChangeMs: z.number().optional(),
4504
+ /** Compression ratio achieved (for storage efficiency) */
4505
+ compressionRatio: z.number().optional(),
4506
+ /** Storage size in bytes (after compression) */
4507
+ storageSizeBytes: z.number().optional(),
4508
+ // Origin & Classification
4509
+ /** Origin classification for analytics */
4510
+ origin: SnapshotOriginSchema.optional(),
4511
+ /** Reason codes for explainability */
4512
+ reasons: z.array(SnapshotReasonCodeSchema).optional(),
4513
+ // AI Detection
4514
+ aiDetection: z.object({
4515
+ detected: z.boolean(),
4516
+ tool: z.string().optional(),
4517
+ confidence: z.number().min(0).max(1).optional()
4518
+ }).optional(),
4519
+ // Session linkage
4520
+ /** Vreko session ID */
4521
+ sessionId: z.string().optional(),
4522
+ /** External task ID (from LLM agent) */
4523
+ taskId: z.string().optional(),
4524
+ // UI fields
4525
+ name: z.string().optional(),
4526
+ icon: z.string().optional()
4527
+ });
4528
+ z.object({
4529
+ /** Schema version - always 2 for V2 */
4530
+ schemaVersion: z.literal(2),
4531
+ /** Unique ID: vreko-{timestamp}-{random} */
4532
+ id: z.string(),
4533
+ /** Sequential snapshot number (1-based, monotonic) */
4534
+ seq: z.number().int().positive(),
4535
+ /** Parent snapshot seq (null for root) */
4536
+ parentSeq: z.number().int().positive().nullable(),
4537
+ /** Parent snapshot ID (null for root) */
4538
+ parentId: z.string().nullable(),
4539
+ /** Unix timestamp (ms) */
4540
+ timestamp: z.number(),
4541
+ /** Human-readable name */
4542
+ name: z.string(),
4543
+ /** Checkpoint type */
4544
+ type: CheckpointTypeSchema,
4545
+ /** The main file that triggered this snapshot */
4546
+ anchorFile: z.string(),
4547
+ /** Files in snapshot (path → ref). Empty for PRE checkpoints. */
4548
+ files: z.record(z.string(), SnapshotFileRefV2Schema),
4549
+ /** Optional metadata */
4550
+ metadata: z.object({
4551
+ /** Risk score 0-1 */
4552
+ riskScore: z.number().min(0).max(1).optional(),
4553
+ /** Origin classification */
4554
+ origin: SnapshotOriginSchema.optional(),
4555
+ /** Stable reason codes */
4556
+ reasons: z.array(SnapshotReasonCodeSchema).optional(),
4557
+ /** AI detection info */
4558
+ aiDetection: z.object({
4559
+ detected: z.boolean(),
4560
+ tool: z.string().optional(),
4561
+ confidence: z.number().optional()
4562
+ }).optional(),
4563
+ /** Vreko session ID */
4564
+ sessionId: z.string().optional(),
4565
+ /** External task ID */
4566
+ taskId: z.string().optional(),
4567
+ /** DORA: Time since last change */
4568
+ timeSinceLastChangeMs: z.number().optional()
4569
+ }).optional()
4570
+ });
4571
+ z.object({
4572
+ /** Unique ID */
4573
+ id: z.string(),
4574
+ /** Unix timestamp (ms) */
4575
+ timestamp: z.number(),
4576
+ /** Human-readable name */
4577
+ name: z.string(),
4578
+ /** Trigger reason */
4579
+ trigger: z.enum([
4580
+ "auto",
4581
+ "manual",
4582
+ "ai-detected",
4583
+ "pre-save"
4584
+ ]),
4585
+ /** Main file that triggered snapshot */
4586
+ anchorFile: z.string(),
4587
+ /** Files in snapshot (path → ref) */
4588
+ files: z.record(z.string(), z.object({
4589
+ blob: z.string(),
4590
+ size: z.number()
4591
+ })),
4592
+ /** Optional metadata */
4593
+ metadata: z.object({
4594
+ riskScore: z.number().optional(),
4595
+ aiDetection: z.object({
4596
+ detected: z.boolean(),
4597
+ tool: z.string().optional(),
4598
+ confidence: z.number().optional()
4599
+ }).optional(),
4600
+ sessionId: z.string().optional(),
4601
+ taskId: z.string().optional()
4602
+ }).optional()
4603
+ });
4604
+ z.object({
4605
+ /** Total files in snapshot */
4606
+ totalFiles: z.number().int().nonnegative(),
4607
+ /** New blobs written to storage (not deduplicated) */
4608
+ newBlobsWritten: z.number().int().nonnegative(),
4609
+ /** Files that were deduplicated (already existed in CAS) */
4610
+ dedupedFiles: z.number().int().nonnegative(),
4611
+ /** Deduplication ratio (0-1) - higher means more storage saved */
4612
+ dedupRatio: z.number().min(0).max(1),
4613
+ /** Actual bytes written to storage */
4614
+ bytesWritten: z.number().int().nonnegative(),
4615
+ /** Original size of all files (before dedup) */
4616
+ originalSize: z.number().int().nonnegative(),
4617
+ /** Storage savings in bytes (originalSize - bytesWritten) */
4618
+ bytesSaved: z.number().int().nonnegative()
4619
+ });
4620
+ z.object({
4621
+ workspaceId: z.string(),
4622
+ period: z.object({
4623
+ start: z.number(),
4624
+ end: z.number()
4625
+ }),
4626
+ risk: RiskScoreDetailSchema,
4627
+ fileStats: z.object({
4628
+ total: z.number(),
4629
+ byLanguage: z.record(z.string(), z.number()),
4630
+ byRisk: z.record(z.string(), z.number())
4631
+ }),
4632
+ snapshotStats: z.object({
4633
+ total: z.number(),
4634
+ frequency: z.number(),
4635
+ averageSize: z.number().optional()
4636
+ }),
4637
+ snapshotRecommendations: z.object({
4638
+ shouldCreateSnapshot: z.boolean(),
4639
+ reason: z.string(),
4640
+ urgency: RiskSeveritySchema,
4641
+ suggestedTiming: z.string()
4642
+ }),
4643
+ trends: z.object({
4644
+ risk: z.array(z.object({
4645
+ timestamp: z.number(),
4646
+ score: z.number()
4647
+ })),
4648
+ activity: z.array(z.object({
4649
+ timestamp: z.number(),
4650
+ count: z.number()
4651
+ }))
4652
+ })
4653
+ });
4654
+ var DashboardSnapshotSchema = z.object({
4655
+ id: z.string(),
4656
+ file: z.string(),
4657
+ message: z.string(),
4658
+ time: z.string(),
4659
+ risk: z.enum([
4660
+ "Low",
4661
+ "Medium",
4662
+ "High",
4663
+ "Critical"
4664
+ ]),
4665
+ ai: z.string()
4666
+ });
4667
+ var LearningDataSchema = z.object({
4668
+ day: z.string(),
4669
+ learned: z.number()
4670
+ });
4671
+ var AttributionDataSchema = z.object({
4672
+ name: z.string(),
4673
+ value: z.number(),
4674
+ color: z.string()
4675
+ });
4676
+ var DashboardDataSchema = z.object({
4677
+ // Pulse view
4678
+ trustScore: z.number().min(0).max(100),
4679
+ patternsCaught: z.number().int().nonnegative(),
4680
+ activeSessions: z.number().int().nonnegative(),
4681
+ // User context
4682
+ userName: z.string(),
4683
+ userInitials: z.string(),
4684
+ tier: z.string(),
4685
+ // Sessions view
4686
+ snapshots: z.array(DashboardSnapshotSchema),
4687
+ // Intelligence view
4688
+ learningVelocity: z.array(LearningDataSchema),
4689
+ aiAttribution: z.array(AttributionDataSchema),
4690
+ totalLearned: z.number().int().nonnegative(),
4691
+ growthPercentage: z.number().int().nonnegative()
4692
+ });
4693
+ var DashboardDataErrorSchema = z.object({
4694
+ error: z.literal(true),
4695
+ code: z.enum([
4696
+ "UNAUTHORIZED",
4697
+ "NOT_FOUND",
4698
+ "INTERNAL_ERROR"
4699
+ ]),
4700
+ message: z.string()
4701
+ });
4702
+ z.union([
4703
+ DashboardDataSchema,
4704
+ DashboardDataErrorSchema
4705
+ ]);
4706
+ var PROTECTION_STATUSES = [
4707
+ "active",
4708
+ "inactive"
4709
+ ];
4710
+ var RECENT_ACTIVITY_ACTIONS = [
4711
+ "snapshot_created",
4712
+ "recovery_performed",
4713
+ "ai_detected"
4714
+ ];
4715
+ var AI_TOOLS = [
4716
+ "copilot",
4717
+ "cursor",
4718
+ "claude",
4719
+ "windsurf"
4720
+ ];
4721
+ var RecentActivitySchema = z.object({
4722
+ timestamp: z.number().int().positive(),
4723
+ action: z.enum(RECENT_ACTIVITY_ACTIONS),
4724
+ file: z.string().min(1),
4725
+ ai_tool: z.enum(AI_TOOLS).optional()
4726
+ });
4727
+ var AIActivityBreakdownSchema = z.object({
4728
+ copilot: z.number().int().nonnegative(),
4729
+ cursor: z.number().int().nonnegative(),
4730
+ claude: z.number().int().nonnegative(),
4731
+ windsurf: z.number().int().nonnegative().optional()
4732
+ });
4733
+ var DashboardMetricsSchema = z.object({
4734
+ protection_status: z.enum(PROTECTION_STATUSES),
4735
+ total_snapshots: z.number().int().nonnegative(),
4736
+ total_recoveries: z.number().int().nonnegative(),
4737
+ files_protected: z.number().int().nonnegative(),
4738
+ ai_detection_rate: z.number().min(0).max(100),
4739
+ recent_activity: z.array(RecentActivitySchema).max(10),
4740
+ ai_breakdown: AIActivityBreakdownSchema
4741
+ });
4742
+ var DashboardMetricsErrorSchema = z.object({
4743
+ error: z.literal(true),
4744
+ code: z.enum([
4745
+ "UNAUTHORIZED",
4746
+ "NOT_FOUND",
4747
+ "INTERNAL_ERROR"
4748
+ ]),
4749
+ message: z.string()
4750
+ });
4751
+ z.union([
4752
+ DashboardMetricsSchema,
4753
+ DashboardMetricsErrorSchema
4754
+ ]);
4755
+ var AI_TOOLS2 = [
4756
+ "cursor",
4757
+ "copilot",
4758
+ "claude"
4759
+ ];
4760
+ var EVENT_TYPES = [
4761
+ "ai_detected",
4762
+ "snapshot",
4763
+ "recovery",
4764
+ "quiet"
4765
+ ];
4766
+ var RISK_LEVELS = [
4767
+ "high",
4768
+ "medium",
4769
+ "low"
4770
+ ];
4771
+ var FILE_CATEGORIES = [
4772
+ "auth",
4773
+ "config",
4774
+ "api",
4775
+ "ui",
4776
+ "lib",
4777
+ "test",
4778
+ "infra",
4779
+ "types",
4780
+ "hooks",
4781
+ "util"
4782
+ ];
4783
+ var DAYS_OF_WEEK = [
4784
+ "Mon",
4785
+ "Tue",
4786
+ "Wed",
4787
+ "Thu",
4788
+ "Fri",
4789
+ "Sat",
4790
+ "Sun"
4791
+ ];
4792
+ var PIONEER_TIERS = [
4793
+ "Pioneer",
4794
+ "Active Pioneer",
4795
+ "Contributing Pioneer",
4796
+ "Founding Pioneer"
4797
+ ];
4798
+ var ProtectionSchema = z.object({
4799
+ score: z.number().min(0).max(100).describe("Protection confidence score (0-100)"),
4800
+ risksPrevented: z.number().int().nonnegative().describe("Count of proactive protections this week"),
4801
+ context: z.string().describe("Human-readable summary of protected areas"),
4802
+ weekLabel: z.string().default("this week").describe("Rolling window label")
4803
+ });
4804
+ var TimelineEventSchema = z.object({
4805
+ hour: z.number().int().min(0).max(23).describe("Hour of day (0-23)"),
4806
+ type: z.enum(EVENT_TYPES).describe("Visual category for dot color"),
4807
+ tool: z.enum(AI_TOOLS2).optional().describe("AI tool detected (if applicable)"),
4808
+ file: z.string().min(1).describe("Relative file path"),
4809
+ risk: z.enum(RISK_LEVELS).describe("Risk tier for this event"),
4810
+ action: z.string().describe("What Vreko did: auto-protected | monitored | recovered"),
4811
+ blast: z.number().int().nonnegative().optional().describe("Transitive dependency count")
4812
+ });
4813
+ var HeatmapFileSchema = z.object({
4814
+ file: z.string().min(1).describe("Relative file path"),
4815
+ risk: z.number().min(0).max(1).describe("Composite risk score (0-1)"),
4816
+ changes: z.number().int().nonnegative().describe("Change count in rolling window"),
4817
+ aiRatio: z.number().min(0).max(1).describe("Percentage of AI-authored changes (0-1)"),
4818
+ cat: z.enum(FILE_CATEGORIES).describe("File category for color coding")
4819
+ });
4820
+ var AIAttributionSchema = z.object({
4821
+ cursor: z.number().int().nonnegative().describe("Percentage attributed to Cursor"),
4822
+ copilot: z.number().int().nonnegative().describe("Percentage attributed to Copilot"),
4823
+ claude: z.number().int().nonnegative().describe("Percentage attributed to Claude")
4824
+ });
4825
+ var DailyActivitySchema = z.object({
4826
+ day: z.enum(DAYS_OF_WEEK).describe("Day of week"),
4827
+ ai: z.number().int().nonnegative().describe("AI-attributed changes"),
4828
+ human: z.number().int().nonnegative().describe("Human-only changes"),
4829
+ prevented: z.number().int().nonnegative().describe("Proactive protections triggered")
4830
+ });
4831
+ var WeeklyVelocitySchema = z.object({
4832
+ week: z.string().min(1).describe("Week label (e.g., 'W1', 'W2')"),
4833
+ learnings: z.number().int().nonnegative().describe("Cumulative pattern count"),
4834
+ accuracy: z.number().min(0).max(100).describe("AutoDecisionEngine accuracy percentage")
4835
+ });
4836
+ var PioneerSchema = z.object({
4837
+ tier: z.enum(PIONEER_TIERS).describe("Current Pioneer tier"),
4838
+ tierIndex: z.number().int().min(0).max(3).describe("Numeric index for rendering (0-3)"),
4839
+ recentUnlock: z.string().optional().describe("Most recent capability unlocked"),
4840
+ impact: z.string().describe("Cross-user impact statement")
4841
+ });
4842
+ var QuickInsightsSchema = z.object({
4843
+ sessionsThisWeek: z.number().int().nonnegative().describe("Development sessions started"),
4844
+ avgSessionMinutes: z.number().int().nonnegative().describe("Mean session length"),
4845
+ coherencePercent: z.number().min(0).max(100).describe("Session coherence score"),
4846
+ preventedToRecoveredRatio: z.string().describe("Ratio string like '3 : 1'"),
4847
+ fragileFileCount: z.number().int().nonnegative().describe("High-change, high-risk files"),
4848
+ fragileHotspots: z.string().describe("Directory summary like 'auth/ and config/'")
4849
+ });
4850
+ var UserInfoSchema = z.object({
4851
+ name: z.string().nullable().describe("User display name"),
4852
+ email: z.string().email().describe("User email address")
4853
+ });
4854
+ var SessionMetricsSchema = z.object({
4855
+ activeSessionCount: z.number().int().nonnegative().describe("Currently active sessions"),
4856
+ lastActivityTime: z.string().datetime().describe("ISO timestamp of last activity")
4857
+ });
4858
+ var PioneerDashboardSchema = z.object({
4859
+ version: z.literal(1).describe("Schema version for migrations"),
4860
+ computedAt: z.number().int().positive().describe("Unix timestamp when digest was computed"),
4861
+ // User info (from old dashboard)
4862
+ user: UserInfoSchema.describe("Current user information"),
4863
+ sessionMetrics: SessionMetricsSchema.describe("Active session metrics"),
4864
+ protection: ProtectionSchema.describe("Hero section data"),
4865
+ timeline: z.array(TimelineEventSchema).max(24).describe("24h activity timeline"),
4866
+ heatmap: z.array(HeatmapFileSchema).describe("File risk treemap data"),
4867
+ ai: AIAttributionSchema.describe("AI tool attribution"),
4868
+ weekly: z.array(DailyActivitySchema).length(7).describe("Weekly activity bars"),
4869
+ velocity: z.array(WeeklyVelocitySchema).min(4).describe("Learning velocity curve"),
4870
+ pioneer: PioneerSchema.describe("Pioneer journey data"),
4871
+ insights: QuickInsightsSchema.describe("Quick insight cards")
4872
+ });
4873
+ var PioneerDashboardSuccessSchema = z.object({
4874
+ status: z.literal("success"),
4875
+ digest: PioneerDashboardSchema,
4876
+ stalenessMinutes: z.number().int().nonnegative().describe("Minutes since last sync")
4877
+ });
4878
+ var PioneerDashboardEmptySchema = z.object({
4879
+ status: z.literal("empty"),
4880
+ message: z.string().default("No digest synced yet")
4881
+ });
4882
+ var PioneerDashboardErrorSchema = z.object({
4883
+ status: z.literal("error"),
4884
+ code: z.enum([
4885
+ "UNAUTHORIZED",
4886
+ "NOT_FOUND",
4887
+ "INTERNAL_ERROR"
4888
+ ]),
4889
+ message: z.string()
4890
+ });
4891
+ z.discriminatedUnion("status", [
4892
+ PioneerDashboardSuccessSchema,
4893
+ PioneerDashboardEmptySchema,
4894
+ PioneerDashboardErrorSchema
4895
+ ]);
4896
+ ({
4897
+ sessionMetrics: {
4898
+ lastActivityTime: (/* @__PURE__ */ new Date()).toISOString()
4899
+ }});
4900
+ var AIToolSchema = z.enum([
4901
+ "cursor",
4902
+ "copilot",
4903
+ "claude",
4904
+ "windsurf",
4905
+ "codeium",
4906
+ "tabnine",
4907
+ "cody",
4908
+ "continue",
4909
+ "aider"
4910
+ ]);
4911
+ z.object({
4912
+ detected: z.boolean(),
4913
+ confidence: z.number().min(0).max(1),
4914
+ tool: AIToolSchema.nullable(),
4915
+ patterns: z.array(z.string()),
4916
+ evidence: z.array(z.string()).optional()
4917
+ });
4918
+ z.object({
4919
+ userId: z.string(),
4920
+ email: z.string().email(),
4921
+ role: z.enum([
4922
+ "user",
4923
+ "pro",
4924
+ "team",
4925
+ "admin"
4926
+ ]),
4927
+ workspaceId: z.string().optional()
4928
+ });
4929
+ var RiskLevelSchema = z.enum([
4930
+ "low",
4931
+ "medium",
4932
+ "high",
4933
+ "critical"
4934
+ ]);
4935
+ z.number().min(0).max(10);
4936
+ var SessionStateSchema = z.enum([
4937
+ "active",
4938
+ "ended",
4939
+ "idle",
4940
+ "paused"
4941
+ ]);
4942
+ z.object({
4943
+ sessionId: z.string(),
4944
+ state: SessionStateSchema,
4945
+ workspaceId: z.string(),
4946
+ startedAt: z.date(),
4947
+ recommendations: z.array(z.string()),
4948
+ riskLevel: RiskLevelSchema
4949
+ });
4950
+ z.discriminatedUnion("type", [
4951
+ z.object({
4952
+ type: z.literal("connected"),
4953
+ pid: z.number().int().optional()
4954
+ }),
4955
+ z.object({
4956
+ type: z.literal("disconnected"),
4957
+ reason: z.string().optional()
4958
+ }),
4959
+ z.object({
4960
+ type: z.literal("error"),
4961
+ code: z.string().optional(),
4962
+ message: z.string()
4963
+ }),
4964
+ // JSON-RPC traffic (responses + notifications) arrives on the same stream.
4965
+ z.object({
4966
+ type: z.literal("message"),
4967
+ payload: JsonRpcMessageSchema
4968
+ })
4969
+ ]);
4970
+ z.object({
4971
+ device_code: z.string(),
4972
+ user_code: z.string(),
4973
+ verification_uri: z.string().url(),
4974
+ verification_uri_complete: z.string().url().optional(),
4975
+ expires_in: z.number().int().positive(),
4976
+ interval: z.number().int().positive().default(5)
4977
+ });
4978
+ z.object({
4979
+ access_token: z.string(),
4980
+ token_type: z.string(),
4981
+ refresh_token: z.string().optional(),
4982
+ expires_in: z.number().int().positive().optional(),
4983
+ // Tiered-license fields: present on some backends, absent on others. Explicit
4984
+ // so a missing tier is `undefined`, not a crash on property access.
4985
+ license_tier: z.enum([
4986
+ "pro",
4987
+ "team",
4988
+ "trial"
4989
+ ]).optional(),
4990
+ seats: z.number().int().optional()
4991
+ });
4992
+
4993
+ export { FEATURE_FLAGS, FeatureManager, LogLevel, NoOpInstrumentationProvider, PIONEER_EVENTS, SENSITIVE_PATTERNS, TIER_UPGRADE_SAGA, WorkspaceRegistrationSchema, createLogger, extractErrorCode, getEffectiveTier, getTierFeatures, getTierLimit, isFeatureAvailableAtTier, shouldMergeAttribution, validateTelemetryEvent };
4994
+ //# sourceMappingURL=chunk-WZEZLVOW.js.map
4995
+ //# sourceMappingURL=chunk-WZEZLVOW.js.map