@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,1951 @@
1
+ #!/usr/bin/env node
2
+ import { LearningApiSchema } from './chunk-VTSNRV3V.js';
3
+ import { __name } from './chunk-EWOJGXRX.js';
4
+ import { existsSync, unlinkSync, readFileSync } from 'fs';
5
+ import * as os from 'os';
6
+ import { homedir } from 'os';
7
+ import * as path from 'path';
8
+ import { join } from 'path';
9
+ import * as net from 'net';
10
+ import { z } from 'zod';
11
+ import pRetry from 'p-retry';
12
+
13
+ process.env.VREKO_CLI='true';process.env.NODE_NO_WARNINGS='1';
14
+ var DaemonHealthState = z.enum([
15
+ "healthy",
16
+ "degraded",
17
+ "unhealthy",
18
+ "unknown"
19
+ ]);
20
+ var SubsystemName = z.enum([
21
+ "ipc",
22
+ "mcp",
23
+ "supervisor",
24
+ "fileWatcher",
25
+ "sessions",
26
+ "sync"
27
+ ]);
28
+ var SubsystemStatus = z.object({
29
+ /** Current health state of this subsystem */
30
+ state: DaemonHealthState,
31
+ /** Human-readable reason for current state (omitted when healthy) */
32
+ reason: z.string().optional(),
33
+ /** ISO8601 timestamp of last state transition */
34
+ lastTransition: z.string().datetime().nullable()
35
+ });
36
+ var DaemonHealthReport = z.object({
37
+ /** Aggregate health state (worst of all subsystems, with hysteresis) */
38
+ state: DaemonHealthState,
39
+ /** Daemon uptime in milliseconds */
40
+ uptime: z.number().nonnegative(),
41
+ /** Per-subsystem health breakdown */
42
+ subsystems: z.record(SubsystemName, SubsystemStatus),
43
+ /** ISO8601 timestamp of last aggregate state transition */
44
+ lastTransition: z.string().datetime().nullable(),
45
+ /** Human-readable reason for degraded/unhealthy state */
46
+ degradedReason: z.string().optional(),
47
+ /** ISO8601 timestamp of this report */
48
+ timestamp: z.string().datetime()
49
+ });
50
+ z.object({
51
+ /** Previous aggregate state */
52
+ previousState: DaemonHealthState,
53
+ /** New aggregate state */
54
+ currentState: DaemonHealthState,
55
+ /** Human-readable reason for the transition */
56
+ reason: z.string(),
57
+ /** Unix timestamp (ms) when the transition occurred */
58
+ timestamp: z.number().nonnegative(),
59
+ /** Full health report at time of transition */
60
+ report: DaemonHealthReport
61
+ });
62
+ DaemonHealthReport.extend({
63
+ // Daemon resource state
64
+ memoryMb: z.number().nonnegative(),
65
+ memoryLimitMb: z.number().positive(),
66
+ ipcQueueDepth: z.number().nonnegative(),
67
+ activeRequests: z.number().nonnegative(),
68
+ // Lifecycle state
69
+ lastCleanShutdown: z.boolean(),
70
+ supervisorMode: z.enum([
71
+ "launchd",
72
+ "systemd",
73
+ "extension",
74
+ "none"
75
+ ]),
76
+ // Component breakdown
77
+ components: z.object({
78
+ ipcServer: z.enum([
79
+ "ok",
80
+ "degraded"
81
+ ]),
82
+ fileWatcher: z.enum([
83
+ "ok",
84
+ "degraded",
85
+ "unavailable"
86
+ ]),
87
+ syncService: z.enum([
88
+ "ok",
89
+ "degraded",
90
+ "disabled"
91
+ ]),
92
+ intelligenceService: z.enum([
93
+ "ok",
94
+ "degraded"
95
+ ])
96
+ })
97
+ });
98
+ var AITool = z.enum([
99
+ "cursor",
100
+ "claude-code",
101
+ "copilot",
102
+ "windsurf",
103
+ "cline",
104
+ "universal"
105
+ ]);
106
+ var FileAccessRule = z.object({
107
+ pattern: z.string(),
108
+ permission: z.enum([
109
+ "allow",
110
+ "deny",
111
+ "caution"
112
+ ]),
113
+ source: z.string()
114
+ });
115
+ z.object({
116
+ // Identity
117
+ tool: AITool,
118
+ filePath: z.string(),
119
+ fileName: z.string(),
120
+ lastModifiedAt: z.number(),
121
+ rawContent: z.string(),
122
+ // Extracted intelligence
123
+ protectedFiles: z.array(z.string()),
124
+ focusedDomains: z.array(z.string()),
125
+ explicitInstructions: z.array(z.string()),
126
+ toolPermissions: z.array(z.string()),
127
+ workflowConstraints: z.array(z.string()),
128
+ fileAccessRules: z.array(FileAccessRule),
129
+ behaviorRules: z.array(z.string()),
130
+ // Computed
131
+ vrekoInstructionsPresent: z.boolean(),
132
+ vrekoSectionHash: z.string().nullable()
133
+ });
134
+ z.object({
135
+ id: z.string(),
136
+ conflictType: z.enum([
137
+ "file-access",
138
+ "workflow",
139
+ "behavior",
140
+ "scope-overlap",
141
+ "coverage-gap"
142
+ ]),
143
+ tools: z.array(AITool),
144
+ files: z.array(z.string()),
145
+ description: z.string(),
146
+ severity: z.enum([
147
+ "info",
148
+ "warn",
149
+ "error"
150
+ ]),
151
+ recommendation: z.string(),
152
+ detectedAt: z.number()
153
+ });
154
+ z.object({
155
+ fileName: z.string().optional(),
156
+ pattern: z.string().optional(),
157
+ tool: AITool,
158
+ priority: z.number().default(0)
159
+ });
160
+ z.object({
161
+ filePath: z.string(),
162
+ tool: AITool,
163
+ exists: z.boolean(),
164
+ lastModified: z.number().nullable()
165
+ });
166
+ var SessionContextResult = z.object({
167
+ /** Fragile files within scope of current task */
168
+ fragileFilesInScope: z.array(z.object({
169
+ path: z.string(),
170
+ fragility: z.number(),
171
+ reason: z.string().optional()
172
+ })),
173
+ /** Co-change patterns within scope */
174
+ coChangePatternsInScope: z.array(z.object({
175
+ source: z.string(),
176
+ target: z.string(),
177
+ confidence: z.number()
178
+ })),
179
+ /** Warning about concurrent sessions */
180
+ concurrentSessionWarning: z.object({
181
+ sessionId: z.string(),
182
+ workspacePath: z.string(),
183
+ touchedFiles: z.array(z.string())
184
+ }).nullable()
185
+ });
186
+ z.object({
187
+ /** Session ID (primary identifier) */
188
+ id: z.string(),
189
+ /** Task ID (alias for extension compatibility) */
190
+ taskId: z.string().optional(),
191
+ /** Workspace path */
192
+ workspacePath: z.string(),
193
+ /** Session start timestamp (ISO string) */
194
+ startedAt: z.string(),
195
+ /** Current session state */
196
+ state: z.enum([
197
+ "active",
198
+ "ended"
199
+ ]),
200
+ /** Session metadata */
201
+ metadata: z.object({
202
+ task: z.string().optional(),
203
+ keywords: z.array(z.string()).optional(),
204
+ aiToolsDetected: z.array(z.string()).optional(),
205
+ highestRiskLevel: z.enum([
206
+ "low",
207
+ "medium",
208
+ "high"
209
+ ]).optional()
210
+ }),
211
+ /** Files touched in this session */
212
+ touchedFiles: z.array(z.string()).optional(),
213
+ /** Baseline context enrichment */
214
+ context: SessionContextResult.nullable(),
215
+ /** Learnings loaded for this session (from enrichment) */
216
+ learnings: z.array(z.object({
217
+ id: z.string().optional(),
218
+ type: z.string().optional(),
219
+ trigger: z.string(),
220
+ action: z.string(),
221
+ relevanceScore: z.number().optional()
222
+ })).optional()
223
+ });
224
+ z.object({
225
+ /** Whether the session was ended successfully */
226
+ success: z.boolean(),
227
+ /** Session ID that was ended */
228
+ sessionId: z.string().optional(),
229
+ /** Coherence score (0-1) */
230
+ coherenceScore: z.number().min(0).max(1).optional(),
231
+ /** Session duration in milliseconds */
232
+ duration: z.number().optional(),
233
+ /** Number of files modified */
234
+ filesModified: z.number().optional(),
235
+ /** Number of learnings captured */
236
+ learningsCaptured: z.number().optional(),
237
+ /** Number of snapshots created */
238
+ snapshotsCreated: z.number().optional()
239
+ });
240
+ var SessionSummarySchema = z.object({
241
+ sessionId: z.string(),
242
+ workspace: z.string(),
243
+ startedAt: z.number(),
244
+ endedAt: z.number().nullable(),
245
+ duration: z.number(),
246
+ filesModified: z.number(),
247
+ snapshotsCreated: z.number(),
248
+ restoresTriggered: z.number(),
249
+ aiEditsDetected: z.number(),
250
+ protectionLevel: z.enum([
251
+ "standard",
252
+ "heightened",
253
+ "maximum"
254
+ ])
255
+ });
256
+ var SessionPatternSchema = z.object({
257
+ type: z.enum([
258
+ "co-change",
259
+ "fragile-file",
260
+ "temporal",
261
+ "behavioral"
262
+ ]),
263
+ description: z.string(),
264
+ confidence: z.number().min(0).max(1),
265
+ filesInvolved: z.array(z.string()),
266
+ promotedToHot: z.boolean()
267
+ });
268
+ var SessionLearningsSchema = z.object({
269
+ patterns: z.array(SessionPatternSchema),
270
+ totalNew: z.number(),
271
+ totalPromoted: z.number(),
272
+ totalPruned: z.number()
273
+ });
274
+ var PitfallWarningSchema = z.object({
275
+ trigger: z.string(),
276
+ risk: z.string(),
277
+ outcome: z.enum([
278
+ "heeded",
279
+ "dismissed",
280
+ "auto-resolved"
281
+ ]),
282
+ filesInvolved: z.array(z.string()),
283
+ timestamp: z.number()
284
+ });
285
+ var PitfallsAvoidedSchema = z.object({
286
+ warnings: z.array(PitfallWarningSchema),
287
+ estimatedTimeSaved: z.number()
288
+ });
289
+ var IntelligenceMetricsSchema = z.object({
290
+ tokenSavingsEstimate: z.number(),
291
+ coherenceScore: z.number().min(0).max(100),
292
+ contextReusageRate: z.number().min(0).max(1),
293
+ intelligenceEventsTotal: z.number()
294
+ });
295
+ var TimelineEventSchema = z.object({
296
+ timestamp: z.number(),
297
+ type: z.enum([
298
+ "session-start",
299
+ "session-end",
300
+ "snapshot-created",
301
+ "snapshot-restored",
302
+ "learning-added",
303
+ "learning-promoted",
304
+ "warning-fired",
305
+ "ai-edit-detected",
306
+ "protection-changed",
307
+ "fragile-detected",
308
+ "risk-spike"
309
+ ]),
310
+ summary: z.string(),
311
+ detail: z.string().optional(),
312
+ filesInvolved: z.array(z.string()).optional(),
313
+ severity: z.enum([
314
+ "info",
315
+ "warning",
316
+ "critical"
317
+ ]).optional()
318
+ });
319
+ var CeremonyPayloadSchema = z.object({
320
+ summary: SessionSummarySchema,
321
+ learnings: SessionLearningsSchema,
322
+ pitfalls: PitfallsAvoidedSchema,
323
+ metrics: IntelligenceMetricsSchema,
324
+ timeline: z.array(TimelineEventSchema)
325
+ }).superRefine((payload, ctx) => {
326
+ const sessionStart = payload.summary.startedAt;
327
+ const sessionEnd = payload.summary.endedAt ?? Date.now();
328
+ for (const event of payload.timeline) {
329
+ if (event.timestamp < sessionStart) {
330
+ ctx.addIssue({
331
+ code: "custom",
332
+ message: `Timeline event ${event.type} has timestamp before session start`,
333
+ path: [
334
+ "timeline"
335
+ ]
336
+ });
337
+ }
338
+ if (event.timestamp > sessionEnd) {
339
+ ctx.addIssue({
340
+ code: "custom",
341
+ message: `Timeline event ${event.type} has timestamp after session end`,
342
+ path: [
343
+ "timeline"
344
+ ]
345
+ });
346
+ }
347
+ }
348
+ const patternCount = payload.learnings.patterns.length;
349
+ const totalLearnings = payload.learnings.totalNew + payload.learnings.totalPromoted;
350
+ if (patternCount > 0 && totalLearnings === 0) {
351
+ ctx.addIssue({
352
+ code: "custom",
353
+ message: "Learnings has patterns but totalNew + totalPromoted is 0",
354
+ path: [
355
+ "learnings"
356
+ ]
357
+ });
358
+ }
359
+ if (payload.metrics.coherenceScore > 100) {
360
+ ctx.addIssue({
361
+ code: "custom",
362
+ message: "coherenceScore must be between 0-100",
363
+ path: [
364
+ "metrics",
365
+ "coherenceScore"
366
+ ]
367
+ });
368
+ }
369
+ if (payload.summary.filesModified > 10 && payload.metrics.intelligenceEventsTotal < 5) {
370
+ ctx.addIssue({
371
+ code: "custom",
372
+ message: "High file modification count with low intelligence events - possible under-instrumentation",
373
+ path: [
374
+ "metrics"
375
+ ]
376
+ });
377
+ }
378
+ });
379
+ var CoherenceScoreSchema = z.discriminatedUnion("type", [
380
+ z.object({
381
+ type: z.literal("numeric"),
382
+ value: z.number().min(0).max(1)
383
+ }),
384
+ z.object({
385
+ type: z.literal("categorical"),
386
+ level: z.enum([
387
+ "high",
388
+ "medium",
389
+ "low",
390
+ "scattered"
391
+ ]),
392
+ /** Optional numeric approximation for analytics */
393
+ approximateValue: z.number().min(0).max(1).optional()
394
+ })
395
+ ]);
396
+ z.object({
397
+ /** Session ID */
398
+ sessionId: z.string(),
399
+ /** Files modified during session */
400
+ filesModified: z.number(),
401
+ /** Snapshots created during session */
402
+ snapshotsCreated: z.number(),
403
+ /** Learnings captured during session */
404
+ learningsCaptured: z.number(),
405
+ /** Pitfalls avoided (proactive warnings heeded) */
406
+ pitfallsAvoided: z.number().optional(),
407
+ /** Estimated token savings */
408
+ tokensSaved: z.number().optional(),
409
+ /** Coherence score - discriminated union for type-safe handling */
410
+ coherenceScore: CoherenceScoreSchema.optional(),
411
+ /** Key insights from the session */
412
+ insights: z.array(z.string()).optional(),
413
+ /** Items to carry forward to next session */
414
+ carryForward: z.array(z.string()).optional(),
415
+ /** Commit message suggestion */
416
+ commitMessage: z.string().optional(),
417
+ /** Full ceremony payload (March 18 spec) */
418
+ ceremony: CeremonyPayloadSchema.optional(),
419
+ /** Top learnings from ceremony */
420
+ topLearnings: z.array(z.object({
421
+ content: z.string(),
422
+ captureMethod: z.string(),
423
+ confidence: z.number()
424
+ })).optional(),
425
+ /** Duration in ms */
426
+ duration: z.number().optional()
427
+ });
428
+ z.object({
429
+ /** Whether there's an active session */
430
+ active: z.boolean(),
431
+ /** Current session ID if active */
432
+ id: z.string().optional(),
433
+ /** Task ID if active */
434
+ taskId: z.string().optional(),
435
+ /** Task description */
436
+ task: z.string().optional(),
437
+ /** Session start timestamp */
438
+ startedAt: z.string().optional(),
439
+ /** Files modified count */
440
+ filesModified: z.number().optional(),
441
+ /** Snapshot count */
442
+ snapshotCount: z.number().optional()
443
+ });
444
+ z.object({
445
+ /** Whether the learning was added successfully */
446
+ success: z.boolean(),
447
+ /** Learning ID */
448
+ id: z.string(),
449
+ /** Tier assigned (hot, warm, cold) */
450
+ tier: z.enum([
451
+ "hot",
452
+ "warm",
453
+ "cold"
454
+ ]),
455
+ /** Whether this is a new learning vs update */
456
+ isNew: z.boolean().optional()
457
+ });
458
+ var LearningSearchEntry = z.object({
459
+ /** Learning ID */
460
+ id: z.string(),
461
+ /** Learning type */
462
+ type: z.string().optional(),
463
+ /** Trigger condition */
464
+ trigger: z.string(),
465
+ /** Action to take */
466
+ action: z.string(),
467
+ /** Relevance score (0-1) */
468
+ relevanceScore: z.number().min(0).max(1).optional(),
469
+ /** Source of the learning */
470
+ source: z.string().optional(),
471
+ /** Tier of the learning */
472
+ tier: z.enum([
473
+ "hot",
474
+ "warm",
475
+ "cold"
476
+ ]).optional()
477
+ });
478
+ z.object({
479
+ /** Search results */
480
+ results: z.array(LearningSearchEntry),
481
+ /** Total matching learnings */
482
+ total: z.number().optional(),
483
+ /** Query that was searched */
484
+ query: z.string().optional()
485
+ });
486
+ var FragileFileEntry = z.object({
487
+ /** File path */
488
+ path: z.string(),
489
+ /** Fragility score (0-1) */
490
+ fragility: z.number().min(0).max(1),
491
+ /** Reason for fragility */
492
+ reason: z.string().optional()
493
+ });
494
+ var CoChangeEntry = z.object({
495
+ /** Source file */
496
+ source: z.string(),
497
+ /** Target file (changes when source changes) */
498
+ target: z.string(),
499
+ /** Confidence score (0-1) */
500
+ confidence: z.number().min(0).max(1)
501
+ });
502
+ z.object({
503
+ /** Elevated, deduplicated learnings (LearningApi format) */
504
+ learnings: z.array(LearningApiSchema),
505
+ /** Fragile files in scope */
506
+ fragileFiles: z.array(FragileFileEntry).optional(),
507
+ /** Co-change patterns */
508
+ coChanges: z.array(CoChangeEntry).optional(),
509
+ /** Files that were queried */
510
+ files: z.array(z.string()),
511
+ /** Compiled wire format context (for LLM consumption) */
512
+ compiled: z.string(),
513
+ /** Token estimate for compiled context */
514
+ compiledTokens: z.number(),
515
+ /** Estimated tokens saved vs natural language */
516
+ tokensSaved: z.number(),
517
+ /** Metadata about what's included */
518
+ metadata: z.object({
519
+ /** Number of learnings included */
520
+ learningCount: z.number().optional(),
521
+ /** Number of fragile files included */
522
+ fragileFileCount: z.number().optional(),
523
+ /** Number of co-change patterns included */
524
+ coChangePatternCount: z.number().optional(),
525
+ /** Estimated token count */
526
+ tokenCount: z.number().optional(),
527
+ /** Whether context was loaded from cache */
528
+ fromCache: z.boolean().optional()
529
+ }).optional()
530
+ });
531
+ z.object({
532
+ /** Composite risk score */
533
+ score: z.number(),
534
+ /** Action recommendation */
535
+ action: z.enum([
536
+ "PROCEED",
537
+ "PROCEED_WITH_SNAPSHOT",
538
+ "WARN",
539
+ "BLOCK"
540
+ ]),
541
+ /** Risk level classification */
542
+ level: z.enum([
543
+ "L",
544
+ "M",
545
+ "H"
546
+ ]),
547
+ /** Contributing factors from all pillars */
548
+ factors: z.array(z.object({
549
+ source: z.string(),
550
+ score: z.number(),
551
+ description: z.string()
552
+ })),
553
+ /** Git risk pillar data */
554
+ gitRisk: z.object({
555
+ multiplier: z.number(),
556
+ uncommittedChanges: z.boolean().optional(),
557
+ detachedHead: z.boolean().optional(),
558
+ onMainBranch: z.boolean().optional()
559
+ }).optional(),
560
+ /** Fatigue pillar data */
561
+ fatigue: z.object({
562
+ level: z.enum([
563
+ "rested",
564
+ "normal",
565
+ "elevated",
566
+ "fatigued"
567
+ ]),
568
+ riskBoost: z.number()
569
+ }).optional(),
570
+ /** Rollback warning from pillar 2 */
571
+ rollbackWarning: z.object({
572
+ confidence: z.number(),
573
+ message: z.string(),
574
+ riskBoost: z.number()
575
+ }).optional(),
576
+ /** Poisoning detection from pillar 5 */
577
+ poisoning: z.object({
578
+ detected: z.boolean(),
579
+ files: z.array(z.string()).optional(),
580
+ riskBoost: z.number().optional()
581
+ }).optional(),
582
+ /** Per-file risk breakdown */
583
+ fileRisks: z.record(z.string(), z.object({
584
+ fragility: z.number(),
585
+ rollbackCount: z.number().optional(),
586
+ reason: z.string().optional()
587
+ })).optional(),
588
+ /** Co-change alerts */
589
+ coChanges: z.array(z.object({
590
+ source: z.string(),
591
+ target: z.string(),
592
+ confidence: z.number()
593
+ })).optional()
594
+ });
595
+ z.string().describe("LLM hint for vreko_pulse - deterministic advisory prose, \u2264400 word-tokens");
596
+ z.object({
597
+ /** Array of fragile file entries in contract shape */
598
+ files: z.array(FragileFileEntry),
599
+ /** Total count of files returned */
600
+ total: z.number().int().nonnegative()
601
+ });
602
+ z.object({
603
+ items: z.array(z.object({
604
+ fileA: z.string(),
605
+ fileB: z.string(),
606
+ frequency: z.number(),
607
+ occurrences: z.number(),
608
+ relationship: z.string(),
609
+ reason: z.string(),
610
+ lastObserved: z.string()
611
+ })),
612
+ total: z.number().int().nonnegative()
613
+ });
614
+ z.object({
615
+ learningsCount: z.number().int().nonnegative(),
616
+ patternsCount: z.number().int().nonnegative(),
617
+ fragileFilesCount: z.number().int().nonnegative(),
618
+ coChangePatternsCount: z.number().int().nonnegative(),
619
+ totalSessions: z.number().int().nonnegative(),
620
+ linesAnalyzed: z.number().int().nonnegative(),
621
+ totalSnapshots: z.number().int().nonnegative(),
622
+ totalRestores: z.number().int().nonnegative(),
623
+ snapshotsToday: z.number().int().nonnegative(),
624
+ snapshotsThisWeek: z.number().int().nonnegative(),
625
+ linesAnalyzedToday: z.number().int().nonnegative(),
626
+ restoresThisWeek: z.number().int().nonnegative(),
627
+ patternsThisWeek: z.number().int().nonnegative(),
628
+ healthScore: z.number(),
629
+ healthTrajectory: z.string(),
630
+ risksPrevented: z.number().int().nonnegative(),
631
+ risksPreventedContext: z.string().optional(),
632
+ accuracy: z.number(),
633
+ coherencePercent: z.number().int(),
634
+ preventedToRecoveredRatio: z.number()
635
+ });
636
+ z.object({
637
+ warnings: z.array(z.object({
638
+ code: z.string(),
639
+ level: z.enum([
640
+ "info",
641
+ "warning",
642
+ "error"
643
+ ]),
644
+ message: z.string(),
645
+ file: z.string().optional(),
646
+ suggestion: z.string().optional()
647
+ })),
648
+ total: z.number().int().nonnegative()
649
+ });
650
+ z.object({
651
+ score: z.number().int().min(0).max(100),
652
+ status: z.enum([
653
+ "healthy",
654
+ "warning",
655
+ "critical"
656
+ ]),
657
+ accuracy: z.number(),
658
+ metrics: z.object({
659
+ vitals: z.object({
660
+ trajectory: z.string(),
661
+ pressure: z.number(),
662
+ pulse: z.string()
663
+ }).nullable(),
664
+ session: z.object({
665
+ duration: z.number(),
666
+ totalToolCalls: z.number().int(),
667
+ filesTouched: z.number().int()
668
+ }).nullable()
669
+ })
670
+ });
671
+ z.object({
672
+ candidates: z.array(z.object({
673
+ file: z.string(),
674
+ window: z.string(),
675
+ confidence: z.number(),
676
+ surfaceable: z.boolean(),
677
+ wording: z.string(),
678
+ coChangePartners: z.array(z.string()),
679
+ kind: z.string()
680
+ })),
681
+ total: z.number().int().nonnegative()
682
+ });
683
+ z.union([
684
+ z.object({
685
+ captured: z.literal(true),
686
+ domain: z.string(),
687
+ type: z.string(),
688
+ outcome: z.string().optional(),
689
+ risksPreventedContext: z.string().optional()
690
+ }),
691
+ z.object({
692
+ captured: z.literal(false),
693
+ error: z.string()
694
+ })
695
+ ]);
696
+ z.object({
697
+ recorded: z.boolean(),
698
+ patternId: z.string().optional(),
699
+ outcome: z.string().optional(),
700
+ notes: z.string().optional(),
701
+ revertedWithin5Min: z.boolean().optional(),
702
+ accuracyImpact: z.string().optional()
703
+ });
704
+ z.object({
705
+ patterns: z.array(z.unknown()),
706
+ total: z.number().int().nonnegative()
707
+ });
708
+ z.object({
709
+ success: z.boolean()
710
+ });
711
+ z.object({
712
+ sessions: z.array(z.unknown()),
713
+ hasMore: z.boolean()
714
+ });
715
+ z.unknown();
716
+ z.object({
717
+ sessions: z.array(z.unknown()),
718
+ hasMore: z.boolean().optional(),
719
+ nextCursor: z.string().optional()
720
+ });
721
+ z.unknown();
722
+ z.object({
723
+ updated: z.boolean()
724
+ });
725
+ z.unknown();
726
+ z.unknown();
727
+ z.unknown();
728
+ z.unknown();
729
+ z.unknown();
730
+ z.object({
731
+ success: z.boolean(),
732
+ snapshotId: z.string().optional()
733
+ });
734
+ z.unknown();
735
+ z.object({
736
+ deletedCount: z.number().int().nonnegative().optional(),
737
+ success: z.boolean().optional()
738
+ }).passthrough();
739
+ z.object({
740
+ protected: z.boolean().optional(),
741
+ success: z.boolean().optional()
742
+ }).passthrough();
743
+ z.object({
744
+ protected: z.boolean().optional(),
745
+ success: z.boolean().optional()
746
+ }).passthrough();
747
+ z.object({
748
+ renamed: z.boolean().optional(),
749
+ success: z.boolean().optional()
750
+ }).passthrough();
751
+ z.object({
752
+ /** Absolute path to the file on disk. */
753
+ path: z.string(),
754
+ /** Serialized artifact content (markdown/text). */
755
+ content: z.string(),
756
+ /** SHA-256 of `content` - used for skip-if-unchanged checks. */
757
+ hash: z.string(),
758
+ /** Milliseconds since epoch when the artifact was generated. */
759
+ generatedAt: z.number(),
760
+ /**
761
+ * Who owns this file. `vreko` = daemon may overwrite; `user` = hands off.
762
+ * DocsEmitter only writes files it owns; any path a user has taken over
763
+ * (tracked via a separate manifest in future phases) must be skipped.
764
+ */
765
+ owner: z.enum([
766
+ "vreko",
767
+ "user"
768
+ ])
769
+ });
770
+ z.object({
771
+ daemon: z.object({
772
+ memoryLimitMb: z.number().positive().default(512),
773
+ idleTimeoutMinutes: z.number().positive().default(15),
774
+ maxWorkspaces: z.number().positive().default(50),
775
+ maxClients: z.number().positive().int().default(10),
776
+ drainWindowMs: z.number().positive().default(15e3),
777
+ logLevel: z.enum([
778
+ "debug",
779
+ "info",
780
+ "warn",
781
+ "error"
782
+ ]).default("info"),
783
+ crashLoopThreshold: z.number().positive().int().default(3),
784
+ updateBehavior: z.enum([
785
+ "auto",
786
+ "prompt",
787
+ "never"
788
+ ]).default("auto")
789
+ }).default({}),
790
+ supervisor: z.object({
791
+ mode: z.enum([
792
+ "auto",
793
+ "extension",
794
+ "os"
795
+ ]).default("auto")
796
+ }).default({})
797
+ });
798
+ var IssueSchema = z.object({
799
+ id: z.string(),
800
+ severity: z.enum([
801
+ "warning",
802
+ "error"
803
+ ]),
804
+ description: z.string(),
805
+ fix: z.string().optional()
806
+ });
807
+ var StartStatusOutput = z.discriminatedUnion("ok", [
808
+ z.object({
809
+ ok: z.literal(true),
810
+ serviceRunning: z.boolean(),
811
+ bootProfile: z.string(),
812
+ tui: z.boolean()
813
+ }),
814
+ z.object({
815
+ ok: z.literal(false),
816
+ error: z.string()
817
+ })
818
+ ]);
819
+ var WorkspaceStatusOutput = z.object({
820
+ initialized: z.boolean(),
821
+ loggedIn: z.boolean(),
822
+ user: z.object({
823
+ email: z.string(),
824
+ tier: z.enum([
825
+ "free",
826
+ "pro"
827
+ ])
828
+ }).optional(),
829
+ workspace: z.object({
830
+ id: z.string().optional(),
831
+ tier: z.string().optional(),
832
+ syncEnabled: z.boolean().optional()
833
+ }).optional(),
834
+ vitals: z.object({
835
+ framework: z.string().optional(),
836
+ packageManager: z.string().optional(),
837
+ typescript: z.boolean().optional(),
838
+ typescriptStrict: z.boolean().optional()
839
+ }).optional(),
840
+ session: z.object({
841
+ id: z.string(),
842
+ task: z.string().optional(),
843
+ startedAt: z.string(),
844
+ snapshotCount: z.number()
845
+ }).optional(),
846
+ protection: z.object({
847
+ count: z.number(),
848
+ patterns: z.array(z.string())
849
+ }),
850
+ violations: z.object({
851
+ total: z.number(),
852
+ recent: z.number()
853
+ }),
854
+ snapshots: z.object({
855
+ count: z.number(),
856
+ totalSize: z.string()
857
+ }),
858
+ intelligence: z.object({
859
+ overallRisk: z.string(),
860
+ confidence: z.number(),
861
+ topDriver: z.string(),
862
+ snapshotFrequency: z.string()
863
+ }).optional(),
864
+ topologyWarning: z.object({
865
+ fileCap: z.number(),
866
+ reachedAt: z.string(),
867
+ workspacePath: z.string()
868
+ }).optional(),
869
+ issues: z.array(IssueSchema)
870
+ });
871
+ var __defProp = Object.defineProperty;
872
+ var __name2 = /* @__PURE__ */ __name((target, value) => __defProp(target, "name", {
873
+ value,
874
+ configurable: true
875
+ }), "__name");
876
+ var JsonRpcClientError = class extends Error {
877
+ static {
878
+ __name(this, "JsonRpcClientError");
879
+ }
880
+ static {
881
+ __name2(this, "JsonRpcClientError");
882
+ }
883
+ code;
884
+ data;
885
+ constructor(message, code, data) {
886
+ super(message);
887
+ this.name = "JsonRpcClientError";
888
+ this.code = code;
889
+ this.data = data;
890
+ }
891
+ };
892
+ var ConnectionTimeoutError = class extends Error {
893
+ static {
894
+ __name(this, "ConnectionTimeoutError");
895
+ }
896
+ static {
897
+ __name2(this, "ConnectionTimeoutError");
898
+ }
899
+ constructor(message = "Connection timeout") {
900
+ super(message);
901
+ this.name = "ConnectionTimeoutError";
902
+ }
903
+ };
904
+ var RequestTimeoutError = class extends Error {
905
+ static {
906
+ __name(this, "RequestTimeoutError");
907
+ }
908
+ static {
909
+ __name2(this, "RequestTimeoutError");
910
+ }
911
+ requestId;
912
+ constructor(message = "Request timeout", requestId) {
913
+ super(message), this.requestId = requestId;
914
+ this.name = "RequestTimeoutError";
915
+ }
916
+ };
917
+ function getDefaultSocketPath() {
918
+ const platform2 = os.platform();
919
+ if (platform2 === "win32") {
920
+ return "\\\\.\\pipe\\vreko-service";
921
+ }
922
+ const homeDir = os.homedir();
923
+ const vrekoPath = path.join(homeDir, ".vreko", "service.sock");
924
+ if (existsSync(vrekoPath)) {
925
+ return vrekoPath;
926
+ }
927
+ return path.join(homeDir, ".vreko", "service.sock");
928
+ }
929
+ __name(getDefaultSocketPath, "getDefaultSocketPath");
930
+ __name2(getDefaultSocketPath, "getDefaultSocketPath");
931
+ var IpcConnection = class {
932
+ static {
933
+ __name(this, "IpcConnection");
934
+ }
935
+ static {
936
+ __name2(this, "IpcConnection");
937
+ }
938
+ socket = null;
939
+ buffer = "";
940
+ listeners = {};
941
+ socketPath;
942
+ timeout;
943
+ constructor(options = {}) {
944
+ this.socketPath = options.socketPath ?? getDefaultSocketPath();
945
+ this.timeout = options.timeout ?? 5e3;
946
+ }
947
+ /**
948
+ * Connect to the IPC socket
949
+ *
950
+ * Fixed race conditions:
951
+ * - Uses settled flag to prevent timeout firing after successful connect
952
+ * - Destroys socket on error to prevent orphaned handles
953
+ * - Cleanup function ensures timeout is always cleared
954
+ */
955
+ async connect() {
956
+ return new Promise((resolve, reject) => {
957
+ const socket = net.createConnection({
958
+ path: this.socketPath
959
+ });
960
+ let timeoutId = null;
961
+ let settled = false;
962
+ const cleanup = /* @__PURE__ */ __name2(() => {
963
+ if (timeoutId) {
964
+ clearTimeout(timeoutId);
965
+ timeoutId = null;
966
+ }
967
+ }, "cleanup");
968
+ if (this.timeout > 0) {
969
+ timeoutId = setTimeout(() => {
970
+ if (settled) {
971
+ return;
972
+ }
973
+ settled = true;
974
+ cleanup();
975
+ socket.destroy();
976
+ reject(new ConnectionTimeoutError(`Connection timeout after ${this.timeout}ms`));
977
+ }, this.timeout);
978
+ timeoutId.unref();
979
+ }
980
+ socket.once("connect", () => {
981
+ if (settled) {
982
+ return;
983
+ }
984
+ settled = true;
985
+ cleanup();
986
+ this.socket = socket;
987
+ this.setupSocketHandlers();
988
+ resolve();
989
+ });
990
+ socket.once("error", (error) => {
991
+ if (settled) {
992
+ return;
993
+ }
994
+ settled = true;
995
+ cleanup();
996
+ socket.destroy();
997
+ reject(error);
998
+ });
999
+ });
1000
+ }
1001
+ /**
1002
+ * Set up socket event handlers
1003
+ *
1004
+ * IMPORTANT: Removes old listeners before adding new ones to prevent
1005
+ * memory leak on reconnect. Without this, each reconnect would add
1006
+ * duplicate handlers that never get garbage collected.
1007
+ */
1008
+ setupSocketHandlers() {
1009
+ if (!this.socket) {
1010
+ return;
1011
+ }
1012
+ this.socket.removeAllListeners("data");
1013
+ this.socket.removeAllListeners("close");
1014
+ this.socket.removeAllListeners("error");
1015
+ this.socket.on("data", (chunk) => {
1016
+ this.buffer += chunk.toString("utf8");
1017
+ this.processBuffer();
1018
+ });
1019
+ this.socket.on("close", (hadError) => {
1020
+ const error = hadError ? new Error("Socket closed with error") : void 0;
1021
+ this.emit("close", error);
1022
+ this.socket = null;
1023
+ this.buffer = "";
1024
+ });
1025
+ this.socket.on("error", (error) => {
1026
+ this.emit("error", error);
1027
+ this.buffer = "";
1028
+ });
1029
+ }
1030
+ /**
1031
+ * Process incoming data buffer (newline-delimited JSON)
1032
+ */
1033
+ processBuffer() {
1034
+ let newlineIndex;
1035
+ while ((newlineIndex = this.buffer.indexOf("\n")) !== -1) {
1036
+ const line = this.buffer.slice(0, newlineIndex);
1037
+ this.buffer = this.buffer.slice(newlineIndex + 1);
1038
+ if (line.trim().length === 0) {
1039
+ continue;
1040
+ }
1041
+ try {
1042
+ const message = JSON.parse(line);
1043
+ this.emit("message", message);
1044
+ } catch (error) {
1045
+ this.emit("error", new Error(`Failed to parse JSON-RPC message: ${error.message}`));
1046
+ }
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Send a JSON-RPC request
1051
+ *
1052
+ * TOCTOU Fix: Captures socket reference at start to prevent race condition
1053
+ * where socket becomes null between the check and the write.
1054
+ */
1055
+ async send(request) {
1056
+ const socket = this.socket;
1057
+ if (!socket || socket.destroyed) {
1058
+ throw new Error("Socket not connected");
1059
+ }
1060
+ return new Promise((resolve, reject) => {
1061
+ const data = `${JSON.stringify(request)}
1062
+ `;
1063
+ socket.write(data, "utf8", (error) => {
1064
+ if (error) {
1065
+ reject(error);
1066
+ } else {
1067
+ resolve();
1068
+ }
1069
+ });
1070
+ });
1071
+ }
1072
+ /**
1073
+ * Close the connection
1074
+ *
1075
+ * Proper cleanup:
1076
+ * - Removes all listeners to prevent memory leaks
1077
+ * - Calls end() for graceful close
1078
+ * - Calls destroy() to ensure immediate cleanup
1079
+ * - Resets buffer to prevent stale data on reconnect
1080
+ */
1081
+ close() {
1082
+ if (this.socket) {
1083
+ this.socket.removeAllListeners();
1084
+ this.socket.end();
1085
+ this.socket.destroy();
1086
+ this.socket = null;
1087
+ }
1088
+ this.buffer = "";
1089
+ }
1090
+ /**
1091
+ * Check if connected
1092
+ */
1093
+ isConnected() {
1094
+ return this.socket !== null && !this.socket.destroyed;
1095
+ }
1096
+ /**
1097
+ * Register event listener
1098
+ */
1099
+ on(event, handler) {
1100
+ this.listeners[event] = handler;
1101
+ }
1102
+ /**
1103
+ * Remove event listener
1104
+ */
1105
+ off(event) {
1106
+ delete this.listeners[event];
1107
+ }
1108
+ /**
1109
+ * Emit event
1110
+ */
1111
+ emit(event, ...args) {
1112
+ const handler = this.listeners[event];
1113
+ if (handler) {
1114
+ handler(...args);
1115
+ }
1116
+ }
1117
+ };
1118
+ var ReconnectManager = class {
1119
+ static {
1120
+ __name(this, "ReconnectManager");
1121
+ }
1122
+ static {
1123
+ __name2(this, "ReconnectManager");
1124
+ }
1125
+ isReconnecting = false;
1126
+ abortController = null;
1127
+ options;
1128
+ constructor(options = {}) {
1129
+ this.options = {
1130
+ maxAttempts: options.maxAttempts ?? 5,
1131
+ initialDelay: options.initialDelay ?? 1e3,
1132
+ maxDelay: options.maxDelay ?? 3e4,
1133
+ backoffMultiplier: options.backoffMultiplier ?? 2
1134
+ };
1135
+ }
1136
+ /**
1137
+ * Start reconnection process
1138
+ */
1139
+ async start(connectFn, onAttempt, onFailed) {
1140
+ if (this.isReconnecting) {
1141
+ return;
1142
+ }
1143
+ this.isReconnecting = true;
1144
+ this.abortController = new AbortController();
1145
+ const pRetryOptions = {
1146
+ retries: this.options.maxAttempts,
1147
+ factor: this.options.backoffMultiplier,
1148
+ minTimeout: this.options.initialDelay,
1149
+ maxTimeout: this.options.maxDelay,
1150
+ randomize: false,
1151
+ signal: this.abortController.signal,
1152
+ onFailedAttempt: /* @__PURE__ */ __name2((error) => {
1153
+ if (onAttempt) {
1154
+ onAttempt(error.attemptNumber, this.options.maxAttempts);
1155
+ }
1156
+ }, "onFailedAttempt")
1157
+ };
1158
+ try {
1159
+ await pRetry(connectFn, pRetryOptions);
1160
+ this.reset();
1161
+ } catch (error) {
1162
+ this.reset();
1163
+ if (onFailed) {
1164
+ onFailed();
1165
+ }
1166
+ throw error;
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Stop reconnection process
1171
+ */
1172
+ stop() {
1173
+ if (this.abortController) {
1174
+ this.abortController.abort();
1175
+ this.abortController = null;
1176
+ }
1177
+ this.reset();
1178
+ }
1179
+ /**
1180
+ * Reset reconnection state
1181
+ */
1182
+ reset() {
1183
+ this.isReconnecting = false;
1184
+ }
1185
+ /**
1186
+ * Check if currently reconnecting
1187
+ */
1188
+ isActive() {
1189
+ return this.isReconnecting;
1190
+ }
1191
+ /**
1192
+ * Get current attempt number (not tracked in p-retry wrapper)
1193
+ * @deprecated p-retry handles attempt tracking internally
1194
+ */
1195
+ getCurrentAttempt() {
1196
+ return this.isReconnecting ? 1 : 0;
1197
+ }
1198
+ };
1199
+ function createContextMethods(call) {
1200
+ return {
1201
+ get: /* @__PURE__ */ __name2((params) => call("context/get", params), "get"),
1202
+ validate: /* @__PURE__ */ __name2((params) => call("context/validate", params), "validate"),
1203
+ checkPatterns: /* @__PURE__ */ __name2((params) => call("context/check-patterns", params), "checkPatterns")
1204
+ };
1205
+ }
1206
+ __name(createContextMethods, "createContextMethods");
1207
+ __name2(createContextMethods, "createContextMethods");
1208
+ function createDaemonMethods(call) {
1209
+ return {
1210
+ ping: /* @__PURE__ */ __name2(() => call("daemon/ping"), "ping"),
1211
+ status: /* @__PURE__ */ __name2(() => call("daemon/status"), "status"),
1212
+ shutdown: /* @__PURE__ */ __name2(() => call("daemon/shutdown"), "shutdown"),
1213
+ reload: /* @__PURE__ */ __name2(() => call("daemon/reload"), "reload")
1214
+ };
1215
+ }
1216
+ __name(createDaemonMethods, "createDaemonMethods");
1217
+ __name2(createDaemonMethods, "createDaemonMethods");
1218
+ function createDetectionMethods(call) {
1219
+ return {
1220
+ check: /* @__PURE__ */ __name2((params) => call("detection/check", params), "check")
1221
+ };
1222
+ }
1223
+ __name(createDetectionMethods, "createDetectionMethods");
1224
+ __name2(createDetectionMethods, "createDetectionMethods");
1225
+ function createHealthMethods(call) {
1226
+ return {
1227
+ check: /* @__PURE__ */ __name2((params) => call("health/check", params), "check"),
1228
+ ping: /* @__PURE__ */ __name2(() => call("health/ping"), "ping")
1229
+ };
1230
+ }
1231
+ __name(createHealthMethods, "createHealthMethods");
1232
+ __name2(createHealthMethods, "createHealthMethods");
1233
+ function createIntelligenceMethods(call) {
1234
+ return {
1235
+ capture: /* @__PURE__ */ __name2((params) => call("intelligence/capture", params), "capture"),
1236
+ outcome: /* @__PURE__ */ __name2((params) => call("intelligence/outcome", params), "outcome"),
1237
+ snapshot: /* @__PURE__ */ __name2((params) => call("intelligence/snapshot", params), "snapshot")
1238
+ };
1239
+ }
1240
+ __name(createIntelligenceMethods, "createIntelligenceMethods");
1241
+ __name2(createIntelligenceMethods, "createIntelligenceMethods");
1242
+ function createLearningMethods(call) {
1243
+ return {
1244
+ add: /* @__PURE__ */ __name2((params) => call("learning/add", params), "add"),
1245
+ search: /* @__PURE__ */ __name2((params) => call("learning/search", params), "search"),
1246
+ list: /* @__PURE__ */ __name2((params) => call("learning/list", params), "list"),
1247
+ prune: /* @__PURE__ */ __name2((params) => call("learning/prune", params), "prune"),
1248
+ evaluate: /* @__PURE__ */ __name2((params) => call("learning/evaluate", params), "evaluate"),
1249
+ updateSession: /* @__PURE__ */ __name2((params) => call("learning/update-session", params), "updateSession"),
1250
+ gc: /* @__PURE__ */ __name2((params) => call("learning/gc", params), "gc"),
1251
+ seed: /* @__PURE__ */ __name2((params) => call("learning/seed", params), "seed"),
1252
+ consolidate: /* @__PURE__ */ __name2((params) => call("learning/consolidate", params), "consolidate")
1253
+ };
1254
+ }
1255
+ __name(createLearningMethods, "createLearningMethods");
1256
+ __name2(createLearningMethods, "createLearningMethods");
1257
+ function createMCPMethods(call) {
1258
+ return {
1259
+ snapshotCreated: /* @__PURE__ */ __name2((params) => call("mcp/snapshot-created", params), "snapshotCreated"),
1260
+ fileModified: /* @__PURE__ */ __name2((params) => call("mcp/file-modified", params), "fileModified")
1261
+ };
1262
+ }
1263
+ __name(createMCPMethods, "createMCPMethods");
1264
+ __name2(createMCPMethods, "createMCPMethods");
1265
+ function createMomentumMethods(call) {
1266
+ return {
1267
+ refresh: /* @__PURE__ */ __name2((params) => call("momentum/refresh", params), "refresh"),
1268
+ score: /* @__PURE__ */ __name2((params) => call("momentum/score", params), "score"),
1269
+ sync: /* @__PURE__ */ __name2((params) => call("momentum/sync", params), "sync"),
1270
+ status: /* @__PURE__ */ __name2((params) => call("momentum/status", params), "status")
1271
+ };
1272
+ }
1273
+ __name(createMomentumMethods, "createMomentumMethods");
1274
+ __name2(createMomentumMethods, "createMomentumMethods");
1275
+ function createProtectionMethods(call) {
1276
+ return {
1277
+ evaluate: /* @__PURE__ */ __name2((params) => call("protection/evaluate", params), "evaluate"),
1278
+ levels: /* @__PURE__ */ __name2((params) => call("protection/levels", params), "levels"),
1279
+ set: /* @__PURE__ */ __name2((params) => call("protection/set", params), "set"),
1280
+ listDaemon: /* @__PURE__ */ __name2((params) => call("protection/list-daemon", params), "listDaemon")
1281
+ };
1282
+ }
1283
+ __name(createProtectionMethods, "createProtectionMethods");
1284
+ __name2(createProtectionMethods, "createProtectionMethods");
1285
+ function createSessionMethods(call) {
1286
+ return {
1287
+ current: /* @__PURE__ */ __name2((params) => call("session/current", params), "current"),
1288
+ start: /* @__PURE__ */ __name2((params) => call("session/start", params), "start"),
1289
+ end: /* @__PURE__ */ __name2((params) => call("session/end", params), "end"),
1290
+ list: /* @__PURE__ */ __name2((params) => call("session/list", params), "list"),
1291
+ vitals: /* @__PURE__ */ __name2((params) => call("session/vitals", params), "vitals")
1292
+ };
1293
+ }
1294
+ __name(createSessionMethods, "createSessionMethods");
1295
+ __name2(createSessionMethods, "createSessionMethods");
1296
+ function createSnapshotMethods(call) {
1297
+ return {
1298
+ create: /* @__PURE__ */ __name2((params) => call("snapshot/create", params), "create"),
1299
+ get: /* @__PURE__ */ __name2((params) => call("snapshot/get", params), "get"),
1300
+ list: /* @__PURE__ */ __name2((params) => call("snapshot/list", params), "list"),
1301
+ restore: /* @__PURE__ */ __name2((params) => call("snapshot/restore", params), "restore"),
1302
+ diff: /* @__PURE__ */ __name2((params) => call("snapshot/diff", params), "diff"),
1303
+ delete: /* @__PURE__ */ __name2((params) => call("snapshot/delete", params), "delete")
1304
+ };
1305
+ }
1306
+ __name(createSnapshotMethods, "createSnapshotMethods");
1307
+ __name2(createSnapshotMethods, "createSnapshotMethods");
1308
+ function createSupervisorMethods(call) {
1309
+ return {
1310
+ register: /* @__PURE__ */ __name2((params) => call("supervisor/register", params), "register"),
1311
+ heartbeat: /* @__PURE__ */ __name2((params) => call("supervisor/heartbeat", params), "heartbeat"),
1312
+ systemHealth: /* @__PURE__ */ __name2((params) => call("system/health", params), "systemHealth")
1313
+ };
1314
+ }
1315
+ __name(createSupervisorMethods, "createSupervisorMethods");
1316
+ __name2(createSupervisorMethods, "createSupervisorMethods");
1317
+ function createSyncMethods(call) {
1318
+ return {
1319
+ status: /* @__PURE__ */ __name2((params) => call("sync/status-daemon", params), "status"),
1320
+ force: /* @__PURE__ */ __name2((params) => call("sync/force", params), "force"),
1321
+ stop: /* @__PURE__ */ __name2((params) => call("sync/stop", params), "stop"),
1322
+ start: /* @__PURE__ */ __name2((params) => call("sync/start", params), "start"),
1323
+ queue: /* @__PURE__ */ __name2((params) => call("sync/queue", params), "queue")
1324
+ };
1325
+ }
1326
+ __name(createSyncMethods, "createSyncMethods");
1327
+ __name2(createSyncMethods, "createSyncMethods");
1328
+ function createValidationMethods(call) {
1329
+ return {
1330
+ quick: /* @__PURE__ */ __name2((params) => call("validate/quick", params), "quick"),
1331
+ comprehensive: /* @__PURE__ */ __name2((params) => call("validate/comprehensive", params), "comprehensive")
1332
+ };
1333
+ }
1334
+ __name(createValidationMethods, "createValidationMethods");
1335
+ __name2(createValidationMethods, "createValidationMethods");
1336
+ function createViolationMethods(call) {
1337
+ return {
1338
+ report: /* @__PURE__ */ __name2((params) => call("violation/report", params), "report"),
1339
+ list: /* @__PURE__ */ __name2((params) => call("violation/list", params), "list")
1340
+ };
1341
+ }
1342
+ __name(createViolationMethods, "createViolationMethods");
1343
+ __name2(createViolationMethods, "createViolationMethods");
1344
+ function createWatchMethods(call) {
1345
+ return {
1346
+ subscribe: /* @__PURE__ */ __name2((params) => call("watch/subscribe", params), "subscribe"),
1347
+ unsubscribe: /* @__PURE__ */ __name2((params) => call("watch/unsubscribe", params), "unsubscribe"),
1348
+ fileChanged: /* @__PURE__ */ __name2((params) => call("watch/file-changed", params), "fileChanged")
1349
+ };
1350
+ }
1351
+ __name(createWatchMethods, "createWatchMethods");
1352
+ __name2(createWatchMethods, "createWatchMethods");
1353
+ function createWorkspaceMethods(call) {
1354
+ return {
1355
+ analyze: /* @__PURE__ */ __name2((params) => call("workspace/analyze", params), "analyze"),
1356
+ status: /* @__PURE__ */ __name2((params) => call("workspace/status", params), "status")
1357
+ };
1358
+ }
1359
+ __name(createWorkspaceMethods, "createWorkspaceMethods");
1360
+ __name2(createWorkspaceMethods, "createWorkspaceMethods");
1361
+ var VrekoLocalClient = class {
1362
+ static {
1363
+ __name(this, "VrekoLocalClient");
1364
+ }
1365
+ static {
1366
+ __name2(this, "VrekoLocalClient");
1367
+ }
1368
+ connection;
1369
+ reconnectManager;
1370
+ state = "disconnected";
1371
+ nextId = 1;
1372
+ pending = /* @__PURE__ */ new Map();
1373
+ eventHandlers = {};
1374
+ options;
1375
+ /** Stored params from the last initialize() call - replayed after auto-reconnect */
1376
+ initializeParams = null;
1377
+ // Method namespaces - original
1378
+ health;
1379
+ session;
1380
+ snapshot;
1381
+ protection;
1382
+ detection;
1383
+ // Method namespaces - new domains
1384
+ learning;
1385
+ context;
1386
+ validation;
1387
+ violation;
1388
+ sync;
1389
+ intelligence;
1390
+ momentum;
1391
+ watch;
1392
+ mcp;
1393
+ supervisor;
1394
+ daemon;
1395
+ workspace;
1396
+ constructor(options = {}) {
1397
+ this.options = {
1398
+ socketPath: options.socketPath ?? getDefaultSocketPath(),
1399
+ timeout: options.timeout ?? 3e4,
1400
+ autoReconnect: options.autoReconnect ?? true,
1401
+ maxReconnectAttempts: options.maxReconnectAttempts ?? 5,
1402
+ reconnectDelay: options.reconnectDelay ?? 1e3,
1403
+ maxReconnectDelay: options.maxReconnectDelay ?? 3e4
1404
+ };
1405
+ this.connection = new IpcConnection({
1406
+ socketPath: this.options.socketPath,
1407
+ timeout: 5e3
1408
+ });
1409
+ this.reconnectManager = new ReconnectManager({
1410
+ maxAttempts: this.options.maxReconnectAttempts,
1411
+ initialDelay: this.options.reconnectDelay,
1412
+ maxDelay: this.options.maxReconnectDelay
1413
+ });
1414
+ const callFn = this.call.bind(this);
1415
+ this.health = createHealthMethods(callFn);
1416
+ this.session = createSessionMethods(callFn);
1417
+ this.snapshot = createSnapshotMethods(callFn);
1418
+ this.protection = createProtectionMethods(callFn);
1419
+ this.detection = createDetectionMethods(callFn);
1420
+ this.learning = createLearningMethods(callFn);
1421
+ this.context = createContextMethods(callFn);
1422
+ this.validation = createValidationMethods(callFn);
1423
+ this.violation = createViolationMethods(callFn);
1424
+ this.sync = createSyncMethods(callFn);
1425
+ this.intelligence = createIntelligenceMethods(callFn);
1426
+ this.momentum = createMomentumMethods(callFn);
1427
+ this.watch = createWatchMethods(callFn);
1428
+ this.mcp = createMCPMethods(callFn);
1429
+ this.supervisor = createSupervisorMethods(callFn);
1430
+ this.daemon = createDaemonMethods(callFn);
1431
+ this.workspace = createWorkspaceMethods(callFn);
1432
+ this.setupConnectionHandlers();
1433
+ }
1434
+ /**
1435
+ * Set up IPC connection event handlers
1436
+ */
1437
+ setupConnectionHandlers() {
1438
+ this.connection.on("message", (message) => {
1439
+ if ("method" in message && !("id" in message)) {
1440
+ const notification = message;
1441
+ this.emit("notification", notification.method, notification.params);
1442
+ return;
1443
+ }
1444
+ const response = message;
1445
+ if (response.id === null) {
1446
+ this.emit("error", new Error("Received error response with null id"));
1447
+ return;
1448
+ }
1449
+ const pending = this.pending.get(response.id);
1450
+ if (!pending) {
1451
+ this.emit("error", new Error(`Received response for unknown request ID: ${response.id}`));
1452
+ return;
1453
+ }
1454
+ clearTimeout(pending.timeout);
1455
+ this.pending.delete(response.id);
1456
+ if ("error" in response) {
1457
+ const error = new JsonRpcClientError(response.error.message, response.error.code, response.error.data);
1458
+ pending.reject(error);
1459
+ return;
1460
+ }
1461
+ pending.resolve(response.result);
1462
+ });
1463
+ this.connection.on("close", (error) => {
1464
+ if (this.state !== "closed") {
1465
+ this.setState("disconnected");
1466
+ }
1467
+ this.emit("disconnected", error);
1468
+ for (const [, pending] of this.pending.entries()) {
1469
+ clearTimeout(pending.timeout);
1470
+ pending.reject(new Error("Connection closed"));
1471
+ }
1472
+ this.pending.clear();
1473
+ if (this.options.autoReconnect && this.state !== "closed" && !this.reconnectManager.isActive()) {
1474
+ this.attemptReconnect();
1475
+ }
1476
+ });
1477
+ this.connection.on("error", (error) => {
1478
+ this.emit("error", error);
1479
+ });
1480
+ }
1481
+ /**
1482
+ * Attempt to reconnect
1483
+ */
1484
+ async attemptReconnect() {
1485
+ this.setState("reconnecting");
1486
+ try {
1487
+ await this.reconnectManager.start(async () => {
1488
+ await this.connection.connect();
1489
+ if (this.initializeParams) {
1490
+ await this.initialize(this.initializeParams);
1491
+ }
1492
+ this.setState("connected");
1493
+ this.emit("connected");
1494
+ }, (attempt, maxAttempts) => {
1495
+ this.emit("reconnecting", attempt, maxAttempts);
1496
+ }, () => {
1497
+ this.emit("reconnectFailed");
1498
+ });
1499
+ } catch (error) {
1500
+ this.setState("disconnected");
1501
+ this.emit("error", error);
1502
+ }
1503
+ }
1504
+ /**
1505
+ * Connect to the local service
1506
+ */
1507
+ async connect() {
1508
+ if (this.state === "connected" || this.state === "connecting") {
1509
+ return;
1510
+ }
1511
+ this.setState("connecting");
1512
+ try {
1513
+ await this.connection.connect();
1514
+ this.setState("connected");
1515
+ this.emit("connected");
1516
+ } catch (error) {
1517
+ this.setState("disconnected");
1518
+ throw error;
1519
+ }
1520
+ }
1521
+ /**
1522
+ * Close the connection
1523
+ */
1524
+ close() {
1525
+ this.reconnectManager.stop();
1526
+ this.connection.close();
1527
+ this.setState("closed");
1528
+ for (const [, pending] of this.pending.entries()) {
1529
+ clearTimeout(pending.timeout);
1530
+ pending.reject(new Error("Client closed"));
1531
+ }
1532
+ this.pending.clear();
1533
+ }
1534
+ /**
1535
+ * Make a JSON-RPC method call
1536
+ */
1537
+ async call(method, params) {
1538
+ if (!this.connection.isConnected()) {
1539
+ throw new Error("Not connected to service");
1540
+ }
1541
+ const id = this.nextId++;
1542
+ const request = {
1543
+ jsonrpc: "2.0",
1544
+ id,
1545
+ method,
1546
+ params
1547
+ };
1548
+ return new Promise((resolve, reject) => {
1549
+ const timeout = setTimeout(() => {
1550
+ this.pending.delete(id);
1551
+ reject(new RequestTimeoutError(`Request timeout after ${this.options.timeout}ms`, id));
1552
+ }, this.options.timeout).unref();
1553
+ this.pending.set(id, {
1554
+ resolve,
1555
+ reject,
1556
+ timeout
1557
+ });
1558
+ this.connection.send(request).catch((error) => {
1559
+ clearTimeout(timeout);
1560
+ this.pending.delete(id);
1561
+ reject(error);
1562
+ });
1563
+ });
1564
+ }
1565
+ /**
1566
+ * Initialize the client connection
1567
+ *
1568
+ * Must be called before any other method calls.
1569
+ * Params are stored and automatically replayed after auto-reconnect.
1570
+ */
1571
+ async initialize(params) {
1572
+ this.initializeParams = params;
1573
+ return this.call("initialize", params);
1574
+ }
1575
+ /**
1576
+ * Get current connection state
1577
+ */
1578
+ getState() {
1579
+ return this.state;
1580
+ }
1581
+ /**
1582
+ * Check if connected
1583
+ */
1584
+ isConnected() {
1585
+ return this.state === "connected";
1586
+ }
1587
+ /**
1588
+ * Register event listener
1589
+ */
1590
+ on(event, handler) {
1591
+ this.eventHandlers[event] = handler;
1592
+ }
1593
+ /**
1594
+ * Remove event listener
1595
+ */
1596
+ off(event) {
1597
+ delete this.eventHandlers[event];
1598
+ }
1599
+ /**
1600
+ * Set connection state and emit event
1601
+ */
1602
+ setState(state) {
1603
+ if (this.state !== state) {
1604
+ this.state = state;
1605
+ this.emit("stateChange", state);
1606
+ }
1607
+ }
1608
+ /**
1609
+ * Emit event to registered handlers
1610
+ */
1611
+ emit(event, ...args) {
1612
+ const handler = this.eventHandlers[event];
1613
+ if (handler) {
1614
+ handler(...args);
1615
+ }
1616
+ }
1617
+ };
1618
+
1619
+ // src/service-adapter/local-service-adapter.ts
1620
+ function getServicePidPath() {
1621
+ return join(homedir(), ".vreko", "service.pid");
1622
+ }
1623
+ __name(getServicePidPath, "getServicePidPath");
1624
+ function getServiceSocketPath() {
1625
+ return process.env.VREKO_DAEMON_SOCKET ?? getDefaultSocketPath();
1626
+ }
1627
+ __name(getServiceSocketPath, "getServiceSocketPath");
1628
+ function getReadyMarkerPath() {
1629
+ return join(homedir(), ".vreko", ".ready");
1630
+ }
1631
+ __name(getReadyMarkerPath, "getReadyMarkerPath");
1632
+ function cleanupStaleArtifacts() {
1633
+ const pidPath = getServicePidPath();
1634
+ const socketPath = getServiceSocketPath();
1635
+ const readyPath = getReadyMarkerPath();
1636
+ const cleaned = [];
1637
+ try {
1638
+ if (existsSync(pidPath)) {
1639
+ unlinkSync(pidPath);
1640
+ cleaned.push("PID file");
1641
+ }
1642
+ } catch {
1643
+ }
1644
+ try {
1645
+ if (existsSync(socketPath)) {
1646
+ unlinkSync(socketPath);
1647
+ cleaned.push("socket");
1648
+ }
1649
+ } catch {
1650
+ }
1651
+ try {
1652
+ if (existsSync(readyPath)) {
1653
+ unlinkSync(readyPath);
1654
+ cleaned.push("ready marker");
1655
+ }
1656
+ } catch {
1657
+ }
1658
+ if (cleaned.length > 0) {
1659
+ process.stderr.write(`[vreko] Cleaned up stale daemon artifacts: ${cleaned.join(", ")}
1660
+ `);
1661
+ }
1662
+ }
1663
+ __name(cleanupStaleArtifacts, "cleanupStaleArtifacts");
1664
+ function isServiceRunning() {
1665
+ const pidPath = getServicePidPath();
1666
+ if (!existsSync(pidPath)) {
1667
+ return false;
1668
+ }
1669
+ try {
1670
+ const pid = Number.parseInt(readFileSync(pidPath, "utf-8").trim(), 10);
1671
+ if (Number.isNaN(pid)) {
1672
+ cleanupStaleArtifacts();
1673
+ return false;
1674
+ }
1675
+ process.kill(pid, 0);
1676
+ return true;
1677
+ } catch (error) {
1678
+ if (error.code === "ESRCH") {
1679
+ cleanupStaleArtifacts();
1680
+ }
1681
+ return false;
1682
+ }
1683
+ }
1684
+ __name(isServiceRunning, "isServiceRunning");
1685
+ async function isServiceHealthy() {
1686
+ const pidPath = getServicePidPath();
1687
+ if (!existsSync(pidPath)) {
1688
+ return false;
1689
+ }
1690
+ try {
1691
+ const pid = Number.parseInt(readFileSync(pidPath, "utf-8").trim(), 10);
1692
+ if (Number.isNaN(pid)) {
1693
+ cleanupStaleArtifacts();
1694
+ return false;
1695
+ }
1696
+ try {
1697
+ process.kill(pid, 0);
1698
+ } catch (error) {
1699
+ const code = error.code;
1700
+ if (code === "ESRCH") {
1701
+ cleanupStaleArtifacts();
1702
+ return false;
1703
+ }
1704
+ }
1705
+ const client = new VrekoLocalClient({
1706
+ socketPath: getServiceSocketPath(),
1707
+ timeout: 5e3,
1708
+ autoReconnect: false
1709
+ });
1710
+ try {
1711
+ await client.connect();
1712
+ await client.initialize({
1713
+ protocolVersion: "1.0.0",
1714
+ clientInfo: {
1715
+ name: "vreko-cli",
1716
+ version: "1.0.0"
1717
+ },
1718
+ capabilities: {
1719
+ notifications: false
1720
+ }
1721
+ });
1722
+ await client.health.ping();
1723
+ return true;
1724
+ } catch (error) {
1725
+ const code = error.code;
1726
+ if (code === "ECONNREFUSED" || code === "ENOENT") {
1727
+ process.stderr.write("[vreko] Daemon process exists but socket not accepting connections (likely hung)\n");
1728
+ }
1729
+ return false;
1730
+ } finally {
1731
+ client.close();
1732
+ }
1733
+ } catch {
1734
+ return false;
1735
+ }
1736
+ }
1737
+ __name(isServiceHealthy, "isServiceHealthy");
1738
+ function readServicePid() {
1739
+ const pidPath = getServicePidPath();
1740
+ try {
1741
+ const content = readFileSync(pidPath, "utf-8").trim();
1742
+ const pid = Number.parseInt(content, 10);
1743
+ return Number.isNaN(pid) ? null : pid;
1744
+ } catch {
1745
+ return null;
1746
+ }
1747
+ }
1748
+ __name(readServicePid, "readServicePid");
1749
+ function createServiceClient() {
1750
+ return new VrekoLocalClient({
1751
+ timeout: 3e4,
1752
+ autoReconnect: false
1753
+ });
1754
+ }
1755
+ __name(createServiceClient, "createServiceClient");
1756
+ async function connectServiceClient(client) {
1757
+ await client.connect();
1758
+ await client.initialize({
1759
+ protocolVersion: "1.0.0",
1760
+ clientInfo: {
1761
+ name: "vreko-cli",
1762
+ version: "1.0.0"
1763
+ },
1764
+ capabilities: {
1765
+ notifications: false
1766
+ }
1767
+ });
1768
+ }
1769
+ __name(connectServiceClient, "connectServiceClient");
1770
+ async function pruneLearningsViaDaemon(workspaceRoot, client) {
1771
+ try {
1772
+ const result = await client.learning.prune({
1773
+ workspace: workspaceRoot
1774
+ });
1775
+ return {
1776
+ success: true,
1777
+ result
1778
+ };
1779
+ } catch (error) {
1780
+ return {
1781
+ success: false,
1782
+ error: error instanceof Error ? error.message : String(error)
1783
+ };
1784
+ }
1785
+ }
1786
+ __name(pruneLearningsViaDaemon, "pruneLearningsViaDaemon");
1787
+ async function gcLearningsViaDaemon(workspaceRoot, client, options) {
1788
+ try {
1789
+ const result = await client.call("learning/gc", {
1790
+ workspace: workspaceRoot,
1791
+ operation: options?.operation ?? "all",
1792
+ dryRun: options?.dryRun ?? true
1793
+ });
1794
+ return {
1795
+ success: true,
1796
+ result
1797
+ };
1798
+ } catch (error) {
1799
+ return {
1800
+ success: false,
1801
+ error: error instanceof Error ? error.message : String(error)
1802
+ };
1803
+ }
1804
+ }
1805
+ __name(gcLearningsViaDaemon, "gcLearningsViaDaemon");
1806
+ async function listLearningsViaDaemon(workspaceRoot, client, limit) {
1807
+ try {
1808
+ const result = await client.learning.list({
1809
+ workspace: workspaceRoot,
1810
+ limit: limit ?? 50
1811
+ });
1812
+ return {
1813
+ success: true,
1814
+ result
1815
+ };
1816
+ } catch (error) {
1817
+ return {
1818
+ success: false,
1819
+ error: error instanceof Error ? error.message : String(error)
1820
+ };
1821
+ }
1822
+ }
1823
+ __name(listLearningsViaDaemon, "listLearningsViaDaemon");
1824
+ async function searchLearningsViaDaemon(workspaceRoot, client, keywords, limit) {
1825
+ try {
1826
+ const result = await client.learning.search({
1827
+ workspace: workspaceRoot,
1828
+ keywords,
1829
+ limit: limit ?? 10
1830
+ });
1831
+ return {
1832
+ success: true,
1833
+ result
1834
+ };
1835
+ } catch (error) {
1836
+ return {
1837
+ success: false,
1838
+ error: error instanceof Error ? error.message : String(error)
1839
+ };
1840
+ }
1841
+ }
1842
+ __name(searchLearningsViaDaemon, "searchLearningsViaDaemon");
1843
+ async function createSessionViaDaemon(client, params) {
1844
+ try {
1845
+ const session = await client.session.start({
1846
+ workspacePath: params?.workspacePath,
1847
+ metadata: params?.metadata
1848
+ });
1849
+ return {
1850
+ success: true,
1851
+ result: {
1852
+ id: session.id,
1853
+ name: session.name,
1854
+ workspacePath: session.workspacePath,
1855
+ metadata: session.metadata,
1856
+ createdAt: session.startedAt,
1857
+ lastActivityAt: session.lastActivityAt
1858
+ }
1859
+ };
1860
+ } catch (error) {
1861
+ return {
1862
+ success: false,
1863
+ error: error instanceof Error ? error.message : String(error)
1864
+ };
1865
+ }
1866
+ }
1867
+ __name(createSessionViaDaemon, "createSessionViaDaemon");
1868
+ async function endSessionViaDaemon(client, sessionId, workspacePath) {
1869
+ try {
1870
+ await client.call("session/end-daemon", {
1871
+ sessionId,
1872
+ workspacePath
1873
+ });
1874
+ return {
1875
+ success: true
1876
+ };
1877
+ } catch (error) {
1878
+ return {
1879
+ success: false,
1880
+ error: error instanceof Error ? error.message : String(error)
1881
+ };
1882
+ }
1883
+ }
1884
+ __name(endSessionViaDaemon, "endSessionViaDaemon");
1885
+ async function getSessionStatusViaDaemon(client, sessionId, workspacePath) {
1886
+ try {
1887
+ const result = await client.call("session/status", {
1888
+ sessionId,
1889
+ workspacePath
1890
+ });
1891
+ return {
1892
+ success: true,
1893
+ result
1894
+ };
1895
+ } catch (error) {
1896
+ return {
1897
+ success: false,
1898
+ error: error instanceof Error ? error.message : String(error)
1899
+ };
1900
+ }
1901
+ }
1902
+ __name(getSessionStatusViaDaemon, "getSessionStatusViaDaemon");
1903
+ function formatDuration(ms) {
1904
+ const seconds = Math.floor(ms / 1e3);
1905
+ const minutes = Math.floor(seconds / 60);
1906
+ const hours = Math.floor(minutes / 60);
1907
+ const days = Math.floor(hours / 24);
1908
+ if (days > 0) {
1909
+ return `${days}d ${hours % 24}h`;
1910
+ }
1911
+ if (hours > 0) {
1912
+ return `${hours}h ${minutes % 60}m`;
1913
+ }
1914
+ if (minutes > 0) {
1915
+ return `${minutes}m ${seconds % 60}s`;
1916
+ }
1917
+ return `${seconds}s`;
1918
+ }
1919
+ __name(formatDuration, "formatDuration");
1920
+ function formatBytes(bytes) {
1921
+ const units = [
1922
+ "B",
1923
+ "KB",
1924
+ "MB",
1925
+ "GB"
1926
+ ];
1927
+ let unitIndex = 0;
1928
+ let value = bytes;
1929
+ while (value >= 1024 && unitIndex < units.length - 1) {
1930
+ value /= 1024;
1931
+ unitIndex++;
1932
+ }
1933
+ return `${value.toFixed(1)}${units[unitIndex]}`;
1934
+ }
1935
+ __name(formatBytes, "formatBytes");
1936
+ function getLogPath() {
1937
+ return join(homedir(), ".vreko", "daemon", "daemon.log");
1938
+ }
1939
+ __name(getLogPath, "getLogPath");
1940
+ var DAEMON_GENERATION = 2;
1941
+ function getDaemonVersion() {
1942
+ return {
1943
+ generation: DAEMON_GENERATION,
1944
+ version: "2.0.0"
1945
+ };
1946
+ }
1947
+ __name(getDaemonVersion, "getDaemonVersion");
1948
+
1949
+ export { DAEMON_GENERATION, JsonRpcClientError, StartStatusOutput, VrekoLocalClient, WorkspaceStatusOutput, connectServiceClient, createServiceClient, createSessionViaDaemon, endSessionViaDaemon, formatBytes, formatDuration, gcLearningsViaDaemon, getDaemonVersion, getDefaultSocketPath, getLogPath, getServicePidPath, getServiceSocketPath, getSessionStatusViaDaemon, isServiceHealthy, isServiceRunning, listLearningsViaDaemon, pruneLearningsViaDaemon, readServicePid, searchLearningsViaDaemon };
1950
+ //# sourceMappingURL=chunk-GSUGROXB.js.map
1951
+ //# sourceMappingURL=chunk-GSUGROXB.js.map