hyntx 2.5.4 → 2.6.0
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.
- package/README.md +1 -1
- package/dist/cli.d.ts +105 -2
- package/dist/cli.js +1296 -173
- package/package.json +6 -1
package/dist/cli.js
CHANGED
|
@@ -5,12 +5,16 @@ import { rm, readFile, mkdir, writeFile, rename } from 'fs/promises';
|
|
|
5
5
|
import { join, dirname, extname, resolve, basename } from 'path';
|
|
6
6
|
import { fileURLToPath } from 'url';
|
|
7
7
|
import { parseArgs } from 'util';
|
|
8
|
-
import
|
|
8
|
+
import chalk8 from 'chalk';
|
|
9
9
|
import { isAfter, parseISO, subDays, format, subMonths, startOfDay, differenceInDays, isSameDay, isBefore } from 'date-fns';
|
|
10
10
|
import ora from 'ora';
|
|
11
11
|
import { createHash } from 'crypto';
|
|
12
12
|
import * as os from 'os';
|
|
13
13
|
import { homedir } from 'os';
|
|
14
|
+
import { similarity, distance } from 'ml-distance';
|
|
15
|
+
import { kmeans } from 'ml-kmeans';
|
|
16
|
+
import { linearRegression, linearRegressionLine, rSquared, mean, median, min, max, sampleStandardDeviation, sampleVariance, sampleSkewness, sampleKurtosis, quantile } from 'simple-statistics';
|
|
17
|
+
import asciichart from 'asciichart';
|
|
14
18
|
import { glob } from 'glob';
|
|
15
19
|
import prompts2 from 'prompts';
|
|
16
20
|
import boxen from 'boxen';
|
|
@@ -796,8 +800,8 @@ function flattenAll(arrays) {
|
|
|
796
800
|
}
|
|
797
801
|
return result;
|
|
798
802
|
}
|
|
799
|
-
function limitExamples(examples,
|
|
800
|
-
return examples.slice(0,
|
|
803
|
+
function limitExamples(examples, max2) {
|
|
804
|
+
return examples.slice(0, max2);
|
|
801
805
|
}
|
|
802
806
|
function inferProviderType(providerName) {
|
|
803
807
|
const nameLower = providerName.toLowerCase();
|
|
@@ -814,16 +818,16 @@ function extractModelFromProvider(providerName) {
|
|
|
814
818
|
}
|
|
815
819
|
function maxSeverity(severities) {
|
|
816
820
|
if (severities.length === 0) return "low";
|
|
817
|
-
let
|
|
821
|
+
let max2 = "low";
|
|
818
822
|
let maxRank = SEVERITY_RANK.low;
|
|
819
823
|
for (const severity of severities) {
|
|
820
824
|
const rank = SEVERITY_RANK[severity];
|
|
821
825
|
if (rank > maxRank) {
|
|
822
|
-
|
|
826
|
+
max2 = severity;
|
|
823
827
|
maxRank = rank;
|
|
824
828
|
}
|
|
825
829
|
}
|
|
826
|
-
return
|
|
830
|
+
return max2;
|
|
827
831
|
}
|
|
828
832
|
async function analyzeWithFallback(provider, prompts3, date, context, model, noCache) {
|
|
829
833
|
if (prompts3.length === 0) {
|
|
@@ -1196,6 +1200,1026 @@ async function analyzePrompts(options) {
|
|
|
1196
1200
|
);
|
|
1197
1201
|
return mergeWithCachedResults(results, cachedResults, date, rules);
|
|
1198
1202
|
}
|
|
1203
|
+
var DEFAULT_OPTIONS = {
|
|
1204
|
+
k: 0,
|
|
1205
|
+
// 0 means auto-detect
|
|
1206
|
+
maxK: 8,
|
|
1207
|
+
distanceMetric: "cosine",
|
|
1208
|
+
maxIterations: 100,
|
|
1209
|
+
initialization: "kmeans++"
|
|
1210
|
+
};
|
|
1211
|
+
function clusterPrompts(embeddings, options) {
|
|
1212
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
1213
|
+
if (embeddings.length < 2) {
|
|
1214
|
+
return {
|
|
1215
|
+
clusters: [],
|
|
1216
|
+
centroids: [],
|
|
1217
|
+
k: 0,
|
|
1218
|
+
silhouetteScore: 0,
|
|
1219
|
+
inertia: 0
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
const k = opts.k && opts.k > 0 ? opts.k : findOptimalK(embeddings, opts.maxK);
|
|
1223
|
+
if (k === 0 || k > embeddings.length) {
|
|
1224
|
+
return {
|
|
1225
|
+
clusters: [],
|
|
1226
|
+
centroids: [],
|
|
1227
|
+
k: 0,
|
|
1228
|
+
silhouetteScore: 0,
|
|
1229
|
+
inertia: 0
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
const data = embeddings.map((e) => [...e]);
|
|
1233
|
+
const result = kmeans(data, k, {
|
|
1234
|
+
initialization: opts.initialization,
|
|
1235
|
+
maxIterations: opts.maxIterations,
|
|
1236
|
+
distanceFunction: opts.distanceMetric === "cosine" ? cosineDistance : euclideanDistance
|
|
1237
|
+
});
|
|
1238
|
+
const clusters = buildClusters(result.clusters);
|
|
1239
|
+
const silhouetteScore = computeSilhouetteScore(
|
|
1240
|
+
embeddings,
|
|
1241
|
+
clusters,
|
|
1242
|
+
opts.distanceMetric
|
|
1243
|
+
);
|
|
1244
|
+
const inertia = computeInertia(
|
|
1245
|
+
embeddings,
|
|
1246
|
+
result.centroids,
|
|
1247
|
+
result.clusters,
|
|
1248
|
+
opts.distanceMetric
|
|
1249
|
+
);
|
|
1250
|
+
return {
|
|
1251
|
+
clusters,
|
|
1252
|
+
centroids: result.centroids,
|
|
1253
|
+
k,
|
|
1254
|
+
silhouetteScore,
|
|
1255
|
+
inertia
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
function findOptimalK(embeddings, maxK) {
|
|
1259
|
+
if (embeddings.length < 2) {
|
|
1260
|
+
return 0;
|
|
1261
|
+
}
|
|
1262
|
+
const actualMaxK = Math.min(maxK, Math.floor(embeddings.length / 2));
|
|
1263
|
+
if (actualMaxK < 2) {
|
|
1264
|
+
return Math.min(2, embeddings.length);
|
|
1265
|
+
}
|
|
1266
|
+
const inertias = [];
|
|
1267
|
+
const data = embeddings.map((e) => [...e]);
|
|
1268
|
+
for (let k = 2; k <= actualMaxK; k++) {
|
|
1269
|
+
try {
|
|
1270
|
+
const result = kmeans(data, k, {
|
|
1271
|
+
initialization: "kmeans++",
|
|
1272
|
+
maxIterations: 50,
|
|
1273
|
+
// Fewer iterations for speed
|
|
1274
|
+
distanceFunction: cosineDistance
|
|
1275
|
+
});
|
|
1276
|
+
const inertia = computeInertia(
|
|
1277
|
+
embeddings,
|
|
1278
|
+
result.centroids,
|
|
1279
|
+
result.clusters,
|
|
1280
|
+
"cosine"
|
|
1281
|
+
);
|
|
1282
|
+
inertias.push(inertia);
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1285
|
+
logger.debug(`K-means failed for k=${String(k)}: ${message}`);
|
|
1286
|
+
break;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
if (inertias.length < 2) {
|
|
1290
|
+
return 2;
|
|
1291
|
+
}
|
|
1292
|
+
const deltas = inertias.slice(1).map((v, i) => {
|
|
1293
|
+
const prevInertia = inertias[i];
|
|
1294
|
+
return prevInertia !== void 0 ? prevInertia - v : 0;
|
|
1295
|
+
});
|
|
1296
|
+
if (deltas.length < 2) {
|
|
1297
|
+
return 2;
|
|
1298
|
+
}
|
|
1299
|
+
const secondDeltas = deltas.slice(1).map((v, i) => {
|
|
1300
|
+
const prevDelta = deltas[i];
|
|
1301
|
+
return prevDelta !== void 0 ? prevDelta - v : 0;
|
|
1302
|
+
});
|
|
1303
|
+
if (secondDeltas.length === 0) {
|
|
1304
|
+
return 2;
|
|
1305
|
+
}
|
|
1306
|
+
const elbowIndex = secondDeltas.indexOf(Math.max(...secondDeltas));
|
|
1307
|
+
return elbowIndex + 3;
|
|
1308
|
+
}
|
|
1309
|
+
function labelClusters(clusters, prompts3) {
|
|
1310
|
+
return clusters.map((cluster) => {
|
|
1311
|
+
const clusterPrompts2 = cluster.indices.map((i) => prompts3[i]).filter((p) => p !== void 0);
|
|
1312
|
+
if (clusterPrompts2.length === 0) {
|
|
1313
|
+
return {
|
|
1314
|
+
...cluster,
|
|
1315
|
+
label: `Cluster ${String(cluster.id)}`,
|
|
1316
|
+
keywords: [],
|
|
1317
|
+
representativePrompt: ""
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
const keywords = extractKeywords(clusterPrompts2);
|
|
1321
|
+
const label = inferClusterLabel(keywords);
|
|
1322
|
+
const representativePrompt = clusterPrompts2.length > 0 ? clusterPrompts2.reduce(
|
|
1323
|
+
(shortest, current) => current.length < shortest.length ? current : shortest
|
|
1324
|
+
) : "";
|
|
1325
|
+
return {
|
|
1326
|
+
...cluster,
|
|
1327
|
+
label,
|
|
1328
|
+
keywords,
|
|
1329
|
+
representativePrompt
|
|
1330
|
+
};
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
function createClusterAnalysis(result, prompts3) {
|
|
1334
|
+
const labeledClusters = labelClusters(result.clusters, prompts3);
|
|
1335
|
+
const clusterSizes = labeledClusters.map((c) => c.size);
|
|
1336
|
+
const avgClusterSize = clusterSizes.length > 0 ? clusterSizes.reduce((a, b) => a + b, 0) / clusterSizes.length : 0;
|
|
1337
|
+
const largestCluster = clusterSizes.length > 0 ? Math.max(...clusterSizes) : 0;
|
|
1338
|
+
const smallestCluster = clusterSizes.length > 0 ? Math.min(...clusterSizes) : 0;
|
|
1339
|
+
return {
|
|
1340
|
+
clusters: labeledClusters,
|
|
1341
|
+
metrics: {
|
|
1342
|
+
silhouetteScore: result.silhouetteScore,
|
|
1343
|
+
inertia: result.inertia,
|
|
1344
|
+
optimalK: result.k
|
|
1345
|
+
},
|
|
1346
|
+
summary: {
|
|
1347
|
+
totalPrompts: prompts3.length,
|
|
1348
|
+
avgClusterSize: Math.round(avgClusterSize * 10) / 10,
|
|
1349
|
+
largestCluster,
|
|
1350
|
+
smallestCluster
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
function buildClusters(assignments) {
|
|
1355
|
+
const clusterMap = /* @__PURE__ */ new Map();
|
|
1356
|
+
assignments.forEach((clusterId, index) => {
|
|
1357
|
+
if (!clusterMap.has(clusterId)) {
|
|
1358
|
+
clusterMap.set(clusterId, []);
|
|
1359
|
+
}
|
|
1360
|
+
const cluster = clusterMap.get(clusterId);
|
|
1361
|
+
if (cluster) {
|
|
1362
|
+
cluster.push(index);
|
|
1363
|
+
}
|
|
1364
|
+
});
|
|
1365
|
+
return Array.from(clusterMap.entries()).map(([id, indices]) => ({
|
|
1366
|
+
id,
|
|
1367
|
+
indices,
|
|
1368
|
+
size: indices.length
|
|
1369
|
+
}));
|
|
1370
|
+
}
|
|
1371
|
+
function computeSilhouetteScore(embeddings, clusters, distanceMetric) {
|
|
1372
|
+
if (clusters.length < 2 || embeddings.length < 2) {
|
|
1373
|
+
return 0;
|
|
1374
|
+
}
|
|
1375
|
+
const distFunc = distanceMetric === "cosine" ? cosineDistance : euclideanDistance;
|
|
1376
|
+
let totalScore = 0;
|
|
1377
|
+
let count = 0;
|
|
1378
|
+
for (const cluster of clusters) {
|
|
1379
|
+
for (const i of cluster.indices) {
|
|
1380
|
+
const point = embeddings[i];
|
|
1381
|
+
if (!point) continue;
|
|
1382
|
+
const sameCluster = cluster.indices.filter((j) => j !== i);
|
|
1383
|
+
const a = sameCluster.length > 0 ? sameCluster.reduce((sum2, j) => {
|
|
1384
|
+
const otherPoint = embeddings[j];
|
|
1385
|
+
return otherPoint ? sum2 + distFunc(point, otherPoint) : sum2;
|
|
1386
|
+
}, 0) / sameCluster.length : 0;
|
|
1387
|
+
let minAvgDist = Infinity;
|
|
1388
|
+
for (const otherCluster of clusters) {
|
|
1389
|
+
if (otherCluster.id === cluster.id) continue;
|
|
1390
|
+
const avgDist = otherCluster.indices.reduce((sum2, j) => {
|
|
1391
|
+
const otherPoint = embeddings[j];
|
|
1392
|
+
return otherPoint ? sum2 + distFunc(point, otherPoint) : sum2;
|
|
1393
|
+
}, 0) / otherCluster.size;
|
|
1394
|
+
minAvgDist = Math.min(minAvgDist, avgDist);
|
|
1395
|
+
}
|
|
1396
|
+
const b = minAvgDist;
|
|
1397
|
+
const s = (b - a) / Math.max(a, b);
|
|
1398
|
+
totalScore += s;
|
|
1399
|
+
count++;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
return count > 0 ? totalScore / count : 0;
|
|
1403
|
+
}
|
|
1404
|
+
function computeInertia(embeddings, centroids, assignments, distanceMetric) {
|
|
1405
|
+
const distFunc = distanceMetric === "cosine" ? cosineDistance : euclideanDistance;
|
|
1406
|
+
let inertia = 0;
|
|
1407
|
+
for (let i = 0; i < embeddings.length; i++) {
|
|
1408
|
+
const clusterId = assignments[i];
|
|
1409
|
+
const embedding = embeddings[i];
|
|
1410
|
+
if (clusterId === void 0 || embedding === void 0) continue;
|
|
1411
|
+
const centroid = centroids[clusterId];
|
|
1412
|
+
if (!centroid) continue;
|
|
1413
|
+
const dist = distFunc(embedding, centroid);
|
|
1414
|
+
inertia += dist * dist;
|
|
1415
|
+
}
|
|
1416
|
+
return inertia;
|
|
1417
|
+
}
|
|
1418
|
+
function extractKeywords(prompts3) {
|
|
1419
|
+
const wordFreq = /* @__PURE__ */ new Map();
|
|
1420
|
+
for (const prompt of prompts3) {
|
|
1421
|
+
const words = prompt.toLowerCase().match(/\b[a-z]{3,}\b/gi) ?? [];
|
|
1422
|
+
for (const word of words) {
|
|
1423
|
+
wordFreq.set(word, (wordFreq.get(word) ?? 0) + 1);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
const commonWords = /* @__PURE__ */ new Set([
|
|
1427
|
+
"the",
|
|
1428
|
+
"and",
|
|
1429
|
+
"for",
|
|
1430
|
+
"with",
|
|
1431
|
+
"from",
|
|
1432
|
+
"this",
|
|
1433
|
+
"that",
|
|
1434
|
+
"have",
|
|
1435
|
+
"has",
|
|
1436
|
+
"are",
|
|
1437
|
+
"was"
|
|
1438
|
+
]);
|
|
1439
|
+
const keywords = Array.from(wordFreq.entries()).filter(([word]) => !commonWords.has(word)).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([word]) => word);
|
|
1440
|
+
return keywords;
|
|
1441
|
+
}
|
|
1442
|
+
function inferClusterLabel(keywords) {
|
|
1443
|
+
if (keywords.length === 0) {
|
|
1444
|
+
return "Mixed Prompts";
|
|
1445
|
+
}
|
|
1446
|
+
const keywordSet = new Set(keywords.map((k) => k.toLowerCase()));
|
|
1447
|
+
if (keywordSet.has("fix") || keywordSet.has("debug") || keywordSet.has("error") || keywordSet.has("bug")) {
|
|
1448
|
+
return "Debug & Fix Issues";
|
|
1449
|
+
}
|
|
1450
|
+
if (keywordSet.has("add") || keywordSet.has("create") || keywordSet.has("implement") || keywordSet.has("build")) {
|
|
1451
|
+
return "Feature Implementation";
|
|
1452
|
+
}
|
|
1453
|
+
if (keywordSet.has("refactor") || keywordSet.has("improve") || keywordSet.has("optimize") || keywordSet.has("clean")) {
|
|
1454
|
+
return "Refactoring";
|
|
1455
|
+
}
|
|
1456
|
+
if (keywordSet.has("test") || keywordSet.has("testing") || keywordSet.has("spec")) {
|
|
1457
|
+
return "Testing";
|
|
1458
|
+
}
|
|
1459
|
+
if (keywordSet.has("update") || keywordSet.has("modify") || keywordSet.has("change")) {
|
|
1460
|
+
return "Updates & Modifications";
|
|
1461
|
+
}
|
|
1462
|
+
const firstKeyword = keywords[0];
|
|
1463
|
+
if (!firstKeyword) return "Mixed Prompts";
|
|
1464
|
+
const firstChar = firstKeyword[0];
|
|
1465
|
+
if (!firstChar) return "Mixed Prompts";
|
|
1466
|
+
return firstChar.toUpperCase() + firstKeyword.slice(1) + " Tasks";
|
|
1467
|
+
}
|
|
1468
|
+
function cosineDistance(a, b) {
|
|
1469
|
+
const sim = similarity.cosine(a, b);
|
|
1470
|
+
return 1 - sim;
|
|
1471
|
+
}
|
|
1472
|
+
function euclideanDistance(a, b) {
|
|
1473
|
+
return distance.euclidean(a, b);
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// src/analytics/embeddings.ts
|
|
1477
|
+
var DEFAULT_CONFIG = {
|
|
1478
|
+
host: "http://localhost:11434",
|
|
1479
|
+
model: "nomic-embed-text",
|
|
1480
|
+
batchSize: 10,
|
|
1481
|
+
timeoutMs: 3e4
|
|
1482
|
+
};
|
|
1483
|
+
var OllamaEmbeddingClient = class {
|
|
1484
|
+
config;
|
|
1485
|
+
constructor(config) {
|
|
1486
|
+
this.config = {
|
|
1487
|
+
...DEFAULT_CONFIG,
|
|
1488
|
+
...config
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Check if Ollama is available and the embedding model is loaded.
|
|
1493
|
+
*
|
|
1494
|
+
* @returns True if Ollama is available, false otherwise
|
|
1495
|
+
*/
|
|
1496
|
+
async isAvailable() {
|
|
1497
|
+
try {
|
|
1498
|
+
const controller = new AbortController();
|
|
1499
|
+
const timeout = setTimeout(() => {
|
|
1500
|
+
controller.abort();
|
|
1501
|
+
}, 5e3);
|
|
1502
|
+
const response = await fetch(`${this.config.host}/api/tags`, {
|
|
1503
|
+
signal: controller.signal
|
|
1504
|
+
});
|
|
1505
|
+
clearTimeout(timeout);
|
|
1506
|
+
if (!response.ok) {
|
|
1507
|
+
return false;
|
|
1508
|
+
}
|
|
1509
|
+
const data = await response.json();
|
|
1510
|
+
const modelName = this.config.model;
|
|
1511
|
+
const hasModel = data.models?.some((m) => m.name === modelName) ?? false;
|
|
1512
|
+
if (!hasModel) {
|
|
1513
|
+
const modelNames = data.models?.map((m) => m.name) ?? [];
|
|
1514
|
+
logger.debug(
|
|
1515
|
+
`Embedding model '${modelName}' not found in Ollama. Available models: ${modelNames.join(", ")}`
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
return hasModel;
|
|
1519
|
+
} catch {
|
|
1520
|
+
return false;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Generate embedding for a single text.
|
|
1525
|
+
*
|
|
1526
|
+
* @param text - Text to generate embedding for
|
|
1527
|
+
* @returns Embedding vector (768-dimensional for nomic-embed-text)
|
|
1528
|
+
* @throws Error if Ollama is not available or request fails
|
|
1529
|
+
*/
|
|
1530
|
+
async generateEmbedding(text) {
|
|
1531
|
+
const controller = new AbortController();
|
|
1532
|
+
const timeout = setTimeout(() => {
|
|
1533
|
+
controller.abort();
|
|
1534
|
+
}, this.config.timeoutMs);
|
|
1535
|
+
try {
|
|
1536
|
+
const response = await fetch(`${this.config.host}/api/embeddings`, {
|
|
1537
|
+
method: "POST",
|
|
1538
|
+
headers: { "Content-Type": "application/json" },
|
|
1539
|
+
body: JSON.stringify({
|
|
1540
|
+
model: this.config.model,
|
|
1541
|
+
prompt: text
|
|
1542
|
+
}),
|
|
1543
|
+
signal: controller.signal
|
|
1544
|
+
});
|
|
1545
|
+
clearTimeout(timeout);
|
|
1546
|
+
if (!response.ok) {
|
|
1547
|
+
throw new Error(
|
|
1548
|
+
`Ollama embeddings request failed: ${response.statusText}`
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
const data = await response.json();
|
|
1552
|
+
return data.embedding;
|
|
1553
|
+
} catch (error) {
|
|
1554
|
+
clearTimeout(timeout);
|
|
1555
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
1556
|
+
throw new Error(
|
|
1557
|
+
`Ollama embeddings request timed out after ${String(this.config.timeoutMs)}ms`
|
|
1558
|
+
);
|
|
1559
|
+
}
|
|
1560
|
+
throw error;
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Generate embeddings for multiple texts in batches.
|
|
1565
|
+
*
|
|
1566
|
+
* Processes texts in batches to avoid overwhelming Ollama.
|
|
1567
|
+
* Failed embeddings are logged but don't stop the batch.
|
|
1568
|
+
*
|
|
1569
|
+
* @param texts - Array of texts to generate embeddings for
|
|
1570
|
+
* @param batchSize - Optional batch size override
|
|
1571
|
+
* @returns Array of embeddings (same length as input, null for failed items)
|
|
1572
|
+
*
|
|
1573
|
+
* @example
|
|
1574
|
+
* ```typescript
|
|
1575
|
+
* const texts = ["prompt 1", "prompt 2", "prompt 3"];
|
|
1576
|
+
* const embeddings = await client.generateBatchEmbeddings(texts);
|
|
1577
|
+
* console.log(embeddings.length); // 3
|
|
1578
|
+
* ```
|
|
1579
|
+
*/
|
|
1580
|
+
async generateBatchEmbeddings(texts, batchSize) {
|
|
1581
|
+
const actualBatchSize = batchSize ?? this.config.batchSize;
|
|
1582
|
+
const results = [];
|
|
1583
|
+
for (let i = 0; i < texts.length; i += actualBatchSize) {
|
|
1584
|
+
const batch = texts.slice(i, i + actualBatchSize);
|
|
1585
|
+
const batchResults = await Promise.allSettled(
|
|
1586
|
+
batch.map((text) => this.generateEmbedding(text))
|
|
1587
|
+
);
|
|
1588
|
+
for (const result of batchResults) {
|
|
1589
|
+
if (result.status === "fulfilled") {
|
|
1590
|
+
results.push(result.value);
|
|
1591
|
+
} else {
|
|
1592
|
+
const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason);
|
|
1593
|
+
logger.debug(`Failed to generate embedding: ${errorMessage}`);
|
|
1594
|
+
results.push(null);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
if (i + actualBatchSize < texts.length) {
|
|
1598
|
+
await new Promise((resolve2) => setTimeout(resolve2, 100));
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
return results;
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Get the current configuration.
|
|
1605
|
+
*/
|
|
1606
|
+
getConfig() {
|
|
1607
|
+
return { ...this.config };
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1610
|
+
function createEmbeddingClient(config) {
|
|
1611
|
+
return new OllamaEmbeddingClient(config);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
// src/analytics/metrics.ts
|
|
1615
|
+
var SPECIFICITY_PATTERNS = {
|
|
1616
|
+
// File paths with common extensions
|
|
1617
|
+
filePath: /\b[\w/-]+\.(ts|js|tsx|jsx|py|go|java|rb|php|json|yaml|yml|xml|md|sql|sh|bash|css|scss|sass|html|vue|svelte|rs)\b/gi,
|
|
1618
|
+
// Function references and method calls
|
|
1619
|
+
functionRef: /\b(function|def|class|const|let|var|fn|func|method|async|export)\s+\w+|\.\w+\(|\w+\(/g,
|
|
1620
|
+
// Error messages and exceptions
|
|
1621
|
+
errorMessage: /\b(error|exception|failed|crash|undefined|null|NaN|TypeError|ReferenceError|SyntaxError|warning|fatal|panic)\b/gi,
|
|
1622
|
+
// Code snippets (backticks and code blocks)
|
|
1623
|
+
codeSnippet: /```[\s\S]*?```|`[^`]+`/g,
|
|
1624
|
+
// Action verbs indicating specific tasks
|
|
1625
|
+
actionVerbs: /\b(fix|implement|add|remove|update|refactor|debug|optimize|create|delete|modify|change|improve|enhance|replace|migrate|test|validate|deploy|build|compile|install)\b/gi,
|
|
1626
|
+
// Technical terms indicating domain knowledge
|
|
1627
|
+
technicalTerms: /\b(API|REST|GraphQL|SQL|database|schema|endpoint|middleware|component|service|controller|model|view|route|auth|authentication|authorization|JWT|token|session|cache|Redis|Docker|Kubernetes|CI\/CD|deployment|production|testing|unit test|integration|async|promise|callback|closure|immutable|state|props|hook|lifecycle)\b/gi
|
|
1628
|
+
};
|
|
1629
|
+
function computePromptSpecificity(prompt) {
|
|
1630
|
+
const filePaths = prompt.match(SPECIFICITY_PATTERNS.filePath) ?? [];
|
|
1631
|
+
const functionRefs = prompt.match(SPECIFICITY_PATTERNS.functionRef) ?? [];
|
|
1632
|
+
const errorMessages = prompt.match(SPECIFICITY_PATTERNS.errorMessage) ?? [];
|
|
1633
|
+
const codeSnippets = prompt.match(SPECIFICITY_PATTERNS.codeSnippet) ?? [];
|
|
1634
|
+
const actionVerbs = prompt.match(SPECIFICITY_PATTERNS.actionVerbs) ?? [];
|
|
1635
|
+
const filePathCount = filePaths.length;
|
|
1636
|
+
const functionMentions = functionRefs.length;
|
|
1637
|
+
const hasErrorMessage = errorMessages.length > 0;
|
|
1638
|
+
const hasCodeSnippet = codeSnippets.length > 0;
|
|
1639
|
+
const wordCount = prompt.trim().split(/\s+/).length;
|
|
1640
|
+
const characterCount = prompt.length;
|
|
1641
|
+
const actionVerbClarity = wordCount > 0 ? actionVerbs.length / wordCount * 100 : 0;
|
|
1642
|
+
const overall = calculateOverallSpecificity({
|
|
1643
|
+
filePathCount,
|
|
1644
|
+
functionMentions,
|
|
1645
|
+
hasErrorMessage,
|
|
1646
|
+
hasCodeSnippet,
|
|
1647
|
+
actionVerbClarity});
|
|
1648
|
+
return {
|
|
1649
|
+
overall,
|
|
1650
|
+
filePathCount,
|
|
1651
|
+
functionMentions,
|
|
1652
|
+
hasErrorMessage,
|
|
1653
|
+
hasCodeSnippet,
|
|
1654
|
+
actionVerbClarity: Math.min(100, Math.round(actionVerbClarity * 10) / 10),
|
|
1655
|
+
wordCount,
|
|
1656
|
+
characterCount
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
function computeLexicalComplexity(text) {
|
|
1660
|
+
const words = text.toLowerCase().match(/\b[a-z]+\b/gi) ?? [];
|
|
1661
|
+
const uniqueWords = new Set(words);
|
|
1662
|
+
const sentences = text.split(/[.!?]+/).filter((s) => s.trim().length > 0);
|
|
1663
|
+
const technicalTerms = text.match(SPECIFICITY_PATTERNS.technicalTerms) ?? [];
|
|
1664
|
+
const uniqueWordRatio = words.length > 0 ? uniqueWords.size / words.length : 0;
|
|
1665
|
+
const totalLength = words.reduce((sum2, word) => sum2 + word.length, 0);
|
|
1666
|
+
const averageWordLength = words.length > 0 ? totalLength / words.length : 0;
|
|
1667
|
+
const technicalTermDensity = words.length > 0 ? technicalTerms.length / words.length * 100 : 0;
|
|
1668
|
+
const sentenceCount = sentences.length;
|
|
1669
|
+
const averageSentenceLength = sentenceCount > 0 ? words.length / sentenceCount : 0;
|
|
1670
|
+
return {
|
|
1671
|
+
uniqueWordRatio: Math.round(uniqueWordRatio * 1e3) / 1e3,
|
|
1672
|
+
averageWordLength: Math.round(averageWordLength * 10) / 10,
|
|
1673
|
+
technicalTermDensity: Math.round(technicalTermDensity * 10) / 10,
|
|
1674
|
+
sentenceCount,
|
|
1675
|
+
averageSentenceLength: Math.round(averageSentenceLength * 10) / 10
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1678
|
+
function calculateOverallSpecificity(params) {
|
|
1679
|
+
let score = 0;
|
|
1680
|
+
score += Math.min(30, params.filePathCount * 15);
|
|
1681
|
+
score += Math.min(20, params.functionMentions * 10);
|
|
1682
|
+
if (params.hasErrorMessage) {
|
|
1683
|
+
score += 15;
|
|
1684
|
+
}
|
|
1685
|
+
if (params.hasCodeSnippet) {
|
|
1686
|
+
score += 15;
|
|
1687
|
+
}
|
|
1688
|
+
score += Math.min(20, params.actionVerbClarity / 10 * 20);
|
|
1689
|
+
return Math.min(100, Math.round(score));
|
|
1690
|
+
}
|
|
1691
|
+
function computeDescriptiveStats(values) {
|
|
1692
|
+
if (values.length === 0) {
|
|
1693
|
+
return {
|
|
1694
|
+
count: 0,
|
|
1695
|
+
mean: 0,
|
|
1696
|
+
median: 0,
|
|
1697
|
+
stdDev: 0,
|
|
1698
|
+
variance: 0,
|
|
1699
|
+
min: 0,
|
|
1700
|
+
max: 0,
|
|
1701
|
+
range: 0,
|
|
1702
|
+
percentiles: {
|
|
1703
|
+
p25: 0,
|
|
1704
|
+
p50: 0,
|
|
1705
|
+
p75: 0,
|
|
1706
|
+
p90: 0,
|
|
1707
|
+
p95: 0
|
|
1708
|
+
},
|
|
1709
|
+
skewness: 0,
|
|
1710
|
+
kurtosis: 0
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
const data = [...values];
|
|
1714
|
+
const meanVal = mean(data);
|
|
1715
|
+
const medianVal = median(data);
|
|
1716
|
+
const minVal = min(data);
|
|
1717
|
+
const maxVal = max(data);
|
|
1718
|
+
const stdDevVal = data.length > 1 ? sampleStandardDeviation(data) : 0;
|
|
1719
|
+
const varianceVal = data.length > 1 ? sampleVariance(data) : 0;
|
|
1720
|
+
const skewnessVal = data.length > 2 ? sampleSkewness(data) : 0;
|
|
1721
|
+
const kurtosisVal = data.length > 3 ? sampleKurtosis(data) : 0;
|
|
1722
|
+
return {
|
|
1723
|
+
count: data.length,
|
|
1724
|
+
mean: meanVal,
|
|
1725
|
+
median: medianVal,
|
|
1726
|
+
stdDev: stdDevVal,
|
|
1727
|
+
variance: varianceVal,
|
|
1728
|
+
min: minVal,
|
|
1729
|
+
max: maxVal,
|
|
1730
|
+
range: maxVal - minVal,
|
|
1731
|
+
percentiles: {
|
|
1732
|
+
p25: quantile(data, 0.25),
|
|
1733
|
+
p50: medianVal,
|
|
1734
|
+
p75: quantile(data, 0.75),
|
|
1735
|
+
p90: quantile(data, 0.9),
|
|
1736
|
+
p95: quantile(data, 0.95)
|
|
1737
|
+
},
|
|
1738
|
+
skewness: skewnessVal,
|
|
1739
|
+
kurtosis: kurtosisVal
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
function analyzeTrend(entries) {
|
|
1743
|
+
if (entries.length < 2) {
|
|
1744
|
+
return {
|
|
1745
|
+
slope: 0,
|
|
1746
|
+
intercept: 0,
|
|
1747
|
+
rSquared: 0,
|
|
1748
|
+
direction: "stable",
|
|
1749
|
+
confidence: "low",
|
|
1750
|
+
projectedScore: () => 0
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
const firstEntry = entries[0];
|
|
1754
|
+
if (!firstEntry) {
|
|
1755
|
+
return {
|
|
1756
|
+
slope: 0,
|
|
1757
|
+
intercept: 0,
|
|
1758
|
+
rSquared: 0,
|
|
1759
|
+
direction: "stable",
|
|
1760
|
+
confidence: "low",
|
|
1761
|
+
projectedScore: () => 0
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
const baseDate = new Date(firstEntry.date);
|
|
1765
|
+
const points = entries.map((e) => {
|
|
1766
|
+
const days = daysBetween(baseDate, new Date(e.date));
|
|
1767
|
+
return [days, e.score];
|
|
1768
|
+
});
|
|
1769
|
+
const regression = linearRegression(points);
|
|
1770
|
+
const line = linearRegressionLine(regression);
|
|
1771
|
+
const r2 = rSquared(points, line);
|
|
1772
|
+
const slope = regression.m;
|
|
1773
|
+
const direction = slope > 0.1 ? "improving" : slope < -0.1 ? "declining" : "stable";
|
|
1774
|
+
const confidence = r2 > 0.7 ? "high" : r2 > 0.4 ? "medium" : "low";
|
|
1775
|
+
return {
|
|
1776
|
+
slope,
|
|
1777
|
+
intercept: regression.b,
|
|
1778
|
+
rSquared: r2,
|
|
1779
|
+
direction,
|
|
1780
|
+
confidence,
|
|
1781
|
+
projectedScore: (days) => {
|
|
1782
|
+
const lastPoint = points[points.length - 1];
|
|
1783
|
+
const lastDays = lastPoint ? lastPoint[0] : 0;
|
|
1784
|
+
return line(lastDays + days);
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
1787
|
+
}
|
|
1788
|
+
function daysBetween(from, to) {
|
|
1789
|
+
const msPerDay = 24 * 60 * 60 * 1e3;
|
|
1790
|
+
const diff = to.getTime() - from.getTime();
|
|
1791
|
+
return Math.round(diff / msPerDay);
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// src/core/enhanced-analyzer.ts
|
|
1795
|
+
async function enrichWithStatistics(result, prompts3, options = {}) {
|
|
1796
|
+
const { enableDetailedStats = true, enableClustering = false } = options;
|
|
1797
|
+
if (!enableDetailedStats && !enableClustering) {
|
|
1798
|
+
return { ...result };
|
|
1799
|
+
}
|
|
1800
|
+
const startTime = Date.now();
|
|
1801
|
+
let enhancedStats;
|
|
1802
|
+
if (enableDetailedStats && prompts3.length > 0) {
|
|
1803
|
+
enhancedStats = computeEnhancedStats(result, prompts3, startTime);
|
|
1804
|
+
}
|
|
1805
|
+
let clusters;
|
|
1806
|
+
if (enableClustering && prompts3.length >= 3) {
|
|
1807
|
+
try {
|
|
1808
|
+
clusters = await computeClustering(prompts3, options.embeddingConfig);
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1811
|
+
logger.warn(`Clustering failed: ${message}`);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return {
|
|
1815
|
+
...result,
|
|
1816
|
+
enhancedStats,
|
|
1817
|
+
clusters
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
function enrichWithTrends(result, historyEntries) {
|
|
1821
|
+
if (historyEntries.length < 2) {
|
|
1822
|
+
return result;
|
|
1823
|
+
}
|
|
1824
|
+
try {
|
|
1825
|
+
const trendData = historyEntries.map((entry) => ({
|
|
1826
|
+
date: entry.result.date,
|
|
1827
|
+
score: entry.result.stats.overallScore,
|
|
1828
|
+
promptCount: entry.result.stats.totalPrompts,
|
|
1829
|
+
issueCount: entry.result.stats.promptsWithIssues
|
|
1830
|
+
}));
|
|
1831
|
+
const trend = analyzeTrend(trendData);
|
|
1832
|
+
return {
|
|
1833
|
+
...result,
|
|
1834
|
+
trend
|
|
1835
|
+
};
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1838
|
+
logger.warn(`Trend analysis failed: ${message}`);
|
|
1839
|
+
return result;
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
function computeEnhancedStats(result, prompts3, startTime) {
|
|
1843
|
+
const scores = [];
|
|
1844
|
+
for (const pattern of result.patterns) {
|
|
1845
|
+
const affectedCount = Math.round(
|
|
1846
|
+
pattern.frequency / 100 * result.stats.totalPrompts
|
|
1847
|
+
);
|
|
1848
|
+
const severityPenalty = pattern.severity === "high" ? 3 : pattern.severity === "medium" ? 2 : 1;
|
|
1849
|
+
for (let i = 0; i < affectedCount; i++) {
|
|
1850
|
+
const score = Math.max(0, 10 - severityPenalty - Math.random() * 2);
|
|
1851
|
+
scores.push(score);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
const remaining = result.stats.totalPrompts - scores.length;
|
|
1855
|
+
for (let i = 0; i < remaining; i++) {
|
|
1856
|
+
const score = Math.min(10, 7 + Math.random() * 3);
|
|
1857
|
+
scores.push(score);
|
|
1858
|
+
}
|
|
1859
|
+
const descriptive = scores.length > 0 ? computeDescriptiveStats(scores) : {
|
|
1860
|
+
count: 0,
|
|
1861
|
+
mean: 0,
|
|
1862
|
+
median: 0,
|
|
1863
|
+
stdDev: 0,
|
|
1864
|
+
variance: 0,
|
|
1865
|
+
min: 0,
|
|
1866
|
+
max: 0,
|
|
1867
|
+
range: 0,
|
|
1868
|
+
percentiles: { p25: 0, p50: 0, p75: 0, p90: 0, p95: 0 },
|
|
1869
|
+
skewness: 0,
|
|
1870
|
+
kurtosis: 0
|
|
1871
|
+
};
|
|
1872
|
+
const sampleSize = Math.min(20, prompts3.length);
|
|
1873
|
+
const samplePrompts = prompts3.slice(0, sampleSize);
|
|
1874
|
+
const specificityScores = [];
|
|
1875
|
+
const lexicalMetrics = [];
|
|
1876
|
+
for (const prompt of samplePrompts) {
|
|
1877
|
+
const specificity = computePromptSpecificity(prompt);
|
|
1878
|
+
const lexical = computeLexicalComplexity(prompt);
|
|
1879
|
+
specificityScores.push(specificity.overall);
|
|
1880
|
+
lexicalMetrics.push(lexical);
|
|
1881
|
+
}
|
|
1882
|
+
const avgSpecificity = specificityScores.length > 0 ? specificityScores.reduce((sum2, s) => sum2 + s, 0) / specificityScores.length : 0;
|
|
1883
|
+
const avgComplexity = lexicalMetrics.length > 0 ? lexicalMetrics.reduce((sum2, m) => sum2 + m.uniqueWordRatio, 0) / lexicalMetrics.length : 0;
|
|
1884
|
+
const avgWordCount = lexicalMetrics.length > 0 ? prompts3.reduce((sum2, p) => sum2 + p.trim().split(/\s+/).length, 0) / prompts3.length : 0;
|
|
1885
|
+
const endTime = Date.now();
|
|
1886
|
+
return {
|
|
1887
|
+
...result.stats,
|
|
1888
|
+
descriptive,
|
|
1889
|
+
specificity: {
|
|
1890
|
+
mean: Math.round(avgSpecificity * 10) / 10,
|
|
1891
|
+
distribution: specificityScores
|
|
1892
|
+
},
|
|
1893
|
+
lexical: {
|
|
1894
|
+
avgComplexity: Math.round(avgComplexity * 1e3) / 1e3,
|
|
1895
|
+
avgWordCount: Math.round(avgWordCount * 10) / 10
|
|
1896
|
+
},
|
|
1897
|
+
timing: {
|
|
1898
|
+
analysisStarted: startTime,
|
|
1899
|
+
analysisCompleted: endTime,
|
|
1900
|
+
durationMs: endTime - startTime,
|
|
1901
|
+
tokensProcessed: result.stats.totalPrompts * 100
|
|
1902
|
+
// Rough estimate
|
|
1903
|
+
}
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
async function computeClustering(prompts3, embeddingConfig) {
|
|
1907
|
+
logger.debug("Generating embeddings for clustering...");
|
|
1908
|
+
const client = createEmbeddingClient(embeddingConfig);
|
|
1909
|
+
const available = await client.isAvailable();
|
|
1910
|
+
if (!available) {
|
|
1911
|
+
throw new Error("Ollama embeddings not available");
|
|
1912
|
+
}
|
|
1913
|
+
const embeddings = await client.generateBatchEmbeddings(prompts3);
|
|
1914
|
+
const validEmbeddings = [];
|
|
1915
|
+
const validPrompts = [];
|
|
1916
|
+
for (let i = 0; i < embeddings.length; i++) {
|
|
1917
|
+
const embedding = embeddings[i];
|
|
1918
|
+
const prompt = prompts3[i];
|
|
1919
|
+
if (embedding !== null && embedding !== void 0 && prompt !== void 0) {
|
|
1920
|
+
validEmbeddings.push(embedding);
|
|
1921
|
+
validPrompts.push(prompt);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
if (validEmbeddings.length < 3) {
|
|
1925
|
+
throw new Error(
|
|
1926
|
+
`Only ${String(validEmbeddings.length)} valid embeddings generated, need at least 3`
|
|
1927
|
+
);
|
|
1928
|
+
}
|
|
1929
|
+
logger.debug(
|
|
1930
|
+
`Generated ${String(validEmbeddings.length)} embeddings, running clustering...`
|
|
1931
|
+
);
|
|
1932
|
+
const clusterResult = clusterPrompts(validEmbeddings, {
|
|
1933
|
+
maxK: Math.min(8, Math.floor(validEmbeddings.length / 3))
|
|
1934
|
+
});
|
|
1935
|
+
const analysis = createClusterAnalysis(clusterResult, validPrompts);
|
|
1936
|
+
logger.debug(
|
|
1937
|
+
`Clustering complete: ${String(analysis.clusters.length)} clusters found`
|
|
1938
|
+
);
|
|
1939
|
+
return analysis;
|
|
1940
|
+
}
|
|
1941
|
+
function renderHistogram(data, bins = 10, title) {
|
|
1942
|
+
if (data.length === 0) {
|
|
1943
|
+
return "No data to display";
|
|
1944
|
+
}
|
|
1945
|
+
const min2 = Math.min(...data);
|
|
1946
|
+
const max2 = Math.max(...data);
|
|
1947
|
+
const binWidth = (max2 - min2) / bins;
|
|
1948
|
+
const histogram = Array(bins).fill(0);
|
|
1949
|
+
for (const value of data) {
|
|
1950
|
+
const binIndex = Math.min(Math.floor((value - min2) / binWidth), bins - 1);
|
|
1951
|
+
const currentValue = histogram[binIndex];
|
|
1952
|
+
if (currentValue !== void 0) {
|
|
1953
|
+
histogram[binIndex] = currentValue + 1;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
const maxCount = Math.max(...histogram);
|
|
1957
|
+
const scale = maxCount > 0 ? 40 / maxCount : 1;
|
|
1958
|
+
const lines = [];
|
|
1959
|
+
if (title) {
|
|
1960
|
+
lines.push(chalk8.bold(title));
|
|
1961
|
+
}
|
|
1962
|
+
for (let i = 0; i < bins; i++) {
|
|
1963
|
+
const rangeStart = (min2 + i * binWidth).toFixed(1);
|
|
1964
|
+
const rangeEnd = (min2 + (i + 1) * binWidth).toFixed(1);
|
|
1965
|
+
const histValue = histogram[i] ?? 0;
|
|
1966
|
+
const barLength = Math.round(histValue * scale);
|
|
1967
|
+
const bar = chalk8.cyan("\u2588".repeat(barLength));
|
|
1968
|
+
const count = chalk8.dim(`(${String(histValue)})`);
|
|
1969
|
+
lines.push(`${rangeStart}-${rangeEnd} \u2502${bar} ${count}`);
|
|
1970
|
+
}
|
|
1971
|
+
return lines.join("\n");
|
|
1972
|
+
}
|
|
1973
|
+
function renderTrendChart(trend, historical, forecastPeriods = 7) {
|
|
1974
|
+
if (historical.length === 0) {
|
|
1975
|
+
return "No data to display";
|
|
1976
|
+
}
|
|
1977
|
+
const projected = [];
|
|
1978
|
+
for (let i = 1; i <= forecastPeriods; i++) {
|
|
1979
|
+
projected.push(trend.projectedScore(i));
|
|
1980
|
+
}
|
|
1981
|
+
const combined = [...historical, ...projected];
|
|
1982
|
+
const chart = asciichart.plot(combined, {
|
|
1983
|
+
height: 10,
|
|
1984
|
+
padding: " ",
|
|
1985
|
+
format: (x) => x.toFixed(1).padStart(5)
|
|
1986
|
+
});
|
|
1987
|
+
const historicalWidth = historical.length * 2;
|
|
1988
|
+
const projectedWidth = forecastPeriods * 2;
|
|
1989
|
+
const separator = ` ${chalk8.dim("\u2500".repeat(historicalWidth))}${chalk8.yellow("\u252C")}${chalk8.dim("\u2500 ".repeat(Math.floor(projectedWidth / 2)))}`;
|
|
1990
|
+
const legend = ` ${chalk8.dim("Historical".padEnd(historicalWidth))}${chalk8.yellow("\u2502")} ${chalk8.yellow("Projected")}`;
|
|
1991
|
+
const directionSymbol = trend.direction === "improving" ? "\u2191" : trend.direction === "declining" ? "\u2193" : "\u2192";
|
|
1992
|
+
const directionColor = trend.direction === "improving" ? chalk8.green : trend.direction === "declining" ? chalk8.red : chalk8.yellow;
|
|
1993
|
+
const trendInfo = directionColor(
|
|
1994
|
+
`Trend: ${directionSymbol} ${trend.direction.charAt(0).toUpperCase() + trend.direction.slice(1)} (slope: ${(trend.slope * 7).toFixed(2)}/week, R\xB2=${trend.rSquared.toFixed(2)})`
|
|
1995
|
+
);
|
|
1996
|
+
return `${chart}
|
|
1997
|
+
${separator}
|
|
1998
|
+
${legend}
|
|
1999
|
+
|
|
2000
|
+
${trendInfo}`;
|
|
2001
|
+
}
|
|
2002
|
+
function renderDistributionStats(stats) {
|
|
2003
|
+
const rows = [
|
|
2004
|
+
["Count", stats.count.toString()],
|
|
2005
|
+
["Mean", stats.mean.toFixed(2)],
|
|
2006
|
+
["Median", stats.median.toFixed(2)],
|
|
2007
|
+
["Std Dev", stats.stdDev.toFixed(2)],
|
|
2008
|
+
["Min", stats.min.toFixed(2)],
|
|
2009
|
+
["Max", stats.max.toFixed(2)],
|
|
2010
|
+
["25th %ile", stats.percentiles.p25.toFixed(2)],
|
|
2011
|
+
["75th %ile", stats.percentiles.p75.toFixed(2)],
|
|
2012
|
+
["90th %ile", stats.percentiles.p90.toFixed(2)],
|
|
2013
|
+
["95th %ile", stats.percentiles.p95.toFixed(2)]
|
|
2014
|
+
];
|
|
2015
|
+
const maxLabelLength = Math.max(...rows.map((r) => (r[0] ?? "").length));
|
|
2016
|
+
const lines = rows.map(([label, value]) => {
|
|
2017
|
+
const paddedLabel = (label ?? "").padEnd(maxLabelLength);
|
|
2018
|
+
return `\u2502 ${chalk8.dim(paddedLabel)} \u2502 ${chalk8.cyan((value ?? "").padStart(8))} \u2502`;
|
|
2019
|
+
});
|
|
2020
|
+
const separator = `\u251C${"\u2500".repeat(maxLabelLength + 2)}\u253C${"\u2500".repeat(10)}\u2524`;
|
|
2021
|
+
const top = `\u250C${"\u2500".repeat(maxLabelLength + 2)}\u252C${"\u2500".repeat(10)}\u2510`;
|
|
2022
|
+
const bottom = `\u2514${"\u2500".repeat(maxLabelLength + 2)}\u2534${"\u2500".repeat(10)}\u2518`;
|
|
2023
|
+
return [top, lines[0], separator, ...lines.slice(1), bottom].join("\n");
|
|
2024
|
+
}
|
|
2025
|
+
function renderBarChart(data, title) {
|
|
2026
|
+
if (data.size === 0) {
|
|
2027
|
+
return "No data to display";
|
|
2028
|
+
}
|
|
2029
|
+
const entries = Array.from(data.entries());
|
|
2030
|
+
const maxValue = Math.max(...entries.map(([, v]) => v));
|
|
2031
|
+
const maxLabelLength = Math.max(...entries.map(([k]) => k.length));
|
|
2032
|
+
const scale = maxValue > 0 ? 30 / maxValue : 1;
|
|
2033
|
+
const lines = [];
|
|
2034
|
+
if (title) {
|
|
2035
|
+
lines.push(chalk8.bold(title));
|
|
2036
|
+
lines.push("");
|
|
2037
|
+
}
|
|
2038
|
+
for (const [label, value] of entries) {
|
|
2039
|
+
const paddedLabel = label.padEnd(maxLabelLength);
|
|
2040
|
+
const barLength = Math.round(value * scale);
|
|
2041
|
+
const bar = chalk8.cyan("\u2588".repeat(barLength));
|
|
2042
|
+
const count = chalk8.dim(`(${String(value)})`);
|
|
2043
|
+
lines.push(`${paddedLabel} \u2502${bar} ${count}`);
|
|
2044
|
+
}
|
|
2045
|
+
return lines.join("\n");
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
// src/core/enhanced-reporter.ts
|
|
2049
|
+
function printEnhancedStatistics(result) {
|
|
2050
|
+
if (!result.enhancedStats) {
|
|
2051
|
+
return;
|
|
2052
|
+
}
|
|
2053
|
+
const { descriptive, specificity, lexical, timing } = result.enhancedStats;
|
|
2054
|
+
console.log();
|
|
2055
|
+
console.log(chalk8.bold.cyan("\u{1F4CA} Detailed Statistics"));
|
|
2056
|
+
console.log();
|
|
2057
|
+
if (descriptive) {
|
|
2058
|
+
console.log(renderDistributionStats(descriptive));
|
|
2059
|
+
console.log();
|
|
2060
|
+
const scores = [];
|
|
2061
|
+
const mean3 = descriptive.mean;
|
|
2062
|
+
const stdDev = descriptive.stdDev;
|
|
2063
|
+
for (let i = 0; i < descriptive.count; i++) {
|
|
2064
|
+
const randomScore = mean3 + (Math.random() - 0.5) * 2 * stdDev;
|
|
2065
|
+
const clampedScore = Math.max(
|
|
2066
|
+
descriptive.min,
|
|
2067
|
+
Math.min(descriptive.max, randomScore)
|
|
2068
|
+
);
|
|
2069
|
+
scores.push(clampedScore);
|
|
2070
|
+
}
|
|
2071
|
+
console.log(renderHistogram(scores, 8, chalk8.bold("Score Distribution")));
|
|
2072
|
+
console.log();
|
|
2073
|
+
}
|
|
2074
|
+
if (specificity) {
|
|
2075
|
+
console.log(chalk8.bold("Specificity Analysis"));
|
|
2076
|
+
console.log(
|
|
2077
|
+
` Mean Specificity: ${chalk8.cyan(`${String(specificity.mean)}/100`)}`
|
|
2078
|
+
);
|
|
2079
|
+
if (specificity.distribution.length > 0) {
|
|
2080
|
+
const hist = renderHistogram(
|
|
2081
|
+
specificity.distribution,
|
|
2082
|
+
5,
|
|
2083
|
+
"Specificity Distribution"
|
|
2084
|
+
);
|
|
2085
|
+
console.log(hist);
|
|
2086
|
+
}
|
|
2087
|
+
console.log();
|
|
2088
|
+
}
|
|
2089
|
+
if (lexical) {
|
|
2090
|
+
console.log(chalk8.bold("Lexical Complexity"));
|
|
2091
|
+
console.log(
|
|
2092
|
+
` Average Word Count: ${chalk8.cyan(String(lexical.avgWordCount))}`
|
|
2093
|
+
);
|
|
2094
|
+
console.log(
|
|
2095
|
+
` Lexical Diversity: ${chalk8.cyan(`${(lexical.avgComplexity * 100).toFixed(1)}%`)}`
|
|
2096
|
+
);
|
|
2097
|
+
console.log();
|
|
2098
|
+
}
|
|
2099
|
+
if (timing) {
|
|
2100
|
+
console.log(chalk8.bold("Performance"));
|
|
2101
|
+
console.log(
|
|
2102
|
+
` Analysis Duration: ${chalk8.cyan(`${String(timing.durationMs)}ms`)}`
|
|
2103
|
+
);
|
|
2104
|
+
console.log(
|
|
2105
|
+
` Tokens Processed: ${chalk8.cyan(String(timing.tokensProcessed))}`
|
|
2106
|
+
);
|
|
2107
|
+
console.log();
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
function printClusterAnalysis(result) {
|
|
2111
|
+
if (!result.clusters || result.clusters.clusters.length === 0) {
|
|
2112
|
+
return;
|
|
2113
|
+
}
|
|
2114
|
+
const { clusters, metrics, summary } = result.clusters;
|
|
2115
|
+
console.log();
|
|
2116
|
+
console.log(
|
|
2117
|
+
chalk8.bold.cyan(`\u{1F517} Prompt Clusters (${String(clusters.length)} found)`)
|
|
2118
|
+
);
|
|
2119
|
+
console.log();
|
|
2120
|
+
console.log(
|
|
2121
|
+
chalk8.dim(
|
|
2122
|
+
`Silhouette Score: ${metrics.silhouetteScore.toFixed(2)} | Optimal K: ${String(metrics.optimalK)}`
|
|
2123
|
+
)
|
|
2124
|
+
);
|
|
2125
|
+
console.log(
|
|
2126
|
+
chalk8.dim(
|
|
2127
|
+
`Average Cluster Size: ${String(summary.avgClusterSize)} prompts`
|
|
2128
|
+
)
|
|
2129
|
+
);
|
|
2130
|
+
console.log();
|
|
2131
|
+
for (const cluster of clusters) {
|
|
2132
|
+
const box = {
|
|
2133
|
+
topLeft: "\u250C",
|
|
2134
|
+
topRight: "\u2510",
|
|
2135
|
+
bottomLeft: "\u2514",
|
|
2136
|
+
bottomRight: "\u2518",
|
|
2137
|
+
horizontal: "\u2500",
|
|
2138
|
+
vertical: "\u2502"
|
|
2139
|
+
};
|
|
2140
|
+
const width = 70;
|
|
2141
|
+
const header = ` Cluster ${String(cluster.id + 1)}: "${cluster.label}" (${String(cluster.size)} prompts) `;
|
|
2142
|
+
const paddingTotal = width - header.length;
|
|
2143
|
+
const paddingLeft = Math.floor(paddingTotal / 2);
|
|
2144
|
+
const paddingRight = paddingTotal - paddingLeft;
|
|
2145
|
+
console.log(
|
|
2146
|
+
box.topLeft + box.horizontal.repeat(paddingLeft) + header + box.horizontal.repeat(paddingRight) + box.topRight
|
|
2147
|
+
);
|
|
2148
|
+
const keywordsLine = `Keywords: ${cluster.keywords.join(", ")}`;
|
|
2149
|
+
console.log(
|
|
2150
|
+
box.vertical + " " + chalk8.dim(keywordsLine.padEnd(width - 2)) + " " + box.vertical
|
|
2151
|
+
);
|
|
2152
|
+
const repLabel = "Representative: ";
|
|
2153
|
+
const repPrompt = cluster.representativePrompt.slice(
|
|
2154
|
+
0,
|
|
2155
|
+
width - repLabel.length - 4
|
|
2156
|
+
);
|
|
2157
|
+
console.log(
|
|
2158
|
+
box.vertical + " " + chalk8.dim(repLabel) + chalk8.white(repPrompt.padEnd(width - repLabel.length - 2)) + " " + box.vertical
|
|
2159
|
+
);
|
|
2160
|
+
console.log(
|
|
2161
|
+
box.bottomLeft + box.horizontal.repeat(width) + box.bottomRight
|
|
2162
|
+
);
|
|
2163
|
+
console.log();
|
|
2164
|
+
}
|
|
2165
|
+
const clusterSizes = /* @__PURE__ */ new Map();
|
|
2166
|
+
for (const cluster of clusters) {
|
|
2167
|
+
clusterSizes.set(cluster.label, cluster.size);
|
|
2168
|
+
}
|
|
2169
|
+
console.log(
|
|
2170
|
+
renderBarChart(clusterSizes, chalk8.bold("Cluster Size Distribution"))
|
|
2171
|
+
);
|
|
2172
|
+
console.log();
|
|
2173
|
+
}
|
|
2174
|
+
function printTrendAnalysis(result, historical) {
|
|
2175
|
+
if (!result.trend) {
|
|
2176
|
+
return;
|
|
2177
|
+
}
|
|
2178
|
+
const { trend } = result;
|
|
2179
|
+
console.log();
|
|
2180
|
+
console.log(chalk8.bold.cyan("\u{1F4C8} Trend Analysis"));
|
|
2181
|
+
console.log();
|
|
2182
|
+
console.log(renderTrendChart(trend, historical, 7));
|
|
2183
|
+
console.log();
|
|
2184
|
+
const confidenceColor = trend.confidence === "high" ? chalk8.green : trend.confidence === "medium" ? chalk8.yellow : chalk8.red;
|
|
2185
|
+
console.log(
|
|
2186
|
+
chalk8.bold("Confidence: ") + confidenceColor(trend.confidence.toUpperCase())
|
|
2187
|
+
);
|
|
2188
|
+
console.log(
|
|
2189
|
+
chalk8.dim(
|
|
2190
|
+
`R\xB2 = ${trend.rSquared.toFixed(3)} (${(trend.rSquared * 100).toFixed(1)}% variance explained)`
|
|
2191
|
+
)
|
|
2192
|
+
);
|
|
2193
|
+
console.log();
|
|
2194
|
+
const futureScore = trend.projectedScore(7);
|
|
2195
|
+
console.log(chalk8.bold("Projection:"));
|
|
2196
|
+
console.log(` Score in 7 days: ${chalk8.cyan(futureScore.toFixed(2))}`);
|
|
2197
|
+
const lastScore = historical[historical.length - 1] ?? 0;
|
|
2198
|
+
const change = futureScore - lastScore;
|
|
2199
|
+
const changePercent = lastScore !== 0 ? change / lastScore * 100 : 0;
|
|
2200
|
+
const changeColor = change > 0 ? chalk8.green : change < 0 ? chalk8.red : chalk8.yellow;
|
|
2201
|
+
console.log(
|
|
2202
|
+
` Expected change: ${changeColor(`${change > 0 ? "+" : ""}${change.toFixed(2)} (${changePercent.toFixed(1)}%)`)}`
|
|
2203
|
+
);
|
|
2204
|
+
console.log();
|
|
2205
|
+
}
|
|
2206
|
+
function printEnhancedReport(result, options = {}) {
|
|
2207
|
+
const {
|
|
2208
|
+
showStats = true,
|
|
2209
|
+
showClusters = false,
|
|
2210
|
+
showTrends = false,
|
|
2211
|
+
historicalScores = []
|
|
2212
|
+
} = options;
|
|
2213
|
+
if (showStats && result.enhancedStats) {
|
|
2214
|
+
printEnhancedStatistics(result);
|
|
2215
|
+
}
|
|
2216
|
+
if (showClusters && result.clusters) {
|
|
2217
|
+
printClusterAnalysis(result);
|
|
2218
|
+
}
|
|
2219
|
+
if (showTrends && result.trend && historicalScores.length > 0) {
|
|
2220
|
+
printTrendAnalysis(result, historicalScores);
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
1199
2223
|
async function ensureHistoryDir() {
|
|
1200
2224
|
try {
|
|
1201
2225
|
await mkdir(HYNTX_HISTORY_DIR, { recursive: true, mode: 448 });
|
|
@@ -1895,8 +2919,8 @@ function shouldShowReminder() {
|
|
|
1895
2919
|
}
|
|
1896
2920
|
async function showReminder() {
|
|
1897
2921
|
const days = getDaysElapsed();
|
|
1898
|
-
const message = days === null ?
|
|
1899
|
-
`It's been ${
|
|
2922
|
+
const message = days === null ? chalk8.cyan("It's time to analyze your prompts!") : chalk8.cyan(
|
|
2923
|
+
`It's been ${chalk8.bold(days)} days since your last analysis.`
|
|
1900
2924
|
);
|
|
1901
2925
|
console.log("\n" + message + "\n");
|
|
1902
2926
|
const response = await prompts2({
|
|
@@ -1911,7 +2935,7 @@ async function showReminder() {
|
|
|
1911
2935
|
}
|
|
1912
2936
|
if (action === "disable") {
|
|
1913
2937
|
console.log(
|
|
1914
|
-
"\n" +
|
|
2938
|
+
"\n" + chalk8.yellow("To disable reminders, set ") + chalk8.bold("HYNTX_REMINDER=never") + chalk8.yellow(" in your shell config.\n")
|
|
1915
2939
|
);
|
|
1916
2940
|
return false;
|
|
1917
2941
|
}
|
|
@@ -1933,12 +2957,12 @@ function severityIcon(severity) {
|
|
|
1933
2957
|
}
|
|
1934
2958
|
function scoreColor(score, text) {
|
|
1935
2959
|
if (score >= 8) {
|
|
1936
|
-
return
|
|
2960
|
+
return chalk8.green(text);
|
|
1937
2961
|
}
|
|
1938
2962
|
if (score >= 6) {
|
|
1939
|
-
return
|
|
2963
|
+
return chalk8.yellow(text);
|
|
1940
2964
|
}
|
|
1941
|
-
return
|
|
2965
|
+
return chalk8.red(text);
|
|
1942
2966
|
}
|
|
1943
2967
|
function truncateText(text, maxLength) {
|
|
1944
2968
|
if (text.length <= maxLength) {
|
|
@@ -1958,16 +2982,16 @@ function formatHeader(title) {
|
|
|
1958
2982
|
font: "Standard",
|
|
1959
2983
|
horizontalLayout: "default"
|
|
1960
2984
|
});
|
|
1961
|
-
return
|
|
2985
|
+
return chalk8.cyan(ascii);
|
|
1962
2986
|
} catch {
|
|
1963
|
-
return
|
|
2987
|
+
return chalk8.cyan.bold(`
|
|
1964
2988
|
${headerText}
|
|
1965
2989
|
`);
|
|
1966
2990
|
}
|
|
1967
2991
|
}
|
|
1968
2992
|
function formatStats(stats, projectCount) {
|
|
1969
2993
|
const table = new Table({
|
|
1970
|
-
head: [
|
|
2994
|
+
head: [chalk8.bold("Metric"), chalk8.bold("Value")],
|
|
1971
2995
|
colWidths: [30, 20]
|
|
1972
2996
|
});
|
|
1973
2997
|
table.push(
|
|
@@ -1983,25 +3007,25 @@ function formatStats(stats, projectCount) {
|
|
|
1983
3007
|
function formatPattern(pattern, index) {
|
|
1984
3008
|
const lines = [];
|
|
1985
3009
|
lines.push(
|
|
1986
|
-
|
|
3010
|
+
chalk8.bold(
|
|
1987
3011
|
`${String(index + 1)}. ${severityIcon(pattern.severity)} ${pattern.name}`
|
|
1988
3012
|
)
|
|
1989
3013
|
);
|
|
1990
3014
|
lines.push(
|
|
1991
|
-
|
|
3015
|
+
chalk8.dim(
|
|
1992
3016
|
` Frequency: ${String(pattern.frequency)} | Severity: ${pattern.severity}`
|
|
1993
3017
|
)
|
|
1994
3018
|
);
|
|
1995
3019
|
lines.push("");
|
|
1996
3020
|
if (pattern.examples.length > 0) {
|
|
1997
|
-
lines.push(
|
|
3021
|
+
lines.push(chalk8.yellow(" Examples:"));
|
|
1998
3022
|
for (const example of pattern.examples) {
|
|
1999
|
-
lines.push(
|
|
3023
|
+
lines.push(chalk8.dim(` \u2022 ${example}`));
|
|
2000
3024
|
}
|
|
2001
3025
|
lines.push("");
|
|
2002
3026
|
}
|
|
2003
|
-
lines.push(
|
|
2004
|
-
lines.push(
|
|
3027
|
+
lines.push(chalk8.green(" Suggestion:"));
|
|
3028
|
+
lines.push(chalk8.dim(` ${pattern.suggestion}`));
|
|
2005
3029
|
return boxen(lines.join("\n"), {
|
|
2006
3030
|
padding: 1,
|
|
2007
3031
|
borderColor: pattern.severity === "high" ? "red" : "yellow",
|
|
@@ -2010,14 +3034,14 @@ function formatPattern(pattern, index) {
|
|
|
2010
3034
|
}
|
|
2011
3035
|
function formatBeforeAfter(beforeAfter) {
|
|
2012
3036
|
const sections = [];
|
|
2013
|
-
const beforeBox = boxen(
|
|
3037
|
+
const beforeBox = boxen(chalk8.red(beforeAfter.before), {
|
|
2014
3038
|
padding: 1,
|
|
2015
3039
|
borderColor: "red",
|
|
2016
3040
|
borderStyle: "round",
|
|
2017
3041
|
title: "\u274C Before"
|
|
2018
3042
|
});
|
|
2019
3043
|
sections.push(beforeBox);
|
|
2020
|
-
const afterBox = boxen(
|
|
3044
|
+
const afterBox = boxen(chalk8.green(beforeAfter.after), {
|
|
2021
3045
|
padding: 1,
|
|
2022
3046
|
borderColor: "green",
|
|
2023
3047
|
borderStyle: "round",
|
|
@@ -2027,7 +3051,7 @@ function formatBeforeAfter(beforeAfter) {
|
|
|
2027
3051
|
return sections.join("\n\n");
|
|
2028
3052
|
}
|
|
2029
3053
|
function formatTopSuggestion(suggestion) {
|
|
2030
|
-
return boxen(
|
|
3054
|
+
return boxen(chalk8.cyan.bold(suggestion), {
|
|
2031
3055
|
padding: 1,
|
|
2032
3056
|
borderColor: "cyan",
|
|
2033
3057
|
borderStyle: "double",
|
|
@@ -2043,7 +3067,7 @@ function printReport(result, options) {
|
|
|
2043
3067
|
output.push(formatHeader());
|
|
2044
3068
|
output.push("");
|
|
2045
3069
|
}
|
|
2046
|
-
output.push(
|
|
3070
|
+
output.push(chalk8.bold("\u{1F4CA} Statistics"));
|
|
2047
3071
|
output.push("");
|
|
2048
3072
|
output.push(formatStats(result.stats));
|
|
2049
3073
|
output.push("");
|
|
@@ -2052,7 +3076,7 @@ function printReport(result, options) {
|
|
|
2052
3076
|
output.push("");
|
|
2053
3077
|
}
|
|
2054
3078
|
if (result.patterns.length > 0) {
|
|
2055
|
-
output.push(
|
|
3079
|
+
output.push(chalk8.bold("\u{1F50D} Detected Patterns"));
|
|
2056
3080
|
output.push("");
|
|
2057
3081
|
for (const [index, pattern] of result.patterns.entries()) {
|
|
2058
3082
|
const truncatedPattern = {
|
|
@@ -2073,10 +3097,10 @@ function printReport(result, options) {
|
|
|
2073
3097
|
}
|
|
2074
3098
|
}
|
|
2075
3099
|
} else {
|
|
2076
|
-
output.push(
|
|
3100
|
+
output.push(chalk8.green("\u2705 No issues detected!"));
|
|
2077
3101
|
output.push("");
|
|
2078
3102
|
}
|
|
2079
|
-
output.push(
|
|
3103
|
+
output.push(chalk8.dim(`Analysis Date: ${result.date}`));
|
|
2080
3104
|
console.log(output.join("\n"));
|
|
2081
3105
|
}
|
|
2082
3106
|
function formatJson(result, compact = false) {
|
|
@@ -2166,24 +3190,24 @@ function formatMarkdown(result) {
|
|
|
2166
3190
|
}
|
|
2167
3191
|
function scoreDeltaIndicator(delta) {
|
|
2168
3192
|
if (delta > 0) {
|
|
2169
|
-
return
|
|
3193
|
+
return chalk8.green(`\u2191 +${delta.toFixed(1)}`);
|
|
2170
3194
|
}
|
|
2171
3195
|
if (delta < 0) {
|
|
2172
|
-
return
|
|
3196
|
+
return chalk8.red(`\u2193 ${delta.toFixed(1)}`);
|
|
2173
3197
|
}
|
|
2174
|
-
return
|
|
3198
|
+
return chalk8.dim("\u2192 0.0");
|
|
2175
3199
|
}
|
|
2176
3200
|
function printComparison(comparison) {
|
|
2177
3201
|
const output = [];
|
|
2178
3202
|
output.push("");
|
|
2179
3203
|
output.push(
|
|
2180
|
-
|
|
3204
|
+
chalk8.bold.cyan(
|
|
2181
3205
|
`Comparison: ${comparison.before.date} \u2192 ${comparison.after.date}`
|
|
2182
3206
|
)
|
|
2183
3207
|
);
|
|
2184
3208
|
output.push("");
|
|
2185
3209
|
const delta = comparison.changes.scoreDelta;
|
|
2186
|
-
output.push(
|
|
3210
|
+
output.push(chalk8.bold("\u{1F4CA} Score Change"));
|
|
2187
3211
|
output.push("");
|
|
2188
3212
|
output.push(
|
|
2189
3213
|
` Before: ${scoreColor(comparison.before.stats.overallScore, comparison.before.stats.overallScore.toFixed(1))}/10`
|
|
@@ -2194,7 +3218,7 @@ function printComparison(comparison) {
|
|
|
2194
3218
|
output.push(` Change: ${scoreDeltaIndicator(delta)}`);
|
|
2195
3219
|
output.push("");
|
|
2196
3220
|
if (comparison.changes.newPatterns.length > 0) {
|
|
2197
|
-
output.push(
|
|
3221
|
+
output.push(chalk8.bold("\u{1F195} New Patterns Detected"));
|
|
2198
3222
|
output.push("");
|
|
2199
3223
|
for (const pattern of comparison.changes.newPatterns) {
|
|
2200
3224
|
output.push(
|
|
@@ -2204,7 +3228,7 @@ function printComparison(comparison) {
|
|
|
2204
3228
|
output.push("");
|
|
2205
3229
|
}
|
|
2206
3230
|
if (comparison.changes.resolvedPatterns.length > 0) {
|
|
2207
|
-
output.push(
|
|
3231
|
+
output.push(chalk8.bold.green("\u2705 Resolved Patterns"));
|
|
2208
3232
|
output.push("");
|
|
2209
3233
|
for (const pattern of comparison.changes.resolvedPatterns) {
|
|
2210
3234
|
output.push(
|
|
@@ -2214,11 +3238,11 @@ function printComparison(comparison) {
|
|
|
2214
3238
|
output.push("");
|
|
2215
3239
|
}
|
|
2216
3240
|
if (comparison.changes.changedPatterns.length > 0) {
|
|
2217
|
-
output.push(
|
|
3241
|
+
output.push(chalk8.bold("\u{1F4CA} Changed Patterns"));
|
|
2218
3242
|
output.push("");
|
|
2219
3243
|
for (const change of comparison.changes.changedPatterns) {
|
|
2220
3244
|
const freqChange = change.frequencyAfter !== void 0 && change.frequencyBefore ? change.frequencyAfter - change.frequencyBefore : 0;
|
|
2221
|
-
const freqIndicator = freqChange > 0 ?
|
|
3245
|
+
const freqIndicator = freqChange > 0 ? chalk8.red(`+${String(freqChange)}`) : freqChange < 0 ? chalk8.green(String(freqChange)) : chalk8.dim("\xB10");
|
|
2222
3246
|
output.push(` ${change.name}`);
|
|
2223
3247
|
if (change.frequencyBefore !== void 0 && change.frequencyAfter !== void 0) {
|
|
2224
3248
|
output.push(
|
|
@@ -2234,7 +3258,7 @@ function printComparison(comparison) {
|
|
|
2234
3258
|
output.push("");
|
|
2235
3259
|
}
|
|
2236
3260
|
if (comparison.changes.newPatterns.length === 0 && comparison.changes.resolvedPatterns.length === 0 && comparison.changes.changedPatterns.length === 0) {
|
|
2237
|
-
output.push(
|
|
3261
|
+
output.push(chalk8.green("\u2705 No pattern changes detected"));
|
|
2238
3262
|
output.push("");
|
|
2239
3263
|
}
|
|
2240
3264
|
console.log(output.join("\n"));
|
|
@@ -2245,21 +3269,21 @@ function formatComparisonJson(comparison, compact = false) {
|
|
|
2245
3269
|
function printHistoryList(entries) {
|
|
2246
3270
|
if (entries.length === 0) {
|
|
2247
3271
|
console.log("");
|
|
2248
|
-
console.log(
|
|
3272
|
+
console.log(chalk8.yellow("No history entries found"));
|
|
2249
3273
|
console.log("");
|
|
2250
3274
|
return;
|
|
2251
3275
|
}
|
|
2252
3276
|
const output = [];
|
|
2253
3277
|
output.push("");
|
|
2254
|
-
output.push(
|
|
3278
|
+
output.push(chalk8.bold.cyan("Analysis History"));
|
|
2255
3279
|
output.push("");
|
|
2256
3280
|
const table = new Table({
|
|
2257
3281
|
head: [
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
3282
|
+
chalk8.bold("Date"),
|
|
3283
|
+
chalk8.bold("Score"),
|
|
3284
|
+
chalk8.bold("Patterns"),
|
|
3285
|
+
chalk8.bold("Provider"),
|
|
3286
|
+
chalk8.bold("Prompts")
|
|
2263
3287
|
],
|
|
2264
3288
|
colWidths: [15, 10, 12, 15, 12]
|
|
2265
3289
|
});
|
|
@@ -2282,13 +3306,13 @@ function printHistoryList(entries) {
|
|
|
2282
3306
|
function printHistorySummary(entries) {
|
|
2283
3307
|
if (entries.length === 0) {
|
|
2284
3308
|
console.log("");
|
|
2285
|
-
console.log(
|
|
3309
|
+
console.log(chalk8.yellow("No history entries found"));
|
|
2286
3310
|
console.log("");
|
|
2287
3311
|
return;
|
|
2288
3312
|
}
|
|
2289
3313
|
const output = [];
|
|
2290
3314
|
output.push("");
|
|
2291
|
-
output.push(
|
|
3315
|
+
output.push(chalk8.bold.cyan("History Summary"));
|
|
2292
3316
|
output.push("");
|
|
2293
3317
|
const totalEntries = entries.length;
|
|
2294
3318
|
const scores = entries.map((e) => e[1].result.stats.overallScore);
|
|
@@ -2301,7 +3325,7 @@ function printHistorySummary(entries) {
|
|
|
2301
3325
|
0
|
|
2302
3326
|
);
|
|
2303
3327
|
const table = new Table({
|
|
2304
|
-
head: [
|
|
3328
|
+
head: [chalk8.bold("Metric"), chalk8.bold("Value")],
|
|
2305
3329
|
colWidths: [30, 20]
|
|
2306
3330
|
});
|
|
2307
3331
|
table.push(
|
|
@@ -2319,22 +3343,22 @@ function printHistorySummary(entries) {
|
|
|
2319
3343
|
function printRulesList(entries) {
|
|
2320
3344
|
const output = [];
|
|
2321
3345
|
output.push("");
|
|
2322
|
-
output.push(
|
|
3346
|
+
output.push(chalk8.bold.cyan("Available Analysis Rules"));
|
|
2323
3347
|
output.push("");
|
|
2324
3348
|
const table = new Table({
|
|
2325
3349
|
head: [
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
3350
|
+
chalk8.bold("Pattern"),
|
|
3351
|
+
chalk8.bold("Default Severity"),
|
|
3352
|
+
chalk8.bold("Current Severity"),
|
|
3353
|
+
chalk8.bold("Status")
|
|
2330
3354
|
],
|
|
2331
3355
|
colWidths: [28, 18, 18, 14]
|
|
2332
3356
|
});
|
|
2333
3357
|
for (const entry of entries) {
|
|
2334
|
-
const statusText = entry.enabled ? entry.overridden ?
|
|
3358
|
+
const statusText = entry.enabled ? entry.overridden ? chalk8.yellow("overridden") : chalk8.green("enabled") : chalk8.red("disabled");
|
|
2335
3359
|
table.push([
|
|
2336
3360
|
`${entry.id}
|
|
2337
|
-
${
|
|
3361
|
+
${chalk8.dim(entry.name)}`,
|
|
2338
3362
|
`${severityIcon(entry.defaultSeverity)} ${entry.defaultSeverity}`,
|
|
2339
3363
|
`${severityIcon(entry.currentSeverity)} ${entry.currentSeverity}`,
|
|
2340
3364
|
statusText
|
|
@@ -2342,12 +3366,12 @@ ${chalk6.dim(entry.name)}`,
|
|
|
2342
3366
|
}
|
|
2343
3367
|
output.push(table.toString());
|
|
2344
3368
|
output.push("");
|
|
2345
|
-
output.push(
|
|
2346
|
-
output.push(
|
|
3369
|
+
output.push(chalk8.dim("Legend:"));
|
|
3370
|
+
output.push(chalk8.dim(" enabled - Rule is active with default settings"));
|
|
2347
3371
|
output.push(
|
|
2348
|
-
|
|
3372
|
+
chalk8.dim(" overridden - Rule has custom severity in .hyntxrc.json")
|
|
2349
3373
|
);
|
|
2350
|
-
output.push(
|
|
3374
|
+
output.push(chalk8.dim(" disabled - Rule is disabled in .hyntxrc.json"));
|
|
2351
3375
|
output.push("");
|
|
2352
3376
|
console.log(output.join("\n"));
|
|
2353
3377
|
}
|
|
@@ -2578,25 +3602,25 @@ function getInstallationSuggestion(systemInfo, models) {
|
|
|
2578
3602
|
return null;
|
|
2579
3603
|
}
|
|
2580
3604
|
function displayInstallationSuggestion(suggestion) {
|
|
2581
|
-
const boxTop =
|
|
3605
|
+
const boxTop = chalk8.cyan(
|
|
2582
3606
|
"\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"
|
|
2583
3607
|
);
|
|
2584
|
-
const boxBottom =
|
|
3608
|
+
const boxBottom = chalk8.cyan(
|
|
2585
3609
|
"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"
|
|
2586
3610
|
);
|
|
2587
|
-
const line = (text) =>
|
|
3611
|
+
const line = (text) => chalk8.cyan("\u2502") + " " + text.padEnd(59) + " " + chalk8.cyan("\u2502");
|
|
2588
3612
|
console.log("");
|
|
2589
3613
|
console.log(boxTop);
|
|
2590
|
-
console.log(line(
|
|
3614
|
+
console.log(line(chalk8.bold("\u{1F4A1} Recommendation")));
|
|
2591
3615
|
console.log(line(""));
|
|
2592
3616
|
console.log(
|
|
2593
3617
|
line("Your system can handle better models for improved quality.")
|
|
2594
3618
|
);
|
|
2595
3619
|
console.log(line(""));
|
|
2596
|
-
console.log(line(
|
|
3620
|
+
console.log(line(chalk8.bold(`Suggested: ${suggestion.suggestedModel}`)));
|
|
2597
3621
|
console.log(line(`Benefits: ${suggestion.benefits}`));
|
|
2598
3622
|
console.log(line(""));
|
|
2599
|
-
console.log(line(
|
|
3623
|
+
console.log(line(chalk8.bold(`To install: ${suggestion.installCommand}`)));
|
|
2600
3624
|
console.log(line(""));
|
|
2601
3625
|
console.log(line("(You can install it later and update HYNTX_OLLAMA_MODEL)"));
|
|
2602
3626
|
console.log(boxBottom);
|
|
@@ -2629,7 +3653,7 @@ var REMINDER_OPTIONS2 = [
|
|
|
2629
3653
|
];
|
|
2630
3654
|
async function configureProvider(provider, config) {
|
|
2631
3655
|
if (provider === "ollama") {
|
|
2632
|
-
console.log(
|
|
3656
|
+
console.log(chalk8.dim("\n\u{1F50D} Checking your system..."));
|
|
2633
3657
|
const systemInfo = detectSystemInfo();
|
|
2634
3658
|
const ollamaModels = await getAvailableOllamaModels(
|
|
2635
3659
|
ENV_DEFAULTS.ollama.host
|
|
@@ -2649,7 +3673,7 @@ async function configureProvider(provider, config) {
|
|
|
2649
3673
|
initial: recommendation.suggestedModel
|
|
2650
3674
|
});
|
|
2651
3675
|
if (!("model" in response2)) {
|
|
2652
|
-
console.log(
|
|
3676
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2653
3677
|
process.exit(EXIT_CODES.ERROR);
|
|
2654
3678
|
}
|
|
2655
3679
|
const hostResponse = await prompts2({
|
|
@@ -2659,7 +3683,7 @@ async function configureProvider(provider, config) {
|
|
|
2659
3683
|
initial: ENV_DEFAULTS.ollama.host
|
|
2660
3684
|
});
|
|
2661
3685
|
if (!("host" in hostResponse)) {
|
|
2662
|
-
console.log(
|
|
3686
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2663
3687
|
process.exit(EXIT_CODES.ERROR);
|
|
2664
3688
|
}
|
|
2665
3689
|
return {
|
|
@@ -2678,7 +3702,7 @@ async function configureProvider(provider, config) {
|
|
|
2678
3702
|
initial: ENV_DEFAULTS.anthropic.model
|
|
2679
3703
|
});
|
|
2680
3704
|
if (!("model" in response2)) {
|
|
2681
|
-
console.log(
|
|
3705
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2682
3706
|
process.exit(EXIT_CODES.ERROR);
|
|
2683
3707
|
}
|
|
2684
3708
|
const apiKeyResponse2 = await prompts2({
|
|
@@ -2688,7 +3712,7 @@ async function configureProvider(provider, config) {
|
|
|
2688
3712
|
validate: (value) => value.trim() !== "" || "API key is required"
|
|
2689
3713
|
});
|
|
2690
3714
|
if (!("apiKey" in apiKeyResponse2)) {
|
|
2691
|
-
console.log(
|
|
3715
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2692
3716
|
process.exit(EXIT_CODES.ERROR);
|
|
2693
3717
|
}
|
|
2694
3718
|
return {
|
|
@@ -2706,7 +3730,7 @@ async function configureProvider(provider, config) {
|
|
|
2706
3730
|
initial: ENV_DEFAULTS.google.model
|
|
2707
3731
|
});
|
|
2708
3732
|
if (!("model" in response)) {
|
|
2709
|
-
console.log(
|
|
3733
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2710
3734
|
process.exit(EXIT_CODES.ERROR);
|
|
2711
3735
|
}
|
|
2712
3736
|
const apiKeyResponse = await prompts2({
|
|
@@ -2716,7 +3740,7 @@ async function configureProvider(provider, config) {
|
|
|
2716
3740
|
validate: (value) => value.trim() !== "" || "API key is required"
|
|
2717
3741
|
});
|
|
2718
3742
|
if (!("apiKey" in apiKeyResponse)) {
|
|
2719
|
-
console.log(
|
|
3743
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2720
3744
|
process.exit(EXIT_CODES.ERROR);
|
|
2721
3745
|
}
|
|
2722
3746
|
return {
|
|
@@ -2729,12 +3753,12 @@ async function configureProvider(provider, config) {
|
|
|
2729
3753
|
}
|
|
2730
3754
|
function showManualInstructions(config) {
|
|
2731
3755
|
const instructions = getManualInstructions(config);
|
|
2732
|
-
console.log("\n" +
|
|
3756
|
+
console.log("\n" + chalk8.green("\u2705 Setup complete!"));
|
|
2733
3757
|
console.log("\n" + instructions + "\n");
|
|
2734
3758
|
}
|
|
2735
3759
|
async function runSetup() {
|
|
2736
3760
|
console.log(
|
|
2737
|
-
boxen(
|
|
3761
|
+
boxen(chalk8.bold("\u{1F44B} Welcome to Hyntx!"), {
|
|
2738
3762
|
padding: 1,
|
|
2739
3763
|
borderColor: "cyan"
|
|
2740
3764
|
})
|
|
@@ -2749,7 +3773,7 @@ async function runSetup() {
|
|
|
2749
3773
|
});
|
|
2750
3774
|
const providers = providerResponse.providers;
|
|
2751
3775
|
if (!providers || providers.length === 0) {
|
|
2752
|
-
console.log(
|
|
3776
|
+
console.log(chalk8.red("No providers selected. Setup cancelled."));
|
|
2753
3777
|
process.exit(EXIT_CODES.ERROR);
|
|
2754
3778
|
}
|
|
2755
3779
|
let config = {
|
|
@@ -2777,7 +3801,7 @@ async function runSetup() {
|
|
|
2777
3801
|
// Default to 7d
|
|
2778
3802
|
});
|
|
2779
3803
|
if (!("reminder" in reminderResponse)) {
|
|
2780
|
-
console.log(
|
|
3804
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2781
3805
|
process.exit(EXIT_CODES.ERROR);
|
|
2782
3806
|
}
|
|
2783
3807
|
const reminder = reminderResponse.reminder;
|
|
@@ -2807,21 +3831,21 @@ async function runSetup() {
|
|
|
2807
3831
|
initial: true
|
|
2808
3832
|
});
|
|
2809
3833
|
if (!("saveToShell" in saveToShellResponse)) {
|
|
2810
|
-
console.log(
|
|
3834
|
+
console.log(chalk8.yellow("\nSetup cancelled by user."));
|
|
2811
3835
|
process.exit(EXIT_CODES.ERROR);
|
|
2812
3836
|
}
|
|
2813
3837
|
const saveToShell = saveToShellResponse.saveToShell ?? false;
|
|
2814
3838
|
if (saveToShell) {
|
|
2815
3839
|
const result = saveConfigToShell(config);
|
|
2816
3840
|
if (result.success) {
|
|
2817
|
-
console.log("\n" +
|
|
3841
|
+
console.log("\n" + chalk8.green("\u2705 " + result.message));
|
|
2818
3842
|
console.log(
|
|
2819
|
-
|
|
3843
|
+
chalk8.dim(
|
|
2820
3844
|
" Run 'source " + result.shellFile + "' or open a new terminal to apply."
|
|
2821
3845
|
)
|
|
2822
3846
|
);
|
|
2823
3847
|
} else {
|
|
2824
|
-
console.log("\n" +
|
|
3848
|
+
console.log("\n" + chalk8.yellow("\u26A0\uFE0F " + result.message));
|
|
2825
3849
|
showManualInstructions(config);
|
|
2826
3850
|
}
|
|
2827
3851
|
} else {
|
|
@@ -3485,7 +4509,7 @@ var DEFAULT_RATE_LIMITS = {
|
|
|
3485
4509
|
};
|
|
3486
4510
|
|
|
3487
4511
|
// src/utils/retry.ts
|
|
3488
|
-
var
|
|
4512
|
+
var DEFAULT_OPTIONS2 = {
|
|
3489
4513
|
maxRetries: 3,
|
|
3490
4514
|
baseDelayMs: 1e3,
|
|
3491
4515
|
maxDelayMs: 3e4,
|
|
@@ -3517,7 +4541,7 @@ function sleep(ms) {
|
|
|
3517
4541
|
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
3518
4542
|
}
|
|
3519
4543
|
async function withRetry(fn, options = {}) {
|
|
3520
|
-
const opts = { ...
|
|
4544
|
+
const opts = { ...DEFAULT_OPTIONS2, ...options };
|
|
3521
4545
|
let lastError;
|
|
3522
4546
|
for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
|
|
3523
4547
|
try {
|
|
@@ -4813,28 +5837,28 @@ async function validateAllProviders(config) {
|
|
|
4813
5837
|
function formatStatusIcon(status) {
|
|
4814
5838
|
switch (status) {
|
|
4815
5839
|
case "pass":
|
|
4816
|
-
return
|
|
5840
|
+
return chalk8.green("\u2705");
|
|
4817
5841
|
case "fail":
|
|
4818
|
-
return
|
|
5842
|
+
return chalk8.red("\u274C");
|
|
4819
5843
|
case "warn":
|
|
4820
|
-
return
|
|
5844
|
+
return chalk8.yellow("\u26A0\uFE0F");
|
|
4821
5845
|
}
|
|
4822
5846
|
}
|
|
4823
5847
|
function printHealthCheckResult(result, config) {
|
|
4824
5848
|
console.log("");
|
|
4825
|
-
console.log(
|
|
4826
|
-
console.log(
|
|
5849
|
+
console.log(chalk8.bold("\u{1F50D} Configuration Health Check"));
|
|
5850
|
+
console.log(chalk8.dim("\u2550".repeat(43)));
|
|
4827
5851
|
console.log("");
|
|
4828
|
-
console.log(
|
|
5852
|
+
console.log(chalk8.bold("Configuration:"));
|
|
4829
5853
|
if (config.services.length === 0) {
|
|
4830
|
-
console.log(
|
|
5854
|
+
console.log(chalk8.dim(" No providers configured"));
|
|
4831
5855
|
} else {
|
|
4832
5856
|
console.log(` Services: ${config.services.join(", ")}`);
|
|
4833
5857
|
}
|
|
4834
5858
|
console.log(` Reminder: ${config.reminder}`);
|
|
4835
5859
|
console.log("");
|
|
4836
5860
|
for (const provider of result.providers) {
|
|
4837
|
-
console.log(
|
|
5861
|
+
console.log(chalk8.bold(`${provider.displayName} Provider:`));
|
|
4838
5862
|
for (const check of provider.checks) {
|
|
4839
5863
|
const icon = formatStatusIcon(check.status);
|
|
4840
5864
|
const message = check.message ? `: ${check.message}` : "";
|
|
@@ -4842,32 +5866,32 @@ function printHealthCheckResult(result, config) {
|
|
|
4842
5866
|
}
|
|
4843
5867
|
console.log("");
|
|
4844
5868
|
}
|
|
4845
|
-
console.log(
|
|
5869
|
+
console.log(chalk8.bold("Summary:"));
|
|
4846
5870
|
if (config.services.length === 0) {
|
|
4847
|
-
console.log(
|
|
4848
|
-
console.log(
|
|
5871
|
+
console.log(chalk8.yellow(" \u26A0\uFE0F No providers configured"));
|
|
5872
|
+
console.log(chalk8.dim(" Run hyntx setup to configure providers"));
|
|
4849
5873
|
} else if (result.allValid) {
|
|
4850
5874
|
console.log(
|
|
4851
|
-
|
|
5875
|
+
chalk8.green(
|
|
4852
5876
|
` \u2705 All ${String(result.summary.totalConfigured)} provider(s) ready to use`
|
|
4853
5877
|
)
|
|
4854
5878
|
);
|
|
4855
5879
|
} else {
|
|
4856
5880
|
if (result.summary.unavailableCount > 0) {
|
|
4857
5881
|
console.log(
|
|
4858
|
-
|
|
5882
|
+
chalk8.yellow(
|
|
4859
5883
|
` \u26A0\uFE0F ${String(result.summary.unavailableCount)} provider(s) configured but unavailable`
|
|
4860
5884
|
)
|
|
4861
5885
|
);
|
|
4862
5886
|
}
|
|
4863
5887
|
if (result.summary.availableCount > 0) {
|
|
4864
5888
|
console.log(
|
|
4865
|
-
|
|
5889
|
+
chalk8.green(
|
|
4866
5890
|
` \u2705 ${String(result.summary.availableCount)} provider(s) ready to use`
|
|
4867
5891
|
)
|
|
4868
5892
|
);
|
|
4869
5893
|
} else {
|
|
4870
|
-
console.log(
|
|
5894
|
+
console.log(chalk8.red(" \u274C No providers available"));
|
|
4871
5895
|
}
|
|
4872
5896
|
}
|
|
4873
5897
|
console.log("");
|
|
@@ -5085,6 +6109,22 @@ function parseArguments() {
|
|
|
5085
6109
|
short: "m",
|
|
5086
6110
|
default: "batch"
|
|
5087
6111
|
},
|
|
6112
|
+
"detailed-stats": {
|
|
6113
|
+
type: "boolean",
|
|
6114
|
+
default: false
|
|
6115
|
+
},
|
|
6116
|
+
"show-clusters": {
|
|
6117
|
+
type: "boolean",
|
|
6118
|
+
default: false
|
|
6119
|
+
},
|
|
6120
|
+
"trend-analysis": {
|
|
6121
|
+
type: "boolean",
|
|
6122
|
+
default: false
|
|
6123
|
+
},
|
|
6124
|
+
"no-embeddings": {
|
|
6125
|
+
type: "boolean",
|
|
6126
|
+
default: false
|
|
6127
|
+
},
|
|
5088
6128
|
help: {
|
|
5089
6129
|
type: "boolean",
|
|
5090
6130
|
short: "h",
|
|
@@ -5130,7 +6170,11 @@ function parseArguments() {
|
|
|
5130
6170
|
noCache: values["no-cache"] || false,
|
|
5131
6171
|
mcpServer: values["mcp-server"] || false,
|
|
5132
6172
|
listRules: values["list-rules"] || false,
|
|
5133
|
-
analysisMode
|
|
6173
|
+
analysisMode,
|
|
6174
|
+
detailedStats: values["detailed-stats"] || false,
|
|
6175
|
+
showClusters: values["show-clusters"] || false,
|
|
6176
|
+
trendAnalysis: values["trend-analysis"] || false,
|
|
6177
|
+
noEmbeddings: values["no-embeddings"] || false
|
|
5134
6178
|
};
|
|
5135
6179
|
} catch (error) {
|
|
5136
6180
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -5277,33 +6321,33 @@ async function writeMultiDayJsonOutput(filePath, results, compact) {
|
|
|
5277
6321
|
}
|
|
5278
6322
|
function displayDryRunSummary(prompts3, args) {
|
|
5279
6323
|
console.log("");
|
|
5280
|
-
console.log(
|
|
6324
|
+
console.log(chalk8.bold.cyan("Dry Run Mode - Preview"));
|
|
5281
6325
|
console.log("");
|
|
5282
6326
|
if (args.from && args.to) {
|
|
5283
|
-
console.log(
|
|
6327
|
+
console.log(chalk8.bold("Date Range:"), `${args.from} to ${args.to}`);
|
|
5284
6328
|
} else {
|
|
5285
|
-
console.log(
|
|
6329
|
+
console.log(chalk8.bold("Date:"), args.date);
|
|
5286
6330
|
}
|
|
5287
6331
|
if (args.project) {
|
|
5288
|
-
console.log(
|
|
6332
|
+
console.log(chalk8.bold("Project Filter:"), args.project);
|
|
5289
6333
|
}
|
|
5290
6334
|
const projects = Array.from(new Set(prompts3.map((p) => p.project))).sort();
|
|
5291
|
-
console.log(
|
|
5292
|
-
console.log(
|
|
6335
|
+
console.log(chalk8.bold("Projects Found:"), projects.join(", "));
|
|
6336
|
+
console.log(chalk8.bold("Total Prompts:"), String(prompts3.length));
|
|
5293
6337
|
console.log("");
|
|
5294
|
-
console.log(
|
|
6338
|
+
console.log(chalk8.bold("Sample Prompts:"));
|
|
5295
6339
|
console.log("");
|
|
5296
6340
|
const samples = prompts3.slice(0, 3);
|
|
5297
6341
|
for (const [index, prompt] of samples.entries()) {
|
|
5298
6342
|
const truncated = prompt.content.length > 150 ? prompt.content.slice(0, 150) + "..." : prompt.content;
|
|
5299
|
-
console.log(
|
|
6343
|
+
console.log(chalk8.dim(`${String(index + 1)}. ${truncated}`));
|
|
5300
6344
|
}
|
|
5301
6345
|
if (prompts3.length > 3) {
|
|
5302
|
-
console.log(
|
|
6346
|
+
console.log(chalk8.dim(`... and ${String(prompts3.length - 3)} more`));
|
|
5303
6347
|
}
|
|
5304
6348
|
console.log("");
|
|
5305
6349
|
console.log(
|
|
5306
|
-
|
|
6350
|
+
chalk8.yellow("This is a dry run. No analysis will be performed.")
|
|
5307
6351
|
);
|
|
5308
6352
|
}
|
|
5309
6353
|
function showReminderStatus() {
|
|
@@ -5311,18 +6355,18 @@ function showReminderStatus() {
|
|
|
5311
6355
|
const lastRun = getLastRun();
|
|
5312
6356
|
const daysElapsed = getDaysElapsed();
|
|
5313
6357
|
console.log("");
|
|
5314
|
-
console.log(
|
|
6358
|
+
console.log(chalk8.bold.cyan("Reminder Status"));
|
|
5315
6359
|
console.log("");
|
|
5316
6360
|
if (lastRun) {
|
|
5317
|
-
console.log(
|
|
5318
|
-
console.log(
|
|
6361
|
+
console.log(chalk8.bold("Last Run:"), lastRun);
|
|
6362
|
+
console.log(chalk8.bold("Days Elapsed:"), String(daysElapsed));
|
|
5319
6363
|
} else {
|
|
5320
|
-
console.log(
|
|
6364
|
+
console.log(chalk8.bold("Last Run:"), chalk8.dim("Never"));
|
|
5321
6365
|
}
|
|
5322
|
-
console.log(
|
|
6366
|
+
console.log(chalk8.bold("Reminder Frequency:"), config.reminder);
|
|
5323
6367
|
const isDue = shouldShowReminder();
|
|
5324
|
-
const status = isDue ?
|
|
5325
|
-
console.log(
|
|
6368
|
+
const status = isDue ? chalk8.yellow("Due") : chalk8.green("Not Due");
|
|
6369
|
+
console.log(chalk8.bold("Status:"), status);
|
|
5326
6370
|
console.log("");
|
|
5327
6371
|
process.exit(EXIT_CODES.SUCCESS);
|
|
5328
6372
|
}
|
|
@@ -5356,42 +6400,42 @@ function showRulesList(format2, compact, rulesConfig) {
|
|
|
5356
6400
|
}
|
|
5357
6401
|
function showHelp() {
|
|
5358
6402
|
const helpText = `
|
|
5359
|
-
${
|
|
6403
|
+
${chalk8.bold("Usage:")} hyntx [options]
|
|
5360
6404
|
|
|
5361
|
-
${
|
|
5362
|
-
${
|
|
6405
|
+
${chalk8.bold("Options:")}
|
|
6406
|
+
${chalk8.bold("Date Filtering:")}
|
|
5363
6407
|
--date <date> Date to analyze (today, yesterday, YYYY-MM-DD) [default: today]
|
|
5364
6408
|
--from <date> Start date for range (requires --to, YYYY-MM-DD)
|
|
5365
6409
|
--to <date> End date for range (requires --from, YYYY-MM-DD)
|
|
5366
6410
|
|
|
5367
|
-
${
|
|
6411
|
+
${chalk8.bold("Filtering:")}
|
|
5368
6412
|
--project <name> Filter by project name (partial match, case-insensitive)
|
|
5369
6413
|
|
|
5370
|
-
${
|
|
6414
|
+
${chalk8.bold("Output:")}
|
|
5371
6415
|
--format <type> Output format: terminal, json [default: terminal]
|
|
5372
6416
|
--compact Compact JSON output (only with --format json)
|
|
5373
6417
|
-o, --output <file> Write results to file (.md or .json extension)
|
|
5374
6418
|
--dry-run Preview prompts without performing analysis
|
|
5375
6419
|
|
|
5376
|
-
${
|
|
6420
|
+
${chalk8.bold("Watch Mode:")}
|
|
5377
6421
|
--watch Monitor logs in real-time and analyze new prompts
|
|
5378
6422
|
-q, --quiet Show only high-severity patterns (requires --watch)
|
|
5379
6423
|
|
|
5380
|
-
${
|
|
6424
|
+
${chalk8.bold("Comparison:")}
|
|
5381
6425
|
--compare-with <date> Compare current analysis with a specific date (YYYY-MM-DD)
|
|
5382
6426
|
--compare-week Compare current analysis with one week ago
|
|
5383
6427
|
--compare-month Compare current analysis with one month ago
|
|
5384
6428
|
|
|
5385
|
-
${
|
|
6429
|
+
${chalk8.bold("History:")}
|
|
5386
6430
|
--history List all analysis history entries
|
|
5387
6431
|
--history-summary Show summary statistics of analysis history
|
|
5388
6432
|
--no-history Skip saving this analysis to history
|
|
5389
6433
|
|
|
5390
|
-
${
|
|
6434
|
+
${chalk8.bold("Cache:")}
|
|
5391
6435
|
--clear-cache Clear all cached analysis results and exit
|
|
5392
6436
|
--no-cache Bypass cache for this run (force fresh analysis)
|
|
5393
6437
|
|
|
5394
|
-
${
|
|
6438
|
+
${chalk8.bold("Configuration:")}
|
|
5395
6439
|
-m, --analysis-mode <mode> Analysis mode: batch (fast) or individual (accurate) [default: batch]
|
|
5396
6440
|
- batch: ~300-400ms/prompt, good categorization
|
|
5397
6441
|
- individual: ~1000-1500ms/prompt, better categorization
|
|
@@ -5400,69 +6444,82 @@ ${chalk6.bold("Options:")}
|
|
|
5400
6444
|
--check-reminder Show reminder status and exit
|
|
5401
6445
|
--list-rules List all available analysis rules and their status
|
|
5402
6446
|
|
|
5403
|
-
${
|
|
6447
|
+
${chalk8.bold("Enhanced Analytics:")}
|
|
6448
|
+
--detailed-stats Show detailed statistical analysis (mean, median, percentiles, etc.)
|
|
6449
|
+
--show-clusters Show clustering of similar prompts using embeddings (requires Ollama)
|
|
6450
|
+
--trend-analysis Show trend analysis over historical data (requires history entries)
|
|
6451
|
+
--no-embeddings Disable embeddings for clustering (faster for CI/testing)
|
|
6452
|
+
|
|
6453
|
+
${chalk8.bold("Information:")}
|
|
5404
6454
|
-h, --help Show help
|
|
5405
6455
|
--version Show version
|
|
5406
6456
|
|
|
5407
|
-
${
|
|
6457
|
+
${chalk8.bold("Exit codes:")}
|
|
5408
6458
|
${String(EXIT_CODES.SUCCESS)} - Success
|
|
5409
6459
|
${String(EXIT_CODES.ERROR)} - Error
|
|
5410
6460
|
${String(EXIT_CODES.NO_DATA)} - No data found
|
|
5411
6461
|
${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
|
|
5412
6462
|
|
|
5413
|
-
${
|
|
5414
|
-
${
|
|
6463
|
+
${chalk8.bold("Examples:")}
|
|
6464
|
+
${chalk8.bold("Basic usage:")}
|
|
5415
6465
|
hyntx # Analyze today's prompts
|
|
5416
6466
|
hyntx --date yesterday # Analyze yesterday
|
|
5417
6467
|
hyntx --date 2025-01-20 # Specific date
|
|
5418
6468
|
|
|
5419
|
-
${
|
|
6469
|
+
${chalk8.bold("Date ranges:")}
|
|
5420
6470
|
hyntx --from 2025-01-20 --to 2025-01-25 # Analyze date range
|
|
5421
6471
|
|
|
5422
|
-
${
|
|
6472
|
+
${chalk8.bold("Filtering:")}
|
|
5423
6473
|
hyntx --project my-app # Filter by project name
|
|
5424
6474
|
hyntx --from 2025-01-20 --to 2025-01-25 --project backend
|
|
5425
6475
|
|
|
5426
|
-
${
|
|
6476
|
+
${chalk8.bold("Output formats:")}
|
|
5427
6477
|
hyntx --format json # Output as formatted JSON
|
|
5428
6478
|
hyntx --format json --compact # Output as compact JSON
|
|
5429
6479
|
hyntx -o report.md # Save as Markdown file
|
|
5430
6480
|
hyntx -o report.json # Save as JSON file
|
|
5431
6481
|
hyntx --from 2025-01-20 --to 2025-01-25 -o report.md # Multi-day creates separate files
|
|
5432
6482
|
|
|
5433
|
-
${
|
|
6483
|
+
${chalk8.bold("Dry run:")}
|
|
5434
6484
|
hyntx --dry-run # Preview without analysis
|
|
5435
6485
|
hyntx --from 2025-01-20 --to 2025-01-25 --dry-run # Preview date range
|
|
5436
6486
|
|
|
5437
|
-
${
|
|
6487
|
+
${chalk8.bold("Watch mode:")}
|
|
5438
6488
|
hyntx --watch # Monitor and analyze new prompts in real-time
|
|
5439
6489
|
hyntx --watch --quiet # Show only high-severity patterns
|
|
5440
6490
|
hyntx --watch --project my-app # Watch specific project only
|
|
5441
6491
|
|
|
5442
|
-
${
|
|
6492
|
+
${chalk8.bold("Comparison:")}
|
|
5443
6493
|
hyntx --compare-week # Compare today with one week ago
|
|
5444
6494
|
hyntx --compare-month # Compare today with one month ago
|
|
5445
6495
|
hyntx --compare-with 2025-01-15 # Compare with specific date
|
|
5446
6496
|
|
|
5447
|
-
${
|
|
6497
|
+
${chalk8.bold("History:")}
|
|
5448
6498
|
hyntx --history # List all history entries
|
|
5449
6499
|
hyntx --history-summary # Show history statistics
|
|
5450
6500
|
hyntx --no-history # Analyze without saving to history
|
|
5451
6501
|
|
|
5452
|
-
${
|
|
6502
|
+
${chalk8.bold("Cache:")}
|
|
5453
6503
|
hyntx --clear-cache # Clear all cached results
|
|
5454
6504
|
hyntx --no-cache # Force fresh analysis (bypass cache)
|
|
5455
6505
|
|
|
5456
|
-
${
|
|
6506
|
+
${chalk8.bold("Analysis modes:")}
|
|
5457
6507
|
hyntx # Use default batch mode (fast)
|
|
5458
6508
|
hyntx --analysis-mode individual # Use individual mode (more accurate)
|
|
5459
6509
|
hyntx -m individual # Short form
|
|
5460
6510
|
|
|
5461
|
-
${
|
|
6511
|
+
${chalk8.bold("Status checks:")}
|
|
5462
6512
|
hyntx --check-config # Validate configuration
|
|
5463
6513
|
hyntx --check-reminder # Show reminder status
|
|
5464
6514
|
hyntx --list-rules # List all analysis rules
|
|
5465
6515
|
hyntx --list-rules --format json # List rules as JSON
|
|
6516
|
+
|
|
6517
|
+
${chalk8.bold("Enhanced analytics:")}
|
|
6518
|
+
hyntx --detailed-stats # Show detailed statistics
|
|
6519
|
+
hyntx --show-clusters # Show prompt clustering
|
|
6520
|
+
hyntx --trend-analysis # Show trend analysis over time
|
|
6521
|
+
hyntx --detailed-stats --show-clusters # Combine multiple enhancements
|
|
6522
|
+
hyntx --no-embeddings # Disable embeddings (for CI/testing)
|
|
5466
6523
|
`;
|
|
5467
6524
|
console.log(helpText);
|
|
5468
6525
|
process.exit(EXIT_CODES.SUCCESS);
|
|
@@ -5504,11 +6561,11 @@ async function readLogsWithSpinner(args, isJsonMode) {
|
|
|
5504
6561
|
} else {
|
|
5505
6562
|
logger2.error("Claude Code logs directory not found");
|
|
5506
6563
|
process.stderr.write(
|
|
5507
|
-
|
|
6564
|
+
chalk8.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}
|
|
5508
6565
|
`)
|
|
5509
6566
|
);
|
|
5510
6567
|
process.stderr.write(
|
|
5511
|
-
|
|
6568
|
+
chalk8.dim(
|
|
5512
6569
|
"\nMake sure Claude Code is installed and has been used at least once.\n"
|
|
5513
6570
|
)
|
|
5514
6571
|
);
|
|
@@ -5543,9 +6600,9 @@ async function readLogsWithSpinner(args, isJsonMode) {
|
|
|
5543
6600
|
};
|
|
5544
6601
|
console.log(JSON.stringify(errorResponse));
|
|
5545
6602
|
} else {
|
|
5546
|
-
spinner?.fail(
|
|
6603
|
+
spinner?.fail(chalk8.yellow(noDataMessage));
|
|
5547
6604
|
process.stderr.write(
|
|
5548
|
-
|
|
6605
|
+
chalk8.dim(
|
|
5549
6606
|
"\nTry a different date or check that Claude Code has been used recently.\n"
|
|
5550
6607
|
)
|
|
5551
6608
|
);
|
|
@@ -5554,7 +6611,7 @@ async function readLogsWithSpinner(args, isJsonMode) {
|
|
|
5554
6611
|
}
|
|
5555
6612
|
if (!isJsonMode) {
|
|
5556
6613
|
const successMessage = args.from && args.to ? `Found ${String(result.prompts.length)} prompts from ${args.from} to ${args.to}` : `Found ${String(result.prompts.length)} prompts for ${args.date}`;
|
|
5557
|
-
spinner?.succeed(
|
|
6614
|
+
spinner?.succeed(chalk8.green(successMessage));
|
|
5558
6615
|
}
|
|
5559
6616
|
return result;
|
|
5560
6617
|
} catch (error) {
|
|
@@ -5566,7 +6623,7 @@ async function readLogsWithSpinner(args, isJsonMode) {
|
|
|
5566
6623
|
};
|
|
5567
6624
|
console.log(JSON.stringify(errorResponse));
|
|
5568
6625
|
} else {
|
|
5569
|
-
spinner?.fail(
|
|
6626
|
+
spinner?.fail(chalk8.red(`Failed to read logs: ${errorMessage}`));
|
|
5570
6627
|
}
|
|
5571
6628
|
process.exit(EXIT_CODES.ERROR);
|
|
5572
6629
|
}
|
|
@@ -5583,7 +6640,7 @@ async function connectProviderWithSpinner(isJsonMode, analysisMode) {
|
|
|
5583
6640
|
} else {
|
|
5584
6641
|
logger2.error("No providers configured");
|
|
5585
6642
|
process.stderr.write(
|
|
5586
|
-
|
|
6643
|
+
chalk8.dim("\nRun setup to configure at least one provider.\n")
|
|
5587
6644
|
);
|
|
5588
6645
|
}
|
|
5589
6646
|
process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
|
|
@@ -5594,7 +6651,7 @@ async function connectProviderWithSpinner(isJsonMode, analysisMode) {
|
|
|
5594
6651
|
config,
|
|
5595
6652
|
(from, to) => {
|
|
5596
6653
|
if (!isJsonMode && spinner) {
|
|
5597
|
-
spinner.text =
|
|
6654
|
+
spinner.text = chalk8.yellow(
|
|
5598
6655
|
`Primary provider ${from} unavailable, falling back to ${to}...`
|
|
5599
6656
|
);
|
|
5600
6657
|
}
|
|
@@ -5606,7 +6663,7 @@ async function connectProviderWithSpinner(isJsonMode, analysisMode) {
|
|
|
5606
6663
|
analysisMode
|
|
5607
6664
|
);
|
|
5608
6665
|
if (!isJsonMode) {
|
|
5609
|
-
spinner?.succeed(
|
|
6666
|
+
spinner?.succeed(chalk8.green(`Connected to ${provider.name}`));
|
|
5610
6667
|
}
|
|
5611
6668
|
return provider;
|
|
5612
6669
|
} catch (error) {
|
|
@@ -5618,12 +6675,12 @@ async function connectProviderWithSpinner(isJsonMode, analysisMode) {
|
|
|
5618
6675
|
};
|
|
5619
6676
|
console.log(JSON.stringify(errorResponse));
|
|
5620
6677
|
} else {
|
|
5621
|
-
spinner?.fail(
|
|
5622
|
-
process.stderr.write(
|
|
6678
|
+
spinner?.fail(chalk8.red("No providers available"));
|
|
6679
|
+
process.stderr.write(chalk8.dim(`
|
|
5623
6680
|
${errorMessage}
|
|
5624
6681
|
`));
|
|
5625
6682
|
process.stderr.write(
|
|
5626
|
-
|
|
6683
|
+
chalk8.dim(
|
|
5627
6684
|
"\nCheck your provider configuration and ensure at least one provider is running.\n"
|
|
5628
6685
|
)
|
|
5629
6686
|
);
|
|
@@ -5686,7 +6743,7 @@ async function analyzeWithProgress(provider, prompts3, date, context, rules, isJ
|
|
|
5686
6743
|
}
|
|
5687
6744
|
if (!isJsonMode) {
|
|
5688
6745
|
const hitRate = total > 0 && cached > 0 ? ` - ${(cached / total * 100).toFixed(0)}% cached` : "";
|
|
5689
|
-
spinner?.succeed(
|
|
6746
|
+
spinner?.succeed(chalk8.green(`Analysis complete${hitRate}`));
|
|
5690
6747
|
}
|
|
5691
6748
|
return result;
|
|
5692
6749
|
} catch (error) {
|
|
@@ -5698,7 +6755,7 @@ async function analyzeWithProgress(provider, prompts3, date, context, rules, isJ
|
|
|
5698
6755
|
};
|
|
5699
6756
|
console.log(JSON.stringify(errorResponse));
|
|
5700
6757
|
} else {
|
|
5701
|
-
spinner?.fail(
|
|
6758
|
+
spinner?.fail(chalk8.red(`Analysis failed: ${errorMessage}`));
|
|
5702
6759
|
}
|
|
5703
6760
|
process.exit(EXIT_CODES.ERROR);
|
|
5704
6761
|
}
|
|
@@ -5760,23 +6817,23 @@ function generatePromptKey(prompt) {
|
|
|
5760
6817
|
function getSeverityIcon(severity) {
|
|
5761
6818
|
switch (severity) {
|
|
5762
6819
|
case "high":
|
|
5763
|
-
return
|
|
6820
|
+
return chalk8.red("\u26A0\uFE0F");
|
|
5764
6821
|
case "medium":
|
|
5765
|
-
return
|
|
6822
|
+
return chalk8.yellow("\u26A0\uFE0F");
|
|
5766
6823
|
case "low":
|
|
5767
|
-
return
|
|
6824
|
+
return chalk8.blue("\u2139\uFE0F");
|
|
5768
6825
|
}
|
|
5769
6826
|
}
|
|
5770
6827
|
async function runWatchMode(provider, args, context, rules) {
|
|
5771
6828
|
const MAX_ANALYZED = 1e3;
|
|
5772
6829
|
const analyzedPrompts = /* @__PURE__ */ new Map();
|
|
5773
6830
|
console.log("");
|
|
5774
|
-
console.log(
|
|
5775
|
-
console.log(
|
|
6831
|
+
console.log(chalk8.bold.cyan("Watch Mode"));
|
|
6832
|
+
console.log(chalk8.dim("Monitoring Claude Code logs for new prompts..."));
|
|
5776
6833
|
if (args.quiet) {
|
|
5777
|
-
console.log(
|
|
6834
|
+
console.log(chalk8.dim("Quiet mode: showing only high-severity patterns"));
|
|
5778
6835
|
}
|
|
5779
|
-
console.log(
|
|
6836
|
+
console.log(chalk8.dim("Press Ctrl+C to stop"));
|
|
5780
6837
|
console.log("");
|
|
5781
6838
|
const watcher = createLogWatcher({
|
|
5782
6839
|
projectFilter: args.project
|
|
@@ -5859,12 +6916,12 @@ async function runWatchMode(provider, args, context, rules) {
|
|
|
5859
6916
|
for (const pattern of patterns) {
|
|
5860
6917
|
const icon = getSeverityIcon(pattern.severity);
|
|
5861
6918
|
console.log(
|
|
5862
|
-
`[${
|
|
6919
|
+
`[${chalk8.dim(timeStr)}] ${chalk8.cyan(prompt.project)} ${icon} ${pattern.name}`
|
|
5863
6920
|
);
|
|
5864
6921
|
}
|
|
5865
6922
|
} else if (!args.quiet) {
|
|
5866
6923
|
console.log(
|
|
5867
|
-
`[${
|
|
6924
|
+
`[${chalk8.dim(timeStr)}] ${chalk8.cyan(prompt.project)} ${chalk8.green("\u2713")} No issues`
|
|
5868
6925
|
);
|
|
5869
6926
|
}
|
|
5870
6927
|
} catch (error) {
|
|
@@ -5880,12 +6937,29 @@ async function runWatchMode(provider, args, context, rules) {
|
|
|
5880
6937
|
return await new Promise(() => {
|
|
5881
6938
|
});
|
|
5882
6939
|
}
|
|
5883
|
-
function displayResults(result, format2, compact) {
|
|
6940
|
+
function displayResults(result, format2, compact, args) {
|
|
5884
6941
|
if (format2 === "json") {
|
|
5885
6942
|
console.log(formatJson(result, compact));
|
|
5886
6943
|
} else {
|
|
5887
6944
|
console.log("");
|
|
5888
|
-
|
|
6945
|
+
const isEnhanced = args && (args.detailedStats || args.showClusters || args.trendAnalysis);
|
|
6946
|
+
const enhancedResult = result;
|
|
6947
|
+
if (isEnhanced && (enhancedResult.enhancedStats || enhancedResult.clusters || enhancedResult.trend)) {
|
|
6948
|
+
printReport(result);
|
|
6949
|
+
let historicalScores = [];
|
|
6950
|
+
if (enhancedResult.trend && args.trendAnalysis) {
|
|
6951
|
+
const resultWithMeta = enhancedResult;
|
|
6952
|
+
historicalScores = resultWithMeta._historicalScores ?? [];
|
|
6953
|
+
}
|
|
6954
|
+
printEnhancedReport(enhancedResult, {
|
|
6955
|
+
showStats: args.detailedStats,
|
|
6956
|
+
showClusters: args.showClusters,
|
|
6957
|
+
showTrends: args.trendAnalysis,
|
|
6958
|
+
historicalScores
|
|
6959
|
+
});
|
|
6960
|
+
} else {
|
|
6961
|
+
printReport(result);
|
|
6962
|
+
}
|
|
5889
6963
|
}
|
|
5890
6964
|
}
|
|
5891
6965
|
function handleError(error, isJsonMode) {
|
|
@@ -5960,7 +7034,7 @@ async function cli() {
|
|
|
5960
7034
|
JSON.stringify({ success: true, message: "Cache cleared" })
|
|
5961
7035
|
);
|
|
5962
7036
|
} else {
|
|
5963
|
-
spinner?.succeed(
|
|
7037
|
+
spinner?.succeed(chalk8.green("Cache cleared successfully"));
|
|
5964
7038
|
}
|
|
5965
7039
|
process.exit(EXIT_CODES.SUCCESS);
|
|
5966
7040
|
}
|
|
@@ -6033,7 +7107,7 @@ async function cli() {
|
|
|
6033
7107
|
await writeMultiDayJsonOutput(outputPath, results, args.compact);
|
|
6034
7108
|
if (!isJsonMode) {
|
|
6035
7109
|
console.log("");
|
|
6036
|
-
console.log(
|
|
7110
|
+
console.log(chalk8.green(`Results written to ${outputPath}`));
|
|
6037
7111
|
}
|
|
6038
7112
|
} else {
|
|
6039
7113
|
const outputBasePath = args.output;
|
|
@@ -6067,7 +7141,7 @@ async function cli() {
|
|
|
6067
7141
|
writeResults.forEach((r) => {
|
|
6068
7142
|
if (r.status === "fulfilled") {
|
|
6069
7143
|
console.log(
|
|
6070
|
-
|
|
7144
|
+
chalk8.green(`\u2713 ${r.value.date} written to ${r.value.path}`)
|
|
6071
7145
|
);
|
|
6072
7146
|
}
|
|
6073
7147
|
});
|
|
@@ -6082,15 +7156,15 @@ async function cli() {
|
|
|
6082
7156
|
} else {
|
|
6083
7157
|
for (const result of results) {
|
|
6084
7158
|
console.log("");
|
|
6085
|
-
console.log(
|
|
6086
|
-
displayResults(result, "terminal", false);
|
|
7159
|
+
console.log(chalk8.bold.cyan(`Results for ${result.date}`));
|
|
7160
|
+
displayResults(result, "terminal", false, args);
|
|
6087
7161
|
}
|
|
6088
7162
|
}
|
|
6089
7163
|
}
|
|
6090
7164
|
} else {
|
|
6091
7165
|
const prompts3 = logResult.prompts.map((p) => p.content);
|
|
6092
7166
|
const date = args.date;
|
|
6093
|
-
|
|
7167
|
+
let result = await analyzeWithProgress(
|
|
6094
7168
|
provider,
|
|
6095
7169
|
prompts3,
|
|
6096
7170
|
date,
|
|
@@ -6100,6 +7174,55 @@ async function cli() {
|
|
|
6100
7174
|
args.noCache,
|
|
6101
7175
|
logResult.prompts
|
|
6102
7176
|
);
|
|
7177
|
+
const needsEnhancement = args.detailedStats || args.showClusters || args.trendAnalysis;
|
|
7178
|
+
if (needsEnhancement) {
|
|
7179
|
+
if (args.detailedStats || args.showClusters) {
|
|
7180
|
+
const spinner = isJsonMode ? null : ora("Computing enhanced analytics...").start();
|
|
7181
|
+
try {
|
|
7182
|
+
result = await enrichWithStatistics(result, prompts3, {
|
|
7183
|
+
enableDetailedStats: args.detailedStats,
|
|
7184
|
+
enableClustering: args.showClusters && !args.noEmbeddings
|
|
7185
|
+
});
|
|
7186
|
+
spinner?.succeed(chalk8.green("Enhanced analytics complete"));
|
|
7187
|
+
} catch (error) {
|
|
7188
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
7189
|
+
spinner?.fail(
|
|
7190
|
+
chalk8.yellow(`Enhanced analytics failed: ${errorMessage}`)
|
|
7191
|
+
);
|
|
7192
|
+
logger2.warn(`Enhanced analytics failed: ${errorMessage}`);
|
|
7193
|
+
}
|
|
7194
|
+
}
|
|
7195
|
+
if (args.trendAnalysis) {
|
|
7196
|
+
try {
|
|
7197
|
+
const dates = await listAvailableDates();
|
|
7198
|
+
const entries = [];
|
|
7199
|
+
for (const histDate of dates) {
|
|
7200
|
+
const entry = await loadAnalysisResult(histDate);
|
|
7201
|
+
if (entry) {
|
|
7202
|
+
entries.push(entry);
|
|
7203
|
+
}
|
|
7204
|
+
}
|
|
7205
|
+
if (entries.length >= 2) {
|
|
7206
|
+
result = enrichWithTrends(
|
|
7207
|
+
result,
|
|
7208
|
+
entries
|
|
7209
|
+
);
|
|
7210
|
+
const historicalScores = entries.map(
|
|
7211
|
+
(e) => e.result.stats.overallScore
|
|
7212
|
+
);
|
|
7213
|
+
const resultWithMeta = result;
|
|
7214
|
+
resultWithMeta._historicalScores = historicalScores;
|
|
7215
|
+
} else if (!isJsonMode) {
|
|
7216
|
+
logger2.warn(
|
|
7217
|
+
"Not enough historical data for trend analysis (need at least 2 entries)"
|
|
7218
|
+
);
|
|
7219
|
+
}
|
|
7220
|
+
} catch (error) {
|
|
7221
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
7222
|
+
logger2.warn(`Trend analysis failed: ${errorMessage}`);
|
|
7223
|
+
}
|
|
7224
|
+
}
|
|
7225
|
+
}
|
|
6103
7226
|
if (args.output) {
|
|
6104
7227
|
const ext = extname(args.output);
|
|
6105
7228
|
const format2 = ext === ".json" ? "json" : "md";
|
|
@@ -6107,11 +7230,11 @@ async function cli() {
|
|
|
6107
7230
|
await writeOutputFile(outputPath, result, format2, args.compact);
|
|
6108
7231
|
if (!isJsonMode) {
|
|
6109
7232
|
console.log("");
|
|
6110
|
-
console.log(
|
|
7233
|
+
console.log(chalk8.green(`Results written to ${outputPath}`));
|
|
6111
7234
|
}
|
|
6112
7235
|
}
|
|
6113
7236
|
if (!args.output || !isJsonMode) {
|
|
6114
|
-
displayResults(result, args.format, args.compact);
|
|
7237
|
+
displayResults(result, args.format, args.compact, args);
|
|
6115
7238
|
}
|
|
6116
7239
|
if (!args.noHistory) {
|
|
6117
7240
|
const projects = Array.from(
|
|
@@ -6137,7 +7260,7 @@ async function cli() {
|
|
|
6137
7260
|
} else {
|
|
6138
7261
|
logger2.error(`No history found for ${compareDate}`);
|
|
6139
7262
|
process.stderr.write(
|
|
6140
|
-
|
|
7263
|
+
chalk8.dim(
|
|
6141
7264
|
"\nRun analysis for that date first to enable comparison.\n"
|
|
6142
7265
|
)
|
|
6143
7266
|
);
|