@triedotdev/mcp 1.0.59 → 1.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +17 -13
  2. package/dist/{agent-smith-O7RG7WQ3.js → agent-smith-4IJZHSNQ.js} +3 -2
  3. package/dist/{agent-smith-runner-EW4C4PTF.js → agent-smith-runner-4PE3GOUX.js} +5 -3
  4. package/dist/{agent-smith-runner-EW4C4PTF.js.map → agent-smith-runner-4PE3GOUX.js.map} +1 -1
  5. package/dist/{chunk-HUQQSQOD.js → chunk-3XWSM2DU.js} +73 -44
  6. package/dist/chunk-3XWSM2DU.js.map +1 -0
  7. package/dist/{chunk-KLKY34RE.js → chunk-4EHBRED6.js} +139 -12
  8. package/dist/chunk-4EHBRED6.js.map +1 -0
  9. package/dist/{chunk-6ODT4U4O.js → chunk-C7LXN754.js} +539 -194
  10. package/dist/chunk-C7LXN754.js.map +1 -0
  11. package/dist/{chunk-AVOMCNBD.js → chunk-DV3JQTLQ.js} +23 -86
  12. package/dist/chunk-DV3JQTLQ.js.map +1 -0
  13. package/dist/{chunk-3CS6Z2SL.js → chunk-MVUCBUBR.js} +7 -2
  14. package/dist/chunk-MVUCBUBR.js.map +1 -0
  15. package/dist/{chunk-3B2JBLSP.js → chunk-NM7ZVUHO.js} +682 -37
  16. package/dist/chunk-NM7ZVUHO.js.map +1 -0
  17. package/dist/chunk-RAZUNSBI.js +171 -0
  18. package/dist/chunk-RAZUNSBI.js.map +1 -0
  19. package/dist/{chunk-MR755QGT.js → chunk-ULOW5HSH.js} +7 -2
  20. package/dist/chunk-ULOW5HSH.js.map +1 -0
  21. package/dist/cli/main.js +6 -5
  22. package/dist/cli/main.js.map +1 -1
  23. package/dist/cli/yolo-daemon.js +10 -9
  24. package/dist/cli/yolo-daemon.js.map +1 -1
  25. package/dist/index.js +30 -18
  26. package/dist/index.js.map +1 -1
  27. package/dist/{vibe-code-signatures-4CBHUSI7.js → vibe-code-signatures-TGMQXYGO.js} +3 -2
  28. package/dist/{vulnerability-signatures-J3CUQ7VR.js → vulnerability-signatures-GOVD4Q24.js} +3 -2
  29. package/dist/workers/agent-worker.js +4 -3
  30. package/dist/workers/agent-worker.js.map +1 -1
  31. package/package.json +1 -1
  32. package/dist/chunk-3B2JBLSP.js.map +0 -1
  33. package/dist/chunk-3CS6Z2SL.js.map +0 -1
  34. package/dist/chunk-6ODT4U4O.js.map +0 -1
  35. package/dist/chunk-AVOMCNBD.js.map +0 -1
  36. package/dist/chunk-HUQQSQOD.js.map +0 -1
  37. package/dist/chunk-KLKY34RE.js.map +0 -1
  38. package/dist/chunk-MR755QGT.js.map +0 -1
  39. /package/dist/{agent-smith-O7RG7WQ3.js.map → agent-smith-4IJZHSNQ.js.map} +0 -0
  40. /package/dist/{vibe-code-signatures-4CBHUSI7.js.map → vibe-code-signatures-TGMQXYGO.js.map} +0 -0
  41. /package/dist/{vulnerability-signatures-J3CUQ7VR.js.map → vulnerability-signatures-GOVD4Q24.js.map} +0 -0
@@ -6,7 +6,10 @@ import {
6
6
  getRecentIssues,
7
7
  getSkillRegistry,
8
8
  loadContextState
9
- } from "./chunk-HUQQSQOD.js";
9
+ } from "./chunk-3XWSM2DU.js";
10
+ import {
11
+ isInteractiveMode
12
+ } from "./chunk-RAZUNSBI.js";
10
13
 
11
14
  // src/orchestrator/triager.ts
12
15
  var Triager = class {
@@ -103,11 +106,15 @@ var Triager = class {
103
106
  if (this.contextState?.healthScore !== void 0 && this.contextState.healthScore < 50) {
104
107
  if (riskLevel === "low" || riskLevel === "medium") {
105
108
  effectiveRiskLevel = "high";
106
- console.error(` \u{1F4CA} Health score ${this.contextState.healthScore}% - escalating to ${effectiveRiskLevel.toUpperCase()} risk`);
109
+ if (!isInteractiveMode()) {
110
+ console.error(` \u{1F4CA} Health score ${this.contextState.healthScore}% - escalating to ${effectiveRiskLevel.toUpperCase()} risk`);
111
+ }
107
112
  }
108
113
  }
109
114
  if (effectiveRiskLevel === "critical" || effectiveRiskLevel === "high") {
110
- console.error(` \u26A0\uFE0F ${effectiveRiskLevel.toUpperCase()} risk - activating all agents for comprehensive review`);
115
+ if (!isInteractiveMode()) {
116
+ console.error(` \u26A0\uFE0F ${effectiveRiskLevel.toUpperCase()} risk - activating all agents for comprehensive review`);
117
+ }
111
118
  return this.getAllAgents().filter((agent) => agent.shouldActivate(context));
112
119
  }
113
120
  const scores = this.scoreAgents(context, effectiveRiskLevel);
@@ -540,6 +547,7 @@ var Triager = class {
540
547
  return { agent, confidence, reasons, tier, isCustom: false };
541
548
  }
542
549
  logAgentScoring(scores) {
550
+ if (isInteractiveMode()) return;
543
551
  console.error("\n \u{1F4CA} Agent Confidence Scores:");
544
552
  const sorted = [...scores].sort((a, b) => b.confidence - a.confidence);
545
553
  for (const score of sorted) {
@@ -966,7 +974,9 @@ var CacheManager = class {
966
974
  await mkdir(this.cacheDir, { recursive: true });
967
975
  await writeFile(this.indexPath, JSON.stringify(index, null, 2));
968
976
  } catch (error) {
969
- console.warn("Failed to save cache index:", error);
977
+ if (!isInteractiveMode()) {
978
+ console.warn("Failed to save cache index:", error);
979
+ }
970
980
  }
971
981
  }
972
982
  /**
@@ -1037,7 +1047,9 @@ var CacheManager = class {
1037
1047
  const cleanedIndex = this.cleanupExpired(index);
1038
1048
  await this.saveIndex(cleanedIndex);
1039
1049
  } catch (error) {
1040
- console.warn("Failed to cache result:", error);
1050
+ if (!isInteractiveMode()) {
1051
+ console.warn("Failed to cache result:", error);
1052
+ }
1041
1053
  }
1042
1054
  }
1043
1055
  /**
@@ -1094,7 +1106,9 @@ var CacheManager = class {
1094
1106
  };
1095
1107
  await this.saveIndex(emptyIndex);
1096
1108
  } catch (error) {
1097
- console.warn("Failed to clear cache:", error);
1109
+ if (!isInteractiveMode()) {
1110
+ console.warn("Failed to clear cache:", error);
1111
+ }
1098
1112
  }
1099
1113
  }
1100
1114
  };
@@ -1106,7 +1120,9 @@ var Executor = class {
1106
1120
  const cacheEnabled = options?.cacheEnabled ?? true;
1107
1121
  const maxConcurrency = options?.maxConcurrency ?? calculateOptimalConcurrency();
1108
1122
  const useWorkerThreads = options?.useWorkerThreads ?? false;
1109
- console.error(`\u26A1 Executing ${agents.length} agents ${parallel ? "in parallel" : "sequentially"}...`);
1123
+ if (!isInteractiveMode()) {
1124
+ console.error(`\u26A1 Executing ${agents.length} agents ${parallel ? "in parallel" : "sequentially"}...`);
1125
+ }
1110
1126
  if (parallel) {
1111
1127
  const cacheManager = cacheEnabled ? new CacheManager(context.workingDir) : null;
1112
1128
  const executor = new ParallelExecutor(cacheManager, maxConcurrency, {
@@ -1129,10 +1145,14 @@ var Executor = class {
1129
1145
  const results = await Promise.allSettled(promises);
1130
1146
  return results.map((result, index) => {
1131
1147
  if (result.status === "fulfilled") {
1132
- console.error(`\u2705 ${agents[index].name} completed in ${result.value.executionTime}ms`);
1148
+ if (!isInteractiveMode()) {
1149
+ console.error(`\u2705 ${agents[index].name} completed in ${result.value.executionTime}ms`);
1150
+ }
1133
1151
  return result.value;
1134
1152
  } else {
1135
- console.error(`\u274C ${agents[index].name} failed:`, result.reason);
1153
+ if (!isInteractiveMode()) {
1154
+ console.error(`\u274C ${agents[index].name} failed:`, result.reason);
1155
+ }
1136
1156
  return {
1137
1157
  agent: agents[index].name,
1138
1158
  issues: [],
@@ -1143,7 +1163,9 @@ var Executor = class {
1143
1163
  }
1144
1164
  });
1145
1165
  } catch (error) {
1146
- console.error("Executor error:", error);
1166
+ if (!isInteractiveMode()) {
1167
+ console.error("Executor error:", error);
1168
+ }
1147
1169
  return agents.map((agent) => ({
1148
1170
  agent: agent.name,
1149
1171
  issues: [],
@@ -1170,8 +1192,113 @@ var Executor = class {
1170
1192
  }
1171
1193
  };
1172
1194
 
1195
+ // src/agent/git.ts
1196
+ import { execFile } from "child_process";
1197
+ import { existsSync } from "fs";
1198
+ import path from "path";
1199
+ import { promisify } from "util";
1200
+ var execFileAsync = promisify(execFile);
1201
+ async function execGit(args, cwd) {
1202
+ try {
1203
+ const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
1204
+ maxBuffer: 10 * 1024 * 1024
1205
+ });
1206
+ return stdout.trim();
1207
+ } catch (error) {
1208
+ const stderr = error?.stderr?.toString();
1209
+ if (stderr?.includes("not a git repository") || stderr?.includes("does not have any commits")) {
1210
+ return null;
1211
+ }
1212
+ throw error;
1213
+ }
1214
+ }
1215
+ async function ensureRepo(projectPath) {
1216
+ const result = await execGit(["rev-parse", "--is-inside-work-tree"], projectPath);
1217
+ return result === "true";
1218
+ }
1219
+ function parseNameStatus(output) {
1220
+ return output.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
1221
+ const parts = line.split(" ");
1222
+ const status = parts[0] ?? "";
1223
+ const filePath = parts[1] ?? "";
1224
+ const oldPath = parts[2];
1225
+ const change = { status, path: filePath };
1226
+ if (oldPath) change.oldPath = oldPath;
1227
+ return change;
1228
+ }).filter((entry) => entry.path.length > 0);
1229
+ }
1230
+ async function getStagedChanges(projectPath) {
1231
+ const isRepo = await ensureRepo(projectPath);
1232
+ if (!isRepo) return [];
1233
+ const output = await execGit(["diff", "--cached", "--name-status"], projectPath);
1234
+ if (!output) return [];
1235
+ return parseNameStatus(output);
1236
+ }
1237
+ async function getUncommittedChanges(projectPath) {
1238
+ const isRepo = await ensureRepo(projectPath);
1239
+ if (!isRepo) return [];
1240
+ const changes = [];
1241
+ const unstaged = await execGit(["diff", "--name-status"], projectPath);
1242
+ if (unstaged) {
1243
+ changes.push(...parseNameStatus(unstaged));
1244
+ }
1245
+ const untracked = await execGit(["ls-files", "--others", "--exclude-standard"], projectPath);
1246
+ if (untracked) {
1247
+ changes.push(
1248
+ ...untracked.split("\n").map((p) => p.trim()).filter(Boolean).map((p) => ({ status: "??", path: p }))
1249
+ );
1250
+ }
1251
+ return changes;
1252
+ }
1253
+ async function getWorkingTreeDiff(projectPath, stagedOnly = false) {
1254
+ const isRepo = await ensureRepo(projectPath);
1255
+ if (!isRepo) return "";
1256
+ const args = stagedOnly ? ["diff", "--cached", "--unified=3", "--no-color"] : ["diff", "--unified=3", "--no-color"];
1257
+ const diff = await execGit(args, projectPath);
1258
+ return diff ?? "";
1259
+ }
1260
+ async function isGitRepo(projectPath) {
1261
+ const result = await execGit(["rev-parse", "--is-inside-work-tree"], projectPath);
1262
+ return result === "true";
1263
+ }
1264
+ async function getChangedFilesSinceTimestamp(projectPath, timestamp) {
1265
+ const isRepo = await isGitRepo(projectPath);
1266
+ if (!isRepo) return null;
1267
+ try {
1268
+ const sinceDate = new Date(timestamp).toISOString();
1269
+ const committedChanges = await execGit(
1270
+ ["log", `--since=${sinceDate}`, "--name-only", "--pretty=format:"],
1271
+ projectPath
1272
+ );
1273
+ const stagedChanges = await execGit(["diff", "--cached", "--name-only"], projectPath);
1274
+ const unstagedChanges = await execGit(["diff", "--name-only"], projectPath);
1275
+ const untrackedFiles = await execGit(
1276
+ ["ls-files", "--others", "--exclude-standard"],
1277
+ projectPath
1278
+ );
1279
+ const changedFiles = /* @__PURE__ */ new Set();
1280
+ const addFiles = (output) => {
1281
+ if (output) {
1282
+ output.split("\n").map((f) => f.trim()).filter(Boolean).forEach((f) => changedFiles.add(path.join(projectPath, f)));
1283
+ }
1284
+ };
1285
+ addFiles(committedChanges);
1286
+ addFiles(stagedChanges);
1287
+ addFiles(unstagedChanges);
1288
+ addFiles(untrackedFiles);
1289
+ return Array.from(changedFiles);
1290
+ } catch {
1291
+ return null;
1292
+ }
1293
+ }
1294
+
1173
1295
  export {
1174
1296
  Triager,
1175
- Executor
1297
+ Executor,
1298
+ getStagedChanges,
1299
+ getUncommittedChanges,
1300
+ getWorkingTreeDiff,
1301
+ isGitRepo,
1302
+ getChangedFilesSinceTimestamp
1176
1303
  };
1177
- //# sourceMappingURL=chunk-KLKY34RE.js.map
1304
+ //# sourceMappingURL=chunk-4EHBRED6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/orchestrator/triager.ts","../src/utils/parallel-executor.ts","../src/utils/cache-manager.ts","../src/orchestrator/executor.ts","../src/agent/git.ts"],"sourcesContent":["import type { CodeContext, RiskLevel, Agent, TriagingConfig } from '../types/index.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { CustomSkill } from '../skills/built-in/custom-skill.js';\nimport { loadContextState, type ContextState } from '../utils/context-state.js';\nimport { getMemoryStats, getRecentIssues } from '../memory/issue-store.js';\nimport { getHistoricalInsights } from '../memory/compactor.js';\nimport { getGlobalMemoryStats } from '../memory/global-memory.js';\nimport { isInteractiveMode } from '../utils/progress.js';\n\ninterface AgentScore {\n agent: Agent;\n confidence: number;\n reasons: string[];\n tier: number;\n isCustom: boolean;\n}\n\ninterface MemoryInsights {\n issuesByAgent: Record<string, number>;\n recentAgents: Set<string>;\n recurringPatternAgents: Set<string>;\n trend: 'improving' | 'stable' | 'declining' | 'unknown';\n crossProjectAgents: Set<string>;\n}\n\nexport class Triager {\n private agentRegistry = getSkillRegistry();\n private config: TriagingConfig;\n private customSkillsLoaded = false;\n private contextState: ContextState | null = null;\n private memoryInsights: MemoryInsights | null = null;\n\n constructor(config?: Partial<TriagingConfig>) {\n this.config = {\n minConfidence: 0.15,\n maxAgents: 11,\n timeoutMs: 60000,\n enableCostAware: false,\n enableDependencies: true,\n ...config\n };\n }\n\n /**\n * Load previous context state for smart triaging\n */\n private async loadPreviousContext(): Promise<void> {\n if (this.contextState === null) {\n try {\n this.contextState = await loadContextState();\n } catch {\n this.contextState = null;\n }\n }\n }\n\n /**\n * Load memory insights for memory-influenced triaging\n */\n private async loadMemoryInsights(): Promise<void> {\n if (this.memoryInsights !== null) return;\n\n try {\n const [stats, recent, historical, global] = await Promise.all([\n getMemoryStats().catch(() => null),\n getRecentIssues({ limit: 20 }).catch(() => []),\n getHistoricalInsights(process.cwd()).catch(() => null),\n getGlobalMemoryStats().catch(() => null),\n ]);\n\n const recentAgents = new Set<string>();\n for (const issue of recent) {\n recentAgents.add(issue.agent);\n }\n\n const recurringPatternAgents = new Set<string>();\n if (historical?.recurringPatterns) {\n for (const pattern of historical.recurringPatterns) {\n recurringPatternAgents.add(pattern.agent);\n }\n }\n\n const crossProjectAgents = new Set<string>();\n if (global?.patternsByAgent) {\n for (const [agent, count] of Object.entries(global.patternsByAgent)) {\n if (count >= 2) {\n crossProjectAgents.add(agent);\n }\n }\n }\n\n this.memoryInsights = {\n issuesByAgent: stats?.issuesByAgent || {},\n recentAgents,\n recurringPatternAgents,\n trend: historical?.improvementTrend || 'unknown',\n crossProjectAgents,\n };\n } catch {\n this.memoryInsights = {\n issuesByAgent: {},\n recentAgents: new Set(),\n recurringPatternAgents: new Set(),\n trend: 'unknown',\n crossProjectAgents: new Set(),\n };\n }\n }\n\n /**\n * Ensure custom skills are loaded before triaging\n */\n private async ensureCustomSkillsLoaded(): Promise<void> {\n if (!this.customSkillsLoaded) {\n await this.agentRegistry.loadCustomSkills();\n this.customSkillsLoaded = true;\n }\n }\n\n async selectAgents(context: CodeContext, riskLevel: RiskLevel): Promise<Agent[]> {\n // Load custom skills if not already loaded\n await this.ensureCustomSkillsLoaded();\n \n // Load previous context state and memory insights for smart triaging\n await Promise.all([\n this.loadPreviousContext(),\n this.loadMemoryInsights(),\n ]);\n \n // Escalate risk based on previous health score\n let effectiveRiskLevel = riskLevel;\n if (this.contextState?.healthScore !== undefined && this.contextState.healthScore < 50) {\n // Low health score = escalate to high risk\n if (riskLevel === 'low' || riskLevel === 'medium') {\n effectiveRiskLevel = 'high';\n if (!isInteractiveMode()) {\n console.error(` 📊 Health score ${this.contextState.healthScore}% - escalating to ${effectiveRiskLevel.toUpperCase()} risk`);\n }\n }\n }\n \n // HIGH or CRITICAL RISK = ALL AGENTS (except those that explicitly decline)\n if (effectiveRiskLevel === 'critical' || effectiveRiskLevel === 'high') {\n if (!isInteractiveMode()) {\n console.error(` ⚠️ ${effectiveRiskLevel.toUpperCase()} risk - activating all agents for comprehensive review`);\n }\n // Filter out agents that explicitly return false from shouldActivate\n // (e.g., agent-smith, super-reviewer which are manually invoked only)\n return this.getAllAgents().filter(agent => agent.shouldActivate(context));\n }\n\n // Score all agents based on context (with history boost)\n const scores = this.scoreAgents(context, effectiveRiskLevel);\n \n // Boost agents based on context state (last scan) and memory (patterns over time)\n this.boostAgentsWithHistory(scores);\n this.boostAgentsWithMemory(scores);\n \n // Log scoring for transparency\n this.logAgentScoring(scores);\n\n // Filter by confidence threshold\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n\n // Sort by tier (priority) then confidence\n qualified.sort((a, b) => {\n if (a.tier !== b.tier) return a.tier - b.tier;\n return b.confidence - a.confidence;\n });\n\n // Resolve dependencies if enabled\n if (this.config.enableDependencies) {\n return this.resolveDependencies(qualified.map(s => s.agent));\n }\n\n return qualified.map(s => s.agent);\n }\n\n /**\n * Boost confidence for agents that found issues in previous scans\n */\n private boostAgentsWithHistory(scores: AgentScore[]): void {\n if (!this.contextState?.agentStatus) return;\n \n for (const score of scores) {\n const previousRun = this.contextState.agentStatus[score.agent.name];\n if (previousRun?.issuesFound && previousRun.issuesFound > 0) {\n // Boost confidence for agents that found issues before\n const boost = Math.min(0.3, previousRun.issuesFound * 0.05);\n score.confidence = Math.min(1.0, score.confidence + boost);\n score.reasons.push(`found ${previousRun.issuesFound} issues in last scan`);\n }\n }\n }\n\n /**\n * Boost confidence for agents based on memory patterns\n */\n private boostAgentsWithMemory(scores: AgentScore[]): void {\n if (!this.memoryInsights) return;\n\n for (const score of scores) {\n const agentName = score.agent.name;\n \n // Boost if agent has found many issues historically\n const historicalCount = this.memoryInsights.issuesByAgent[agentName] || 0;\n if (historicalCount >= 10) {\n const boost = Math.min(0.2, historicalCount * 0.01);\n score.confidence = Math.min(1.0, score.confidence + boost);\n score.reasons.push(`${historicalCount} historical issues`);\n }\n\n // Boost if agent found issues recently\n if (this.memoryInsights.recentAgents.has(agentName)) {\n score.confidence = Math.min(1.0, score.confidence + 0.1);\n score.reasons.push('recent activity');\n }\n\n // Boost if agent has recurring patterns (persistent problems)\n if (this.memoryInsights.recurringPatternAgents.has(agentName)) {\n score.confidence = Math.min(1.0, score.confidence + 0.15);\n score.reasons.push('recurring patterns');\n }\n\n // Boost if this agent type has cross-project patterns\n if (this.memoryInsights.crossProjectAgents.has(agentName)) {\n score.confidence = Math.min(1.0, score.confidence + 0.1);\n score.reasons.push('cross-project pattern');\n }\n }\n\n // If codebase is declining, boost all agents slightly\n if (this.memoryInsights.trend === 'declining') {\n for (const score of scores) {\n if (score.confidence > 0) {\n score.confidence = Math.min(1.0, score.confidence + 0.05);\n }\n }\n }\n }\n\n private scoreAgents(context: CodeContext, riskLevel: RiskLevel): AgentScore[] {\n const allAgents = this.getAllAgents();\n const scores: AgentScore[] = [];\n\n for (const agent of allAgents) {\n const score = this.scoreAgent(agent, context, riskLevel);\n scores.push(score);\n }\n\n return scores;\n }\n\n private scoreAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n // Check if this is a custom skill\n if (agent instanceof CustomSkill) {\n return this.scoreCustomSkill(agent, context, riskLevel);\n }\n \n // Built-in agent scoring\n return this.scoreBuiltinAgent(agent, context, riskLevel);\n }\n\n /**\n * Score custom skills using their activation rules\n */\n private scoreCustomSkill(agent: CustomSkill, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n \n // Use the agent's built-in activation confidence\n let confidence = agent.getActivationConfidence(context);\n \n if (confidence > 0) {\n reasons.push(`custom skill: ${agent.getMetadata().category}`);\n \n // Add metadata info\n const meta = agent.getMetadata();\n if (meta.patternCount > 0) {\n reasons.push(`${meta.patternCount} detection patterns`);\n }\n }\n \n // Risk escalation for custom skills too\n if (riskLevel === 'high' && confidence > 0) {\n confidence = Math.min(1.0, confidence * 1.2);\n }\n \n return {\n agent,\n confidence,\n reasons,\n tier: agent.priority.tier,\n isCustom: true,\n };\n }\n\n /**\n * Score built-in agents\n */\n private scoreBuiltinAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n let confidence = 0;\n let tier = 3; // default to lowest tier\n\n // TIER 1: ALWAYS RUN AGENTS\n if (agent.name === 'typecheck') {\n tier = 1;\n confidence = 1.0;\n reasons.push('fundamental type safety');\n }\n\n if (agent.name === 'comprehension') {\n tier = 1;\n confidence = 1.0;\n reasons.push('stakeholder communication');\n }\n\n // TIER 2: CONTEXT-DEPENDENT AGENTS\n if (agent.name === 'security') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('auth code'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payment code'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('database access'); }\n if (context.touchesCrypto) { confidence += 0.35; reasons.push('cryptographic operations'); }\n if (context.touchesUserData) { confidence += 0.3; reasons.push('user data'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesThirdPartyAPI) { confidence += 0.2; reasons.push('third-party integration'); }\n if (context.patterns?.hasFileUploads) { confidence += 0.3; reasons.push('file uploads'); }\n \n // Risk escalation\n if (riskLevel === 'high') confidence *= 1.2;\n }\n\n if (agent.name === 'privacy') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.5; reasons.push('PII handling'); }\n if (context.touchesAuth) { confidence += 0.3; reasons.push('credentials'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging (may expose data)'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.3; reasons.push('email handling'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form data'); }\n }\n\n if (agent.name === 'legal') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.4; reasons.push('GDPR/CCPA'); }\n if (context.touchesPayments) { confidence += 0.35; reasons.push('PCI-DSS'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.25; reasons.push('CAN-SPAM'); }\n }\n\n if (agent.name === 'accessibility') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.6; reasons.push('UI components'); }\n if (context.framework === 'react' || context.framework === 'vue') { \n confidence += 0.2; \n reasons.push(`${context.framework} framework`); \n }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form UX'); }\n }\n\n if (agent.name === 'test') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.4; reasons.push('new feature'); }\n if (context.touchesAuth) { confidence += 0.35; reasons.push('auth needs tests'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payments need tests'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API testing'); }\n if (!context.hasTests) { confidence += 0.2; reasons.push('no existing tests'); }\n if (context.complexity === 'high') { confidence += 0.25; reasons.push('complex code'); }\n }\n\n if (agent.name === 'software-architect') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.35; reasons.push('architecture review'); }\n if (context.touchesDatabase) { confidence += 0.35; reasons.push('data modeling'); }\n if (context.linesChanged > 200) { confidence += 0.3; reasons.push('large change'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API design'); }\n if (context.patterns?.hasWebSockets) { confidence += 0.3; reasons.push('real-time architecture'); }\n if (context.patterns?.hasQueue) { confidence += 0.3; reasons.push('async architecture'); }\n }\n\n if (agent.name === 'devops') {\n tier = 2;\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesFileSystem) { confidence += 0.3; reasons.push('file operations'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging'); }\n if (context.touchesErrorHandling) { confidence += 0.2; reasons.push('error handling'); }\n if (context.patterns?.hasCaching) { confidence += 0.25; reasons.push('caching'); }\n if (context.patterns?.hasRateLimiting) { confidence += 0.3; reasons.push('rate limiting'); }\n }\n\n if (agent.name === 'bug-finding') {\n tier = 2;\n if (context.touchesPayments) { confidence += 0.5; reasons.push('payments = zero bugs'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new code'); }\n if (context.patterns?.hasAsyncCode) { confidence += 0.35; reasons.push('async patterns'); }\n if (context.complexity === 'high') { confidence += 0.3; reasons.push('complex logic'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('data mutations'); }\n }\n\n if (agent.name === 'user-testing') {\n tier = 3; // lower priority - only when clearly needed\n if (context.touchesUI) { confidence += 0.5; reasons.push('UI changes'); }\n if (context.isNewFeature && context.touchesUI) { confidence += 0.3; reasons.push('new UI feature'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.25; reasons.push('form UX'); }\n }\n \n if (agent.name === 'trie_clean') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.4; reasons.push('UI code'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new feature'); }\n if (context.framework === 'react') { confidence += 0.2; reasons.push('React code'); }\n }\n\n if (agent.name === 'soc2') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('authentication'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesLogging) { confidence += 0.3; reasons.push('logging'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.2; reasons.push('data access'); }\n }\n\n if (agent.name === 'moneybags') {\n tier = 3; // Runs after primary agents\n if (context.touchesPayments) { confidence += 0.6; reasons.push('payment code = high cost risk'); }\n if (context.touchesAuth) { confidence += 0.4; reasons.push('auth bugs are expensive'); }\n if (context.touchesHealthData) { confidence += 0.5; reasons.push('HIPAA violations'); }\n if (context.touchesUserData) { confidence += 0.3; reasons.push('PII exposure costs'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('data loss risk'); }\n if (context.isNewFeature) { confidence += 0.2; reasons.push('new code risk'); }\n \n // Only activate if there's significant risk\n if (riskLevel === 'high' || riskLevel === 'critical') {\n confidence *= 1.3;\n reasons.push('high-stakes context');\n }\n }\n\n if (agent.name === 'production-ready') {\n tier = 3; // Final gate before shipping\n if (context.touchesAPI) { confidence += 0.4; reasons.push('API deployment'); }\n if (context.touchesDatabase) { confidence += 0.35; reasons.push('database operations'); }\n if (context.touchesAuth) { confidence += 0.35; reasons.push('auth system'); }\n if (context.touchesPayments) { confidence += 0.5; reasons.push('payment processing'); }\n if (context.linesChanged > 200) { confidence += 0.3; reasons.push('significant changes'); }\n \n // Always run on high/critical risk\n if (riskLevel === 'high' || riskLevel === 'critical') {\n confidence += 0.4;\n reasons.push('production gate check');\n }\n }\n\n // Cap confidence at 1.0\n confidence = Math.min(1.0, confidence);\n\n return { agent, confidence, reasons, tier, isCustom: false };\n }\n\n private logAgentScoring(scores: AgentScore[]): void {\n if (isInteractiveMode()) return;\n \n console.error('\\n 📊 Agent Confidence Scores:');\n \n const sorted = [...scores].sort((a, b) => b.confidence - a.confidence);\n \n for (const score of sorted) {\n const bar = this.getConfidenceBar(score.confidence);\n const status = score.confidence >= this.config.minConfidence ? '✓' : '✗';\n const tierLabel = score.tier === 1 ? '[T1]' : score.tier === 2 ? '[T2]' : '[T3]';\n const customLabel = score.isCustom ? ' 📚' : '';\n \n console.error(` ${status} ${score.agent.name.padEnd(18)} ${tierLabel} ${bar} ${(score.confidence * 100).toFixed(0)}%${customLabel}`);\n \n if (score.reasons.length > 0 && score.confidence > 0) {\n console.error(` └─ ${score.reasons.join(', ')}`);\n }\n }\n console.error('');\n }\n\n private getConfidenceBar(confidence: number): string {\n const filled = Math.round(confidence * 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private resolveDependencies(agents: Agent[]): Agent[] {\n const agentNames = new Set(agents.map(a => a.name));\n const resolved: Agent[] = [];\n const added = new Set<string>();\n\n // Define dependencies\n const dependencies: Record<string, string[]> = {\n 'legal': ['privacy'], // legal should see privacy issues first\n 'test': ['bug-finding'], // find bugs before writing tests\n 'user-testing': ['accessibility'], // accessibility before UX\n };\n\n // Add dependencies first\n for (const agent of agents) {\n const deps = dependencies[agent.name] || [];\n for (const depName of deps) {\n if (!added.has(depName)) {\n const depAgent = this.agentRegistry.getAgent(depName);\n if (depAgent && agentNames.has(depName)) {\n resolved.push(depAgent);\n added.add(depName);\n }\n }\n }\n \n if (!added.has(agent.name)) {\n resolved.push(agent);\n added.add(agent.name);\n }\n }\n\n return resolved;\n }\n\n getTriagingReason(context: CodeContext, riskLevel: RiskLevel): string {\n if (riskLevel === 'critical') {\n return 'Critical risk detected - activating all agents for comprehensive review';\n }\n\n const reasons: string[] = [];\n\n if (context.touchesAuth) reasons.push('authentication');\n if (context.touchesPayments) reasons.push('payments');\n if (context.touchesDatabase) reasons.push('database');\n if (context.touchesUserData) reasons.push('user data');\n if (context.touchesUI) reasons.push('UI');\n if (context.touchesAPI) reasons.push('API');\n if (context.isNewFeature) reasons.push('new feature');\n if (context.touchesCrypto) reasons.push('cryptography');\n if (context.touchesThirdPartyAPI) reasons.push('3rd party API');\n\n if (reasons.length === 0) {\n return `${riskLevel} risk - general code changes`;\n }\n\n return `${riskLevel} risk: ${reasons.join(', ')}`;\n }\n\n async getSkippedAgents(context: CodeContext, riskLevel: RiskLevel): Promise<string[]> {\n await this.ensureCustomSkillsLoaded();\n \n if (riskLevel === 'critical') return [];\n\n const scores = this.scoreAgents(context, riskLevel);\n return scores\n .filter(s => s.confidence < this.config.minConfidence)\n .map(s => s.agent.name);\n }\n\n async getTriagingConfidence(context: CodeContext, riskLevel: RiskLevel): Promise<number> {\n await this.ensureCustomSkillsLoaded();\n \n // How confident are we in our triaging decision?\n const scores = this.scoreAgents(context, riskLevel);\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n \n if (qualified.length === 0) return 0.5; // uncertain\n \n // Average confidence of selected agents\n const avgConfidence = qualified.reduce((sum, s) => sum + s.confidence, 0) / qualified.length;\n \n // Boost if we have strong context signals\n const contextStrength = this.getContextStrength(context);\n \n return Math.min(1.0, avgConfidence * 0.7 + contextStrength * 0.3);\n }\n\n private getContextStrength(context: CodeContext): number {\n let signals = 0;\n\n // Count how many context signals we detected\n const checks = [\n context.touchesAuth,\n context.touchesPayments,\n context.touchesDatabase,\n context.touchesAPI,\n context.touchesUI,\n context.touchesUserData,\n context.touchesHealthData,\n context.touchesSecurityConfig,\n context.touchesCrypto,\n context.touchesFileSystem,\n context.isNewFeature,\n ];\n\n for (const check of checks) {\n if (check) signals++;\n }\n\n // More signals = more confidence in triaging\n return signals > 0 ? Math.min(1.0, signals / 3) : 0.3;\n }\n\n private getAllAgents(): Agent[] {\n return this.agentRegistry.getAllAgents();\n }\n \n /**\n * Get custom skills count\n */\n getCustomSkillCount(): number {\n return this.agentRegistry.getCustomSkills().length;\n }\n\n // Backward compatibility alias\n getCustomAgentCount(): number {\n return this.getCustomSkillCount();\n }\n \n /**\n * Reload custom skills\n */\n async reloadCustomSkills(): Promise<void> {\n await this.agentRegistry.reloadCustomSkills();\n }\n\n // Backward compatibility alias\n async reloadCustomAgents(): Promise<void> {\n return this.reloadCustomSkills();\n }\n}\n","import { Worker } from 'worker_threads';\nimport { cpus } from 'os';\nimport type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { StreamingManager } from './streaming.js';\nimport { CacheManager } from './cache-manager.js';\n\ninterface ParallelTask {\n agent: Agent;\n files: string[];\n context: ScanContext;\n priority: number;\n timeoutMs: number;\n}\n\ninterface ParallelResult {\n agent: string;\n result: AgentResult;\n fromCache: boolean;\n executionTime: number;\n}\n\n/**\n * Parallel execution engine for Trie agents\n *\n * Features:\n * - True parallel execution using worker threads\n * - Intelligent scheduling based on agent priority\n * - Result caching and cache-aware scheduling\n * - Real-time progress streaming\n * - Dynamic resource management\n */\nexport class ParallelExecutor {\n private maxWorkers: number;\n private cache: CacheManager | null;\n private streaming?: StreamingManager;\n private activeWorkers: Set<Worker> = new Set();\n private cacheEnabled: boolean = true;\n private useWorkerThreads: boolean = false;\n\n constructor(\n cacheManager: CacheManager | null,\n maxWorkers: number = Math.max(2, Math.min(cpus().length - 1, 8)),\n options?: { cacheEnabled?: boolean; useWorkerThreads?: boolean }\n ) {\n this.maxWorkers = maxWorkers;\n this.cache = cacheManager;\n this.cacheEnabled = options?.cacheEnabled ?? true;\n this.useWorkerThreads = options?.useWorkerThreads ?? false;\n }\n\n /**\n * Set streaming manager for real-time updates\n */\n setStreaming(streaming: StreamingManager): void {\n this.streaming = streaming;\n }\n\n /**\n * Execute agents in parallel with intelligent scheduling\n */\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext\n ): Promise<Map<string, AgentResult>> {\n if (agents.length === 0) {\n return new Map();\n }\n\n // Initialize streaming\n if (this.streaming && this.streaming.getProgress().totalFiles === 0) {\n this.streaming.startScan(files.length);\n }\n\n // Check cache for existing results\n const cacheResults = new Map<string, AgentResult>();\n const uncachedTasks: ParallelTask[] = [];\n\n for (const agent of agents) {\n const cached = await this.checkAgentCache(agent, files);\n if (cached) {\n cacheResults.set(agent.name, cached);\n this.streaming?.completeAgent(agent.name, cached.issues);\n } else {\n uncachedTasks.push({\n agent,\n files,\n context,\n priority: agent.priority?.tier || 2,\n timeoutMs: context?.config?.timeoutMs || 120000\n });\n }\n }\n\n // Sort tasks by priority (tier 1 = highest priority)\n uncachedTasks.sort((a, b) => a.priority - b.priority);\n\n // Execute uncached tasks in parallel\n const parallelResults = await this.executeTasksParallel(uncachedTasks);\n\n // Cache new results\n await this.cacheResults(parallelResults);\n\n // Combine cached and new results\n const allResults = new Map<string, AgentResult>();\n\n // Add cached results\n for (const [agent, result] of cacheResults) {\n allResults.set(agent, result);\n }\n\n // Add new results\n for (const result of parallelResults) {\n allResults.set(result.agent, result.result);\n }\n\n // Complete streaming\n const allIssues = Array.from(allResults.values()).flatMap(r => r.issues);\n this.streaming?.completeScan(allIssues);\n\n return allResults;\n }\n\n /**\n * Check if agent has cached results for given files\n */\n private async checkAgentCache(agent: Agent, files: string[]): Promise<AgentResult | null> {\n if (!this.cacheEnabled || !this.cache) {\n return null;\n }\n\n const cachedIssues = await this.cache.getCachedBatch(files, agent.name);\n\n // Only use cache if we have results for ALL files\n if (cachedIssues.size === files.length) {\n const allIssues = Array.from(cachedIssues.values()).flat();\n return {\n agent: agent.name,\n issues: allIssues,\n executionTime: 0, // Cached\n success: true,\n metadata: {\n filesAnalyzed: files.length,\n linesAnalyzed: 0\n }\n };\n }\n\n return null;\n }\n\n /**\n * Execute tasks in parallel batches\n */\n private async executeTasksParallel(tasks: ParallelTask[]): Promise<ParallelResult[]> {\n if (tasks.length === 0) {\n return [];\n }\n\n const results: ParallelResult[] = [];\n const batches = this.createBatches(tasks, this.maxWorkers);\n\n for (const batch of batches) {\n const batchResults = await Promise.all(\n batch.map(task => this.executeTask(task))\n );\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Create batches for parallel execution\n */\n private createBatches(tasks: ParallelTask[], batchSize: number): ParallelTask[][] {\n const batches: ParallelTask[][] = [];\n\n for (let i = 0; i < tasks.length; i += batchSize) {\n batches.push(tasks.slice(i, i + batchSize));\n }\n\n return batches;\n }\n\n /**\n * Execute a single task\n */\n private async executeTask(task: ParallelTask): Promise<ParallelResult> {\n const startTime = Date.now();\n\n this.streaming?.startAgent(task.agent.name);\n\n try {\n const result = this.useWorkerThreads\n ? await this.executeTaskInWorker(task)\n : await task.agent.scan(task.files, task.context);\n const executionTime = Date.now() - startTime;\n\n this.streaming?.completeAgent(task.agent.name, result.issues);\n\n return {\n agent: task.agent.name,\n result,\n fromCache: false,\n executionTime\n };\n } catch (error) {\n const executionTime = Date.now() - startTime;\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n this.streaming?.reportError(new Error(errorMessage), `Agent: ${task.agent.name}`);\n\n return {\n agent: task.agent.name,\n result: {\n agent: task.agent.name,\n issues: [],\n executionTime,\n success: false,\n error: errorMessage\n },\n fromCache: false,\n executionTime\n };\n }\n }\n\n private async executeTaskInWorker(task: ParallelTask): Promise<AgentResult> {\n // Use dirname to get the dist folder, then resolve to workers subfolder\n // This works whether the code is bundled into chunks or in utils/ folder\n const distDir = new URL('.', import.meta.url);\n const workerUrl = new URL('workers/agent-worker.js', distDir);\n\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerUrl, {\n workerData: {\n agentName: task.agent.name,\n files: task.files,\n context: task.context\n }\n } as ConstructorParameters<typeof Worker>[1]);\n\n this.activeWorkers.add(worker);\n\n const timeout = setTimeout(() => {\n worker.terminate().catch(() => undefined);\n reject(new Error(`Agent ${task.agent.name} timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n worker.on('message', (message) => {\n if (message?.type === 'result') {\n clearTimeout(timeout);\n resolve(message.result as AgentResult);\n } else if (message?.type === 'error') {\n clearTimeout(timeout);\n reject(new Error(message.error));\n }\n });\n\n worker.on('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n\n worker.on('exit', (code) => {\n this.activeWorkers.delete(worker);\n if (code !== 0) {\n clearTimeout(timeout);\n reject(new Error(`Worker stopped with exit code ${code}`));\n }\n });\n });\n }\n\n /**\n * Cache results for future use\n */\n private async cacheResults(results: ParallelResult[]): Promise<void> {\n if (!this.cacheEnabled || !this.cache) {\n return;\n }\n\n const cachePromises = results\n .filter(r => r.result.success && !r.fromCache)\n .map(r => {\n const issuesByFile = this.groupIssuesByFile(r.result.issues);\n const perFilePromises = Object.entries(issuesByFile).map(([file, issues]) =>\n this.cache!.setCached(file, r.agent, issues, r.executionTime)\n );\n return Promise.all(perFilePromises);\n });\n\n await Promise.allSettled(cachePromises);\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n // Terminate any active workers\n const terminationPromises = Array.from(this.activeWorkers).map(worker =>\n worker.terminate()\n );\n\n await Promise.allSettled(terminationPromises);\n this.activeWorkers.clear();\n }\n\n private groupIssuesByFile(issues: AgentResult['issues']): Record<string, AgentResult['issues']> {\n const grouped: Record<string, AgentResult['issues']> = {};\n\n for (const issue of issues) {\n if (!grouped[issue.file]) {\n grouped[issue.file] = [];\n }\n grouped[issue.file]!.push(issue);\n }\n\n return grouped;\n }\n}\n\n/**\n * Smart agent prioritization based on dependencies and execution characteristics\n */\nexport function prioritizeAgents(agents: Agent[]): Agent[] {\n const prioritized = [...agents];\n\n // Sort by priority tier, then by estimated execution time\n prioritized.sort((a, b) => {\n const aTier = a.priority?.tier || 2;\n const bTier = b.priority?.tier || 2;\n\n if (aTier !== bTier) {\n return aTier - bTier; // Lower tier = higher priority\n }\n\n // Within same tier, prioritize faster agents\n const aTime = a.priority?.estimatedTimeMs || 1000;\n const bTime = b.priority?.estimatedTimeMs || 1000;\n\n return aTime - bTime;\n });\n\n return prioritized;\n}\n\n/**\n * Calculate optimal concurrency based on system resources and agent characteristics\n */\nexport function calculateOptimalConcurrency(): number {\n const numCPUs = cpus().length;\n const availableMemoryGB = process.memoryUsage().rss / 1024 / 1024 / 1024;\n\n // Conservative concurrency for stability\n let optimal = Math.max(2, Math.min(numCPUs - 1, 8));\n\n // Reduce concurrency if low memory\n if (availableMemoryGB < 2) {\n optimal = Math.max(2, Math.floor(optimal / 2));\n }\n\n // Increase slightly for systems with lots of CPU cores\n if (numCPUs > 8) {\n optimal = Math.min(optimal + 2, 12);\n }\n\n return optimal;\n}","import { readFile, writeFile, mkdir, stat } from 'fs/promises';\nimport { join } from 'path';\nimport { createHash } from 'crypto';\nimport type { Issue } from '../types/index.js';\nimport { isInteractiveMode } from './progress.js';\n\ninterface CacheEntry {\n version: string;\n timestamp: number;\n fileHash: string;\n fileSize: number;\n agent: string;\n issues: Issue[];\n executionTime: number;\n}\n\ninterface CacheIndex {\n version: string;\n created: number;\n entries: Record<string, CacheEntry>;\n}\n\nexport class CacheManager {\n private cacheDir: string;\n private indexPath: string;\n private readonly VERSION = '1.0.0';\n private readonly MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours\n private readonly MAX_ENTRIES = 1000;\n\n constructor(baseDir: string) {\n this.cacheDir = join(baseDir, '.trie', 'cache');\n this.indexPath = join(this.cacheDir, 'index.json');\n }\n\n /**\n * Generate cache key for a file and agent combination\n */\n private generateCacheKey(filePath: string, agent: string, fileHash: string): string {\n const key = `${filePath}:${agent}:${fileHash}`;\n return createHash('sha256').update(key).digest('hex').slice(0, 16);\n }\n\n /**\n * Get file hash for cache validation\n */\n private async getFileHash(filePath: string): Promise<{ hash: string; size: number; mtime: number }> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const stats = await stat(filePath);\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 16);\n return {\n hash,\n size: stats.size,\n mtime: stats.mtime.getTime()\n };\n } catch {\n return { hash: '', size: 0, mtime: 0 };\n }\n }\n\n /**\n * Load cache index\n */\n private async loadIndex(): Promise<CacheIndex> {\n try {\n const content = await readFile(this.indexPath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n }\n }\n\n /**\n * Save cache index\n */\n private async saveIndex(index: CacheIndex): Promise<void> {\n try {\n await mkdir(this.cacheDir, { recursive: true });\n await writeFile(this.indexPath, JSON.stringify(index, null, 2));\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to save cache index:', error);\n }\n }\n }\n\n /**\n * Clean up expired entries\n */\n private cleanupExpired(index: CacheIndex): CacheIndex {\n const now = Date.now();\n const validEntries: Record<string, CacheEntry> = {};\n\n for (const [key, entry] of Object.entries(index.entries)) {\n if (now - entry.timestamp < this.MAX_AGE_MS) {\n validEntries[key] = entry;\n }\n }\n\n // If still too many, keep the most recent ones\n const entries = Object.entries(validEntries);\n if (entries.length > this.MAX_ENTRIES) {\n entries.sort((a, b) => b[1].timestamp - a[1].timestamp);\n const limited = entries.slice(0, this.MAX_ENTRIES);\n return {\n ...index,\n entries: Object.fromEntries(limited)\n };\n }\n\n return {\n ...index,\n entries: validEntries\n };\n }\n\n /**\n * Get cached result for a file and agent\n */\n async getCached(filePath: string, agent: string): Promise<Issue[] | null> {\n try {\n const { hash, size: _size, mtime: _mtime } = await this.getFileHash(filePath);\n if (!hash) return null;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n const entry = index.entries[cacheKey];\n\n if (!entry) return null;\n\n // Validate entry is still fresh\n const isValid = entry.fileHash === hash &&\n entry.version === this.VERSION &&\n (Date.now() - entry.timestamp) < this.MAX_AGE_MS;\n\n if (!isValid) {\n delete index.entries[cacheKey];\n await this.saveIndex(index);\n return null;\n }\n\n return entry.issues;\n } catch {\n return null;\n }\n }\n\n /**\n * Cache result for a file and agent\n */\n async setCached(\n filePath: string,\n agent: string,\n issues: Issue[],\n executionTime: number\n ): Promise<void> {\n try {\n const { hash, size } = await this.getFileHash(filePath);\n if (!hash) return;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n\n index.entries[cacheKey] = {\n version: this.VERSION,\n timestamp: Date.now(),\n fileHash: hash,\n fileSize: size,\n agent,\n issues,\n executionTime\n };\n\n // Clean up old entries\n const cleanedIndex = this.cleanupExpired(index);\n await this.saveIndex(cleanedIndex);\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to cache result:', error);\n }\n }\n }\n\n /**\n * Check if multiple files have cached results\n */\n async getCachedBatch(files: string[], agent: string): Promise<Map<string, Issue[]>> {\n const results = new Map<string, Issue[]>();\n\n await Promise.all(\n files.map(async (file) => {\n const cached = await this.getCached(file, agent);\n if (cached) {\n results.set(file, cached);\n }\n })\n );\n\n return results;\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n totalEntries: number;\n totalSizeKB: number;\n oldestEntry: number | null;\n newestEntry: number | null;\n agents: string[];\n hitRate?: number;\n }> {\n try {\n const index = await this.loadIndex();\n const entries = Object.values(index.entries);\n\n const totalSizeKB = entries.reduce((acc, entry) => acc + entry.fileSize, 0) / 1024;\n const timestamps = entries.map(e => e.timestamp);\n const agents = [...new Set(entries.map(e => e.agent))];\n\n return {\n totalEntries: entries.length,\n totalSizeKB: Math.round(totalSizeKB),\n oldestEntry: timestamps.length > 0 ? Math.min(...timestamps) : null,\n newestEntry: timestamps.length > 0 ? Math.max(...timestamps) : null,\n agents\n };\n } catch {\n return {\n totalEntries: 0,\n totalSizeKB: 0,\n oldestEntry: null,\n newestEntry: null,\n agents: []\n };\n }\n }\n\n /**\n * Clear all cache\n */\n async clear(): Promise<void> {\n try {\n const emptyIndex: CacheIndex = {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n await this.saveIndex(emptyIndex);\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to clear cache:', error);\n }\n }\n }\n}","import type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { ParallelExecutor, calculateOptimalConcurrency } from '../utils/parallel-executor.js';\nimport { CacheManager } from '../utils/cache-manager.js';\nimport type { StreamingManager } from '../utils/streaming.js';\nimport { isInteractiveMode } from '../utils/progress.js';\n\nexport class Executor {\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext,\n options?: {\n streaming?: StreamingManager;\n parallel?: boolean;\n cacheEnabled?: boolean;\n maxConcurrency?: number;\n useWorkerThreads?: boolean;\n timeoutMs?: number;\n }\n ): Promise<AgentResult[]> {\n const parallel = options?.parallel ?? true;\n const cacheEnabled = options?.cacheEnabled ?? true;\n const maxConcurrency = options?.maxConcurrency ?? calculateOptimalConcurrency();\n const useWorkerThreads = options?.useWorkerThreads ?? false;\n\n if (!isInteractiveMode()) {\n console.error(`⚡ Executing ${agents.length} agents ${parallel ? 'in parallel' : 'sequentially'}...`);\n }\n\n if (parallel) {\n const cacheManager = cacheEnabled ? new CacheManager(context.workingDir) : null;\n const executor = new ParallelExecutor(cacheManager, maxConcurrency, {\n cacheEnabled,\n useWorkerThreads\n });\n\n if (options?.streaming) {\n executor.setStreaming(options.streaming);\n }\n\n const results = await executor.executeAgents(agents, files, {\n ...context,\n config: { timeoutMs: options?.timeoutMs ?? 120000 }\n });\n\n return agents.map(agent => results.get(agent.name)!).filter(Boolean);\n }\n\n // Execute agents in parallel with timeout\n const promises = agents.map(agent =>\n this.executeAgentWithTimeout(agent, files, context, options?.timeoutMs ?? 30000)\n );\n\n try {\n const results = await Promise.allSettled(promises);\n return results.map((result, index) => {\n if (result.status === 'fulfilled') {\n if (!isInteractiveMode()) {\n console.error(`✅ ${agents[index]!.name} completed in ${result.value.executionTime}ms`);\n }\n return result.value;\n } else {\n if (!isInteractiveMode()) {\n console.error(`❌ ${agents[index]!.name} failed:`, result.reason);\n }\n return {\n agent: agents[index]!.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: result.reason instanceof Error ? result.reason.message : String(result.reason)\n };\n }\n });\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error('Executor error:', error);\n }\n return agents.map(agent => ({\n agent: agent.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: 'Execution failed'\n }));\n }\n }\n\n private async executeAgentWithTimeout(\n agent: Agent,\n files: string[],\n context: ScanContext,\n timeoutMs: number = 30000 // 30 second timeout\n ): Promise<AgentResult> {\n return new Promise(async (resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Agent ${agent.name} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n try {\n const result = await agent.scan(files, context);\n clearTimeout(timeout);\n resolve(result);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n }\n });\n }\n}","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface Commit {\n hash: string;\n author: string;\n date: string;\n message: string;\n}\n\nexport interface Change {\n path: string;\n status: string;\n oldPath?: string;\n}\n\nasync function execGit(args: string[], cwd: string): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync('git', ['-C', cwd, ...args], {\n maxBuffer: 10 * 1024 * 1024\n });\n return stdout.trim();\n } catch (error: any) {\n const stderr: string | undefined = error?.stderr?.toString();\n // Gracefully handle non-git directories and repos with no commits\n if (stderr?.includes('not a git repository') || stderr?.includes('does not have any commits')) {\n return null;\n }\n throw error;\n }\n}\n\nasync function ensureRepo(projectPath: string): Promise<boolean> {\n const result = await execGit(['rev-parse', '--is-inside-work-tree'], projectPath);\n return result === 'true';\n}\n\nfunction parseNameStatus(output: string): Change[] {\n return output\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => {\n const parts = line.split('\\t');\n const status = parts[0] ?? '';\n const filePath = parts[1] ?? '';\n const oldPath = parts[2];\n const change: Change = { status, path: filePath };\n if (oldPath) change.oldPath = oldPath;\n return change;\n })\n .filter((entry) => entry.path.length > 0);\n}\n\nexport async function getRecentCommits(projectPath: string, limit: number): Promise<Commit[]> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return [];\n\n const output = await execGit(\n ['log', `-n`, String(limit), '--pretty=format:%H%x09%an%x09%ad%x09%s', '--date=iso'],\n projectPath\n );\n\n if (!output) return [];\n\n return output.split('\\n').map((line) => {\n const [hash, author, date, message] = line.split('\\t');\n return { hash, author, date, message } as Commit;\n });\n}\n\nexport async function getLastCommit(projectPath: string): Promise<Commit | null> {\n const commits = await getRecentCommits(projectPath, 1);\n return commits[0] ?? null;\n}\n\nexport async function getStagedChanges(projectPath: string): Promise<Change[]> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return [];\n\n const output = await execGit(['diff', '--cached', '--name-status'], projectPath);\n if (!output) return [];\n return parseNameStatus(output);\n}\n\nexport async function getUncommittedChanges(projectPath: string): Promise<Change[]> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return [];\n\n const changes: Change[] = [];\n\n const unstaged = await execGit(['diff', '--name-status'], projectPath);\n if (unstaged) {\n changes.push(...parseNameStatus(unstaged));\n }\n\n const untracked = await execGit(['ls-files', '--others', '--exclude-standard'], projectPath);\n if (untracked) {\n changes.push(\n ...untracked\n .split('\\n')\n .map((p) => p.trim())\n .filter(Boolean)\n .map((p) => ({ status: '??', path: p }))\n );\n }\n\n return changes;\n}\n\nexport async function getDiff(projectPath: string, commitHash: string): Promise<string> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return '';\n\n const diff = await execGit(['show', commitHash, '--unified=3', '--no-color'], projectPath);\n return diff ?? '';\n}\n\nexport async function getWorkingTreeDiff(projectPath: string, stagedOnly = false): Promise<string> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return '';\n\n const args = stagedOnly ? ['diff', '--cached', '--unified=3', '--no-color'] : ['diff', '--unified=3', '--no-color'];\n const diff = await execGit(args, projectPath);\n return diff ?? '';\n}\n\nexport async function getUnpushedCommits(projectPath: string): Promise<Commit[]> {\n const isRepo = await ensureRepo(projectPath);\n if (!isRepo) return [];\n\n // Handles detached HEAD by falling back to HEAD if upstream missing\n const upstream = await execGit(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], projectPath);\n if (!upstream) {\n return getRecentCommits(projectPath, 10);\n }\n\n const output = await execGit(['log', `${upstream}..HEAD`, '--pretty=format:%H%x09%an%x09%ad%x09%s', '--date=iso'], projectPath);\n if (!output) return [];\n\n return output.split('\\n').filter(Boolean).map((line) => {\n const [hash, author, date, message] = line.split('\\t');\n return { hash, author, date, message } as Commit;\n });\n}\n\nexport function resolveRepoPath(projectPath: string): string {\n const gitDir = path.join(projectPath, '.git');\n if (existsSync(gitDir)) return projectPath;\n return projectPath;\n}\n\n/**\n * Check if the given path is inside a git repository\n */\nexport async function isGitRepo(projectPath: string): Promise<boolean> {\n const result = await execGit(['rev-parse', '--is-inside-work-tree'], projectPath);\n return result === 'true';\n}\n\n/**\n * Get files changed since a given timestamp\n * Uses git log to find commits after timestamp, then gets affected files\n * Returns null if not a git repo or on error\n */\nexport async function getChangedFilesSinceTimestamp(\n projectPath: string,\n timestamp: number\n): Promise<string[] | null> {\n const isRepo = await isGitRepo(projectPath);\n if (!isRepo) return null;\n\n try {\n // Convert timestamp to ISO date for git\n const sinceDate = new Date(timestamp).toISOString();\n \n // Get all files that changed in commits since the timestamp\n const committedChanges = await execGit(\n ['log', `--since=${sinceDate}`, '--name-only', '--pretty=format:'],\n projectPath\n );\n\n // Get currently modified files (staged + unstaged)\n const stagedChanges = await execGit(['diff', '--cached', '--name-only'], projectPath);\n const unstagedChanges = await execGit(['diff', '--name-only'], projectPath);\n \n // Get untracked files\n const untrackedFiles = await execGit(\n ['ls-files', '--others', '--exclude-standard'],\n projectPath\n );\n\n // Combine all changed files\n const changedFiles = new Set<string>();\n \n const addFiles = (output: string | null) => {\n if (output) {\n output.split('\\n')\n .map(f => f.trim())\n .filter(Boolean)\n .forEach(f => changedFiles.add(path.join(projectPath, f)));\n }\n };\n\n addFiles(committedChanges);\n addFiles(stagedChanges);\n addFiles(unstagedChanges);\n addFiles(untrackedFiles);\n\n return Array.from(changedFiles);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBO,IAAM,UAAN,MAAc;AAAA,EACX,gBAAgB,iBAAiB;AAAA,EACjC;AAAA,EACA,qBAAqB;AAAA,EACrB,eAAoC;AAAA,EACpC,iBAAwC;AAAA,EAEhD,YAAY,QAAkC;AAC5C,SAAK,SAAS;AAAA,MACZ,eAAe;AAAA,MACf,WAAW;AAAA,MACX,WAAW;AAAA,MACX,iBAAiB;AAAA,MACjB,oBAAoB;AAAA,MACpB,GAAG;AAAA,IACL;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,sBAAqC;AACjD,QAAI,KAAK,iBAAiB,MAAM;AAC9B,UAAI;AACF,aAAK,eAAe,MAAM,iBAAiB;AAAA,MAC7C,QAAQ;AACN,aAAK,eAAe;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,qBAAoC;AAChD,QAAI,KAAK,mBAAmB,KAAM;AAElC,QAAI;AACF,YAAM,CAAC,OAAO,QAAQ,YAAY,MAAM,IAAI,MAAM,QAAQ,IAAI;AAAA,QAC5D,eAAe,EAAE,MAAM,MAAM,IAAI;AAAA,QACjC,gBAAgB,EAAE,OAAO,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC,CAAC;AAAA,QAC7C,sBAAsB,QAAQ,IAAI,CAAC,EAAE,MAAM,MAAM,IAAI;AAAA,QACrD,qBAAqB,EAAE,MAAM,MAAM,IAAI;AAAA,MACzC,CAAC;AAED,YAAM,eAAe,oB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