-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeatureCandidates.ts
More file actions
351 lines (304 loc) · 12 KB
/
Copy pathfeatureCandidates.ts
File metadata and controls
351 lines (304 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import type { FeatureInfo } from "./featureDetector.js";
export type FeatureCandidateSource =
| "registry"
| "capability"
| "entity"
| "frontend-page"
| "client-route"
| "ai";
export type ObservationReliability = "high" | "medium" | "low";
export interface FeatureEvidence {
ruleId: string;
source: FeatureCandidateSource;
files: string[];
routePaths?: string[];
entityNames?: string[];
detail: string;
reliability: ObservationReliability;
}
export interface FeatureCandidate {
id: string;
label: string;
source: FeatureCandidateSource;
evidence: FeatureEvidence[];
files: string[];
routePaths: string[];
entityNames: string[];
conclusionConfidence: "high" | "medium" | "low";
/** Internal compatibility payload used while the public snapshot remains V1. */
projection?: FeatureInfo;
}
export type AnchorType = "entity" | "file" | "route-resource" | "alias";
export interface MergeDecision {
candidateIds: [string, string];
outcome: "merged" | "rejected" | "retained";
anchors: Array<{ type: AnchorType; value: string }>;
similarity?: number;
reason: string;
}
export type FeatureCluster = {
id: string;
canonicalCandidateId: string;
canonicalLabel: string;
aliases: string[];
candidates: FeatureCandidate[];
memberIds: string[];
anchors: string[];
decisionRationale: string;
};
export type FeatureReconciliation = {
clusters: FeatureCluster[];
rejectedCandidateIds: string[];
mergeDecisions?: MergeDecision[];
};
const SOURCE_PRIORITY: Record<FeatureCandidateSource, number> = {
"frontend-page": 6,
"client-route": 5,
entity: 4,
capability: 3,
registry: 2,
ai: 0,
};
const RELIABILITY_PRIORITY: Record<ObservationReliability, number> = {
high: 3,
medium: 2,
low: 1,
};
const CONFIDENCE_PRIORITY: Record<FeatureCandidate["conclusionConfidence"], number> = {
high: 3,
medium: 2,
low: 1,
};
/**
* Reconcile complete candidate sets using hard evidence anchors only. Names
* only influence the deterministic canonical-label tie break after candidates
* are already in the same connected component.
*/
const HUB_FILE_THRESHOLD = 5;
export function reconcileFeatureCandidates(
candidates: FeatureCandidate[],
fileReferenceCounts: Record<string, number> = {}
): FeatureReconciliation {
const deterministicCandidates = candidates
.filter((candidate) => candidate.source !== "ai")
.map(normalizeCandidate)
.sort((left, right) => left.id.localeCompare(right.id));
const rejectedCandidateIds = candidates
.filter((candidate) => candidate.source === "ai")
.map((candidate) => candidate.id)
.sort();
const unionFind = new UnionFind(deterministicCandidates.length);
const anchorsByPair = new Map<string, string[]>();
const structuredAnchorsByPair = new Map<string, Array<{ type: AnchorType; value: string }>>();
const mergeDecisions: MergeDecision[] = [];
for (const rejectedId of rejectedCandidateIds) {
mergeDecisions.push({
candidateIds: [rejectedId, ""],
outcome: "rejected",
anchors: [],
reason: "AI-sourced candidate rejected from deterministic reconciliation.",
});
}
for (let left = 0; left < deterministicCandidates.length; left += 1) {
for (let right = left + 1; right < deterministicCandidates.length; right += 1) {
const leftCandidate = deterministicCandidates[left];
const rightCandidate = deterministicCandidates[right];
const structured = findStructuredAnchors(leftCandidate, rightCandidate, fileReferenceCounts);
if (structured.length === 0) {
mergeDecisions.push({
candidateIds: [leftCandidate.id, rightCandidate.id],
outcome: "retained",
anchors: [],
reason: "No hard anchor found; candidates remain separate.",
});
continue;
}
const anchorStrings = structured.map((a) => `${a.type}:${a.value}`);
unionFind.union(left, right);
anchorsByPair.set(`${left}:${right}`, anchorStrings);
structuredAnchorsByPair.set(`${left}:${right}`, structured);
mergeDecisions.push({
candidateIds: [leftCandidate.id, rightCandidate.id],
outcome: "merged",
anchors: structured,
reason: `Merged by hard anchors: ${anchorStrings.join(", ")}.`,
});
}
}
const componentIndexes = new Map<number, number[]>();
deterministicCandidates.forEach((_, index) => {
const root = unionFind.find(index);
const indexes = componentIndexes.get(root) ?? [];
indexes.push(index);
componentIndexes.set(root, indexes);
});
const clusters = [...componentIndexes.values()]
.map((indexes) => createCluster(indexes, deterministicCandidates, anchorsByPair))
.sort((left, right) => left.id.localeCompare(right.id));
return { clusters, rejectedCandidateIds, mergeDecisions };
}
/** Project only deterministic clusters to the established public snapshot shape. */
export function projectFeatureCandidates(clusters: FeatureCluster[]): FeatureInfo[] {
return clusters
.filter((cluster) => cluster.candidates.some((candidate) => candidate.source !== "ai"))
.map((cluster) => {
const projection = projectCompatibilityFeature(cluster);
if (projection) return projection;
const files = uniqueSorted(cluster.candidates.flatMap((candidate) => candidate.files));
const searchTerms = uniqueSorted(cluster.candidates.flatMap((candidate) => [
...candidate.entityNames,
...candidate.routePaths.map(routeResource),
]).filter(Boolean));
const evidence = uniqueSorted(cluster.candidates.flatMap((candidate) =>
candidate.evidence.flatMap((item) => item.files)
));
return {
name: cluster.canonicalLabel,
purpose: `Deterministic ${cluster.canonicalLabel} feature cluster.`,
files,
entryPoints: [],
businessFlow: [],
searchTerms,
confidence: clusterConfidence(cluster.candidates),
evidence,
};
})
.sort((left, right) => left.name.localeCompare(right.name));
}
function projectCompatibilityFeature(cluster: FeatureCluster): FeatureInfo | undefined {
const canonical = cluster.candidates.find(
(candidate) => candidate.id === cluster.canonicalCandidateId
)?.projection;
if (!canonical) return undefined;
const projections = cluster.candidates
.map((candidate) => candidate.projection)
.filter((candidate): candidate is FeatureInfo => Boolean(candidate));
const files = uniqueSorted(projections.flatMap((feature) => feature.files));
const evidence = uniqueSorted(projections.flatMap((feature) => feature.evidence));
const entryPoints = uniqueSorted(projections.flatMap((feature) => feature.entryPoints));
const searchTerms = uniqueSorted(projections.flatMap((feature) => feature.searchTerms)).slice(0, 8);
return {
...canonical,
files,
evidence,
entryPoints,
...(entryPoints[0] ? { entryPoint: entryPoints[0] } : {}),
searchTerms,
confidence: clusterConfidence(cluster.candidates),
};
}
function createCluster(
indexes: number[],
candidates: FeatureCandidate[],
anchorsByPair: Map<string, string[]>
): FeatureCluster {
const members = indexes.map((index) => candidates[index]).sort((left, right) => left.id.localeCompare(right.id));
const canonical = [...members].sort(compareCanonicalCandidates)[0];
const anchors = uniqueSorted(indexes.flatMap((left) => indexes.flatMap((right) =>
left < right ? anchorsByPair.get(`${left}:${right}`) ?? [] : []
)));
return {
id: `cluster:${members.map((candidate) => candidate.id).join("|")}`,
canonicalCandidateId: canonical.id,
canonicalLabel: canonical.label,
aliases: uniqueSorted(members.map((candidate) => candidate.label).filter((label) => label !== canonical.label)),
candidates: members,
memberIds: members.map((candidate) => candidate.id),
anchors,
decisionRationale: anchors.length === 0
? "Single candidate retained because no hard anchor connected it to another candidate."
: `Merged by hard anchors: ${anchors.join(", ")}. Canonical label selected by source priority, evidence reliability, and candidate ID.`,
};
}
function compareCanonicalCandidates(left: FeatureCandidate, right: FeatureCandidate): number {
const source = SOURCE_PRIORITY[right.source] - SOURCE_PRIORITY[left.source];
if (source !== 0) return source;
const reliability = highestReliability(right.evidence) - highestReliability(left.evidence);
if (reliability !== 0) return reliability;
const evidence = right.evidence.length - left.evidence.length;
if (evidence !== 0) return evidence;
return left.id.localeCompare(right.id);
}
function findHardAnchors(left: FeatureCandidate, right: FeatureCandidate): string[] {
return findStructuredAnchors(left, right).map((a) => `${a.type}:${a.value}`);
}
function findStructuredAnchors(
left: FeatureCandidate,
right: FeatureCandidate,
fileReferenceCounts: Record<string, number> = {}
): Array<{ type: AnchorType; value: string }> {
const entityAnchors = intersection(left.entityNames, right.entityNames)
.map((entity) => ({ type: "entity" as const, value: entity }));
const fileAnchors = intersection(left.files, right.files)
.filter((file) => (fileReferenceCounts[file] ?? 0) <= HUB_FILE_THRESHOLD)
.map((file) => ({ type: "file" as const, value: file }));
const routeAnchors = intersection(
left.routePaths.map(routeResource).filter(Boolean),
right.routePaths.map(routeResource).filter(Boolean),
).map((resource) => ({ type: "route-resource" as const, value: resource }));
return [...entityAnchors, ...fileAnchors, ...routeAnchors];
}
function routeResource(routePath: string): string {
const parts = routePath
.split("/")
.filter(Boolean)
.filter((part) => part !== "api" && !part.startsWith("[") && !part.startsWith(":"));
return parts[0]?.toLowerCase() ?? "";
}
function normalizeCandidate(candidate: FeatureCandidate): FeatureCandidate {
return {
...candidate,
evidence: candidate.evidence.map((item) => ({
...item,
files: uniqueSorted(item.files),
...(item.routePaths ? { routePaths: uniqueSorted(item.routePaths) } : {}),
...(item.entityNames ? { entityNames: uniqueSorted(item.entityNames) } : {}),
})).sort((left, right) => left.ruleId.localeCompare(right.ruleId)),
files: uniqueSorted(candidate.files),
routePaths: uniqueSorted(candidate.routePaths),
entityNames: uniqueSorted(candidate.entityNames),
};
}
function clusterConfidence(candidates: FeatureCandidate[]): FeatureCandidate["conclusionConfidence"] {
const corroboratedSources = new Set(candidates.map((candidate) => candidate.source));
const hasHighConclusion = candidates.some((candidate) => candidate.conclusionConfidence === "high");
if (hasHighConclusion && corroboratedSources.size >= 2) return "high";
return candidates
.map((candidate) => candidate.conclusionConfidence)
.sort((left, right) => CONFIDENCE_PRIORITY[right] - CONFIDENCE_PRIORITY[left])[0] ?? "low";
}
function highestReliability(evidence: FeatureEvidence[]): number {
return Math.max(0, ...evidence.map((item) => RELIABILITY_PRIORITY[item.reliability]));
}
function intersection(left: string[], right: string[]): string[] {
const rightSet = new Set(right.map(normalizeAnchor));
return left.filter((value) => rightSet.has(normalizeAnchor(value)));
}
function normalizeAnchor(value: string): string {
return value.trim().toLowerCase();
}
function uniqueSorted(values: string[]): string[] {
return [...new Set(values)].sort((left, right) => left.localeCompare(right));
}
class UnionFind {
private readonly parent: number[];
constructor(size: number) {
this.parent = Array.from({ length: size }, (_, index) => index);
}
find(index: number): number {
if (this.parent[index] !== index) {
this.parent[index] = this.find(this.parent[index]);
}
return this.parent[index];
}
union(left: number, right: number): void {
const leftRoot = this.find(left);
const rightRoot = this.find(right);
if (leftRoot === rightRoot) return;
if (leftRoot < rightRoot) {
this.parent[rightRoot] = leftRoot;
} else {
this.parent[leftRoot] = rightRoot;
}
}
}