@aiready/core 0.23.21 → 0.23.22

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.
@@ -0,0 +1,852 @@
1
+ // src/types/business.ts
2
+ import { z } from "zod";
3
+ var LeadSource = /* @__PURE__ */ ((LeadSource2) => {
4
+ LeadSource2["ClawMoreHero"] = "clawmore-hero";
5
+ LeadSource2["ClawMoreWaitlist"] = "clawmore-waitlist";
6
+ LeadSource2["ClawMoreBeta"] = "clawmore-beta";
7
+ LeadSource2["AiReadyPlatform"] = "aiready-platform";
8
+ return LeadSource2;
9
+ })(LeadSource || {});
10
+ var LeadSourceSchema = z.nativeEnum(LeadSource);
11
+ var LeadSchema = z.object({
12
+ id: z.string(),
13
+ email: z.string().email(),
14
+ name: z.string().min(1),
15
+ interest: z.string().default("General"),
16
+ notes: z.string().optional(),
17
+ timestamp: z.string().datetime(),
18
+ source: LeadSourceSchema,
19
+ status: z.enum(["new", "contacted", "qualified", "converted", "archived"]).default("new")
20
+ });
21
+ var LeadSubmissionSchema = LeadSchema.omit({
22
+ id: true,
23
+ timestamp: true,
24
+ status: true
25
+ });
26
+ var ManagedAccountSchema = z.object({
27
+ id: z.string(),
28
+ // Internal UUID
29
+ accountId: z.string(),
30
+ // AWS Account ID
31
+ userId: z.string(),
32
+ // Owner (caopengau@gmail.com)
33
+ stripeSubscriptionId: z.string(),
34
+ // AI Token Management
35
+ tokenStrategy: z.enum(["managed", "byok"]).default("managed"),
36
+ byokConfig: z.object({
37
+ openaiKey: z.string().optional(),
38
+ anthropicKey: z.string().optional(),
39
+ openrouterKey: z.string().optional()
40
+ }).optional(),
41
+ // Financials (in cents)
42
+ baseFeeCents: z.number().default(2900),
43
+ includedComputeCents: z.number().default(1500),
44
+ // $15.00 AWS included
45
+ includedTokenCents: z.number().default(500),
46
+ // $5.00 Managed Tokens included
47
+ // Pre-paid Balance (credits)
48
+ prepaidTokenBalanceCents: z.number().default(0),
49
+ // Users buy these in $10 packs
50
+ currentMonthlyTokenSpendCents: z.number().default(0),
51
+ // Governance
52
+ status: z.enum(["provisioning", "active", "warning", "quarantined", "suspended"]).default("provisioning"),
53
+ lastCostSyncAt: z.string().datetime().optional(),
54
+ region: z.string().default("ap-southeast-2"),
55
+ // Alerting thresholds (percentage of includedComputeCents)
56
+ alertThresholds: z.array(z.number()).default([50, 80, 100, 150])
57
+ });
58
+
59
+ // src/types/enums.ts
60
+ import { z as z2 } from "zod";
61
+ var Severity = /* @__PURE__ */ ((Severity2) => {
62
+ Severity2["Critical"] = "critical";
63
+ Severity2["Major"] = "major";
64
+ Severity2["Minor"] = "minor";
65
+ Severity2["Info"] = "info";
66
+ return Severity2;
67
+ })(Severity || {});
68
+ var SeveritySchema = z2.nativeEnum(Severity);
69
+ var ToolName = /* @__PURE__ */ ((ToolName2) => {
70
+ ToolName2["PatternDetect"] = "pattern-detect";
71
+ ToolName2["ContextAnalyzer"] = "context-analyzer";
72
+ ToolName2["NamingConsistency"] = "naming-consistency";
73
+ ToolName2["AiSignalClarity"] = "ai-signal-clarity";
74
+ ToolName2["AgentGrounding"] = "agent-grounding";
75
+ ToolName2["TestabilityIndex"] = "testability-index";
76
+ ToolName2["DocDrift"] = "doc-drift";
77
+ ToolName2["DependencyHealth"] = "dependency-health";
78
+ ToolName2["ChangeAmplification"] = "change-amplification";
79
+ ToolName2["CognitiveLoad"] = "cognitive-load";
80
+ ToolName2["PatternEntropy"] = "pattern-entropy";
81
+ ToolName2["ConceptCohesion"] = "concept-cohesion";
82
+ ToolName2["SemanticDistance"] = "semantic-distance";
83
+ return ToolName2;
84
+ })(ToolName || {});
85
+ var ToolNameSchema = z2.nativeEnum(ToolName);
86
+ var FRIENDLY_TOOL_NAMES = {
87
+ ["pattern-detect" /* PatternDetect */]: "Semantic Duplicates",
88
+ ["context-analyzer" /* ContextAnalyzer */]: "Context Fragmentation",
89
+ ["naming-consistency" /* NamingConsistency */]: "Naming Consistency",
90
+ ["ai-signal-clarity" /* AiSignalClarity */]: "AI Signal Clarity",
91
+ ["agent-grounding" /* AgentGrounding */]: "Agent Grounding",
92
+ ["testability-index" /* TestabilityIndex */]: "Testability Index",
93
+ ["doc-drift" /* DocDrift */]: "Documentation Health",
94
+ ["dependency-health" /* DependencyHealth */]: "Dependency Health",
95
+ ["change-amplification" /* ChangeAmplification */]: "Change Amplification",
96
+ ["cognitive-load" /* CognitiveLoad */]: "Cognitive Load",
97
+ ["pattern-entropy" /* PatternEntropy */]: "Pattern Entropy",
98
+ ["concept-cohesion" /* ConceptCohesion */]: "Concept Cohesion",
99
+ ["semantic-distance" /* SemanticDistance */]: "Semantic Distance"
100
+ };
101
+ var IssueType = /* @__PURE__ */ ((IssueType2) => {
102
+ IssueType2["DuplicatePattern"] = "duplicate-pattern";
103
+ IssueType2["PatternInconsistency"] = "pattern-inconsistency";
104
+ IssueType2["ContextFragmentation"] = "context-fragmentation";
105
+ IssueType2["DependencyHealth"] = "dependency-health";
106
+ IssueType2["CircularDependency"] = "circular-dependency";
107
+ IssueType2["DocDrift"] = "doc-drift";
108
+ IssueType2["NamingInconsistency"] = "naming-inconsistency";
109
+ IssueType2["NamingQuality"] = "naming-quality";
110
+ IssueType2["ArchitectureInconsistency"] = "architecture-inconsistency";
111
+ IssueType2["DeadCode"] = "dead-code";
112
+ IssueType2["MissingTypes"] = "missing-types";
113
+ IssueType2["MagicLiteral"] = "magic-literal";
114
+ IssueType2["BooleanTrap"] = "boolean-trap";
115
+ IssueType2["AiSignalClarity"] = "ai-signal-clarity";
116
+ IssueType2["LowTestability"] = "low-testability";
117
+ IssueType2["AgentNavigationFailure"] = "agent-navigation-failure";
118
+ IssueType2["AmbiguousApi"] = "ambiguous-api";
119
+ IssueType2["ChangeAmplification"] = "change-amplification";
120
+ return IssueType2;
121
+ })(IssueType || {});
122
+ var IssueTypeSchema = z2.nativeEnum(IssueType);
123
+ var AnalysisStatus = /* @__PURE__ */ ((AnalysisStatus2) => {
124
+ AnalysisStatus2["Processing"] = "processing";
125
+ AnalysisStatus2["Completed"] = "completed";
126
+ AnalysisStatus2["Failed"] = "failed";
127
+ return AnalysisStatus2;
128
+ })(AnalysisStatus || {});
129
+ var AnalysisStatusSchema = z2.nativeEnum(AnalysisStatus);
130
+ var ModelTier = /* @__PURE__ */ ((ModelTier2) => {
131
+ ModelTier2["Compact"] = "compact";
132
+ ModelTier2["Standard"] = "standard";
133
+ ModelTier2["Extended"] = "extended";
134
+ ModelTier2["Frontier"] = "frontier";
135
+ return ModelTier2;
136
+ })(ModelTier || {});
137
+ var ModelTierSchema = z2.nativeEnum(ModelTier);
138
+
139
+ // src/types/common.ts
140
+ import { z as z3 } from "zod";
141
+ var LocationSchema = z3.object({
142
+ file: z3.string(),
143
+ line: z3.number(),
144
+ column: z3.number().optional(),
145
+ endLine: z3.number().optional(),
146
+ endColumn: z3.number().optional()
147
+ });
148
+
149
+ // src/types/schemas/issue.ts
150
+ import { z as z4 } from "zod";
151
+ var IssueSchema = z4.object({
152
+ type: IssueTypeSchema,
153
+ severity: SeveritySchema,
154
+ message: z4.string(),
155
+ location: LocationSchema,
156
+ suggestion: z4.string().optional()
157
+ });
158
+
159
+ // src/types/schemas/metrics.ts
160
+ import { z as z5 } from "zod";
161
+ var MetricsSchema = z5.object({
162
+ tokenCost: z5.number().optional(),
163
+ complexityScore: z5.number().optional(),
164
+ consistencyScore: z5.number().optional(),
165
+ docFreshnessScore: z5.number().optional(),
166
+ // AI agent readiness metrics (v0.12+)
167
+ aiSignalClarityScore: z5.number().optional(),
168
+ agentGroundingScore: z5.number().optional(),
169
+ testabilityScore: z5.number().optional(),
170
+ docDriftScore: z5.number().optional(),
171
+ dependencyHealthScore: z5.number().optional(),
172
+ modelContextTier: ModelTierSchema.optional(),
173
+ // Business value metrics
174
+ estimatedMonthlyCost: z5.number().optional(),
175
+ estimatedDeveloperHours: z5.number().optional(),
176
+ comprehensionDifficultyIndex: z5.number().optional(),
177
+ // Extended metrics for specific spokes
178
+ totalSymbols: z5.number().optional(),
179
+ totalExports: z5.number().optional()
180
+ });
181
+
182
+ // src/types/schemas/report.ts
183
+ import { z as z6 } from "zod";
184
+ var AnalysisResultSchema = z6.object({
185
+ fileName: z6.string(),
186
+ issues: z6.array(IssueSchema),
187
+ metrics: MetricsSchema
188
+ });
189
+ var SpokeSummarySchema = z6.object({
190
+ totalFiles: z6.number().optional(),
191
+ totalIssues: z6.number().optional(),
192
+ criticalIssues: z6.number().optional(),
193
+ majorIssues: z6.number().optional(),
194
+ score: z6.number().optional()
195
+ }).catchall(z6.any());
196
+ var SpokeOutputSchema = z6.object({
197
+ results: z6.array(AnalysisResultSchema),
198
+ summary: SpokeSummarySchema,
199
+ metadata: z6.object({
200
+ toolName: z6.string(),
201
+ version: z6.string().optional(),
202
+ timestamp: z6.string().optional(),
203
+ config: z6.any().optional()
204
+ }).catchall(z6.any()).optional()
205
+ });
206
+ var UnifiedReportSchema = z6.object({
207
+ summary: z6.object({
208
+ totalFiles: z6.number(),
209
+ totalIssues: z6.number(),
210
+ criticalIssues: z6.number(),
211
+ majorIssues: z6.number(),
212
+ businessImpact: z6.object({
213
+ estimatedMonthlyWaste: z6.number().optional(),
214
+ potentialSavings: z6.number().optional(),
215
+ productivityHours: z6.number().optional()
216
+ }).optional()
217
+ }),
218
+ results: z6.array(AnalysisResultSchema),
219
+ scoring: z6.object({
220
+ overall: z6.number(),
221
+ rating: z6.string(),
222
+ timestamp: z6.string(),
223
+ breakdown: z6.array(
224
+ z6.object({
225
+ toolName: z6.union([ToolNameSchema, z6.string()]),
226
+ score: z6.number()
227
+ }).catchall(z6.any())
228
+ )
229
+ }).optional()
230
+ }).catchall(z6.any());
231
+
232
+ // src/types/schemas/config.ts
233
+ import { z as z7 } from "zod";
234
+ var AIReadyConfigSchema = z7.object({
235
+ /** Target score threshold (0-100) */
236
+ threshold: z7.number().optional(),
237
+ /** Files or directories to include in scan */
238
+ include: z7.array(z7.string()).optional(),
239
+ /** Files or directories to exclude from scan */
240
+ exclude: z7.array(z7.string()).optional(),
241
+ /** Scan-specific configuration */
242
+ scan: z7.object({
243
+ include: z7.array(z7.string()).optional(),
244
+ exclude: z7.array(z7.string()).optional(),
245
+ parallel: z7.boolean().optional(),
246
+ deep: z7.boolean().optional(),
247
+ tools: z7.array(z7.string()).optional()
248
+ }).optional(),
249
+ /** Output-specific configuration */
250
+ output: z7.object({
251
+ /** Output format (json, console, html) */
252
+ format: z7.enum(["json", "console", "html"]).optional(),
253
+ /** Output file path */
254
+ path: z7.string().optional(),
255
+ /** Output directory */
256
+ saveTo: z7.string().optional(),
257
+ /** Whether to show score breakdown in console */
258
+ showBreakdown: z7.boolean().optional(),
259
+ /** Baseline report to compare against */
260
+ compareBaseline: z7.string().optional()
261
+ }).optional(),
262
+ /** Tool-specific configuration overrides (Strictly ToolName -> Config) */
263
+ tools: z7.record(z7.string(), z7.any()).optional(),
264
+ /** Scoring profile and weights */
265
+ scoring: z7.object({
266
+ /** Name of the scoring profile (e.g. "strict", "balanced") */
267
+ profile: z7.string().optional(),
268
+ /** Custom weights for tools and metrics */
269
+ weights: z7.record(z7.string(), z7.number()).optional()
270
+ }).optional(),
271
+ /** Visualizer settings (interactive graph) */
272
+ visualizer: z7.object({
273
+ groupingDirs: z7.array(z7.string()).optional(),
274
+ graph: z7.object({
275
+ maxNodes: z7.number().optional(),
276
+ maxEdges: z7.number().optional()
277
+ }).optional()
278
+ }).optional()
279
+ }).catchall(z7.any());
280
+
281
+ // src/types.ts
282
+ var GLOBAL_INFRA_OPTIONS = [
283
+ "rootDir",
284
+ "include",
285
+ "exclude",
286
+ "tools",
287
+ "scoring"
288
+ ];
289
+ var GLOBAL_SCAN_OPTIONS = [
290
+ "rootDir",
291
+ "include",
292
+ "exclude",
293
+ "config",
294
+ "threshold",
295
+ "output",
296
+ "format",
297
+ "parallel",
298
+ "showBreakdown"
299
+ ];
300
+ var COMMON_FINE_TUNING_OPTIONS = [
301
+ "maxDepth",
302
+ "minSimilarity",
303
+ "threshold",
304
+ "showBreakdown"
305
+ ];
306
+
307
+ // src/utils/visualization.ts
308
+ function generateHTML(graph) {
309
+ const payload = JSON.stringify(graph, null, 2);
310
+ return `<!doctype html>
311
+ <html>
312
+ <head>
313
+ <meta charset="utf-8" />
314
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
315
+ <title>AIReady Visualization</title>
316
+ <style>
317
+ html,body { height: 100%; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0 }
318
+ #container { display:flex; height:100vh }
319
+ #panel { width: 320px; padding: 16px; background: #071130; box-shadow: -2px 0 8px rgba(0,0,0,0.3); overflow:auto }
320
+ #canvasWrap { flex:1; display:flex; align-items:center; justify-content:center }
321
+ canvas { background: #0b1220; border-radius:8px }
322
+ .stat { margin-bottom:12px }
323
+ </style>
324
+ </head>
325
+ <body>
326
+ <div id="container">
327
+ <div id="canvasWrap"><canvas id="canvas" width="1200" height="800"></canvas></div>
328
+ <div id="panel">
329
+ <h2>AIReady Visualization</h2>
330
+ <div class="stat"><strong>Files:</strong> <span id="stat-files"></span></div>
331
+ <div class="stat"><strong>Dependencies:</strong> <span id="stat-deps"></span></div>
332
+ <div class="stat"><strong>Legend</strong></div>
333
+ <div style="font-size:13px;line-height:1.3;color:#cbd5e1;margin-top:8px">
334
+ <div style="margin-bottom:8px"><span style="display:inline-block;width:12px;height:12px;background:#ff4d4f;margin-right:8px;border:1px solid rgba(255,255,255,0.06)"></span><strong>Critical</strong>: highest severity issues.</div>
335
+ <div style="margin-bottom:8px"><span style="display:inline-block;width:12px;height:12px;background:#ff9900;margin-right:8px;border:1px solid rgba(255,255,255,0.06)"></span><strong>Major</strong>: important issues.</div>
336
+ <div style="margin-bottom:8px"><span style="display:inline-block;width:12px;height:12px;background:#ffd666;margin-right:8px;border:1px solid rgba(255,255,255,0.06)"></span><strong>Minor</strong>: low priority issues.</div>
337
+ <div style="margin-bottom:8px"><span style="display:inline-block;width:12px;height:12px;background:#91d5ff;margin-right:8px;border:1px solid rgba(255,255,255,0.06)"></span><strong>Info</strong>: informational notes.</div>
338
+ <div style="margin-top:10px;color:#94a3b8"><strong>Node size</strong>: larger = higher token cost, more issues or dependency weight.</div>
339
+ <div style="margin-top:6px;color:#94a3b8"><strong>Proximity</strong>: nodes that are spatially close are more contextually related; relatedness is represented by distance and size rather than explicit edges.</div>
340
+ <div style="margin-top:6px;color:#94a3b8"><strong>Edge colors</strong>: <span style="color:#fb7e81">Similarity</span>, <span style="color:#84c1ff">Dependency</span>, <span style="color:#ffa500">Reference</span>, default <span style="color:#334155">Other</span>.</div>
341
+ </div>
342
+ </div>
343
+ </div>
344
+
345
+ <script>
346
+ const graphData = ${payload};
347
+ document.getElementById('stat-files').textContent = graphData.metadata.totalFiles;
348
+ document.getElementById('stat-deps').textContent = graphData.metadata.totalDependencies;
349
+
350
+ const canvas = document.getElementById('canvas');
351
+ const ctx = canvas.getContext('2d');
352
+
353
+ const nodes = graphData.nodes.map((n, i) => ({
354
+ ...n,
355
+ x: canvas.width / 2 + Math.cos(i / graphData.nodes.length * Math.PI * 2) * (Math.min(canvas.width, canvas.height) / 3),
356
+ y: canvas.height / 2 + Math.sin(i / graphData.nodes.length * Math.PI * 2) * (Math.min(canvas.width, canvas.height) / 3),
357
+ }));
358
+
359
+ function draw() {
360
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
361
+
362
+ graphData.edges.forEach(edge => {
363
+ const s = nodes.find(n => n.id === edge.source);
364
+ const t = nodes.find(n => n.id === edge.target);
365
+ if (!s || !t) return;
366
+ if (edge.type === 'related') return;
367
+ if (edge.type === 'similarity') {
368
+ ctx.strokeStyle = '#fb7e81';
369
+ ctx.lineWidth = 1.2;
370
+ } else if (edge.type === 'dependency') {
371
+ ctx.strokeStyle = '#84c1ff';
372
+ ctx.lineWidth = 1.0;
373
+ } else if (edge.type === 'reference') {
374
+ ctx.strokeStyle = '#ffa500';
375
+ ctx.lineWidth = 0.9;
376
+ } else {
377
+ ctx.strokeStyle = '#334155';
378
+ ctx.lineWidth = 0.8;
379
+ }
380
+ ctx.beginPath();
381
+ ctx.moveTo(s.x, s.y);
382
+ ctx.lineTo(t.x, t.y);
383
+ ctx.stroke();
384
+ });
385
+
386
+ const groups = {};
387
+ nodes.forEach(n => {
388
+ const g = n.group || '__default';
389
+ if (!groups[g]) groups[g] = { minX: n.x, minY: n.y, maxX: n.x, maxY: n.y };
390
+ groups[g].minX = Math.min(groups[g].minX, n.x);
391
+ groups[g].minY = Math.min(groups[g].minY, n.y);
392
+ groups[g].maxX = Math.max(groups[g].maxX, n.x);
393
+ groups[g].maxY = Math.max(groups[g].maxY, n.y);
394
+ });
395
+
396
+ const groupRelations = {};
397
+ graphData.edges.forEach(edge => {
398
+ const sNode = nodes.find(n => n.id === edge.source);
399
+ const tNode = nodes.find(n => n.id === edge.target);
400
+ if (!sNode || !tNode) return;
401
+ const g1 = sNode.group || '__default';
402
+ const g2 = tNode.group || '__default';
403
+ if (g1 === g2) return;
404
+ const key = g1 < g2 ? g1 + '::' + g2 : g2 + '::' + g1;
405
+ groupRelations[key] = (groupRelations[key] || 0) + 1;
406
+ });
407
+
408
+ Object.keys(groupRelations).forEach(k => {
409
+ const count = groupRelations[k];
410
+ const [ga, gb] = k.split('::');
411
+ if (!groups[ga] || !groups[gb]) return;
412
+ const ax = (groups[ga].minX + groups[ga].maxX) / 2;
413
+ const ay = (groups[ga].minY + groups[ga].maxY) / 2;
414
+ const bx = (groups[gb].minX + groups[gb].maxX) / 2;
415
+ const by = (groups[gb].minY + groups[gb].maxY) / 2;
416
+ ctx.beginPath();
417
+ ctx.strokeStyle = 'rgba(148,163,184,0.25)';
418
+ ctx.lineWidth = Math.min(6, 0.6 + Math.sqrt(count));
419
+ ctx.moveTo(ax, ay);
420
+ ctx.lineTo(bx, by);
421
+ ctx.stroke();
422
+ });
423
+
424
+ Object.keys(groups).forEach(g => {
425
+ if (g === '__default') return;
426
+ const box = groups[g];
427
+ const pad = 16;
428
+ const x = box.minX - pad;
429
+ const y = box.minY - pad;
430
+ const w = (box.maxX - box.minX) + pad * 2;
431
+ const h = (box.maxY - box.minY) + pad * 2;
432
+ ctx.save();
433
+ ctx.fillStyle = 'rgba(30,64,175,0.04)';
434
+ ctx.strokeStyle = 'rgba(30,64,175,0.12)';
435
+ ctx.lineWidth = 1.2;
436
+ const r = 8;
437
+ ctx.beginPath();
438
+ ctx.moveTo(x + r, y);
439
+ ctx.arcTo(x + w, y, x + w, y + h, r);
440
+ ctx.arcTo(x + w, y + h, x, y + h, r);
441
+ ctx.arcTo(x, y + h, x, y, r);
442
+ ctx.arcTo(x, y, x + w, y, r);
443
+ ctx.closePath();
444
+ ctx.fill();
445
+ ctx.stroke();
446
+ ctx.restore();
447
+ ctx.fillStyle = '#94a3b8';
448
+ ctx.font = '11px sans-serif';
449
+ ctx.fillText(g, x + 8, y + 14);
450
+ });
451
+
452
+ nodes.forEach(n => {
453
+ const sizeVal = (n.size || n.value || 1);
454
+ const r = 6 + (sizeVal / 2);
455
+ ctx.beginPath();
456
+ ctx.fillStyle = n.color || '#60a5fa';
457
+ ctx.arc(n.x, n.y, r, 0, Math.PI * 2);
458
+ ctx.fill();
459
+
460
+ ctx.fillStyle = '#e2e8f0';
461
+ ctx.font = '11px sans-serif';
462
+ ctx.textAlign = 'center';
463
+ ctx.fillText(n.label || n.id.split('/').slice(-1)[0], n.x, n.y + r + 12);
464
+ });
465
+ }
466
+
467
+ draw();
468
+ </script>
469
+ </body>
470
+ </html>`;
471
+ }
472
+
473
+ // src/utils/rating-helpers.ts
474
+ var ReadinessRating = /* @__PURE__ */ ((ReadinessRating2) => {
475
+ ReadinessRating2["Excellent"] = "Excellent";
476
+ ReadinessRating2["Good"] = "Good";
477
+ ReadinessRating2["Fair"] = "Fair";
478
+ ReadinessRating2["NeedsWork"] = "Needs Work";
479
+ ReadinessRating2["Critical"] = "Critical";
480
+ return ReadinessRating2;
481
+ })(ReadinessRating || {});
482
+ function getRatingMetadata(score) {
483
+ if (score >= 90) {
484
+ return {
485
+ label: "Excellent",
486
+ slug: "excellent",
487
+ emoji: "\u2705",
488
+ rating: "Excellent" /* Excellent */
489
+ };
490
+ }
491
+ if (score >= 75) {
492
+ return {
493
+ label: "Good",
494
+ slug: "good",
495
+ emoji: "\u{1F44D}",
496
+ rating: "Good" /* Good */
497
+ };
498
+ }
499
+ if (score >= 60) {
500
+ return {
501
+ label: "Fair",
502
+ slug: "fair",
503
+ emoji: "\u{1F44C}",
504
+ rating: "Fair" /* Fair */
505
+ };
506
+ }
507
+ if (score >= 40) {
508
+ return {
509
+ label: "Needs Work",
510
+ slug: "needs-work",
511
+ emoji: "\u{1F528}",
512
+ rating: "Needs Work" /* NeedsWork */
513
+ };
514
+ }
515
+ return {
516
+ label: "Critical",
517
+ slug: "critical",
518
+ emoji: "\u{1F6A8}",
519
+ rating: "Critical" /* Critical */
520
+ };
521
+ }
522
+ function getRatingLabel(score) {
523
+ return getRatingMetadata(score).label;
524
+ }
525
+ function getRatingSlug(score) {
526
+ return getRatingMetadata(score).slug;
527
+ }
528
+ function getRatingEmoji(score) {
529
+ return getRatingMetadata(score).emoji;
530
+ }
531
+ function getToolEmoji(score) {
532
+ return getRatingEmoji(score);
533
+ }
534
+ function getPriorityIcon(priority) {
535
+ switch (priority) {
536
+ case "critical":
537
+ return "\u{1F534}";
538
+ case "high":
539
+ return "\u{1F7E0}";
540
+ case "medium":
541
+ return "\u{1F7E1}";
542
+ case "low":
543
+ return "\u{1F535}";
544
+ default:
545
+ return "\u26AA";
546
+ }
547
+ }
548
+ function getRating(score) {
549
+ return getRatingMetadata(score).rating;
550
+ }
551
+
552
+ // src/scoring-types.ts
553
+ var RecommendationPriority = /* @__PURE__ */ ((RecommendationPriority2) => {
554
+ RecommendationPriority2["High"] = "high";
555
+ RecommendationPriority2["Medium"] = "medium";
556
+ RecommendationPriority2["Low"] = "low";
557
+ return RecommendationPriority2;
558
+ })(RecommendationPriority || {});
559
+
560
+ // src/scoring.ts
561
+ var DEFAULT_TOOL_WEIGHTS = {
562
+ ["pattern-detect" /* PatternDetect */]: 22,
563
+ ["context-analyzer" /* ContextAnalyzer */]: 19,
564
+ ["naming-consistency" /* NamingConsistency */]: 14,
565
+ ["ai-signal-clarity" /* AiSignalClarity */]: 11,
566
+ ["agent-grounding" /* AgentGrounding */]: 10,
567
+ ["testability-index" /* TestabilityIndex */]: 10,
568
+ ["doc-drift" /* DocDrift */]: 8,
569
+ ["dependency-health" /* DependencyHealth */]: 6,
570
+ ["change-amplification" /* ChangeAmplification */]: 8
571
+ };
572
+ var TOOL_NAME_MAP = {
573
+ patterns: "pattern-detect" /* PatternDetect */,
574
+ "pattern-detect": "pattern-detect" /* PatternDetect */,
575
+ context: "context-analyzer" /* ContextAnalyzer */,
576
+ "context-analyzer": "context-analyzer" /* ContextAnalyzer */,
577
+ consistency: "naming-consistency" /* NamingConsistency */,
578
+ "naming-consistency": "naming-consistency" /* NamingConsistency */,
579
+ "ai-signal": "ai-signal-clarity" /* AiSignalClarity */,
580
+ "ai-signal-clarity": "ai-signal-clarity" /* AiSignalClarity */,
581
+ grounding: "agent-grounding" /* AgentGrounding */,
582
+ "agent-grounding": "agent-grounding" /* AgentGrounding */,
583
+ testability: "testability-index" /* TestabilityIndex */,
584
+ "testability-index": "testability-index" /* TestabilityIndex */,
585
+ "doc-drift": "doc-drift" /* DocDrift */,
586
+ "deps-health": "dependency-health" /* DependencyHealth */,
587
+ "dependency-health": "dependency-health" /* DependencyHealth */,
588
+ "change-amp": "change-amplification" /* ChangeAmplification */,
589
+ "change-amplification": "change-amplification" /* ChangeAmplification */
590
+ };
591
+ var ScoringProfile = /* @__PURE__ */ ((ScoringProfile2) => {
592
+ ScoringProfile2["Default"] = "default";
593
+ ScoringProfile2["Agentic"] = "agentic";
594
+ ScoringProfile2["Logic"] = "logic";
595
+ ScoringProfile2["UI"] = "ui";
596
+ ScoringProfile2["Cost"] = "cost";
597
+ ScoringProfile2["Security"] = "security";
598
+ return ScoringProfile2;
599
+ })(ScoringProfile || {});
600
+ var SCORING_PROFILES = {
601
+ ["default" /* Default */]: DEFAULT_TOOL_WEIGHTS,
602
+ ["agentic" /* Agentic */]: {
603
+ ["ai-signal-clarity" /* AiSignalClarity */]: 30,
604
+ ["agent-grounding" /* AgentGrounding */]: 30,
605
+ ["testability-index" /* TestabilityIndex */]: 20,
606
+ ["context-analyzer" /* ContextAnalyzer */]: 10,
607
+ ["naming-consistency" /* NamingConsistency */]: 10
608
+ },
609
+ ["logic" /* Logic */]: {
610
+ ["testability-index" /* TestabilityIndex */]: 40,
611
+ ["naming-consistency" /* NamingConsistency */]: 20,
612
+ ["context-analyzer" /* ContextAnalyzer */]: 20,
613
+ ["pattern-detect" /* PatternDetect */]: 10,
614
+ ["change-amplification" /* ChangeAmplification */]: 10
615
+ },
616
+ ["ui" /* UI */]: {
617
+ ["naming-consistency" /* NamingConsistency */]: 30,
618
+ ["context-analyzer" /* ContextAnalyzer */]: 30,
619
+ ["pattern-detect" /* PatternDetect */]: 20,
620
+ ["doc-drift" /* DocDrift */]: 10,
621
+ ["ai-signal-clarity" /* AiSignalClarity */]: 10
622
+ },
623
+ ["cost" /* Cost */]: {
624
+ ["pattern-detect" /* PatternDetect */]: 50,
625
+ ["context-analyzer" /* ContextAnalyzer */]: 30,
626
+ ["change-amplification" /* ChangeAmplification */]: 10,
627
+ ["dependency-health" /* DependencyHealth */]: 10
628
+ },
629
+ ["security" /* Security */]: {
630
+ ["naming-consistency" /* NamingConsistency */]: 40,
631
+ ["testability-index" /* TestabilityIndex */]: 30,
632
+ ["dependency-health" /* DependencyHealth */]: 20,
633
+ ["context-analyzer" /* ContextAnalyzer */]: 10
634
+ }
635
+ };
636
+ var CONTEXT_TIER_THRESHOLDS = {
637
+ compact: { idealTokens: 3e3, criticalTokens: 1e4, idealDepth: 4 },
638
+ standard: { idealTokens: 5e3, criticalTokens: 15e3, idealDepth: 5 },
639
+ extended: { idealTokens: 15e3, criticalTokens: 5e4, idealDepth: 7 },
640
+ frontier: { idealTokens: 5e4, criticalTokens: 15e4, idealDepth: 10 }
641
+ };
642
+ var SIZE_ADJUSTED_THRESHOLDS = {
643
+ xs: 80,
644
+ // < 50 files
645
+ small: 75,
646
+ // 50-200 files
647
+ medium: 70,
648
+ // 200-500 files
649
+ large: 65,
650
+ // 500-2000 files
651
+ enterprise: 58
652
+ // 2000+ files
653
+ };
654
+ function getProjectSizeTier(fileCount) {
655
+ if (fileCount < 50) return "xs";
656
+ if (fileCount < 200) return "small";
657
+ if (fileCount < 500) return "medium";
658
+ if (fileCount < 2e3) return "large";
659
+ return "enterprise";
660
+ }
661
+ function getRecommendedThreshold(fileCount, modelTier = "standard") {
662
+ const sizeTier = getProjectSizeTier(fileCount);
663
+ const base = SIZE_ADJUSTED_THRESHOLDS[sizeTier];
664
+ const modelBonus = modelTier === "frontier" ? -3 : modelTier === "extended" ? -2 : 0;
665
+ return base + modelBonus;
666
+ }
667
+ function normalizeToolName(shortName) {
668
+ return TOOL_NAME_MAP[shortName.toLowerCase()] ?? shortName;
669
+ }
670
+ function getToolWeight(toolName, toolConfig, cliOverride, profile = "default" /* Default */) {
671
+ if (cliOverride !== void 0) return cliOverride;
672
+ if (toolConfig?.scoreWeight !== void 0) return toolConfig.scoreWeight;
673
+ const profileWeights = SCORING_PROFILES[profile] ?? DEFAULT_TOOL_WEIGHTS;
674
+ return profileWeights[toolName] ?? DEFAULT_TOOL_WEIGHTS[toolName] ?? 5;
675
+ }
676
+ function parseWeightString(weightStr) {
677
+ const weights = /* @__PURE__ */ new Map();
678
+ if (!weightStr) return weights;
679
+ const pairs = weightStr.split(",");
680
+ for (const pair of pairs) {
681
+ const [toolShortName, weightValueStr] = pair.split(":");
682
+ if (toolShortName && weightValueStr) {
683
+ const toolName = normalizeToolName(toolShortName.trim());
684
+ const weight = parseInt(weightValueStr.trim(), 10);
685
+ if (!isNaN(weight) && weight > 0) {
686
+ weights.set(toolName, weight);
687
+ }
688
+ }
689
+ }
690
+ return weights;
691
+ }
692
+ function calculateOverallScore(toolOutputs, config, cliWeights) {
693
+ if (toolOutputs.size === 0) {
694
+ throw new Error("No tool outputs provided for scoring");
695
+ }
696
+ const profile = config?.scoring?.profile || "default" /* Default */;
697
+ const weights = /* @__PURE__ */ new Map();
698
+ for (const [toolName] of toolOutputs.entries()) {
699
+ const cliWeight = cliWeights?.get(toolName);
700
+ const configWeight = config?.tools?.[toolName]?.scoreWeight;
701
+ const weight = cliWeight ?? configWeight ?? getToolWeight(toolName, void 0, void 0, profile);
702
+ weights.set(toolName, weight);
703
+ }
704
+ let weightedSum = 0;
705
+ let totalWeight = 0;
706
+ const breakdown = [];
707
+ const toolsUsed = [];
708
+ const calculationWeights = {};
709
+ for (const [toolName, output] of toolOutputs.entries()) {
710
+ const weight = weights.get(toolName) ?? 5;
711
+ weightedSum += output.score * weight;
712
+ totalWeight += weight;
713
+ toolsUsed.push(toolName);
714
+ calculationWeights[toolName] = weight;
715
+ breakdown.push(output);
716
+ }
717
+ const overall = Math.round(weightedSum / totalWeight);
718
+ const rating = getRating(overall);
719
+ const formulaParts = Array.from(toolOutputs.entries()).map(
720
+ ([name, output]) => {
721
+ const weight = weights.get(name) ?? 5;
722
+ return `(${output.score} \xD7 ${weight})`;
723
+ }
724
+ );
725
+ const formulaStr = `[${formulaParts.join(" + ")}] / ${totalWeight} = ${overall}`;
726
+ return {
727
+ overall,
728
+ rating,
729
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
730
+ toolsUsed,
731
+ breakdown,
732
+ calculation: {
733
+ formula: formulaStr,
734
+ weights: calculationWeights,
735
+ normalized: formulaStr
736
+ }
737
+ };
738
+ }
739
+ function getRatingWithContext(score, fileCount, modelTier = "standard") {
740
+ const threshold = getRecommendedThreshold(fileCount, modelTier);
741
+ const normalized = score - threshold + 70;
742
+ return getRating(normalized);
743
+ }
744
+ function getRatingDisplay(rating) {
745
+ switch (rating) {
746
+ case "Excellent" /* Excellent */:
747
+ return { emoji: "\u2705", color: "green" };
748
+ case "Good" /* Good */:
749
+ return { emoji: "\u{1F44D}", color: "blue" };
750
+ case "Fair" /* Fair */:
751
+ return { emoji: "\u26A0\uFE0F", color: "yellow" };
752
+ case "Needs Work" /* NeedsWork */:
753
+ return { emoji: "\u{1F528}", color: "orange" };
754
+ case "Critical" /* Critical */:
755
+ return { emoji: "\u274C", color: "red" };
756
+ default:
757
+ return { emoji: "\u2753", color: "gray" };
758
+ }
759
+ }
760
+ function formatScore(result) {
761
+ const { emoji } = getRatingDisplay(result.rating);
762
+ return `${result.overall}/100 (${result.rating}) ${emoji}`;
763
+ }
764
+ function formatToolScore(output) {
765
+ let result = ` Score: ${output.score}/100
766
+
767
+ `;
768
+ if (output.factors && output.factors.length > 0) {
769
+ result += ` Factors:
770
+ `;
771
+ output.factors.forEach((factor) => {
772
+ const impactSign = factor.impact > 0 ? "+" : "";
773
+ result += ` \u2022 ${factor.name}: ${impactSign}${factor.impact} - ${factor.description}
774
+ `;
775
+ });
776
+ result += "\n";
777
+ }
778
+ if (output.recommendations && output.recommendations.length > 0) {
779
+ result += ` Recommendations:
780
+ `;
781
+ output.recommendations.forEach((rec, i) => {
782
+ let priorityIcon = "\u{1F535}";
783
+ const prio = rec.priority;
784
+ if (prio === "high" /* High */ || prio === "high")
785
+ priorityIcon = "\u{1F534}";
786
+ else if (prio === "medium" /* Medium */ || prio === "medium")
787
+ priorityIcon = "\u{1F7E1}";
788
+ result += ` ${i + 1}. ${priorityIcon} ${rec.action}
789
+ `;
790
+ result += ` Impact: +${rec.estimatedImpact} points
791
+
792
+ `;
793
+ });
794
+ }
795
+ return result;
796
+ }
797
+
798
+ export {
799
+ LeadSource,
800
+ LeadSourceSchema,
801
+ LeadSchema,
802
+ LeadSubmissionSchema,
803
+ ManagedAccountSchema,
804
+ Severity,
805
+ SeveritySchema,
806
+ ToolName,
807
+ ToolNameSchema,
808
+ FRIENDLY_TOOL_NAMES,
809
+ IssueType,
810
+ IssueTypeSchema,
811
+ AnalysisStatus,
812
+ AnalysisStatusSchema,
813
+ ModelTier,
814
+ ModelTierSchema,
815
+ LocationSchema,
816
+ IssueSchema,
817
+ MetricsSchema,
818
+ AnalysisResultSchema,
819
+ SpokeSummarySchema,
820
+ SpokeOutputSchema,
821
+ UnifiedReportSchema,
822
+ AIReadyConfigSchema,
823
+ GLOBAL_INFRA_OPTIONS,
824
+ GLOBAL_SCAN_OPTIONS,
825
+ COMMON_FINE_TUNING_OPTIONS,
826
+ generateHTML,
827
+ ReadinessRating,
828
+ getRatingMetadata,
829
+ getRatingLabel,
830
+ getRatingSlug,
831
+ getRatingEmoji,
832
+ getToolEmoji,
833
+ getPriorityIcon,
834
+ getRating,
835
+ RecommendationPriority,
836
+ DEFAULT_TOOL_WEIGHTS,
837
+ TOOL_NAME_MAP,
838
+ ScoringProfile,
839
+ SCORING_PROFILES,
840
+ CONTEXT_TIER_THRESHOLDS,
841
+ SIZE_ADJUSTED_THRESHOLDS,
842
+ getProjectSizeTier,
843
+ getRecommendedThreshold,
844
+ normalizeToolName,
845
+ getToolWeight,
846
+ parseWeightString,
847
+ calculateOverallScore,
848
+ getRatingWithContext,
849
+ getRatingDisplay,
850
+ formatScore,
851
+ formatToolScore
852
+ };