@harness-engineering/graph 0.3.1 → 0.3.2

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/dist/index.mjs CHANGED
@@ -466,6 +466,38 @@ function project(nodes, spec) {
466
466
  });
467
467
  }
468
468
 
469
+ // src/query/groupImpact.ts
470
+ var TEST_TYPES = /* @__PURE__ */ new Set(["test_result"]);
471
+ var DOC_TYPES = /* @__PURE__ */ new Set(["adr", "decision", "document", "learning"]);
472
+ var CODE_TYPES = /* @__PURE__ */ new Set([
473
+ "file",
474
+ "module",
475
+ "class",
476
+ "interface",
477
+ "function",
478
+ "method",
479
+ "variable"
480
+ ]);
481
+ function groupNodesByImpact(nodes, excludeId) {
482
+ const tests = [];
483
+ const docs = [];
484
+ const code = [];
485
+ const other = [];
486
+ for (const node of nodes) {
487
+ if (excludeId && node.id === excludeId) continue;
488
+ if (TEST_TYPES.has(node.type)) {
489
+ tests.push(node);
490
+ } else if (DOC_TYPES.has(node.type)) {
491
+ docs.push(node);
492
+ } else if (CODE_TYPES.has(node.type)) {
493
+ code.push(node);
494
+ } else {
495
+ other.push(node);
496
+ }
497
+ }
498
+ return { tests, docs, code, other };
499
+ }
500
+
469
501
  // src/ingest/CodeIngestor.ts
470
502
  import * as fs from "fs/promises";
471
503
  import * as path from "path";
@@ -2443,6 +2475,687 @@ var GraphAnomalyAdapter = class {
2443
2475
  }
2444
2476
  };
2445
2477
 
2478
+ // src/nlq/types.ts
2479
+ var INTENTS = ["impact", "find", "relationships", "explain", "anomaly"];
2480
+
2481
+ // src/nlq/IntentClassifier.ts
2482
+ var SIGNAL_WEIGHTS = {
2483
+ keyword: 0.35,
2484
+ questionWord: 0.2,
2485
+ verbPattern: 0.45
2486
+ };
2487
+ var INTENT_SIGNALS = {
2488
+ impact: {
2489
+ keywords: [
2490
+ "break",
2491
+ "affect",
2492
+ "impact",
2493
+ "change",
2494
+ "depend",
2495
+ "blast",
2496
+ "radius",
2497
+ "risk",
2498
+ "delete",
2499
+ "remove"
2500
+ ],
2501
+ questionWords: ["what", "if"],
2502
+ verbPatterns: [
2503
+ /what\s+(breaks|happens|is affected)/,
2504
+ /if\s+i\s+(change|modify|remove|delete)/,
2505
+ /blast\s+radius/,
2506
+ /what\s+(depend|relies)/
2507
+ ]
2508
+ },
2509
+ find: {
2510
+ keywords: ["find", "where", "locate", "search", "list", "all", "every"],
2511
+ questionWords: ["where"],
2512
+ verbPatterns: [
2513
+ /where\s+is/,
2514
+ /find\s+(the|all|every)/,
2515
+ /show\s+me/,
2516
+ /show\s+(all|every|the)/,
2517
+ /locate\s+/,
2518
+ /list\s+(all|every|the)/
2519
+ ]
2520
+ },
2521
+ relationships: {
2522
+ keywords: [
2523
+ "connect",
2524
+ "call",
2525
+ "import",
2526
+ "use",
2527
+ "depend",
2528
+ "link",
2529
+ "neighbor",
2530
+ "caller",
2531
+ "callee"
2532
+ ],
2533
+ questionWords: ["what", "who"],
2534
+ verbPatterns: [/connects?\s+to/, /depends?\s+on/, /\bcalls?\b/, /\bimports?\b/]
2535
+ },
2536
+ explain: {
2537
+ keywords: ["describe", "explain", "tell", "about", "overview", "summary", "work"],
2538
+ questionWords: ["what", "how"],
2539
+ verbPatterns: [
2540
+ /what\s+is\s+\w/,
2541
+ /describe\s+/,
2542
+ /tell\s+me\s+about/,
2543
+ /how\s+does/,
2544
+ /overview\s+of/,
2545
+ /give\s+me\s+/
2546
+ ]
2547
+ },
2548
+ anomaly: {
2549
+ keywords: [
2550
+ "wrong",
2551
+ "problem",
2552
+ "anomaly",
2553
+ "smell",
2554
+ "issue",
2555
+ "outlier",
2556
+ "hotspot",
2557
+ "suspicious",
2558
+ "risk"
2559
+ ],
2560
+ questionWords: ["what"],
2561
+ verbPatterns: [
2562
+ /what.*(wrong|problem|smell)/,
2563
+ /find.*(issue|anomal|problem)/,
2564
+ /code\s+smell/,
2565
+ /suspicious/,
2566
+ /hotspot/
2567
+ ]
2568
+ }
2569
+ };
2570
+ var IntentClassifier = class {
2571
+ /**
2572
+ * Classify a natural language question into an intent.
2573
+ *
2574
+ * @param question - The natural language question to classify
2575
+ * @returns ClassificationResult with intent, confidence, and per-signal scores
2576
+ */
2577
+ classify(question) {
2578
+ const normalized = question.toLowerCase().trim();
2579
+ const scores = [];
2580
+ for (const intent of INTENTS) {
2581
+ const signals = this.scoreIntent(normalized, INTENT_SIGNALS[intent]);
2582
+ const confidence = this.combineSignals(signals);
2583
+ scores.push({ intent, confidence, signals });
2584
+ }
2585
+ scores.sort((a, b) => b.confidence - a.confidence);
2586
+ const best = scores[0];
2587
+ return {
2588
+ intent: best.intent,
2589
+ confidence: best.confidence,
2590
+ signals: best.signals
2591
+ };
2592
+ }
2593
+ /**
2594
+ * Score individual signals for an intent against the normalized query.
2595
+ */
2596
+ scoreIntent(normalized, signalSet) {
2597
+ return {
2598
+ keyword: this.scoreKeywords(normalized, signalSet.keywords),
2599
+ questionWord: this.scoreQuestionWord(normalized, signalSet.questionWords),
2600
+ verbPattern: this.scoreVerbPatterns(normalized, signalSet.verbPatterns)
2601
+ };
2602
+ }
2603
+ /**
2604
+ * Score keyword signal: uses word-stem matching (checks if any word in the
2605
+ * query starts with the keyword). Saturates at 2 matches to avoid penalizing
2606
+ * intents with many keywords when only a few appear in the query.
2607
+ */
2608
+ scoreKeywords(normalized, keywords) {
2609
+ if (keywords.length === 0) return 0;
2610
+ const words = normalized.split(/\s+/);
2611
+ let matched = 0;
2612
+ for (const keyword of keywords) {
2613
+ if (words.some((w) => w.startsWith(keyword))) {
2614
+ matched++;
2615
+ }
2616
+ }
2617
+ return Math.min(matched / 2, 1);
2618
+ }
2619
+ /**
2620
+ * Score question-word signal: 1.0 if the query starts with a matching
2621
+ * question word, 0 otherwise.
2622
+ */
2623
+ scoreQuestionWord(normalized, questionWords) {
2624
+ const firstWord = normalized.split(/\s+/)[0] ?? "";
2625
+ return questionWords.includes(firstWord) ? 1 : 0;
2626
+ }
2627
+ /**
2628
+ * Score verb-pattern signal: any matching pattern yields a strong score.
2629
+ * Multiple matches increase score but saturate quickly.
2630
+ */
2631
+ scoreVerbPatterns(normalized, patterns) {
2632
+ if (patterns.length === 0) return 0;
2633
+ let matched = 0;
2634
+ for (const pattern of patterns) {
2635
+ if (pattern.test(normalized)) {
2636
+ matched++;
2637
+ }
2638
+ }
2639
+ return matched === 0 ? 0 : Math.min(0.6 + matched * 0.2, 1);
2640
+ }
2641
+ /**
2642
+ * Combine individual signal scores into a single confidence score
2643
+ * using additive weighted scoring. Each signal contributes weight * score,
2644
+ * and the total weights sum to 1.0 so the result is naturally bounded [0, 1].
2645
+ */
2646
+ combineSignals(signals) {
2647
+ let total = 0;
2648
+ for (const key of Object.keys(signals)) {
2649
+ const weight = SIGNAL_WEIGHTS[key];
2650
+ total += signals[key] * weight;
2651
+ }
2652
+ return total;
2653
+ }
2654
+ };
2655
+
2656
+ // src/nlq/EntityExtractor.ts
2657
+ var INTENT_KEYWORDS = /* @__PURE__ */ new Set([
2658
+ // impact
2659
+ "break",
2660
+ "breaks",
2661
+ "affect",
2662
+ "affects",
2663
+ "affected",
2664
+ "impact",
2665
+ "change",
2666
+ "depend",
2667
+ "depends",
2668
+ "blast",
2669
+ "radius",
2670
+ "risk",
2671
+ "delete",
2672
+ "remove",
2673
+ "modify",
2674
+ "happens",
2675
+ // find
2676
+ "find",
2677
+ "where",
2678
+ "locate",
2679
+ "search",
2680
+ "list",
2681
+ "all",
2682
+ "every",
2683
+ "show",
2684
+ // relationships
2685
+ "connect",
2686
+ "connects",
2687
+ "call",
2688
+ "calls",
2689
+ "import",
2690
+ "imports",
2691
+ "use",
2692
+ "uses",
2693
+ "link",
2694
+ "neighbor",
2695
+ "caller",
2696
+ "callers",
2697
+ "callee",
2698
+ "callees",
2699
+ // explain
2700
+ "describe",
2701
+ "explain",
2702
+ "tell",
2703
+ "about",
2704
+ "overview",
2705
+ "summary",
2706
+ "work",
2707
+ "works",
2708
+ // anomaly
2709
+ "wrong",
2710
+ "problem",
2711
+ "problems",
2712
+ "anomaly",
2713
+ "anomalies",
2714
+ "smell",
2715
+ "smells",
2716
+ "issue",
2717
+ "issues",
2718
+ "outlier",
2719
+ "hotspot",
2720
+ "hotspots",
2721
+ "suspicious"
2722
+ ]);
2723
+ var STOP_WORDS2 = /* @__PURE__ */ new Set([
2724
+ "a",
2725
+ "an",
2726
+ "the",
2727
+ "is",
2728
+ "are",
2729
+ "was",
2730
+ "were",
2731
+ "be",
2732
+ "been",
2733
+ "being",
2734
+ "have",
2735
+ "has",
2736
+ "had",
2737
+ "do",
2738
+ "does",
2739
+ "did",
2740
+ "will",
2741
+ "would",
2742
+ "could",
2743
+ "should",
2744
+ "may",
2745
+ "might",
2746
+ "shall",
2747
+ "can",
2748
+ "need",
2749
+ "must",
2750
+ "i",
2751
+ "me",
2752
+ "my",
2753
+ "we",
2754
+ "our",
2755
+ "you",
2756
+ "your",
2757
+ "he",
2758
+ "she",
2759
+ "it",
2760
+ "its",
2761
+ "they",
2762
+ "them",
2763
+ "their",
2764
+ "this",
2765
+ "that",
2766
+ "these",
2767
+ "those",
2768
+ "and",
2769
+ "or",
2770
+ "but",
2771
+ "if",
2772
+ "then",
2773
+ "else",
2774
+ "when",
2775
+ "while",
2776
+ "for",
2777
+ "of",
2778
+ "at",
2779
+ "by",
2780
+ "to",
2781
+ "in",
2782
+ "on",
2783
+ "with",
2784
+ "from",
2785
+ "up",
2786
+ "out",
2787
+ "not",
2788
+ "no",
2789
+ "nor",
2790
+ "so",
2791
+ "too",
2792
+ "very",
2793
+ "just",
2794
+ "also",
2795
+ "what",
2796
+ "who",
2797
+ "how",
2798
+ "which",
2799
+ "where",
2800
+ "why",
2801
+ "there",
2802
+ "here",
2803
+ "any",
2804
+ "some",
2805
+ "each",
2806
+ "than",
2807
+ "like",
2808
+ "get",
2809
+ "give",
2810
+ "go",
2811
+ "make",
2812
+ "see",
2813
+ "know",
2814
+ "take"
2815
+ ]);
2816
+ var PASCAL_OR_CAMEL_RE = /\b([A-Z][a-z]+[A-Za-z]*[a-z][A-Za-z]*|[a-z]+[A-Z][A-Za-z]*)\b/g;
2817
+ var FILE_PATH_RE = /(?:\.\/|[a-zA-Z0-9_-]+\/)[a-zA-Z0-9_\-./]+\.[a-zA-Z]{1,10}/g;
2818
+ var QUOTED_RE = /["']([^"']+)["']/g;
2819
+ var EntityExtractor = class {
2820
+ /**
2821
+ * Extract candidate entity mentions from a natural language query.
2822
+ *
2823
+ * @param query - The natural language query to extract entities from
2824
+ * @returns Array of raw entity strings in priority order, deduplicated
2825
+ */
2826
+ extract(query) {
2827
+ const trimmed = query.trim();
2828
+ if (trimmed.length === 0) return [];
2829
+ const seen = /* @__PURE__ */ new Set();
2830
+ const result = [];
2831
+ const add = (entity) => {
2832
+ if (!seen.has(entity)) {
2833
+ seen.add(entity);
2834
+ result.push(entity);
2835
+ }
2836
+ };
2837
+ const quotedConsumed = /* @__PURE__ */ new Set();
2838
+ for (const match of trimmed.matchAll(QUOTED_RE)) {
2839
+ const inner = match[1].trim();
2840
+ if (inner.length > 0) {
2841
+ add(inner);
2842
+ quotedConsumed.add(inner);
2843
+ }
2844
+ }
2845
+ const casingConsumed = /* @__PURE__ */ new Set();
2846
+ for (const match of trimmed.matchAll(PASCAL_OR_CAMEL_RE)) {
2847
+ const token = match[0];
2848
+ if (!quotedConsumed.has(token)) {
2849
+ add(token);
2850
+ casingConsumed.add(token);
2851
+ }
2852
+ }
2853
+ const pathConsumed = /* @__PURE__ */ new Set();
2854
+ for (const match of trimmed.matchAll(FILE_PATH_RE)) {
2855
+ const path6 = match[0];
2856
+ add(path6);
2857
+ pathConsumed.add(path6);
2858
+ }
2859
+ const quotedWords = /* @__PURE__ */ new Set();
2860
+ for (const q of quotedConsumed) {
2861
+ for (const w of q.split(/\s+/)) {
2862
+ if (w.length > 0) quotedWords.add(w);
2863
+ }
2864
+ }
2865
+ const allConsumed = /* @__PURE__ */ new Set([
2866
+ ...quotedConsumed,
2867
+ ...quotedWords,
2868
+ ...casingConsumed,
2869
+ ...pathConsumed
2870
+ ]);
2871
+ const words = trimmed.split(/\s+/);
2872
+ for (const raw of words) {
2873
+ const cleaned = raw.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "");
2874
+ if (cleaned.length === 0) continue;
2875
+ const lower = cleaned.toLowerCase();
2876
+ if (allConsumed.has(cleaned)) continue;
2877
+ if (STOP_WORDS2.has(lower)) continue;
2878
+ if (INTENT_KEYWORDS.has(lower)) continue;
2879
+ if (cleaned === cleaned.toUpperCase() && /^[A-Z]+$/.test(cleaned)) continue;
2880
+ add(cleaned);
2881
+ }
2882
+ return result;
2883
+ }
2884
+ };
2885
+
2886
+ // src/nlq/EntityResolver.ts
2887
+ var EntityResolver = class {
2888
+ store;
2889
+ fusion;
2890
+ constructor(store, fusion) {
2891
+ this.store = store;
2892
+ this.fusion = fusion;
2893
+ }
2894
+ /**
2895
+ * Resolve an array of raw entity strings to graph nodes.
2896
+ *
2897
+ * @param raws - Raw entity strings from EntityExtractor
2898
+ * @returns Array of ResolvedEntity for each successfully resolved raw string
2899
+ */
2900
+ resolve(raws) {
2901
+ const results = [];
2902
+ for (const raw of raws) {
2903
+ const resolved = this.resolveOne(raw);
2904
+ if (resolved !== void 0) {
2905
+ results.push(resolved);
2906
+ }
2907
+ }
2908
+ return results;
2909
+ }
2910
+ resolveOne(raw) {
2911
+ const exactMatches = this.store.findNodes({ name: raw });
2912
+ if (exactMatches.length > 0) {
2913
+ const node = exactMatches[0];
2914
+ return {
2915
+ raw,
2916
+ nodeId: node.id,
2917
+ node,
2918
+ confidence: 1,
2919
+ method: "exact"
2920
+ };
2921
+ }
2922
+ if (this.fusion) {
2923
+ const fusionResults = this.fusion.search(raw, 5);
2924
+ if (fusionResults.length > 0 && fusionResults[0].score > 0.5) {
2925
+ const top = fusionResults[0];
2926
+ return {
2927
+ raw,
2928
+ nodeId: top.nodeId,
2929
+ node: top.node,
2930
+ confidence: top.score,
2931
+ method: "fusion"
2932
+ };
2933
+ }
2934
+ }
2935
+ if (raw.length < 3) return void 0;
2936
+ const isPathLike = raw.includes("/");
2937
+ const fileNodes = this.store.findNodes({ type: "file" });
2938
+ for (const node of fileNodes) {
2939
+ if (!node.path) continue;
2940
+ if (isPathLike && node.path.includes(raw)) {
2941
+ return { raw, nodeId: node.id, node, confidence: 0.6, method: "path" };
2942
+ }
2943
+ const basename4 = node.path.split("/").pop() ?? "";
2944
+ if (basename4.includes(raw)) {
2945
+ return { raw, nodeId: node.id, node, confidence: 0.6, method: "path" };
2946
+ }
2947
+ if (raw.length >= 4 && node.path.includes(raw)) {
2948
+ return { raw, nodeId: node.id, node, confidence: 0.6, method: "path" };
2949
+ }
2950
+ }
2951
+ return void 0;
2952
+ }
2953
+ };
2954
+
2955
+ // src/nlq/ResponseFormatter.ts
2956
+ var ResponseFormatter = class {
2957
+ /**
2958
+ * Format graph operation results into a human-readable summary.
2959
+ *
2960
+ * @param intent - The classified intent
2961
+ * @param entities - Resolved entities from the query
2962
+ * @param data - Raw result data (shape varies per intent)
2963
+ * @param query - Original natural language query (optional)
2964
+ * @returns Human-readable summary string
2965
+ */
2966
+ format(intent, entities, data, query) {
2967
+ if (data === null || data === void 0) {
2968
+ return "No results found.";
2969
+ }
2970
+ const firstEntity = entities[0];
2971
+ const entityName = firstEntity?.raw ?? "the target";
2972
+ switch (intent) {
2973
+ case "impact":
2974
+ return this.formatImpact(entityName, data);
2975
+ case "find":
2976
+ return this.formatFind(data, query);
2977
+ case "relationships":
2978
+ return this.formatRelationships(entityName, entities, data);
2979
+ case "explain":
2980
+ return this.formatExplain(entityName, entities, data);
2981
+ case "anomaly":
2982
+ return this.formatAnomaly(data);
2983
+ default:
2984
+ return `Processed results for "${entityName}".`;
2985
+ }
2986
+ }
2987
+ formatImpact(entityName, data) {
2988
+ const d = data;
2989
+ const code = this.safeArrayLength(d?.code);
2990
+ const tests = this.safeArrayLength(d?.tests);
2991
+ const docs = this.safeArrayLength(d?.docs);
2992
+ return `Changing **${entityName}** affects ${this.p(code, "code file")}, ${this.p(tests, "test")}, and ${this.p(docs, "doc")}.`;
2993
+ }
2994
+ formatFind(data, query) {
2995
+ const count = Array.isArray(data) ? data.length : 0;
2996
+ if (query) {
2997
+ return `Found ${this.p(count, "match", "matches")} for "${query}".`;
2998
+ }
2999
+ return `Found ${this.p(count, "match", "matches")}.`;
3000
+ }
3001
+ formatRelationships(entityName, entities, data) {
3002
+ const d = data;
3003
+ const edges = Array.isArray(d?.edges) ? d.edges : [];
3004
+ const firstEntity = entities[0];
3005
+ const rootId = firstEntity?.nodeId ?? "";
3006
+ let outbound = 0;
3007
+ let inbound = 0;
3008
+ for (const edge of edges) {
3009
+ if (edge.from === rootId) outbound++;
3010
+ if (edge.to === rootId) inbound++;
3011
+ }
3012
+ return `**${entityName}** has ${outbound} outbound and ${inbound} inbound relationships.`;
3013
+ }
3014
+ formatExplain(entityName, entities, data) {
3015
+ const d = data;
3016
+ const context = Array.isArray(d?.context) ? d.context : [];
3017
+ const firstEntity = entities[0];
3018
+ const nodeType = firstEntity?.node.type ?? "node";
3019
+ const path6 = firstEntity?.node.path ?? "unknown";
3020
+ let neighborCount = 0;
3021
+ const firstContext = context[0];
3022
+ if (firstContext && Array.isArray(firstContext.nodes)) {
3023
+ neighborCount = firstContext.nodes.length;
3024
+ }
3025
+ return `**${entityName}** is a ${nodeType} at \`${path6}\`. Connected to ${neighborCount} nodes.`;
3026
+ }
3027
+ formatAnomaly(data) {
3028
+ const d = data;
3029
+ const outliers = Array.isArray(d?.statisticalOutliers) ? d.statisticalOutliers : [];
3030
+ const artPoints = Array.isArray(d?.articulationPoints) ? d.articulationPoints : [];
3031
+ const count = outliers.length + artPoints.length;
3032
+ if (count === 0) {
3033
+ return "Found 0 anomalies.";
3034
+ }
3035
+ const topItems = [
3036
+ ...outliers.slice(0, 2).map((o) => o.nodeId ?? "unknown outlier"),
3037
+ ...artPoints.slice(0, 1).map((a) => a.nodeId ?? "unknown bottleneck")
3038
+ ].join(", ");
3039
+ return `Found ${this.p(count, "anomaly", "anomalies")}: ${topItems}.`;
3040
+ }
3041
+ safeArrayLength(value) {
3042
+ return Array.isArray(value) ? value.length : 0;
3043
+ }
3044
+ p(count, singular, plural) {
3045
+ const word = count === 1 ? singular : plural ?? singular + "s";
3046
+ return `${count} ${word}`;
3047
+ }
3048
+ };
3049
+
3050
+ // src/nlq/index.ts
3051
+ var ENTITY_REQUIRED_INTENTS = /* @__PURE__ */ new Set(["impact", "relationships", "explain"]);
3052
+ var classifier = new IntentClassifier();
3053
+ var extractor = new EntityExtractor();
3054
+ var formatter = new ResponseFormatter();
3055
+ async function askGraph(store, question) {
3056
+ const fusion = new FusionLayer(store);
3057
+ const resolver = new EntityResolver(store, fusion);
3058
+ const classification = classifier.classify(question);
3059
+ if (classification.confidence < 0.3) {
3060
+ return {
3061
+ intent: classification.intent,
3062
+ intentConfidence: classification.confidence,
3063
+ entities: [],
3064
+ summary: "I'm not sure what you're asking. Try rephrasing your question.",
3065
+ data: null,
3066
+ suggestions: [
3067
+ 'Try "what breaks if I change <name>?" for impact analysis',
3068
+ 'Try "where is <name>?" to find entities',
3069
+ 'Try "what calls <name>?" for relationships',
3070
+ 'Try "what is <name>?" for explanations',
3071
+ 'Try "what looks wrong?" for anomaly detection'
3072
+ ]
3073
+ };
3074
+ }
3075
+ const rawEntities = extractor.extract(question);
3076
+ const entities = resolver.resolve(rawEntities);
3077
+ if (ENTITY_REQUIRED_INTENTS.has(classification.intent) && entities.length === 0) {
3078
+ return {
3079
+ intent: classification.intent,
3080
+ intentConfidence: classification.confidence,
3081
+ entities: [],
3082
+ summary: "Could not find any matching nodes in the graph for your query. Try using exact class names, function names, or file paths.",
3083
+ data: null
3084
+ };
3085
+ }
3086
+ let data;
3087
+ try {
3088
+ data = executeOperation(store, classification.intent, entities, question, fusion);
3089
+ } catch (err) {
3090
+ return {
3091
+ intent: classification.intent,
3092
+ intentConfidence: classification.confidence,
3093
+ entities,
3094
+ summary: `An error occurred while querying the graph: ${err instanceof Error ? err.message : String(err)}`,
3095
+ data: null
3096
+ };
3097
+ }
3098
+ const summary = formatter.format(classification.intent, entities, data, question);
3099
+ return {
3100
+ intent: classification.intent,
3101
+ intentConfidence: classification.confidence,
3102
+ entities,
3103
+ summary,
3104
+ data
3105
+ };
3106
+ }
3107
+ function executeOperation(store, intent, entities, question, fusion) {
3108
+ const cql = new ContextQL(store);
3109
+ switch (intent) {
3110
+ case "impact": {
3111
+ const rootId = entities[0].nodeId;
3112
+ const result = cql.execute({
3113
+ rootNodeIds: [rootId],
3114
+ bidirectional: true,
3115
+ maxDepth: 3
3116
+ });
3117
+ return groupNodesByImpact(result.nodes, rootId);
3118
+ }
3119
+ case "find": {
3120
+ return fusion.search(question, 10);
3121
+ }
3122
+ case "relationships": {
3123
+ const rootId = entities[0].nodeId;
3124
+ const result = cql.execute({
3125
+ rootNodeIds: [rootId],
3126
+ bidirectional: true,
3127
+ maxDepth: 1
3128
+ });
3129
+ return { nodes: result.nodes, edges: result.edges };
3130
+ }
3131
+ case "explain": {
3132
+ const searchResults = fusion.search(question, 10);
3133
+ const contextBlocks = [];
3134
+ const rootIds = entities.length > 0 ? [entities[0].nodeId] : searchResults.slice(0, 3).map((r) => r.nodeId);
3135
+ for (const rootId of rootIds) {
3136
+ const expanded = cql.execute({
3137
+ rootNodeIds: [rootId],
3138
+ maxDepth: 2
3139
+ });
3140
+ const matchingResult = searchResults.find((r) => r.nodeId === rootId);
3141
+ contextBlocks.push({
3142
+ rootNode: rootId,
3143
+ score: matchingResult?.score ?? 1,
3144
+ nodes: expanded.nodes,
3145
+ edges: expanded.edges
3146
+ });
3147
+ }
3148
+ return { searchResults, context: contextBlocks };
3149
+ }
3150
+ case "anomaly": {
3151
+ const adapter = new GraphAnomalyAdapter(store);
3152
+ return adapter.detect();
3153
+ }
3154
+ default:
3155
+ return null;
3156
+ }
3157
+ }
3158
+
2446
3159
  // src/context/Assembler.ts
2447
3160
  var PHASE_NODE_TYPES = {
2448
3161
  implement: ["file", "function", "class", "method", "interface", "variable"],
@@ -3065,6 +3778,447 @@ var GraphFeedbackAdapter = class {
3065
3778
  }
3066
3779
  };
3067
3780
 
3781
+ // src/independence/TaskIndependenceAnalyzer.ts
3782
+ var DEFAULT_EDGE_TYPES = ["imports", "calls", "references"];
3783
+ var TaskIndependenceAnalyzer = class {
3784
+ store;
3785
+ constructor(store) {
3786
+ this.store = store;
3787
+ }
3788
+ analyze(params) {
3789
+ const { tasks } = params;
3790
+ const depth = params.depth ?? 1;
3791
+ const edgeTypes = params.edgeTypes ?? DEFAULT_EDGE_TYPES;
3792
+ this.validate(tasks);
3793
+ const useGraph = this.store != null && depth > 0;
3794
+ const analysisLevel = useGraph ? "graph-expanded" : "file-only";
3795
+ const originalFiles = /* @__PURE__ */ new Map();
3796
+ const expandedFiles = /* @__PURE__ */ new Map();
3797
+ for (const task of tasks) {
3798
+ const origSet = new Set(task.files);
3799
+ originalFiles.set(task.id, origSet);
3800
+ if (useGraph) {
3801
+ const expanded = this.expandViaGraph(task.files, depth, edgeTypes);
3802
+ expandedFiles.set(task.id, expanded);
3803
+ } else {
3804
+ expandedFiles.set(task.id, /* @__PURE__ */ new Map());
3805
+ }
3806
+ }
3807
+ const taskIds = tasks.map((t) => t.id);
3808
+ const pairs = [];
3809
+ for (let i = 0; i < taskIds.length; i++) {
3810
+ for (let j = i + 1; j < taskIds.length; j++) {
3811
+ const idA = taskIds[i];
3812
+ const idB = taskIds[j];
3813
+ const pair = this.computePairOverlap(
3814
+ idA,
3815
+ idB,
3816
+ originalFiles.get(idA),
3817
+ originalFiles.get(idB),
3818
+ expandedFiles.get(idA),
3819
+ expandedFiles.get(idB)
3820
+ );
3821
+ pairs.push(pair);
3822
+ }
3823
+ }
3824
+ const groups = this.buildGroups(taskIds, pairs);
3825
+ const verdict = this.generateVerdict(taskIds, groups, analysisLevel);
3826
+ return {
3827
+ tasks: taskIds,
3828
+ analysisLevel,
3829
+ depth,
3830
+ pairs,
3831
+ groups,
3832
+ verdict
3833
+ };
3834
+ }
3835
+ // --- Private methods ---
3836
+ validate(tasks) {
3837
+ if (tasks.length < 2) {
3838
+ throw new Error("At least 2 tasks are required for independence analysis");
3839
+ }
3840
+ const seenIds = /* @__PURE__ */ new Set();
3841
+ for (const task of tasks) {
3842
+ if (seenIds.has(task.id)) {
3843
+ throw new Error(`Duplicate task ID: "${task.id}"`);
3844
+ }
3845
+ seenIds.add(task.id);
3846
+ if (task.files.length === 0) {
3847
+ throw new Error(`Task "${task.id}" has an empty files array`);
3848
+ }
3849
+ }
3850
+ }
3851
+ expandViaGraph(files, depth, edgeTypes) {
3852
+ const result = /* @__PURE__ */ new Map();
3853
+ const store = this.store;
3854
+ const cql = new ContextQL(store);
3855
+ const fileSet = new Set(files);
3856
+ for (const file of files) {
3857
+ const nodeId = `file:${file}`;
3858
+ const node = store.getNode(nodeId);
3859
+ if (!node) continue;
3860
+ const queryResult = cql.execute({
3861
+ rootNodeIds: [nodeId],
3862
+ maxDepth: depth,
3863
+ includeEdges: edgeTypes,
3864
+ includeTypes: ["file"]
3865
+ });
3866
+ for (const n of queryResult.nodes) {
3867
+ const path6 = n.path ?? n.id.replace(/^file:/, "");
3868
+ if (!fileSet.has(path6)) {
3869
+ if (!result.has(path6)) {
3870
+ result.set(path6, file);
3871
+ }
3872
+ }
3873
+ }
3874
+ }
3875
+ return result;
3876
+ }
3877
+ computePairOverlap(idA, idB, origA, origB, expandedA, expandedB) {
3878
+ const overlaps = [];
3879
+ for (const file of origA) {
3880
+ if (origB.has(file)) {
3881
+ overlaps.push({ file, type: "direct" });
3882
+ }
3883
+ }
3884
+ const directFiles = new Set(overlaps.map((o) => o.file));
3885
+ const transitiveFiles = /* @__PURE__ */ new Set();
3886
+ for (const [file, via] of expandedA) {
3887
+ if (origB.has(file) && !directFiles.has(file) && !transitiveFiles.has(file)) {
3888
+ transitiveFiles.add(file);
3889
+ overlaps.push({ file, type: "transitive", via });
3890
+ }
3891
+ }
3892
+ for (const [file, via] of expandedB) {
3893
+ if (origA.has(file) && !directFiles.has(file) && !transitiveFiles.has(file)) {
3894
+ transitiveFiles.add(file);
3895
+ overlaps.push({ file, type: "transitive", via });
3896
+ }
3897
+ }
3898
+ for (const [file, viaA] of expandedA) {
3899
+ if (expandedB.has(file) && !directFiles.has(file) && !transitiveFiles.has(file)) {
3900
+ transitiveFiles.add(file);
3901
+ overlaps.push({ file, type: "transitive", via: viaA });
3902
+ }
3903
+ }
3904
+ return {
3905
+ taskA: idA,
3906
+ taskB: idB,
3907
+ independent: overlaps.length === 0,
3908
+ overlaps
3909
+ };
3910
+ }
3911
+ buildGroups(taskIds, pairs) {
3912
+ const parent = /* @__PURE__ */ new Map();
3913
+ const rank = /* @__PURE__ */ new Map();
3914
+ for (const id of taskIds) {
3915
+ parent.set(id, id);
3916
+ rank.set(id, 0);
3917
+ }
3918
+ const find = (x) => {
3919
+ let root = x;
3920
+ while (parent.get(root) !== root) {
3921
+ root = parent.get(root);
3922
+ }
3923
+ let current = x;
3924
+ while (current !== root) {
3925
+ const next = parent.get(current);
3926
+ parent.set(current, root);
3927
+ current = next;
3928
+ }
3929
+ return root;
3930
+ };
3931
+ const union = (a, b) => {
3932
+ const rootA = find(a);
3933
+ const rootB = find(b);
3934
+ if (rootA === rootB) return;
3935
+ const rankA = rank.get(rootA);
3936
+ const rankB = rank.get(rootB);
3937
+ if (rankA < rankB) {
3938
+ parent.set(rootA, rootB);
3939
+ } else if (rankA > rankB) {
3940
+ parent.set(rootB, rootA);
3941
+ } else {
3942
+ parent.set(rootB, rootA);
3943
+ rank.set(rootA, rankA + 1);
3944
+ }
3945
+ };
3946
+ for (const pair of pairs) {
3947
+ if (!pair.independent) {
3948
+ union(pair.taskA, pair.taskB);
3949
+ }
3950
+ }
3951
+ const groupMap = /* @__PURE__ */ new Map();
3952
+ for (const id of taskIds) {
3953
+ const root = find(id);
3954
+ if (!groupMap.has(root)) {
3955
+ groupMap.set(root, []);
3956
+ }
3957
+ groupMap.get(root).push(id);
3958
+ }
3959
+ return Array.from(groupMap.values());
3960
+ }
3961
+ generateVerdict(taskIds, groups, analysisLevel) {
3962
+ const total = taskIds.length;
3963
+ const groupCount = groups.length;
3964
+ let verdict;
3965
+ if (groupCount === 1) {
3966
+ verdict = `All ${total} tasks conflict \u2014 must run serially.`;
3967
+ } else if (groupCount === total) {
3968
+ verdict = `All ${total} tasks are independent \u2014 can all run in parallel.`;
3969
+ } else {
3970
+ verdict = `${total} tasks form ${groupCount} independent groups \u2014 ${groupCount} parallel waves possible.`;
3971
+ }
3972
+ if (analysisLevel === "file-only") {
3973
+ verdict += " Graph unavailable \u2014 transitive dependencies not checked.";
3974
+ }
3975
+ return verdict;
3976
+ }
3977
+ };
3978
+
3979
+ // src/independence/ConflictPredictor.ts
3980
+ var ConflictPredictor = class {
3981
+ store;
3982
+ constructor(store) {
3983
+ this.store = store;
3984
+ }
3985
+ predict(params) {
3986
+ const analyzer = new TaskIndependenceAnalyzer(this.store);
3987
+ const result = analyzer.analyze(params);
3988
+ const churnMap = /* @__PURE__ */ new Map();
3989
+ const couplingMap = /* @__PURE__ */ new Map();
3990
+ let churnThreshold = Infinity;
3991
+ let couplingThreshold = Infinity;
3992
+ if (this.store != null) {
3993
+ const complexityResult = new GraphComplexityAdapter(this.store).computeComplexityHotspots();
3994
+ for (const hotspot of complexityResult.hotspots) {
3995
+ const existing = churnMap.get(hotspot.file);
3996
+ if (existing === void 0 || hotspot.changeFrequency > existing) {
3997
+ churnMap.set(hotspot.file, hotspot.changeFrequency);
3998
+ }
3999
+ }
4000
+ const couplingResult = new GraphCouplingAdapter(this.store).computeCouplingData();
4001
+ for (const fileData of couplingResult.files) {
4002
+ couplingMap.set(fileData.file, fileData.fanIn + fileData.fanOut);
4003
+ }
4004
+ churnThreshold = this.computePercentile(Array.from(churnMap.values()), 80);
4005
+ couplingThreshold = this.computePercentile(Array.from(couplingMap.values()), 80);
4006
+ }
4007
+ const conflicts = [];
4008
+ for (const pair of result.pairs) {
4009
+ if (pair.independent) continue;
4010
+ const { severity, reason, mitigation } = this.classifyPair(
4011
+ pair.taskA,
4012
+ pair.taskB,
4013
+ pair.overlaps,
4014
+ churnMap,
4015
+ couplingMap,
4016
+ churnThreshold,
4017
+ couplingThreshold
4018
+ );
4019
+ conflicts.push({
4020
+ taskA: pair.taskA,
4021
+ taskB: pair.taskB,
4022
+ severity,
4023
+ reason,
4024
+ mitigation,
4025
+ overlaps: pair.overlaps
4026
+ });
4027
+ }
4028
+ const taskIds = result.tasks;
4029
+ const groups = this.buildHighSeverityGroups(taskIds, conflicts);
4030
+ const regrouped = !this.groupsEqual(result.groups, groups);
4031
+ let highCount = 0;
4032
+ let mediumCount = 0;
4033
+ let lowCount = 0;
4034
+ for (const c of conflicts) {
4035
+ if (c.severity === "high") highCount++;
4036
+ else if (c.severity === "medium") mediumCount++;
4037
+ else lowCount++;
4038
+ }
4039
+ const verdict = this.generateVerdict(
4040
+ taskIds,
4041
+ groups,
4042
+ result.analysisLevel,
4043
+ highCount,
4044
+ mediumCount,
4045
+ lowCount,
4046
+ regrouped
4047
+ );
4048
+ return {
4049
+ tasks: taskIds,
4050
+ analysisLevel: result.analysisLevel,
4051
+ depth: result.depth,
4052
+ conflicts,
4053
+ groups,
4054
+ summary: {
4055
+ high: highCount,
4056
+ medium: mediumCount,
4057
+ low: lowCount,
4058
+ regrouped
4059
+ },
4060
+ verdict
4061
+ };
4062
+ }
4063
+ // --- Private helpers ---
4064
+ classifyPair(taskA, taskB, overlaps, churnMap, couplingMap, churnThreshold, couplingThreshold) {
4065
+ let maxSeverity = "low";
4066
+ let primaryReason = "";
4067
+ let primaryMitigation = "";
4068
+ for (const overlap of overlaps) {
4069
+ let overlapSeverity;
4070
+ let reason;
4071
+ let mitigation;
4072
+ if (overlap.type === "direct") {
4073
+ overlapSeverity = "high";
4074
+ reason = `Both tasks write to ${overlap.file}`;
4075
+ mitigation = `Serialize: run ${taskA} before ${taskB}`;
4076
+ } else {
4077
+ const churn = churnMap.get(overlap.file);
4078
+ const coupling = couplingMap.get(overlap.file);
4079
+ const via = overlap.via ?? "unknown";
4080
+ if (churn !== void 0 && churn >= churnThreshold && churnThreshold !== Infinity) {
4081
+ overlapSeverity = "medium";
4082
+ reason = `Transitive overlap on high-churn file ${overlap.file} (via ${via})`;
4083
+ mitigation = `Review: ${overlap.file} changes frequently \u2014 coordinate edits between ${taskA} and ${taskB}`;
4084
+ } else if (coupling !== void 0 && coupling >= couplingThreshold && couplingThreshold !== Infinity) {
4085
+ overlapSeverity = "medium";
4086
+ reason = `Transitive overlap on highly-coupled file ${overlap.file} (via ${via})`;
4087
+ mitigation = `Review: ${overlap.file} has high coupling \u2014 coordinate edits between ${taskA} and ${taskB}`;
4088
+ } else {
4089
+ overlapSeverity = "low";
4090
+ reason = `Transitive overlap on ${overlap.file} (via ${via}) \u2014 low risk`;
4091
+ mitigation = `Info: transitive overlap unlikely to cause conflicts`;
4092
+ }
4093
+ }
4094
+ if (this.severityRank(overlapSeverity) > this.severityRank(maxSeverity)) {
4095
+ maxSeverity = overlapSeverity;
4096
+ primaryReason = reason;
4097
+ primaryMitigation = mitigation;
4098
+ } else if (primaryReason === "") {
4099
+ primaryReason = reason;
4100
+ primaryMitigation = mitigation;
4101
+ }
4102
+ }
4103
+ return { severity: maxSeverity, reason: primaryReason, mitigation: primaryMitigation };
4104
+ }
4105
+ severityRank(severity) {
4106
+ switch (severity) {
4107
+ case "high":
4108
+ return 3;
4109
+ case "medium":
4110
+ return 2;
4111
+ case "low":
4112
+ return 1;
4113
+ }
4114
+ }
4115
+ computePercentile(values, percentile) {
4116
+ if (values.length === 0) return Infinity;
4117
+ const sorted = [...values].sort((a, b) => a - b);
4118
+ const index = Math.ceil(percentile / 100 * sorted.length) - 1;
4119
+ return sorted[Math.min(index, sorted.length - 1)];
4120
+ }
4121
+ buildHighSeverityGroups(taskIds, conflicts) {
4122
+ const parent = /* @__PURE__ */ new Map();
4123
+ const rank = /* @__PURE__ */ new Map();
4124
+ for (const id of taskIds) {
4125
+ parent.set(id, id);
4126
+ rank.set(id, 0);
4127
+ }
4128
+ const find = (x) => {
4129
+ let root = x;
4130
+ while (parent.get(root) !== root) {
4131
+ root = parent.get(root);
4132
+ }
4133
+ let current = x;
4134
+ while (current !== root) {
4135
+ const next = parent.get(current);
4136
+ parent.set(current, root);
4137
+ current = next;
4138
+ }
4139
+ return root;
4140
+ };
4141
+ const union = (a, b) => {
4142
+ const rootA = find(a);
4143
+ const rootB = find(b);
4144
+ if (rootA === rootB) return;
4145
+ const rankA = rank.get(rootA);
4146
+ const rankB = rank.get(rootB);
4147
+ if (rankA < rankB) {
4148
+ parent.set(rootA, rootB);
4149
+ } else if (rankA > rankB) {
4150
+ parent.set(rootB, rootA);
4151
+ } else {
4152
+ parent.set(rootB, rootA);
4153
+ rank.set(rootA, rankA + 1);
4154
+ }
4155
+ };
4156
+ for (const conflict of conflicts) {
4157
+ if (conflict.severity === "high") {
4158
+ union(conflict.taskA, conflict.taskB);
4159
+ }
4160
+ }
4161
+ const groupMap = /* @__PURE__ */ new Map();
4162
+ for (const id of taskIds) {
4163
+ const root = find(id);
4164
+ let group = groupMap.get(root);
4165
+ if (group === void 0) {
4166
+ group = [];
4167
+ groupMap.set(root, group);
4168
+ }
4169
+ group.push(id);
4170
+ }
4171
+ return Array.from(groupMap.values());
4172
+ }
4173
+ groupsEqual(a, b) {
4174
+ if (a.length !== b.length) return false;
4175
+ const normalize2 = (groups) => groups.map((g) => [...g].sort()).sort((x, y) => {
4176
+ const xFirst = x[0];
4177
+ const yFirst = y[0];
4178
+ return xFirst.localeCompare(yFirst);
4179
+ });
4180
+ const normA = normalize2(a);
4181
+ const normB = normalize2(b);
4182
+ for (let i = 0; i < normA.length; i++) {
4183
+ const groupA = normA[i];
4184
+ const groupB = normB[i];
4185
+ if (groupA.length !== groupB.length) return false;
4186
+ for (let j = 0; j < groupA.length; j++) {
4187
+ if (groupA[j] !== groupB[j]) return false;
4188
+ }
4189
+ }
4190
+ return true;
4191
+ }
4192
+ generateVerdict(taskIds, groups, analysisLevel, highCount, mediumCount, lowCount, regrouped) {
4193
+ const total = taskIds.length;
4194
+ const groupCount = groups.length;
4195
+ const parts = [];
4196
+ const conflictParts = [];
4197
+ if (highCount > 0) conflictParts.push(`${highCount} high`);
4198
+ if (mediumCount > 0) conflictParts.push(`${mediumCount} medium`);
4199
+ if (lowCount > 0) conflictParts.push(`${lowCount} low`);
4200
+ if (conflictParts.length === 0) {
4201
+ parts.push(`${total} tasks have no conflicts \u2014 can all run in parallel.`);
4202
+ } else {
4203
+ parts.push(`${total} tasks have ${conflictParts.join(", ")} severity conflicts.`);
4204
+ }
4205
+ if (groupCount === 1) {
4206
+ parts.push(`All tasks must run serially.`);
4207
+ } else if (groupCount === total) {
4208
+ parts.push(`${groupCount} parallel groups (all independent).`);
4209
+ } else {
4210
+ parts.push(`${groupCount} parallel groups possible.`);
4211
+ }
4212
+ if (regrouped) {
4213
+ parts.push(`Tasks were regrouped due to high-severity conflicts.`);
4214
+ }
4215
+ if (analysisLevel === "file-only") {
4216
+ parts.push(`Graph unavailable \u2014 severity based on file overlaps only.`);
4217
+ }
4218
+ return parts.join(" ");
4219
+ }
4220
+ };
4221
+
3068
4222
  // src/index.ts
3069
4223
  var VERSION = "0.2.0";
3070
4224
  export {
@@ -3072,11 +4226,14 @@ export {
3072
4226
  CIConnector,
3073
4227
  CURRENT_SCHEMA_VERSION,
3074
4228
  CodeIngestor,
4229
+ ConflictPredictor,
3075
4230
  ConfluenceConnector,
3076
4231
  ContextQL,
3077
4232
  DesignConstraintAdapter,
3078
4233
  DesignIngestor,
3079
4234
  EDGE_TYPES,
4235
+ EntityExtractor,
4236
+ EntityResolver,
3080
4237
  FusionLayer,
3081
4238
  GitIngestor,
3082
4239
  GraphAnomalyAdapter,
@@ -3088,15 +4245,21 @@ export {
3088
4245
  GraphFeedbackAdapter,
3089
4246
  GraphNodeSchema,
3090
4247
  GraphStore,
4248
+ INTENTS,
4249
+ IntentClassifier,
3091
4250
  JiraConnector,
3092
4251
  KnowledgeIngestor,
3093
4252
  NODE_TYPES,
3094
4253
  OBSERVABILITY_TYPES,
4254
+ ResponseFormatter,
3095
4255
  SlackConnector,
3096
4256
  SyncManager,
4257
+ TaskIndependenceAnalyzer,
3097
4258
  TopologicalLinker,
3098
4259
  VERSION,
3099
4260
  VectorStore,
4261
+ askGraph,
4262
+ groupNodesByImpact,
3100
4263
  linkToCode,
3101
4264
  loadGraph,
3102
4265
  project,