@goshenkata/dryscan-core 1.2.4 → 1.2.5
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.js +43 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/db/DryScanDatabase.ts +1 -1
- package/src/extractors/java.ts +25 -5
- package/src/services/DuplicateService.ts +24 -3
package/dist/index.js
CHANGED
|
@@ -368,6 +368,7 @@ var JavaExtractor = class {
|
|
|
368
368
|
filePath: file,
|
|
369
369
|
startLine,
|
|
370
370
|
endLine,
|
|
371
|
+
children: [],
|
|
371
372
|
code: this.stripComments(source.slice(node.startIndex, node.endIndex)),
|
|
372
373
|
unitType: "function" /* FUNCTION */,
|
|
373
374
|
parentId: parentClass?.id,
|
|
@@ -402,9 +403,11 @@ var JavaExtractor = class {
|
|
|
402
403
|
parentId: parentFunction.id,
|
|
403
404
|
parent: parentFunction
|
|
404
405
|
};
|
|
406
|
+
const contextLength = this.config?.contextLength ?? 2048;
|
|
407
|
+
const splitBlocks = this.textSplitBlockIfOverContextLimit(blockUnit, contextLength);
|
|
405
408
|
parentFunction.children = parentFunction.children || [];
|
|
406
|
-
parentFunction.children.push(
|
|
407
|
-
blocks.push(
|
|
409
|
+
parentFunction.children.push(...splitBlocks);
|
|
410
|
+
blocks.push(...splitBlocks);
|
|
408
411
|
}
|
|
409
412
|
}
|
|
410
413
|
for (let i = 0; i < n.namedChildCount; i++) {
|
|
@@ -450,6 +453,21 @@ var JavaExtractor = class {
|
|
|
450
453
|
removeDuplicates(units) {
|
|
451
454
|
return Array.from(new Map(units.map((u) => [u.id, u])).values());
|
|
452
455
|
}
|
|
456
|
+
/** Splits a block unit's code into chunks if it exceeds the context length limit. */
|
|
457
|
+
textSplitBlockIfOverContextLimit(unit, contextLength) {
|
|
458
|
+
if (unit.code.length <= contextLength) return [unit];
|
|
459
|
+
const chunks = [];
|
|
460
|
+
let chunkIndex = 0;
|
|
461
|
+
for (let i = 0; i < unit.code.length; i += contextLength) {
|
|
462
|
+
chunks.push({
|
|
463
|
+
...unit,
|
|
464
|
+
id: `${unit.id}:chunk${chunkIndex}`,
|
|
465
|
+
code: unit.code.slice(i, i + contextLength)
|
|
466
|
+
});
|
|
467
|
+
chunkIndex++;
|
|
468
|
+
}
|
|
469
|
+
return chunks;
|
|
470
|
+
}
|
|
453
471
|
};
|
|
454
472
|
|
|
455
473
|
// src/Gitignore.ts
|
|
@@ -1237,19 +1255,25 @@ var DuplicateService = class {
|
|
|
1237
1255
|
}
|
|
1238
1256
|
config;
|
|
1239
1257
|
cache = DuplicationCache.getInstance();
|
|
1258
|
+
//todo vetter optimisation
|
|
1240
1259
|
async findDuplicates(config) {
|
|
1241
1260
|
this.config = config;
|
|
1261
|
+
const t0 = performance.now();
|
|
1242
1262
|
const allUnits = await this.deps.db.getAllUnits();
|
|
1263
|
+
log5("Starting duplicate analysis on %d units", allUnits.length);
|
|
1243
1264
|
if (allUnits.length < 2) {
|
|
1265
|
+
log5("Not enough units to compare, returning empty result");
|
|
1244
1266
|
const score2 = this.computeDuplicationScore([], allUnits);
|
|
1245
1267
|
return { duplicates: [], score: score2 };
|
|
1246
1268
|
}
|
|
1247
1269
|
const thresholds = this.resolveThresholds(config.threshold);
|
|
1270
|
+
log5("Resolved thresholds: function=%d, block=%d, class=%d", thresholds.function, thresholds.block, thresholds.class);
|
|
1248
1271
|
const duplicates = this.computeDuplicates(allUnits, thresholds);
|
|
1249
1272
|
const filteredDuplicates = duplicates.filter((group) => !this.isGroupExcluded(group));
|
|
1250
|
-
log5("Found %d duplicate groups", filteredDuplicates.length);
|
|
1273
|
+
log5("Found %d duplicate groups (%d excluded)", filteredDuplicates.length, duplicates.length - filteredDuplicates.length);
|
|
1251
1274
|
this.cache.update(filteredDuplicates).catch((err) => log5("Cache update failed: %O", err));
|
|
1252
1275
|
const score = this.computeDuplicationScore(filteredDuplicates, allUnits);
|
|
1276
|
+
log5("findDuplicates completed in %dms", (performance.now() - t0).toFixed(2));
|
|
1253
1277
|
return { duplicates: filteredDuplicates, score };
|
|
1254
1278
|
}
|
|
1255
1279
|
resolveThresholds(functionThreshold) {
|
|
@@ -1273,25 +1297,37 @@ var DuplicateService = class {
|
|
|
1273
1297
|
list.push(unit);
|
|
1274
1298
|
byType.set(unit.unitType, list);
|
|
1275
1299
|
}
|
|
1300
|
+
const t0 = performance.now();
|
|
1276
1301
|
for (const [type, typedUnits] of byType.entries()) {
|
|
1277
1302
|
const threshold = this.getThreshold(type, thresholds);
|
|
1303
|
+
log5("Comparing %d units of type '%s' with threshold %d", typedUnits.length, type, threshold);
|
|
1304
|
+
const typeStart = performance.now();
|
|
1278
1305
|
for (let i = 0; i < typedUnits.length; i++) {
|
|
1279
1306
|
for (let j = i + 1; j < typedUnits.length; j++) {
|
|
1280
1307
|
const left = typedUnits[i];
|
|
1281
1308
|
const right = typedUnits[j];
|
|
1282
|
-
if (this.shouldSkipComparison(left, right))
|
|
1309
|
+
if (this.shouldSkipComparison(left, right)) {
|
|
1310
|
+
log5("Skipping nested block comparison: '%s' and '%s'", left.name, right.name);
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1283
1313
|
const cached = this.cache.get(left.id, right.id, left.filePath, right.filePath);
|
|
1284
1314
|
let similarity = null;
|
|
1285
1315
|
if (cached !== null) {
|
|
1316
|
+
log5("Cache hit for '%s' <-> '%s': similarity=%d", left.name, right.name, cached);
|
|
1286
1317
|
similarity = cached;
|
|
1287
1318
|
} else {
|
|
1288
|
-
if (!left.embedding || !right.embedding)
|
|
1319
|
+
if (!left.embedding || !right.embedding) {
|
|
1320
|
+
log5("Skipping '%s' <-> '%s': missing embedding", left.name, right.name);
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1289
1323
|
similarity = this.computeWeightedSimilarity(left, right);
|
|
1324
|
+
log5("Computed similarity for '%s' <-> '%s': %d", left.name, right.name, similarity);
|
|
1290
1325
|
}
|
|
1291
1326
|
if (similarity === null) continue;
|
|
1292
1327
|
if (similarity >= threshold) {
|
|
1293
1328
|
const exclusionString = this.deps.pairing.pairKeyForUnits(left, right);
|
|
1294
1329
|
if (!exclusionString) continue;
|
|
1330
|
+
log5("Duplicate found: '%s' <-> '%s' (similarity=%d)", left.name, right.name, similarity);
|
|
1295
1331
|
duplicates.push({
|
|
1296
1332
|
id: `${left.id}::${right.id}`,
|
|
1297
1333
|
similarity,
|
|
@@ -1319,7 +1355,9 @@ var DuplicateService = class {
|
|
|
1319
1355
|
}
|
|
1320
1356
|
}
|
|
1321
1357
|
}
|
|
1358
|
+
log5("Type '%s' comparisons completed in %dms", type, (performance.now() - typeStart).toFixed(2));
|
|
1322
1359
|
}
|
|
1360
|
+
log5("computeDuplicates completed in %dms, found %d raw duplicates", (performance.now() - t0).toFixed(2), duplicates.length);
|
|
1323
1361
|
return duplicates.sort((a, b) => b.similarity - a.similarity);
|
|
1324
1362
|
}
|
|
1325
1363
|
isGroupExcluded(group) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/DryScan.ts","../src/const.ts","../src/IndexUnitExtractor.ts","../src/extractors/java.ts","../src/config/indexConfig.ts","../src/config/configStore.ts","../src/config/dryconfig.ts","../src/Gitignore.ts","../src/db/DryScanDatabase.ts","../src/db/entities/FileEntity.ts","../src/db/entities/IndexUnitEntity.ts","../src/services/RepositoryInitializer.ts","../src/services/EmbeddingService.ts","../src/services/UpdateService.ts","../src/DryScanUpdater.ts","../src/services/DuplicationCache.ts","../src/services/DuplicateService.ts","../src/services/ExclusionService.ts","../src/services/PairingService.ts"],"sourcesContent":["import upath from \"upath\";\nimport fs from \"fs/promises\";\nimport { DuplicateAnalysisResult, DuplicateReport } from \"./types\";\nimport { DRYSCAN_DIR, INDEX_DB } from \"./const\";\nimport { defaultExtractors, IndexUnitExtractor } from \"./IndexUnitExtractor\";\nimport { DryScanDatabase } from \"./db/DryScanDatabase\";\nimport { RepositoryInitializer, InitOptions as InitServiceOptions } from \"./services/RepositoryInitializer\";\nimport { UpdateService } from \"./services/UpdateService\";\nimport { DuplicateService } from \"./services/DuplicateService\";\nimport { ExclusionService } from \"./services/ExclusionService\";\nimport { DryScanServiceDeps } from \"./services/types\";\nimport { configStore } from \"./config/configStore\";\nimport { DryConfig } from \"./types\";\nimport { PairingService } from \"./services/PairingService\";\nimport { existsSync } from \"fs\";\n\nexport type InitOptions = InitServiceOptions;\n\n\nexport class DryScan {\n repoPath: string;\n private readonly extractor: IndexUnitExtractor;\n private db: DryScanDatabase;\n private readonly services: {\n initializer: RepositoryInitializer;\n updater: UpdateService;\n duplicate: DuplicateService;\n exclusion: ExclusionService;\n };\n private readonly serviceDeps: DryScanServiceDeps;\n\n constructor(\n repoPath: string,\n extractor?: IndexUnitExtractor,\n db?: DryScanDatabase\n ) {\n this.repoPath = repoPath;\n this.extractor = extractor ?? new IndexUnitExtractor(repoPath, defaultExtractors(repoPath));\n this.db = db ?? new DryScanDatabase();\n\n this.serviceDeps = {\n repoPath: this.repoPath,\n db: this.db,\n extractor: this.extractor,\n pairing: new PairingService(this.extractor),\n };\n\n const exclusion = new ExclusionService(this.serviceDeps);\n this.services = {\n initializer: new RepositoryInitializer(this.serviceDeps, exclusion),\n updater: new UpdateService(this.serviceDeps, exclusion),\n duplicate: new DuplicateService(this.serviceDeps),\n exclusion,\n };\n }\n\n /**\n * Initializes the DryScan repository with a 3-phase analysis:\n * Phase 1: Extract and save all functions\n * Phase 2: Resolve and save internal dependencies\n * Phase 3: Compute and save semantic embeddings\n */\n async init(options?: InitOptions): Promise<void> {\n console.log(`[DryScan] Initializing repository at ${this.repoPath}`);\n\n const dryDir = upath.join(this.repoPath, DRYSCAN_DIR);\n if (existsSync(dryDir)) {\n console.warn(`[DryScan] Warning: a '.dry' folder already exists at ${dryDir}.`);\n }\n console.log(\"[DryScan] Preparing database and cache...\");\n await configStore.init(this.repoPath);\n await this.ensureDatabase();\n console.log(\"[DryScan] Starting initial scan (may take a moment)...\");\n await this.services.initializer.init(options);\n console.log(\"[DryScan] Initial scan complete.\");\n }\n\n /**\n * Updates the index by detecting changed, new, and deleted files.\n * Only reprocesses units in changed files for efficiency.\n * Delegates to DryScanUpdater module for implementation.\n * \n * Update process:\n * 1. List all current source files in repository\n * 2. For each file, check if it's new, changed, or unchanged (via mtime + checksum)\n * 3. Remove old units from changed/deleted files\n * 4. Extract and save units from new/changed files\n * 5. Recompute internal dependencies for affected units\n * 6. Recompute embeddings for affected units\n * 7. Update file tracking metadata\n */\n async updateIndex(): Promise<void> {\n console.log(`[DryScan] Updating index at ${this.repoPath}...`);\n console.log(\"[DryScan] Checking for file changes...\");\n const start = Date.now();\n await this.ensureDatabase();\n await this.services.updater.updateIndex();\n const duration = Date.now() - start;\n console.log(`[DryScan] Index update complete. Took ${duration}ms.`);\n }\n\n\n /**\n * Runs duplicate detection and returns a normalized report payload ready for persistence or display.\n */\n async buildDuplicateReport(): Promise<DuplicateReport> {\n const config = await this.loadConfig();\n const analysis = await this.findDuplicates(config);\n return {\n version: 1,\n generatedAt: new Date().toISOString(),\n threshold: config.threshold,\n grade: analysis.score.grade,\n score: analysis.score,\n duplicates: analysis.duplicates,\n };\n }\n\n /**\n * Finds duplicate code blocks using cosine similarity on embeddings.\n * Automatically updates the index before searching to ensure results are current.\n * Compares all function pairs and returns groups with similarity above the configured threshold.\n *\n * @returns Analysis result with duplicate groups and duplication score\n */\n private async findDuplicates(config: DryConfig): Promise<DuplicateAnalysisResult> {\n console.log(`[DryScan] Finding duplicates (threshold: ${config.threshold})...`);\n await this.ensureDatabase();\n\n console.log(\"[DryScan] Updating index...\");\n const updateStart = Date.now();\n await this.updateIndex();\n const updateDuration = Date.now() - updateStart;\n console.log(`[DryScan] Index update took ${updateDuration}ms.`);\n\n console.log(\"[DryScan] Detecting duplicates...\");\n const dupStart = Date.now();\n const result = await this.services.duplicate.findDuplicates(config);\n const dupDuration = Date.now() - dupStart;\n console.log(`[DryScan] Duplicate detection took ${dupDuration}ms.`);\n\n return result;\n }\n\n /**\n * Cleans excludedPairs entries that no longer match any indexed units.\n * Runs an update first to ensure the index reflects current code.\n */\n async cleanExclusions(): Promise<{ removed: number; kept: number }> {\n await this.updateIndex();\n return this.services.exclusion.cleanExclusions();\n }\n\n private async ensureDatabase(): Promise<void> {\n if (this.db.isInitialized()) return;\n const dbPath = upath.join(this.repoPath, DRYSCAN_DIR, INDEX_DB);\n await fs.mkdir(upath.dirname(dbPath), { recursive: true });\n await this.db.init(dbPath);\n }\n\n private async loadConfig(): Promise<DryConfig> {\n return configStore.get(this.repoPath);\n }\n\n}\n","export const DRYSCAN_DIR = \".dry\";\nexport const INDEX_DB = \"index.db\";\nexport const REPORTS_DIR = \"reports\";\nexport const FILE_CHECKSUM_ALGO = \"md5\";\nexport const BLOCK_HASH_ALGO = \"sha1\";","import path from \"path\";\nimport type { Stats } from \"fs\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport crypto from \"node:crypto\";\nimport debug from \"debug\";\nimport { glob } from \"glob-gitignore\";\nimport { IndexUnit } from \"./types\";\nimport { LanguageExtractor } from \"./extractors/LanguageExtractor\";\nimport { JavaExtractor } from \"./extractors/java\";\nimport { FILE_CHECKSUM_ALGO } from \"./const\";\nimport { configStore } from \"./config/configStore\";\nimport { DryConfig } from \"./types\";\nimport { Gitignore } from \"./Gitignore\"\nimport { Ignore } from \"ignore\";\n\nconst log = debug(\"DryScan:Extractor\");\n\nexport type { LanguageExtractor } from \"./extractors/LanguageExtractor\";\n/**\n * Returns the default set of language extractors supported by DryScan.\n * Extend/override by passing custom extractors into the IndexUnitExtractor constructor.\n */\nexport function defaultExtractors(repoPath: string): LanguageExtractor[] {\n return [new JavaExtractor(repoPath)];\n}\n\n/**\n * Extracts and indexes code units (classes, functions, blocks) for a repository.\n * Owns shared file-system helpers and delegates language-specific parsing to LanguageExtractors.\n */\nexport class IndexUnitExtractor {\n private readonly root: string;\n readonly extractors: LanguageExtractor[];\n private readonly gitignore: Gitignore;\n\n constructor(\n rootPath: string,\n extractors?: LanguageExtractor[]\n ) {\n this.root = rootPath;\n this.extractors = extractors ?? defaultExtractors(rootPath);\n this.gitignore = new Gitignore(this.root);\n log(\"Initialized extractor for %s\", this.root);\n }\n\n /**\n * Lists all supported source files from a path. Honors exclusion globs from config.\n */\n async listSourceFiles(dirPath: string): Promise<string[]> {\n const target = await this.resolveTarget(dirPath);\n const config = await this.loadConfig();\n const ignoreMatcher = await this.gitignore.buildMatcher(config);\n\n if (target.stat.isFile()) {\n return this.filterSingleFile(target.baseRel, ignoreMatcher);\n }\n\n const matches = await this.globSourceFiles(target.baseRel);\n return this.filterSupportedFiles(matches, ignoreMatcher);\n }\n\n /**\n * Computes MD5 checksum of file content to track changes.\n */\n async computeChecksum(filePath: string): Promise<string> {\n const fullPath = path.isAbsolute(filePath)\n ? filePath\n : path.join(this.root, filePath);\n\n const content = await fs.readFile(fullPath, \"utf8\");\n return crypto.createHash(FILE_CHECKSUM_ALGO).update(content).digest(\"hex\");\n }\n\n /**\n * Scans a file or directory and extracts indexable units using the matching LanguageExtractor.\n * The returned units have repo-relative file paths and no embedding attached.\n */\n async scan(targetPath: string): Promise<IndexUnit[]> {\n const fullPath = path.isAbsolute(targetPath)\n ? targetPath\n : path.join(this.root, targetPath);\n\n const stat = await fs.stat(fullPath).catch(() => null);\n if (!stat) {\n throw new Error(`Path not found: ${fullPath}`);\n }\n\n if (stat.isDirectory()) {\n log(\"Scanning directory %s\", fullPath);\n return this.scanDirectory(fullPath);\n }\n\n return this.scanFile(fullPath);\n }\n\n\n /**\n * Scans a directory recursively, extracting units from supported files while honoring exclusions.\n */\n private async scanDirectory(dir: string): Promise<IndexUnit[]> {\n const out: IndexUnit[] = [];\n const relDir = this.relPath(dir);\n const files = await this.listSourceFiles(relDir);\n for (const relFile of files) {\n const absFile = path.join(this.root, relFile);\n const extracted = await this.tryScanSupportedFile(absFile);\n out.push(...extracted);\n }\n return out;\n }\n\n /**\n * Scans a single file and extracts supported units.\n */\n private async scanFile(filePath: string): Promise<IndexUnit[]> {\n return this.tryScanSupportedFile(filePath, true);\n }\n\n /**\n * Extracts units from a supported file.\n * Optionally throws when the file type is unsupported (used when scanning an explicit file).\n */\n private async tryScanSupportedFile(filePath: string, throwOnUnsupported = false): Promise<IndexUnit[]> {\n const extractor = this.extractors.find(ex => ex.supports(filePath));\n if (!extractor) {\n if (throwOnUnsupported) {\n throw new Error(`Unsupported file type: ${filePath}`);\n }\n return [];\n }\n const rel = this.relPath(filePath);\n if (await this.shouldExclude(rel)) {\n log(\"Skipping excluded file %s\", rel);\n return [];\n }\n const source = await fs.readFile(filePath, \"utf8\");\n const units = await extractor.extractFromText(rel, source);\n log(\"Extracted %d units from %s\", units.length, rel);\n return units.map(unit => ({\n ...unit,\n filePath: rel,\n embedding: undefined,\n }));\n }\n\n /**\n * Converts an absolute path to a repo-relative, normalized (POSIX-style) path.\n * This keeps paths stable across platforms and consistent in the index/DB.\n */\n private relPath(absPath: string): string {\n return this.normalizeRelPath(upath.relative(this.root, absPath));\n }\n\n /**\n * Returns true if a repo-relative path matches any configured exclusion glob.\n */\n private async shouldExclude(relPath: string): Promise<boolean> {\n const config = await this.loadConfig();\n const ignoreMatcher = await this.gitignore.buildMatcher(config);\n return ignoreMatcher.ignores(this.normalizeRelPath(relPath));\n }\n\n private async loadConfig(): Promise<DryConfig> {\n return await configStore.get(this.root);\n }\n\n /**\n * Normalizes repo-relative paths and strips leading \"./\" to keep matcher inputs consistent.\n */\n private normalizeRelPath(relPath: string): string {\n const normalized = upath.normalizeTrim(relPath);\n return normalized.startsWith(\"./\") ? normalized.slice(2) : normalized;\n }\n\n private async resolveTarget(dirPath: string): Promise<{ fullPath: string; baseRel: string; stat: Stats; }> {\n const fullPath = path.isAbsolute(dirPath) ? dirPath : path.join(this.root, dirPath);\n const stat = await fs.stat(fullPath).catch(() => null);\n if (!stat) {\n throw new Error(`Path not found: ${fullPath}`);\n }\n const baseRel = this.relPath(fullPath);\n log(\"Listing source files under %s\", fullPath);\n return { fullPath, baseRel, stat };\n }\n\n private async filterSingleFile(baseRel: string, ignoreMatcher: Ignore): Promise<string[]> {\n const relFile = this.normalizeRelPath(baseRel);\n if (ignoreMatcher.ignores(relFile)) return [];\n return this.extractors.some((ex) => ex.supports(relFile)) ? [relFile] : [];\n }\n\n private async globSourceFiles(baseRel: string): Promise<string[]> {\n const pattern = baseRel ? `${baseRel.replace(/\\\\/g, \"/\")}/**/*` : \"**/*\";\n const matches = await glob(pattern, {\n cwd: this.root,\n dot: false,\n nodir: true,\n });\n return matches.map((p: string) => this.normalizeRelPath(p));\n }\n\n private filterSupportedFiles(relPaths: string[], ignoreMatcher: Ignore): string[] {\n return relPaths\n .filter((relPath: string) => !ignoreMatcher.ignores(relPath))\n .filter((relPath: string) => this.extractors.some((ex) => ex.supports(relPath)));\n }\n}\n","import crypto from \"node:crypto\";\nimport Parser from \"tree-sitter\";\nimport Java from \"tree-sitter-java\";\nimport { LanguageExtractor } from \"./LanguageExtractor\";\nimport { IndexUnit, IndexUnitType } from \"../types\";\nimport { indexConfig } from \"../config/indexConfig\";\nimport { DryConfig } from \"../types\";\nimport { configStore } from \"../config/configStore\";\nimport { BLOCK_HASH_ALGO } from \"../const\";\n\nexport class JavaExtractor implements LanguageExtractor {\n readonly id = \"java\";\n readonly exts = [\".java\"];\n\n private parser: Parser;\n private readonly repoPath: string;\n private config?: DryConfig;\n\n constructor(repoPath: string) {\n this.repoPath = repoPath;\n this.parser = new Parser();\n this.parser.setLanguage(Java);\n }\n\n supports(filePath: string): boolean {\n const lower = filePath.toLowerCase();\n return this.exts.some((ext) => lower.endsWith(ext));\n }\n\n async extractFromText(fileRelPath: string, source: string): Promise<IndexUnit[]> {\n if (!source.trim()) return [];\n\n this.config = await configStore.get(this.repoPath);\n\n const tree = this.parser.parse(source);\n const units: IndexUnit[] = [];\n\n const visit = (node: Parser.SyntaxNode, currentClass?: IndexUnit) => {\n if (this.isClassNode(node)) {\n const className = this.getClassName(node, source) || \"<anonymous>\";\n if (this.isDtoClass(node, source, className)) {\n return;\n }\n const startLine = node.startPosition.row;\n const endLine = node.endPosition.row;\n const classLength = endLine - startLine;\n const skipClass = this.shouldSkip(IndexUnitType.CLASS, className, classLength);\n const classId = this.buildId(IndexUnitType.CLASS, className, startLine, endLine);\n const code = this.stripComments(this.stripClassBody(node, source));\n const classUnit: IndexUnit = {\n id: classId,\n name: className,\n filePath: fileRelPath,\n startLine,\n endLine,\n code,\n unitType: IndexUnitType.CLASS,\n children: [],\n };\n if (!skipClass) {\n units.push(classUnit);\n }\n\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (child) visit(child, skipClass ? undefined : classUnit);\n }\n return;\n }\n\n if (this.isFunctionNode(node)) {\n const fnUnit = this.buildFunctionUnit(node, source, fileRelPath, currentClass);\n const fnLength = fnUnit.endLine - fnUnit.startLine;\n const bodyNode = this.getFunctionBody(node);\n const skipFunction = this.shouldSkip(IndexUnitType.FUNCTION, fnUnit.name, fnLength);\n\n if (skipFunction) {\n return;\n }\n\n units.push(fnUnit);\n\n if (bodyNode) {\n const blocks = this.extractBlocks(bodyNode, source, fileRelPath, fnUnit);\n units.push(...blocks);\n }\n }\n\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (child) visit(child, currentClass);\n }\n };\n\n visit(tree.rootNode);\n\n //remove duplicates if any\n return this.removeDuplicates(units);\n }\n\n unitLabel(unit: IndexUnit): string | null {\n if (unit.unitType === IndexUnitType.CLASS) return unit.filePath;\n if (unit.unitType === IndexUnitType.FUNCTION) return this.canonicalFunctionSignature(unit);\n if (unit.unitType === IndexUnitType.BLOCK) return this.normalizedBlockHash(unit);\n return unit.name;\n }\n\n private isClassNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"class_declaration\";\n }\n\n private getClassName(node: Parser.SyntaxNode, source: string): string | null {\n const nameNode = node.childForFieldName?.(\"name\");\n return nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : null;\n }\n\n private isFunctionNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"method_declaration\" || node.type === \"constructor_declaration\";\n }\n\n private getFunctionName(node: Parser.SyntaxNode, source: string, parentClass?: IndexUnit): string | null {\n const nameNode = node.childForFieldName?.(\"name\");\n const nameText = nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : \"<anonymous>\";\n return parentClass ? `${parentClass.name}.${nameText}` : nameText;\n }\n\n private getFunctionBody(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n return node.childForFieldName?.(\"body\") ?? null;\n }\n\n private isBlockNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"block\";\n }\n\n private getMethodBodiesForClass(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n const bodies: Parser.SyntaxNode[] = [];\n const classBody = node.children.find(child => child.type === \"class_body\");\n if (!classBody) return bodies;\n \n for (let i = 0; i < classBody.namedChildCount; i++) {\n const child = classBody.namedChild(i);\n if (!child) continue;\n if (child.type === \"method_declaration\" || child.type === \"constructor_declaration\") {\n const body = child.childForFieldName?.(\"body\");\n if (body) bodies.push(body);\n }\n }\n return bodies;\n }\n\n private canonicalFunctionSignature(unit: IndexUnit): string {\n const arity = this.extractArity(unit.code);\n return `${unit.name}(arity:${arity})`;\n }\n\n private normalizedBlockHash(unit: IndexUnit): string {\n const normalized = this.normalizeCode(unit.code);\n return crypto.createHash(BLOCK_HASH_ALGO).update(normalized).digest(\"hex\");\n }\n\n private shouldSkip(unitType: IndexUnitType, name: string, lineCount: number): boolean {\n if (!this.config) {\n throw new Error(\"Config not loaded before skip evaluation\");\n }\n const config = this.config;\n const minLines = unitType === IndexUnitType.BLOCK\n ? Math.max(indexConfig.blockMinLines, config.minBlockLines ?? 0)\n : config.minLines;\n const belowMin = minLines > 0 && lineCount < minLines;\n const trivial = unitType === IndexUnitType.FUNCTION && this.isTrivialFunction(name);\n return belowMin || trivial;\n }\n\n private isTrivialFunction(fullName: string): boolean {\n const simpleName = fullName.split(\".\").pop() || fullName;\n const isGetter = /^(get|is)[A-Z]/.test(simpleName);\n const isSetter = /^set[A-Z]/.test(simpleName);\n return isGetter || isSetter;\n }\n\n private isDtoClass(node: Parser.SyntaxNode, source: string, className: string): boolean {\n const classBody = node.children.find((child) => child.type === \"class_body\");\n if (!classBody) return false;\n\n let hasField = false;\n\n for (let i = 0; i < classBody.namedChildCount; i++) {\n const child = classBody.namedChild(i);\n if (!child) continue;\n\n if (child.type === \"field_declaration\") {\n hasField = true;\n continue;\n }\n\n if (child.type.includes(\"annotation\")) {\n continue;\n }\n\n if (child.type === \"method_declaration\" || child.type === \"constructor_declaration\") {\n const simpleName = this.getSimpleFunctionName(child, source);\n const fullName = `${className}.${simpleName}`;\n if (!this.isTrivialFunction(fullName)) {\n return false;\n }\n continue;\n }\n\n return false;\n }\n\n return hasField;\n }\n\n private getSimpleFunctionName(node: Parser.SyntaxNode, source: string): string {\n const nameNode = node.childForFieldName?.(\"name\");\n return nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : \"<anonymous>\";\n }\n\n private buildFunctionUnit(\n node: Parser.SyntaxNode,\n source: string,\n file: string,\n parentClass?: IndexUnit\n ): IndexUnit {\n const name = this.getFunctionName(node, source, parentClass) || \"<anonymous>\";\n const startLine = node.startPosition.row;\n const endLine = node.endPosition.row;\n const id = this.buildId(IndexUnitType.FUNCTION, name, startLine, endLine);\n const unit: IndexUnit = {\n id,\n name,\n filePath: file,\n startLine,\n endLine,\n code: this.stripComments(source.slice(node.startIndex, node.endIndex)),\n unitType: IndexUnitType.FUNCTION,\n parentId: parentClass?.id,\n parent: parentClass,\n };\n if (parentClass) {\n parentClass.children = parentClass.children || [];\n parentClass.children.push(unit);\n }\n return unit;\n }\n\n private extractBlocks(\n bodyNode: Parser.SyntaxNode,\n source: string,\n file: string,\n parentFunction: IndexUnit\n ): IndexUnit[] {\n const blocks: IndexUnit[] = [];\n\n const visit = (n: Parser.SyntaxNode) => {\n if (this.isBlockNode(n)) {\n const startLine = n.startPosition.row;\n const endLine = n.endPosition.row;\n const lineCount = endLine - startLine;\n if (this.shouldSkip(IndexUnitType.BLOCK, parentFunction.name, lineCount)) {\n return;\n }\n if (lineCount >= indexConfig.blockMinLines) {\n const id = this.buildId(IndexUnitType.BLOCK, parentFunction.name, startLine, endLine);\n const blockUnit: IndexUnit = {\n id,\n name: parentFunction.name,\n filePath: file,\n startLine,\n endLine,\n code: this.stripComments(source.slice(n.startIndex, n.endIndex)),\n unitType: IndexUnitType.BLOCK,\n parentId: parentFunction.id,\n parent: parentFunction,\n };\n parentFunction.children = parentFunction.children || [];\n parentFunction.children.push(blockUnit);\n blocks.push(blockUnit);\n }\n }\n\n for (let i = 0; i < n.namedChildCount; i++) {\n const child = n.namedChild(i);\n if (child) visit(child);\n }\n };\n\n visit(bodyNode);\n return blocks;\n }\n\n private stripClassBody(node: Parser.SyntaxNode, source: string): string {\n const classStart = node.startIndex;\n let code = source.slice(classStart, node.endIndex);\n\n const methodBodies: Array<{ start: number; end: number }> = [];\n const candidates = this.getMethodBodiesForClass(node);\n\n for (const body of candidates) {\n methodBodies.push({ start: body.startIndex - classStart, end: body.endIndex - classStart });\n }\n\n methodBodies.sort((a, b) => b.start - a.start);\n for (const body of methodBodies) {\n code = code.slice(0, body.start) + \" { }\" + code.slice(body.end);\n }\n\n return code;\n }\n\n private buildId(type: IndexUnitType, name: string, startLine: number, endLine: number): string {\n return `${type}:${name}:${startLine}-${endLine}`;\n }\n\n private extractArity(code: string): number {\n const match = code.match(/^[^{]*?\\(([^)]*)\\)/s);\n if (!match) return 0;\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n return params.length;\n }\n\n private normalizeCode(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n const withoutLineComments = withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/g, \"\");\n return withoutLineComments.replace(/\\s+/g, \"\");\n }\n\n private stripComments(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, (match) => match.replace(/[^\\n\\r]/g, \"\"));\n return withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/g, \"\");\n }\n\nprivate removeDuplicates(units: IndexUnit[]): IndexUnit[] | PromiseLike<IndexUnit[]> {\n return Array.from(new Map(units.map(u => [u.id, u])).values());\n}\n}\n\n","export const indexConfig = {\n blockMinLines: 5,\n thresholds: {\n class: 0.88,\n function: 0.88,\n block: 0.88,\n },\n weights: {\n class: { self: 1 },\n function: { self: 0.8, parentClass: 0.2 },\n block: { self: 0.7, parentFunction: 0.2, parentClass: 0.1 },\n },\n};\n","import upath from \"upath\";\nimport { DryConfig } from \"../types\";\nimport { ensureDefaultConfig, resolveDryConfig, saveDryConfig } from \"./dryconfig\";\n\nclass ConfigStore {\n private readonly cache = new Map<string, DryConfig>();\n private readonly loading = new Map<string, Promise<DryConfig>>();\n\n async init(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n return this.load(key, repoPath);\n }\n\n async get(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n const cached = this.cache.get(key);\n if (cached) return cached;\n return this.load(key, repoPath);\n }\n\n async refresh(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n this.cache.delete(key);\n return this.load(key, repoPath);\n }\n\n async save(repoPath: string, config: DryConfig): Promise<void> {\n const key = this.normalize(repoPath);\n await saveDryConfig(repoPath, config);\n this.cache.set(key, config);\n }\n\n private async load(key: string, repoPath: string): Promise<DryConfig> {\n const existing = this.loading.get(key);\n if (existing) return existing;\n\n const promise = ensureDefaultConfig(repoPath).then(() => resolveDryConfig(repoPath)).then((config) => {\n this.cache.set(key, config);\n this.loading.delete(key);\n return config;\n }).catch((err) => {\n this.loading.delete(key);\n throw err;\n });\n\n this.loading.set(key, promise);\n return promise;\n }\n\n private normalize(repoPath: string): string {\n return upath.normalizeTrim(upath.resolve(repoPath));\n }\n}\n\nexport const configStore = new ConfigStore();\n","import fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { Validator, Schema } from \"jsonschema\";\nimport { DryConfig } from \"../types\";\n\n// Baseline config used when no file is present; exported so tests and constructors can seed defaults.\nexport const DEFAULT_CONFIG: DryConfig = {\n excludedPaths: [\n \"**/test/**\",\n ],\n excludedPairs: [],\n minLines: 3,\n minBlockLines: 5,\n threshold: 0.88,\n embeddingSource: \"http://localhost:11434\",\n contextLength: 2048,\n};\n\nconst validator = new Validator();\n\nconst partialConfigSchema: Schema = {\n type: \"object\",\n properties: {\n excludedPaths: { type: \"array\", items: { type: \"string\" } },\n excludedPairs: { type: \"array\", items: { type: \"string\" } },\n minLines: { type: \"number\" },\n minBlockLines: { type: \"number\" },\n threshold: { type: \"number\" },\n embeddingSource: { type: \"string\" },\n contextLength: { type: \"number\" },\n },\n};\n\nconst fullConfigSchema: Schema = {\n ...partialConfigSchema,\n required: [\n \"excludedPaths\",\n \"excludedPairs\",\n \"minLines\",\n \"minBlockLines\",\n \"threshold\",\n \"embeddingSource\",\n \"contextLength\",\n ],\n};\n\nfunction validateConfig(raw: unknown, schema: Schema, source: string): any {\n const result = validator.validate(raw, schema);\n if (!result.valid) {\n const details = result.errors.map((e) => e.stack).join(\"; \");\n throw new Error(`${source} config is invalid: ${details}`);\n }\n return raw;\n}\n\nasync function readConfigFile(repoPath: string): Promise<Partial<DryConfig>> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n try {\n const content = await fs.readFile(configPath, \"utf8\");\n let parsed: Partial<DryConfig> = {};\n try {\n parsed = JSON.parse(content) as Partial<DryConfig>;\n } catch (parseErr) {\n throw new Error(`Invalid JSON in ${configPath}: ${(parseErr as Error).message}`);\n }\n return parsed;\n } catch (err: any) {\n if (err?.code === \"ENOENT\") {\n return {};\n }\n throw err;\n }\n}\n\n/**\n * Resolves the effective config for a repo using defaults merged with any file config.\n */\nexport async function resolveDryConfig(repoPath: string): Promise<DryConfig> {\n const fileConfigRaw = await readConfigFile(repoPath);\n validateConfig(fileConfigRaw, partialConfigSchema, \"Config file\");\n\n const merged = { ...DEFAULT_CONFIG, ...fileConfigRaw };\n validateConfig(merged, fullConfigSchema, \"Merged\");\n return merged as DryConfig;\n}\n\n// Backwards-compatible helper used by existing callers (file + defaults).\nexport async function loadDryConfig(repoPath: string): Promise<DryConfig> {\n return resolveDryConfig(repoPath);\n}\n\nexport async function saveDryConfig(repoPath: string, config: DryConfig): Promise<void> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n validateConfig(config, fullConfigSchema, \"Config to save\");\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), \"utf8\");\n}\n\nexport async function ensureDefaultConfig(repoPath: string): Promise<void> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n const repoExists = await fs.stat(repoPath).then((s) => s.isDirectory()).catch((err: any) => {\n if (err?.code === \"ENOENT\") return false;\n throw err;\n });\n\n if (!repoExists) return;\n\n const exists = await fs.stat(configPath).then(() => true).catch((err: any) => {\n if (err?.code === \"ENOENT\") return false;\n throw err;\n });\n\n if (!exists) {\n await saveDryConfig(repoPath, DEFAULT_CONFIG);\n }\n}\n","import path from \"path\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { glob } from \"glob-gitignore\";\nimport ignore, { Ignore } from \"ignore\";\nimport { DryConfig } from \"./types\";\n\n/**\n * Gitignore helper that builds ignore matchers by combining default rules,\n * repo .gitignore files, and config-driven exclusions.\n */\nexport class Gitignore {\n private readonly defaultIgnores = [\".git/**\", \".dry/**\"];\n\n constructor(private readonly root: string) {}\n\n async buildMatcher(config: DryConfig): Promise<Ignore> {\n const rules = await this.resolveRules(config);\n return ignore({ allowRelativePaths: true }).add(rules);\n }\n\n private async resolveRules(config: DryConfig): Promise<string[]> {\n const gitignoreRules = await this.loadGitignoreRules();\n const configRules = config.excludedPaths || [];\n return [...this.defaultIgnores, ...gitignoreRules, ...configRules];\n }\n\n private async loadGitignoreRules(): Promise<string[]> {\n const gitignoreFiles = await glob(\"**/.gitignore\", {\n cwd: this.root,\n dot: true,\n nodir: true,\n ignore: this.defaultIgnores,\n });\n\n const rules: string[] = [];\n\n for (const file of gitignoreFiles) {\n const absPath = path.join(this.root, file);\n const dir = upath.normalizeTrim(upath.dirname(file));\n const content = await fs.readFile(absPath, \"utf8\").catch(() => \"\");\n const lines = content.split(/\\r?\\n/);\n\n for (const raw of lines) {\n const trimmed = raw.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n\n const negated = trimmed.startsWith(\"!\");\n const body = negated ? trimmed.slice(1) : trimmed;\n\n const scoped = this.scopeRule(body, dir);\n if (!scoped) continue;\n\n rules.push(negated ? `!${scoped}` : scoped);\n }\n }\n\n return rules;\n }\n\n private scopeRule(rule: string, gitignoreDir: string): string | null {\n const cleaned = rule.replace(/^\\//, \"\");\n if (!cleaned) return null;\n\n if (!gitignoreDir || gitignoreDir === \".\") {\n return cleaned;\n }\n\n return upath.normalizeTrim(upath.join(gitignoreDir, cleaned));\n }\n}\n","import \"reflect-metadata\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { DataSource, Repository, In } from \"typeorm\";\nimport { FileEntity } from \"./entities/FileEntity\";\nimport { IndexUnit } from \"../types\";\nimport { IndexUnitEntity } from \"./entities/IndexUnitEntity\";\n\nexport class DryScanDatabase {\n private dataSource?: DataSource;\n private unitRepository?: Repository<IndexUnitEntity>;\n private fileRepository?: Repository<FileEntity>;\n\n isInitialized(): boolean {\n return !!this.dataSource?.isInitialized;\n }\n\n async init(dbPath: string): Promise<void> {\n await fs.mkdir(upath.dirname(dbPath), { recursive: true });\n\n this.dataSource = new DataSource({\n type: \"sqlite\",\n database: dbPath,\n entities: [IndexUnitEntity, FileEntity],\n synchronize: true,\n logging: false,\n });\n\n await this.dataSource.initialize();\n this.unitRepository = this.dataSource.getRepository(IndexUnitEntity);\n this.fileRepository = this.dataSource.getRepository(FileEntity);\n }\n\n async saveUnit(unit: IndexUnit): Promise<void> {\n await this.saveUnits(unit);\n }\n\n async saveUnits(units: IndexUnit | IndexUnit[]): Promise<void> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n const payload = Array.isArray(units) ? units : [units];\n const BATCH_SIZE = 500;\n for (let i = 0; i < payload.length; i += BATCH_SIZE) {\n console.debug(`[DryScanDatabase] Saving units ${i + 1}-${Math.min(i + BATCH_SIZE, payload.length)} of ${payload.length}...`);\n const batch = payload.slice(i, i + BATCH_SIZE);\n await this.unitRepository.save(batch);\n }\n }\n\n async getUnit(id: string): Promise<IndexUnit | null> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.findOne({ \n where: { id },\n relations: [\"children\", \"parent\"]\n });\n }\n\n async getAllUnits(): Promise<IndexUnit[]> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.find({ relations: [\"children\", \"parent\"] });\n }\n\n async updateUnit(unit: IndexUnit): Promise<void> {\n await this.saveUnits(unit);\n }\n\n async updateUnits(units: IndexUnit | IndexUnit[]): Promise<void> {\n await this.saveUnits(units);\n }\n\n /**\n * Returns total count of indexed units.\n */\n async countUnits(): Promise<number> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.count();\n }\n\n /**\n * Removes index units by their file paths.\n * Used during incremental updates when files change.\n */\n async removeUnitsByFilePaths(filePaths: string[]): Promise<void> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n await this.unitRepository.delete({ filePath: In(filePaths) });\n }\n\n /**\n * Saves file metadata (path, checksum, mtime) to track changes.\n */\n async saveFile(file: FileEntity): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.save(file);\n }\n\n /**\n * Saves multiple file metadata entries.\n */\n async saveFiles(files: FileEntity[]): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.save(files);\n }\n\n /**\n * Gets file metadata by file path.\n */\n async getFile(filePath: string): Promise<FileEntity | null> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n return this.fileRepository.findOne({ where: { filePath } });\n }\n\n /**\n * Gets all tracked files.\n */\n async getAllFiles(): Promise<FileEntity[]> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n return this.fileRepository.find();\n }\n\n /**\n * Removes file metadata entries by file paths.\n * Used when files are deleted from repository.\n */\n async removeFilesByFilePaths(filePaths: string[]): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.delete({ filePath: In(filePaths) });\n }\n\n async close(): Promise<void> {\n if (this.dataSource?.isInitialized) {\n await this.dataSource.destroy();\n }\n }\n}\n","import { Entity, PrimaryColumn, Column } from \"typeorm\";\n\n/**\n * Represents a tracked source file in the repository.\n * Used to detect changes via checksum and mtime for incremental updates.\n */\n@Entity(\"files\")\nexport class FileEntity {\n /**\n * Relative path to the file from repository root.\n * Used as primary key for uniqueness.\n */\n @PrimaryColumn(\"text\")\n filePath!: string;\n\n /**\n * MD5 checksum of file content.\n * Used to detect content changes.\n */\n @Column(\"text\")\n checksum!: string;\n\n /**\n * Last modification time in milliseconds since epoch.\n * Used as fast sanity check before computing checksum.\n */\n @Column(\"integer\")\n mtime!: number;\n}\n","import {\n Column,\n Entity,\n JoinColumn,\n ManyToOne,\n OneToMany,\n PrimaryColumn,\n RelationId,\n} from \"typeorm\";\nimport { IndexUnit, IndexUnitType } from \"../../types\";\n\n@Entity(\"index_units\")\nexport class IndexUnitEntity implements IndexUnit {\n @PrimaryColumn(\"text\")\n id!: string;\n\n @Column(\"text\")\n name!: string;\n\n @Column(\"text\")\n filePath!: string;\n\n @Column(\"integer\")\n startLine!: number;\n\n @Column(\"integer\")\n endLine!: number;\n\n @Column(\"text\")\n code!: string;\n\n @Column(\"text\")\n unitType!: IndexUnitType;\n\n @ManyToOne(() => IndexUnitEntity, (unit) => unit.children, {\n nullable: true,\n onDelete: \"CASCADE\",\n })\n @JoinColumn({ name: \"parent_id\" })\n parent?: IndexUnitEntity | null;\n\n @RelationId((unit: IndexUnitEntity) => unit.parent)\n parentId?: string | null;\n\n @OneToMany(() => IndexUnitEntity, (unit) => unit.parent, { nullable: true })\n children?: IndexUnitEntity[];\n\n @Column(\"simple-array\", { nullable: true })\n embedding?: number[] | null;\n}\n","import path from \"path\";\nimport fs from \"fs/promises\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { ExclusionService } from \"./ExclusionService\";\nimport { IndexUnit } from \"../types\";\nimport { EmbeddingService } from \"./EmbeddingService\";\nimport { FileEntity } from \"../db/entities/FileEntity\";\nimport { IndexUnitExtractor } from \"../IndexUnitExtractor\";\n\nexport interface InitOptions {\n skipEmbeddings?: boolean;\n}\n\nexport class RepositoryInitializer {\n constructor(\n private readonly deps: DryScanServiceDeps,\n private readonly exclusionService: ExclusionService\n ) {}\n\n async init(options?: InitOptions): Promise<void> {\n const extractor = this.deps.extractor;\n\n console.log(\"[DryScan] Phase 1/3: Extracting code units...\");\n await this.initUnits(extractor);\n console.log(\"[DryScan] Phase 2/3: Computing embeddings (may be slow)...\");\n await this.computeEmbeddings(options?.skipEmbeddings === true);\n console.log(\"[DryScan] Phase 3/3: Tracking files...\");\n await this.trackFiles(extractor);\n await this.exclusionService.cleanupExcludedFiles();\n console.log(\"[DryScan] Initialization phases complete.\");\n }\n\n private async initUnits(extractor: IndexUnitExtractor): Promise<void> {\n const units = await extractor.scan(this.deps.repoPath);\n console.log(`[DryScan] Extracted ${units.length} index units.`);\n await this.deps.db.saveUnits(units);\n }\n\n private async computeEmbeddings(skipEmbeddings: boolean): Promise<void> {\n if (skipEmbeddings) {\n console.log(\"[DryScan] Skipping embedding computation by request.\");\n return;\n }\n const allUnits: IndexUnit[] = await this.deps.db.getAllUnits();\n const total = allUnits.length;\n console.log(`[DryScan] Computing embeddings for ${total} units...`);\n\n const updated: IndexUnit[] = [];\n const progressInterval = Math.max(1, Math.ceil(total / 10));\n const embeddingService = new EmbeddingService(this.deps.repoPath);\n\n for (let i = 0; i < total; i++) {\n const unit = allUnits[i];\n try {\n const enriched = await embeddingService.addEmbedding(unit);\n updated.push(enriched);\n } catch (err: any) {\n console.error(\n `[DryScan] Embedding failed for ${unit.filePath} (${unit.name}): ${err?.message || err}`\n );\n throw err;\n }\n\n const completed = i + 1;\n if (completed === total || completed % progressInterval === 0) {\n const pct = Math.floor((completed / total) * 100);\n console.log(`[DryScan] Embeddings ${completed}/${total} (${pct}%)`);\n }\n }\n\n await this.deps.db.updateUnits(updated);\n }\n\n private async trackFiles(extractor: IndexUnitExtractor): Promise<void> {\n const allFunctions = await extractor.listSourceFiles(this.deps.repoPath);\n const fileEntities: FileEntity[] = [];\n\n for (const relPath of allFunctions) {\n const fullPath = path.join(this.deps.repoPath, relPath);\n const stat = await fs.stat(fullPath);\n const checksum = await extractor.computeChecksum(fullPath);\n\n const fileEntity = new FileEntity();\n fileEntity.filePath = relPath;\n fileEntity.checksum = checksum;\n fileEntity.mtime = stat.mtimeMs;\n fileEntities.push(fileEntity);\n }\n\n await this.deps.db.saveFiles(fileEntities);\n console.log(`[DryScan] Tracked ${fileEntities.length} files.`);\n }\n}","import debug from \"debug\";\nimport { OllamaEmbeddings } from \"@langchain/ollama\";\nimport { HuggingFaceInferenceEmbeddings } from \"@langchain/community/embeddings/hf\";\nimport { IndexUnit } from \"../types\";\nimport { configStore } from \"../config/configStore\";\n\nconst log = debug(\"DryScan:EmbeddingService\");\n\n// Model names for each provider\nconst OLLAMA_MODEL = \"qwen3-embedding:0.6b\";\nconst HUGGINGFACE_MODEL = \"Qwen/Qwen3-Embedding-0.6B\";\n\nexport class EmbeddingService {\n constructor(private readonly repoPath: string) { }\n\n /**\n * Generates an embedding for the given index unit using the configured provider.\n * Skips embedding if code exceeds the configured context length.\n */\n async addEmbedding(fn: IndexUnit): Promise<IndexUnit> {\n const config = await configStore.get(this.repoPath);\n const maxContext = config?.contextLength ?? 2048;\n if (fn.code.length > maxContext) {\n log(\n \"Skipping embedding for %s (code length %d exceeds context %d)\",\n fn.id,\n fn.code.length,\n maxContext\n );\n return { ...fn, embedding: null };\n }\n\n const source = config.embeddingSource;\n if (!source) {\n const message = `Embedding source is not configured for repository at ${this.repoPath}`;\n log(message);\n throw new Error(message);\n }\n\n const embeddings = this.buildProvider(source);\n const embedding = await embeddings.embedQuery(fn.code);\n return { ...fn, embedding };\n }\n\n /**\n * Builds the embedding provider based on the source configuration.\n * - URL (http/https): Uses Ollama with \"embeddinggemma\" model\n * - \"huggingface\": Uses HuggingFace Inference API with \"embeddinggemma-300m\" model\n */\n private buildProvider(source: string) {\n // HuggingFace Inference API\n if (source.toLowerCase() === \"huggingface\") {\n log(\"Using HuggingFace Inference with model: %s\", HUGGINGFACE_MODEL);\n return new HuggingFaceInferenceEmbeddings({\n model: HUGGINGFACE_MODEL,\n provider: \"hf-inference\",\n });\n }\n\n // Ollama keyword or direct URL\n const ollamaBaseUrl = this.resolveOllamaBaseUrl(source);\n if (ollamaBaseUrl !== null) {\n log(\"Using Ollama%s with model: %s\", ollamaBaseUrl ? ` at ${ollamaBaseUrl}` : \"\", OLLAMA_MODEL);\n return new OllamaEmbeddings({ model: OLLAMA_MODEL, ...(ollamaBaseUrl && { baseUrl: ollamaBaseUrl }) });\n }\n\n const message = `Unsupported embedding source: ${source || \"(empty)\"}. Use \"huggingface\" or an Ollama URL.`;\n log(message);\n throw new Error(message);\n }\n\n /**\n * Returns the Ollama base URL if source is an HTTP URL, undefined if source is \"ollama\" (use default),\n * or null if source is not an Ollama provider at all.\n */\n private resolveOllamaBaseUrl(source: string): string | undefined | null {\n if (/^https?:\\/\\//i.test(source)) return source;\n if (source.toLowerCase() === \"ollama\") return undefined;\n return null;\n }\n}","import debug from \"debug\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { ExclusionService } from \"./ExclusionService\";\nimport { performIncrementalUpdate } from \"../DryScanUpdater\";\nimport { DuplicationCache } from \"./DuplicationCache\";\n\nconst log = debug(\"DryScan:UpdateService\");\n\nexport class UpdateService {\n constructor(\n private readonly deps: DryScanServiceDeps,\n private readonly exclusionService: ExclusionService\n ) {}\n\n async updateIndex(): Promise<void> {\n const extractor = this.deps.extractor;\n const cache = DuplicationCache.getInstance();\n\n try {\n const changeSet = await performIncrementalUpdate(this.deps.repoPath, extractor, this.deps.db);\n await this.exclusionService.cleanupExcludedFiles();\n await cache.invalidate([...changeSet.changed, ...changeSet.deleted]);\n } catch (err) {\n log(\"Error during index update:\", err);\n throw err;\n }\n }\n}","import path from \"path\";\nimport fs from \"fs/promises\";\nimport debug from \"debug\";\nimport { IndexUnit } from \"./types\";\nimport { IndexUnitExtractor } from \"./IndexUnitExtractor\";\nimport { DryScanDatabase } from \"./db/DryScanDatabase\";\nimport { FileEntity } from \"./db/entities/FileEntity\";\nimport { EmbeddingService } from \"./services/EmbeddingService\";\n\nconst log = debug(\"DryScan:Updater\");\n\n/**\n * DryScan Updater Module\n * \n * This module contains all incremental update logic for DryScan.\n * Separated from DryScan.ts to keep that file focused on core operations.\n * \n * Represents the result of change detection.\n * Categorizes files into added, changed, deleted, and unchanged.\n */\nexport interface FileChangeSet {\n added: string[];\n changed: string[];\n deleted: string[];\n unchanged: string[];\n}\n\n/**\n * Detects which files have been added, changed, or deleted since last scan.\n * Uses mtime as fast check, then checksum for verification.\n * \n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor instance for file operations\n * @param db - Database instance for retrieving tracked files\n * @returns Change set with categorized file paths\n */\nexport async function detectFileChanges(\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase\n): Promise<FileChangeSet> {\n // Get current files in repository\n const currentFiles = await extractor.listSourceFiles(repoPath);\n const currentFileSet = new Set(currentFiles);\n\n // Get tracked files from database\n const trackedFiles = await db.getAllFiles();\n const trackedFileMap = new Map(trackedFiles.map(f => [f.filePath, f]));\n\n const added: string[] = [];\n const changed: string[] = [];\n const unchanged: string[] = [];\n\n // Check each current file\n for (const filePath of currentFiles) {\n const tracked = trackedFileMap.get(filePath);\n \n if (!tracked) {\n // New file\n added.push(filePath);\n continue;\n }\n\n // Check if file changed using mtime first (fast check)\n const fullPath = path.join(repoPath, filePath);\n const stat = await fs.stat(fullPath);\n \n if (stat.mtimeMs !== tracked.mtime) {\n // Mtime changed, verify with checksum\n const currentChecksum = await extractor.computeChecksum(fullPath);\n if (currentChecksum !== tracked.checksum) {\n changed.push(filePath);\n } else {\n // Mtime changed but content same\n unchanged.push(filePath);\n }\n } else {\n unchanged.push(filePath);\n }\n }\n\n // Find deleted files\n const deleted = trackedFiles\n .map(f => f.filePath)\n .filter(fp => !currentFileSet.has(fp));\n\n return { added, changed, deleted, unchanged };\n}\n\n/**\n * Extracts index units from a list of files.\n * Used during incremental updates.\n * \n * @param filePaths - Array of relative file paths to extract from\n * @param extractor - Index unit extractor instance\n * @returns Array of extracted units\n */\nexport async function extractUnitsFromFiles(\n filePaths: string[],\n extractor: IndexUnitExtractor\n): Promise<IndexUnit[]> {\n const allUnits: IndexUnit[] = [];\n \n for (const relPath of filePaths) {\n const functions = await extractor.scan(relPath);\n allUnits.push(...functions);\n }\n \n return allUnits;\n}\n\n/**\n * Updates file tracking metadata after processing changes.\n * Removes deleted files, updates changed files, adds new files.\n * \n * @param changeSet - Set of file changes to apply\n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor for checksum computation\n * @param db - Database instance for file tracking\n */\nexport async function updateFileTracking(\n changeSet: FileChangeSet,\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase\n): Promise<void> {\n // Remove deleted files\n if (changeSet.deleted.length > 0) {\n if (typeof (db as any).removeFilesByFilePaths === \"function\") {\n await (db as any).removeFilesByFilePaths(changeSet.deleted);\n } else if (typeof (db as any).removeFiles === \"function\") {\n await (db as any).removeFiles(changeSet.deleted);\n }\n }\n\n // Create file entities for new and changed files\n const filesToTrack = [...changeSet.added, ...changeSet.changed];\n if (filesToTrack.length > 0) {\n const fileEntities: FileEntity[] = [];\n \n for (const relPath of filesToTrack) {\n const fullPath = path.join(repoPath, relPath);\n const stat = await fs.stat(fullPath);\n const checksum = await extractor.computeChecksum(fullPath);\n \n const fileEntity = new FileEntity();\n fileEntity.filePath = relPath;\n fileEntity.checksum = checksum;\n fileEntity.mtime = stat.mtimeMs;\n \n fileEntities.push(fileEntity);\n }\n \n await db.saveFiles(fileEntities);\n }\n}\n\n/**\n * Performs incremental update of the DryScan index.\n * Detects file changes and reprocesses only affected files.\n * \n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor instance\n * @param db - Database instance (must be initialized)\n */\nexport async function performIncrementalUpdate(\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase,\n): Promise<FileChangeSet> {\n log(\"Starting incremental update\");\n const embeddingService = new EmbeddingService(repoPath);\n \n // Step 1: Detect changes\n const changeSet = await detectFileChanges(repoPath, extractor, db);\n \n if (changeSet.changed.length === 0 && \n changeSet.added.length === 0 && \n changeSet.deleted.length === 0) {\n log(\"No changes detected. Index is up to date.\");\n return changeSet;\n }\n\n log(`Changes detected: ${changeSet.added.length} added, ${changeSet.changed.length} changed, ${changeSet.deleted.length} deleted`);\n\n // Step 2: Remove old data for changed/deleted files\n const filesToRemove = [...changeSet.changed, ...changeSet.deleted];\n if (filesToRemove.length > 0) {\n await db.removeUnitsByFilePaths(filesToRemove);\n log(`Removed units from ${filesToRemove.length} files`);\n }\n\n // Step 3: Extract functions from new/changed files\n const filesToProcess = [...changeSet.added, ...changeSet.changed];\n if (filesToProcess.length > 0) {\n const newUnits = await extractUnitsFromFiles(filesToProcess, extractor);\n await db.saveUnits(newUnits);\n log(`Extracted and saved ${newUnits.length} units from ${filesToProcess.length} files`);\n\n // Step 4: Recompute embeddings for affected units only\n const total = newUnits.length;\n if (total > 0) {\n log(`Recomputing embeddings for ${total} units`);\n const progressInterval = Math.max(1, Math.ceil(total / 10));\n const updatedWithEmbeddings = [] as IndexUnit[];\n\n for (let i = 0; i < total; i++) {\n const unit = newUnits[i];\n try {\n const enriched = await embeddingService.addEmbedding(unit);\n updatedWithEmbeddings.push(enriched);\n } catch (err: any) {\n console.error(\n `[DryScan] embedding failed for ${unit.filePath} (${unit.name}): ${err?.message || err}`\n );\n throw err;\n }\n\n const completed = i + 1;\n if (completed === total || completed % progressInterval === 0) {\n const pct = Math.floor((completed / total) * 100);\n console.log(`[DryScan] Incremental embeddings ${completed}/${total} (${pct}%)`);\n }\n }\n\n await db.updateUnits(updatedWithEmbeddings);\n log(`Recomputed embeddings for ${updatedWithEmbeddings.length} units`);\n }\n }\n\n // Step 5: Update file tracking\n await updateFileTracking(changeSet, repoPath, extractor, db);\n log(\"Incremental update complete\");\n\n return changeSet;\n}\n","import { DuplicateGroup } from \"../types\";\n\n/**\n * In-memory cache for duplicate comparison scores.\n * Stores a global map of comparison keys and a per-file index for fast invalidation.\n */\nexport class DuplicationCache {\n private static instance: DuplicationCache | null = null;\n\n private readonly comparisons = new Map<string, number>();\n private readonly fileIndex = new Map<string, Set<string>>();\n private initialized = false;\n\n static getInstance(): DuplicationCache {\n if (!DuplicationCache.instance) {\n DuplicationCache.instance = new DuplicationCache();\n }\n return DuplicationCache.instance;\n }\n\n /**\n * Updates the cache with fresh duplicate groups. Not awaited by callers to avoid blocking.\n */\n async update(groups: DuplicateGroup[]): Promise<void> {\n if (!groups) return;\n\n for (const group of groups) {\n const key = this.makeKey(group.left.id, group.right.id);\n this.comparisons.set(key, group.similarity);\n this.addKeyForFile(group.left.filePath, key);\n this.addKeyForFile(group.right.filePath, key);\n }\n\n this.initialized = this.initialized || groups.length > 0;\n }\n\n /**\n * Retrieves a cached similarity if present and valid for both file paths.\n * Returns null when the cache has not been initialized or when the pair is missing.\n */\n get(leftId: string, rightId: string, leftFilePath: string, rightFilePath: string): number | null {\n if (!this.initialized) return null;\n\n const key = this.makeKey(leftId, rightId);\n if (!this.fileHasKey(leftFilePath, key) || !this.fileHasKey(rightFilePath, key)) {\n return null;\n }\n\n const value = this.comparisons.get(key);\n return typeof value === \"number\" ? value : null;\n }\n\n /**\n * Invalidates all cached comparisons involving the provided file paths.\n */\n async invalidate(paths: string[]): Promise<void> {\n if (!this.initialized || !paths || paths.length === 0) return;\n\n const unique = new Set(paths);\n for (const filePath of unique) {\n const keys = this.fileIndex.get(filePath);\n if (!keys) continue;\n\n for (const key of keys) {\n this.comparisons.delete(key);\n for (const [otherPath, otherKeys] of this.fileIndex.entries()) {\n if (otherKeys.delete(key) && otherKeys.size === 0) {\n this.fileIndex.delete(otherPath);\n }\n }\n }\n\n this.fileIndex.delete(filePath);\n }\n\n if (this.comparisons.size === 0) {\n this.initialized = false;\n }\n }\n\n /**\n * Clears all cached data. Intended for test setup.\n */\n clear(): void {\n this.comparisons.clear();\n this.fileIndex.clear();\n this.initialized = false;\n }\n\n private addKeyForFile(filePath: string, key: string): void {\n const current = this.fileIndex.get(filePath) ?? new Set<string>();\n current.add(key);\n this.fileIndex.set(filePath, current);\n }\n\n private fileHasKey(filePath: string, key: string): boolean {\n const keys = this.fileIndex.get(filePath);\n return keys ? keys.has(key) : false;\n }\n\n private makeKey(leftId: string, rightId: string): string {\n return [leftId, rightId].sort().join(\"::\");\n }\n}\n","import debug from \"debug\";\nimport shortUuid from \"short-uuid\";\nimport { cosineSimilarity } from \"@langchain/core/utils/math\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { DuplicateAnalysisResult, DuplicateGroup, DuplicationScore, IndexUnit, IndexUnitType } from \"../types\";\nimport { indexConfig } from \"../config/indexConfig\";\nimport { DryConfig } from \"../types\";\nimport { DuplicationCache } from \"./DuplicationCache\";\n\nconst log = debug(\"DryScan:DuplicateService\");\n\nexport class DuplicateService {\n private config?: DryConfig;\n private readonly cache = DuplicationCache.getInstance();\n\n constructor(private readonly deps: DryScanServiceDeps) {}\n\n async findDuplicates(config: DryConfig): Promise<DuplicateAnalysisResult> {\n this.config = config;\n const allUnits = await this.deps.db.getAllUnits();\n if (allUnits.length < 2) {\n const score = this.computeDuplicationScore([], allUnits);\n return { duplicates: [], score };\n }\n\n const thresholds = this.resolveThresholds(config.threshold);\n const duplicates = this.computeDuplicates(allUnits, thresholds);\n const filteredDuplicates = duplicates.filter((group) => !this.isGroupExcluded(group));\n log(\"Found %d duplicate groups\", filteredDuplicates.length);\n\n // Update cache asynchronously; no need to block the main flow.\n this.cache.update(filteredDuplicates).catch((err) => log(\"Cache update failed: %O\", err));\n\n const score = this.computeDuplicationScore(filteredDuplicates, allUnits);\n return { duplicates: filteredDuplicates, score };\n }\n\n private resolveThresholds(functionThreshold?: number): { function: number; block: number; class: number } {\n const defaults = indexConfig.thresholds;\n const clamp = (value: number) => Math.min(1, Math.max(0, value));\n\n const base = functionThreshold ?? defaults.function;\n const blockOffset = defaults.block - defaults.function;\n const classOffset = defaults.class - defaults.function;\n\n const functionThresholdValue = clamp(base);\n return {\n function: functionThresholdValue,\n block: clamp(functionThresholdValue + blockOffset),\n class: clamp(functionThresholdValue + classOffset),\n };\n }\n\n private computeDuplicates(\n units: IndexUnit[],\n thresholds: { function: number; block: number; class: number }\n ): DuplicateGroup[] {\n const duplicates: DuplicateGroup[] = [];\n const byType = new Map<IndexUnitType, IndexUnit[]>();\n\n for (const unit of units) {\n const list = byType.get(unit.unitType) ?? [];\n list.push(unit);\n byType.set(unit.unitType, list);\n }\n\n for (const [type, typedUnits] of byType.entries()) {\n const threshold = this.getThreshold(type, thresholds);\n\n for (let i = 0; i < typedUnits.length; i++) {\n for (let j = i + 1; j < typedUnits.length; j++) {\n const left = typedUnits[i];\n const right = typedUnits[j];\n\n if (this.shouldSkipComparison(left, right)) continue;\n\n const cached = this.cache.get(left.id, right.id, left.filePath, right.filePath);\n let similarity: number | null = null;\n\n if (cached !== null) {\n similarity = cached;\n } else {\n if (!left.embedding || !right.embedding) continue;\n similarity = this.computeWeightedSimilarity(left, right);\n }\n\n if (similarity === null) continue;\n\n if (similarity >= threshold) {\n const exclusionString = this.deps.pairing.pairKeyForUnits(left, right);\n if (!exclusionString) continue;\n\n duplicates.push({\n id: `${left.id}::${right.id}`,\n similarity,\n shortId: shortUuid.generate(),\n exclusionString,\n left: {\n id: left.id,\n name: left.name,\n filePath: left.filePath,\n startLine: left.startLine,\n endLine: left.endLine,\n code: left.code,\n unitType: left.unitType,\n },\n right: {\n id: right.id,\n name: right.name,\n filePath: right.filePath,\n startLine: right.startLine,\n endLine: right.endLine,\n code: right.code,\n unitType: right.unitType,\n },\n });\n }\n }\n }\n }\n\n return duplicates.sort((a, b) => b.similarity - a.similarity);\n }\n\n private isGroupExcluded(group: DuplicateGroup): boolean {\n const config = this.config;\n if (!config || !config.excludedPairs || config.excludedPairs.length === 0) return false;\n const key = this.deps.pairing.pairKeyForUnits(group.left, group.right);\n if (!key) return false;\n const actual = this.deps.pairing.parsePairKey(key);\n if (!actual) return false;\n return config.excludedPairs.some((entry) => {\n const parsed = this.deps.pairing.parsePairKey(entry);\n return parsed ? this.deps.pairing.pairKeyMatches(actual, parsed) : false;\n });\n }\n\n private getThreshold(type: IndexUnitType, thresholds: { function: number; block: number; class: number }): number {\n if (type === IndexUnitType.CLASS) return thresholds.class;\n if (type === IndexUnitType.BLOCK) return thresholds.block;\n return thresholds.function;\n }\n\n private computeWeightedSimilarity(left: IndexUnit, right: IndexUnit): number {\n const selfSimilarity = this.similarityWithFallback(left, right);\n\n if (left.unitType === IndexUnitType.CLASS) {\n return selfSimilarity * indexConfig.weights.class.self;\n }\n\n if (left.unitType === IndexUnitType.FUNCTION) {\n const weights = indexConfig.weights.function;\n const hasParentClass = !!this.findParentOfType(left, IndexUnitType.CLASS) && !!this.findParentOfType(right, IndexUnitType.CLASS);\n const parentClassSimilarity = hasParentClass ? this.parentSimilarity(left, right, IndexUnitType.CLASS) : 0;\n\n // Re-normalize weights when parent context is missing, so standalone units aren't penalized.\n const totalWeight = weights.self + (hasParentClass ? weights.parentClass : 0);\n return ((weights.self * selfSimilarity) + (hasParentClass ? (weights.parentClass * parentClassSimilarity) : 0)) / totalWeight;\n }\n\n const weights = indexConfig.weights.block;\n const hasParentFunction = !!this.findParentOfType(left, IndexUnitType.FUNCTION) && !!this.findParentOfType(right, IndexUnitType.FUNCTION);\n const hasParentClass = !!this.findParentOfType(left, IndexUnitType.CLASS) && !!this.findParentOfType(right, IndexUnitType.CLASS);\n const parentFuncSim = hasParentFunction ? this.parentSimilarity(left, right, IndexUnitType.FUNCTION) : 0;\n const parentClassSim = hasParentClass ? this.parentSimilarity(left, right, IndexUnitType.CLASS) : 0;\n\n // Re-normalize weights when some parent context is missing.\n const totalWeight =\n weights.self +\n (hasParentFunction ? weights.parentFunction : 0) +\n (hasParentClass ? weights.parentClass : 0);\n\n return (\n (weights.self * selfSimilarity) +\n (hasParentFunction ? (weights.parentFunction * parentFuncSim) : 0) +\n (hasParentClass ? (weights.parentClass * parentClassSim) : 0)\n ) / totalWeight;\n }\n\n private parentSimilarity(left: IndexUnit, right: IndexUnit, targetType: IndexUnitType): number {\n const leftParent = this.findParentOfType(left, targetType);\n const rightParent = this.findParentOfType(right, targetType);\n if (!leftParent || !rightParent) return 0;\n return this.similarityWithFallback(leftParent, rightParent);\n }\n\n private similarityWithFallback(left: IndexUnit, right: IndexUnit): number {\n const leftHasEmbedding = this.hasVector(left);\n const rightHasEmbedding = this.hasVector(right);\n\n if (leftHasEmbedding && rightHasEmbedding) {\n return cosineSimilarity([left.embedding as number[]], [right.embedding as number[]])[0][0];\n }\n\n return this.childSimilarity(left, right);\n }\n\n private childSimilarity(left: IndexUnit, right: IndexUnit): number {\n const leftChildren = left.children ?? [];\n const rightChildren = right.children ?? [];\n if (leftChildren.length === 0 || rightChildren.length === 0) return 0;\n\n let best = 0;\n for (const lChild of leftChildren) {\n for (const rChild of rightChildren) {\n if (lChild.unitType !== rChild.unitType) continue;\n const sim = this.similarityWithFallback(lChild, rChild);\n if (sim > best) best = sim;\n }\n }\n return best;\n }\n\n private hasVector(unit: IndexUnit): boolean {\n return Array.isArray(unit.embedding) && unit.embedding.length > 0;\n }\n\n private shouldSkipComparison(left: IndexUnit, right: IndexUnit): boolean {\n if (left.unitType !== IndexUnitType.BLOCK || right.unitType !== IndexUnitType.BLOCK) {\n return false;\n }\n\n if (left.filePath !== right.filePath) {\n return false;\n }\n\n const leftContainsRight = left.startLine <= right.startLine && left.endLine >= right.endLine;\n const rightContainsLeft = right.startLine <= left.startLine && right.endLine >= left.endLine;\n return leftContainsRight || rightContainsLeft;\n }\n\n private findParentOfType(unit: IndexUnit, targetType: IndexUnitType): IndexUnit | null {\n let current: IndexUnit | undefined | null = unit.parent;\n while (current) {\n if (current.unitType === targetType) return current;\n current = current.parent;\n }\n return null;\n }\n\n private computeDuplicationScore(duplicates: DuplicateGroup[], allUnits: IndexUnit[]): DuplicationScore {\n const totalLines = this.calculateTotalLines(allUnits);\n\n if (totalLines === 0 || duplicates.length === 0) {\n return {\n score: 0,\n grade: \"Excellent\",\n totalLines,\n duplicateLines: 0,\n duplicateGroups: 0,\n };\n }\n\n const weightedDuplicateLines = duplicates.reduce((sum, group) => {\n const leftLines = group.left.endLine - group.left.startLine + 1;\n const rightLines = group.right.endLine - group.right.startLine + 1;\n const avgLines = (leftLines + rightLines) / 2;\n return sum + group.similarity * avgLines;\n }, 0);\n\n const score = (weightedDuplicateLines / totalLines) * 100;\n const grade = this.getScoreGrade(score);\n\n return {\n score,\n grade,\n totalLines,\n duplicateLines: Math.round(weightedDuplicateLines),\n duplicateGroups: duplicates.length,\n };\n }\n\n private calculateTotalLines(units: IndexUnit[]): number {\n return units.reduce((sum, unit) => {\n const lines = unit.endLine - unit.startLine + 1;\n return sum + lines;\n }, 0);\n }\n\n private getScoreGrade(score: number): DuplicationScore[\"grade\"] {\n if (score < 5) return \"Excellent\";\n if (score < 15) return \"Good\";\n if (score < 30) return \"Fair\";\n if (score < 50) return \"Poor\";\n return \"Critical\";\n }\n}","import { DryConfig } from \"../types\";\nimport { configStore } from \"../config/configStore\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { IndexUnitType } from \"../types\";\nimport { minimatch } from \"minimatch\";\nimport { ParsedPairKey } from \"./PairingService\";\n\nexport class ExclusionService {\n private config?: DryConfig;\n\n constructor(private readonly deps: DryScanServiceDeps) {}\n\n async cleanupExcludedFiles(): Promise<void> {\n const config = await this.loadConfig();\n if (!config.excludedPaths || config.excludedPaths.length === 0) return;\n\n const units = await this.deps.db.getAllUnits();\n const files = await this.deps.db.getAllFiles();\n\n const unitPathsToRemove = new Set<string>();\n for (const unit of units) {\n if (this.pathExcluded(unit.filePath)) {\n unitPathsToRemove.add(unit.filePath);\n }\n }\n\n const filePathsToRemove = new Set<string>();\n for (const file of files) {\n if (this.pathExcluded(file.filePath)) {\n filePathsToRemove.add(file.filePath);\n }\n }\n\n const paths = [...new Set([...unitPathsToRemove, ...filePathsToRemove])];\n if (paths.length > 0) {\n await this.deps.db.removeUnitsByFilePaths(paths);\n await this.deps.db.removeFilesByFilePaths(paths);\n }\n }\n\n async cleanExclusions(): Promise<{ removed: number; kept: number }> {\n const config = await this.loadConfig();\n const units = await this.deps.db.getAllUnits();\n\n const actualPairsByType = {\n [IndexUnitType.CLASS]: this.buildPairKeys(units, IndexUnitType.CLASS),\n [IndexUnitType.FUNCTION]: this.buildPairKeys(units, IndexUnitType.FUNCTION),\n [IndexUnitType.BLOCK]: this.buildPairKeys(units, IndexUnitType.BLOCK),\n };\n\n const kept: string[] = [];\n const removed: string[] = [];\n\n for (const entry of config.excludedPairs || []) {\n const parsed = this.deps.pairing.parsePairKey(entry);\n if (!parsed) {\n removed.push(entry);\n continue;\n }\n\n const candidates = actualPairsByType[parsed.type];\n const matched = candidates.some((actual) => this.deps.pairing.pairKeyMatches(actual, parsed));\n if (matched) {\n kept.push(entry);\n } else {\n removed.push(entry);\n }\n }\n\n const nextConfig: DryConfig = { ...config, excludedPairs: kept };\n await configStore.save(this.deps.repoPath, nextConfig);\n this.config = nextConfig;\n\n return { removed: removed.length, kept: kept.length };\n }\n\n private pathExcluded(filePath: string): boolean {\n const config = this.config;\n if (!config || !config.excludedPaths || config.excludedPaths.length === 0) return false;\n return config.excludedPaths.some((pattern) => minimatch(filePath, pattern, { dot: true }));\n }\n\n private buildPairKeys(units: any[], type: IndexUnitType): ParsedPairKey[] {\n const typed = units.filter((u) => u.unitType === type);\n const pairs: ParsedPairKey[] = [];\n for (let i = 0; i < typed.length; i++) {\n for (let j = i + 1; j < typed.length; j++) {\n const key = this.deps.pairing.pairKeyForUnits(typed[i], typed[j]);\n const parsed = key ? this.deps.pairing.parsePairKey(key) : null;\n if (parsed) {\n pairs.push(parsed);\n }\n }\n }\n return pairs;\n }\n\n private async loadConfig(): Promise<DryConfig> {\n this.config = await configStore.get(this.deps.repoPath);\n return this.config;\n }\n}","import crypto from \"node:crypto\";\nimport debug from \"debug\";\nimport { minimatch } from \"minimatch\";\nimport { LanguageExtractor } from \"../extractors/LanguageExtractor\";\nimport { IndexUnitExtractor } from \"../IndexUnitExtractor\";\nimport { IndexUnit, IndexUnitType } from \"../types\";\nimport { BLOCK_HASH_ALGO } from \"../const\";\n\nconst log = debug(\"DryScan:pairs\");\n\ntype UnitLike = Pick<IndexUnit, \"unitType\" | \"filePath\" | \"name\" | \"code\">;\n\nexport interface ParsedPairKey {\n type: IndexUnitType;\n left: string;\n right: string;\n key: string;\n}\n\n/**\n * Service for building and parsing pair keys with extractor-aware labeling.\n */\nexport class PairingService {\n constructor(private readonly indexUnitExtractor: IndexUnitExtractor) {}\n\n /**\n * Creates a stable, order-independent key for two units of the same type.\n * Returns null when units differ in type so callers can skip invalid pairs.\n */\n pairKeyForUnits(left: UnitLike, right: UnitLike): string | null {\n if (left.unitType !== right.unitType) {\n log(\"Skipping pair with mismatched types: %s vs %s\", left.unitType, right.unitType);\n return null;\n }\n const type = left.unitType;\n const leftLabel = this.unitLabel(left);\n const rightLabel = this.unitLabel(right);\n const [a, b] = [leftLabel, rightLabel].sort();\n return `${type}|${a}|${b}`;\n }\n\n /**\n * Parses a raw pair key into its components, returning null for malformed values.\n * Sorting is applied so callers can compare pairs without worrying about order.\n */\n parsePairKey(value: string): ParsedPairKey | null {\n const parts = value.split(\"|\");\n if (parts.length !== 3) {\n log(\"Invalid pair key format: %s\", value);\n return null;\n }\n const [typeRaw, leftRaw, rightRaw] = parts;\n const type = this.stringToUnitType(typeRaw);\n if (!type) {\n log(\"Unknown unit type in pair key: %s\", typeRaw);\n return null;\n }\n const [left, right] = [leftRaw, rightRaw].sort();\n return { type, left, right, key: `${type}|${left}|${right}` };\n }\n\n /**\n * Checks whether an actual pair key satisfies a pattern, with glob matching for class paths.\n */\n pairKeyMatches(actual: ParsedPairKey, pattern: ParsedPairKey): boolean {\n if (actual.type !== pattern.type) return false;\n if (actual.type === IndexUnitType.CLASS) {\n // Allow glob matching for class file paths.\n const forward =\n minimatch(actual.left, pattern.left, { dot: true }) &&\n minimatch(actual.right, pattern.right, { dot: true });\n const swapped =\n minimatch(actual.left, pattern.right, { dot: true }) &&\n minimatch(actual.right, pattern.left, { dot: true });\n return forward || swapped;\n }\n\n // Functions and blocks use exact matching on canonical strings.\n return (\n (actual.left === pattern.left && actual.right === pattern.right) ||\n (actual.left === pattern.right && actual.right === pattern.left)\n );\n }\n\n /**\n * Derives a reversible, extractor-aware label for a unit.\n * Extractors may override; fallback uses a fixed format per unit type.\n */\n unitLabel(unit: UnitLike): string {\n const extractor = this.findExtractor(unit.filePath);\n const customLabel = extractor?.unitLabel?.(unit as IndexUnit);\n if (customLabel) return customLabel;\n\n switch (unit.unitType) {\n case IndexUnitType.CLASS:\n return unit.filePath;\n case IndexUnitType.FUNCTION:\n return this.canonicalFunctionSignature(unit);\n case IndexUnitType.BLOCK:\n return this.normalizedBlockHash(unit);\n default:\n return unit.name;\n }\n }\n\n private findExtractor(filePath: string): LanguageExtractor | undefined {\n return this.indexUnitExtractor.extractors.find((ex) => ex.supports(filePath));\n }\n\n private canonicalFunctionSignature(unit: UnitLike): string {\n const arity = this.extractArity(unit.code);\n return `${unit.name}(arity:${arity})`;\n }\n\n /**\n * Normalizes block code (strips comments/whitespace) and hashes it for pair matching.\n */\n private normalizedBlockHash(unit: UnitLike): string {\n const normalized = this.normalizeCode(unit.code);\n return crypto.createHash(BLOCK_HASH_ALGO).update(normalized).digest(\"hex\");\n }\n\n private stringToUnitType(value: string): IndexUnitType | null {\n if (value === IndexUnitType.CLASS) return IndexUnitType.CLASS;\n if (value === IndexUnitType.FUNCTION) return IndexUnitType.FUNCTION;\n if (value === IndexUnitType.BLOCK) return IndexUnitType.BLOCK;\n return null;\n }\n\n private extractArity(code: string): number {\n const match = code.match(/^[^{]*?\\(([^)]*)\\)/s);\n if (!match) return 0;\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n return params.length;\n }\n\n private normalizeCode(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n const withoutLineComments = withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/g, \"\");\n return withoutLineComments.replace(/\\s+/g, \"\");\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAOA,YAAW;AAClB,OAAOC,SAAQ;;;ACDR,IAAM,cAAc;AACpB,IAAM,WAAW;AAEjB,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;;;ACJ/B,OAAOC,WAAU;AAEjB,OAAOC,SAAQ;AACf,OAAOC,YAAW;AAClB,OAAOC,aAAY;AACnB,OAAO,WAAW;AAClB,SAAS,QAAAC,aAAY;;;ACNrB,OAAO,YAAY;AACnB,OAAO,YAAY;AACnB,OAAO,UAAU;;;ACFV,IAAM,cAAc;AAAA,EACzB,eAAe;AAAA,EACf,YAAY;AAAA,IACV,OAAO;AAAA,IACP,UAAU;AAAA,IACV,OAAO;AAAA,EACT;AAAA,EACA,SAAS;AAAA,IACP,OAAO,EAAE,MAAM,EAAE;AAAA,IACjB,UAAU,EAAE,MAAM,KAAK,aAAa,IAAI;AAAA,IACxC,OAAO,EAAE,MAAM,KAAK,gBAAgB,KAAK,aAAa,IAAI;AAAA,EAC5D;AACF;;;ACZA,OAAOC,YAAW;;;ACAlB,OAAO,QAAQ;AACf,OAAO,WAAW;AAClB,SAAS,iBAAyB;AAI3B,IAAM,iBAA4B;AAAA,EACvC,eAAe;AAAA,IACb;AAA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C;AACzD,UAAM,KAAK,GAAG,KAAK,MAAM;AAAA,EAC3B;AAAA,EAEA,MAAc,aAAiC;AAC7C,WAAO,YAAY,IAAI,KAAK,QAAQ;AAAA,EACtC;AAEF;","names":["upath","fs","path","fs","upath","crypto","glob","upath","upath","fs","upath","path","fs","crypto","upath","glob","fs","upath","Column","Entity","PrimaryColumn","PrimaryColumn","Column","Entity","fs","upath","path","fs","debug","log","debug","path","fs","debug","path","fs","debug","log","debug","path","fs","log","debug","debug","log","debug","score","weights","hasParentClass","totalWeight","crypto","debug","minimatch","log","debug","minimatch","crypto","upath","fs"]}
|
|
1
|
+
{"version":3,"sources":["../src/DryScan.ts","../src/const.ts","../src/IndexUnitExtractor.ts","../src/extractors/java.ts","../src/config/indexConfig.ts","../src/config/configStore.ts","../src/config/dryconfig.ts","../src/Gitignore.ts","../src/db/DryScanDatabase.ts","../src/db/entities/FileEntity.ts","../src/db/entities/IndexUnitEntity.ts","../src/services/RepositoryInitializer.ts","../src/services/EmbeddingService.ts","../src/services/UpdateService.ts","../src/DryScanUpdater.ts","../src/services/DuplicationCache.ts","../src/services/DuplicateService.ts","../src/services/ExclusionService.ts","../src/services/PairingService.ts"],"sourcesContent":["import upath from \"upath\";\nimport fs from \"fs/promises\";\nimport { DuplicateAnalysisResult, DuplicateReport } from \"./types\";\nimport { DRYSCAN_DIR, INDEX_DB } from \"./const\";\nimport { defaultExtractors, IndexUnitExtractor } from \"./IndexUnitExtractor\";\nimport { DryScanDatabase } from \"./db/DryScanDatabase\";\nimport { RepositoryInitializer, InitOptions as InitServiceOptions } from \"./services/RepositoryInitializer\";\nimport { UpdateService } from \"./services/UpdateService\";\nimport { DuplicateService } from \"./services/DuplicateService\";\nimport { ExclusionService } from \"./services/ExclusionService\";\nimport { DryScanServiceDeps } from \"./services/types\";\nimport { configStore } from \"./config/configStore\";\nimport { DryConfig } from \"./types\";\nimport { PairingService } from \"./services/PairingService\";\nimport { existsSync } from \"fs\";\n\nexport type InitOptions = InitServiceOptions;\n\n\nexport class DryScan {\n repoPath: string;\n private readonly extractor: IndexUnitExtractor;\n private db: DryScanDatabase;\n private readonly services: {\n initializer: RepositoryInitializer;\n updater: UpdateService;\n duplicate: DuplicateService;\n exclusion: ExclusionService;\n };\n private readonly serviceDeps: DryScanServiceDeps;\n\n constructor(\n repoPath: string,\n extractor?: IndexUnitExtractor,\n db?: DryScanDatabase\n ) {\n this.repoPath = repoPath;\n this.extractor = extractor ?? new IndexUnitExtractor(repoPath, defaultExtractors(repoPath));\n this.db = db ?? new DryScanDatabase();\n\n this.serviceDeps = {\n repoPath: this.repoPath,\n db: this.db,\n extractor: this.extractor,\n pairing: new PairingService(this.extractor),\n };\n\n const exclusion = new ExclusionService(this.serviceDeps);\n this.services = {\n initializer: new RepositoryInitializer(this.serviceDeps, exclusion),\n updater: new UpdateService(this.serviceDeps, exclusion),\n duplicate: new DuplicateService(this.serviceDeps),\n exclusion,\n };\n }\n\n /**\n * Initializes the DryScan repository with a 3-phase analysis:\n * Phase 1: Extract and save all functions\n * Phase 2: Resolve and save internal dependencies\n * Phase 3: Compute and save semantic embeddings\n */\n async init(options?: InitOptions): Promise<void> {\n console.log(`[DryScan] Initializing repository at ${this.repoPath}`);\n\n const dryDir = upath.join(this.repoPath, DRYSCAN_DIR);\n if (existsSync(dryDir)) {\n console.warn(`[DryScan] Warning: a '.dry' folder already exists at ${dryDir}.`);\n }\n console.log(\"[DryScan] Preparing database and cache...\");\n await configStore.init(this.repoPath);\n await this.ensureDatabase();\n console.log(\"[DryScan] Starting initial scan (may take a moment)...\");\n await this.services.initializer.init(options);\n console.log(\"[DryScan] Initial scan complete.\");\n }\n\n /**\n * Updates the index by detecting changed, new, and deleted files.\n * Only reprocesses units in changed files for efficiency.\n * Delegates to DryScanUpdater module for implementation.\n * \n * Update process:\n * 1. List all current source files in repository\n * 2. For each file, check if it's new, changed, or unchanged (via mtime + checksum)\n * 3. Remove old units from changed/deleted files\n * 4. Extract and save units from new/changed files\n * 5. Recompute internal dependencies for affected units\n * 6. Recompute embeddings for affected units\n * 7. Update file tracking metadata\n */\n async updateIndex(): Promise<void> {\n console.log(`[DryScan] Updating index at ${this.repoPath}...`);\n console.log(\"[DryScan] Checking for file changes...\");\n const start = Date.now();\n await this.ensureDatabase();\n await this.services.updater.updateIndex();\n const duration = Date.now() - start;\n console.log(`[DryScan] Index update complete. Took ${duration}ms.`);\n }\n\n\n /**\n * Runs duplicate detection and returns a normalized report payload ready for persistence or display.\n */\n async buildDuplicateReport(): Promise<DuplicateReport> {\n const config = await this.loadConfig();\n const analysis = await this.findDuplicates(config);\n return {\n version: 1,\n generatedAt: new Date().toISOString(),\n threshold: config.threshold,\n grade: analysis.score.grade,\n score: analysis.score,\n duplicates: analysis.duplicates,\n };\n }\n\n /**\n * Finds duplicate code blocks using cosine similarity on embeddings.\n * Automatically updates the index before searching to ensure results are current.\n * Compares all function pairs and returns groups with similarity above the configured threshold.\n *\n * @returns Analysis result with duplicate groups and duplication score\n */\n private async findDuplicates(config: DryConfig): Promise<DuplicateAnalysisResult> {\n console.log(`[DryScan] Finding duplicates (threshold: ${config.threshold})...`);\n await this.ensureDatabase();\n\n console.log(\"[DryScan] Updating index...\");\n const updateStart = Date.now();\n await this.updateIndex();\n const updateDuration = Date.now() - updateStart;\n console.log(`[DryScan] Index update took ${updateDuration}ms.`);\n\n console.log(\"[DryScan] Detecting duplicates...\");\n const dupStart = Date.now();\n const result = await this.services.duplicate.findDuplicates(config);\n const dupDuration = Date.now() - dupStart;\n console.log(`[DryScan] Duplicate detection took ${dupDuration}ms.`);\n\n return result;\n }\n\n /**\n * Cleans excludedPairs entries that no longer match any indexed units.\n * Runs an update first to ensure the index reflects current code.\n */\n async cleanExclusions(): Promise<{ removed: number; kept: number }> {\n await this.updateIndex();\n return this.services.exclusion.cleanExclusions();\n }\n\n private async ensureDatabase(): Promise<void> {\n if (this.db.isInitialized()) return;\n const dbPath = upath.join(this.repoPath, DRYSCAN_DIR, INDEX_DB);\n await fs.mkdir(upath.dirname(dbPath), { recursive: true });\n await this.db.init(dbPath);\n }\n\n private async loadConfig(): Promise<DryConfig> {\n return configStore.get(this.repoPath);\n }\n\n}\n","export const DRYSCAN_DIR = \".dry\";\nexport const INDEX_DB = \"index.db\";\nexport const REPORTS_DIR = \"reports\";\nexport const FILE_CHECKSUM_ALGO = \"md5\";\nexport const BLOCK_HASH_ALGO = \"sha1\";","import path from \"path\";\nimport type { Stats } from \"fs\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport crypto from \"node:crypto\";\nimport debug from \"debug\";\nimport { glob } from \"glob-gitignore\";\nimport { IndexUnit } from \"./types\";\nimport { LanguageExtractor } from \"./extractors/LanguageExtractor\";\nimport { JavaExtractor } from \"./extractors/java\";\nimport { FILE_CHECKSUM_ALGO } from \"./const\";\nimport { configStore } from \"./config/configStore\";\nimport { DryConfig } from \"./types\";\nimport { Gitignore } from \"./Gitignore\"\nimport { Ignore } from \"ignore\";\n\nconst log = debug(\"DryScan:Extractor\");\n\nexport type { LanguageExtractor } from \"./extractors/LanguageExtractor\";\n/**\n * Returns the default set of language extractors supported by DryScan.\n * Extend/override by passing custom extractors into the IndexUnitExtractor constructor.\n */\nexport function defaultExtractors(repoPath: string): LanguageExtractor[] {\n return [new JavaExtractor(repoPath)];\n}\n\n/**\n * Extracts and indexes code units (classes, functions, blocks) for a repository.\n * Owns shared file-system helpers and delegates language-specific parsing to LanguageExtractors.\n */\nexport class IndexUnitExtractor {\n private readonly root: string;\n readonly extractors: LanguageExtractor[];\n private readonly gitignore: Gitignore;\n\n constructor(\n rootPath: string,\n extractors?: LanguageExtractor[]\n ) {\n this.root = rootPath;\n this.extractors = extractors ?? defaultExtractors(rootPath);\n this.gitignore = new Gitignore(this.root);\n log(\"Initialized extractor for %s\", this.root);\n }\n\n /**\n * Lists all supported source files from a path. Honors exclusion globs from config.\n */\n async listSourceFiles(dirPath: string): Promise<string[]> {\n const target = await this.resolveTarget(dirPath);\n const config = await this.loadConfig();\n const ignoreMatcher = await this.gitignore.buildMatcher(config);\n\n if (target.stat.isFile()) {\n return this.filterSingleFile(target.baseRel, ignoreMatcher);\n }\n\n const matches = await this.globSourceFiles(target.baseRel);\n return this.filterSupportedFiles(matches, ignoreMatcher);\n }\n\n /**\n * Computes MD5 checksum of file content to track changes.\n */\n async computeChecksum(filePath: string): Promise<string> {\n const fullPath = path.isAbsolute(filePath)\n ? filePath\n : path.join(this.root, filePath);\n\n const content = await fs.readFile(fullPath, \"utf8\");\n return crypto.createHash(FILE_CHECKSUM_ALGO).update(content).digest(\"hex\");\n }\n\n /**\n * Scans a file or directory and extracts indexable units using the matching LanguageExtractor.\n * The returned units have repo-relative file paths and no embedding attached.\n */\n async scan(targetPath: string): Promise<IndexUnit[]> {\n const fullPath = path.isAbsolute(targetPath)\n ? targetPath\n : path.join(this.root, targetPath);\n\n const stat = await fs.stat(fullPath).catch(() => null);\n if (!stat) {\n throw new Error(`Path not found: ${fullPath}`);\n }\n\n if (stat.isDirectory()) {\n log(\"Scanning directory %s\", fullPath);\n return this.scanDirectory(fullPath);\n }\n\n return this.scanFile(fullPath);\n }\n\n\n /**\n * Scans a directory recursively, extracting units from supported files while honoring exclusions.\n */\n private async scanDirectory(dir: string): Promise<IndexUnit[]> {\n const out: IndexUnit[] = [];\n const relDir = this.relPath(dir);\n const files = await this.listSourceFiles(relDir);\n for (const relFile of files) {\n const absFile = path.join(this.root, relFile);\n const extracted = await this.tryScanSupportedFile(absFile);\n out.push(...extracted);\n }\n return out;\n }\n\n /**\n * Scans a single file and extracts supported units.\n */\n private async scanFile(filePath: string): Promise<IndexUnit[]> {\n return this.tryScanSupportedFile(filePath, true);\n }\n\n /**\n * Extracts units from a supported file.\n * Optionally throws when the file type is unsupported (used when scanning an explicit file).\n */\n private async tryScanSupportedFile(filePath: string, throwOnUnsupported = false): Promise<IndexUnit[]> {\n const extractor = this.extractors.find(ex => ex.supports(filePath));\n if (!extractor) {\n if (throwOnUnsupported) {\n throw new Error(`Unsupported file type: ${filePath}`);\n }\n return [];\n }\n const rel = this.relPath(filePath);\n if (await this.shouldExclude(rel)) {\n log(\"Skipping excluded file %s\", rel);\n return [];\n }\n const source = await fs.readFile(filePath, \"utf8\");\n const units = await extractor.extractFromText(rel, source);\n log(\"Extracted %d units from %s\", units.length, rel);\n return units.map(unit => ({\n ...unit,\n filePath: rel,\n embedding: undefined,\n }));\n }\n\n /**\n * Converts an absolute path to a repo-relative, normalized (POSIX-style) path.\n * This keeps paths stable across platforms and consistent in the index/DB.\n */\n private relPath(absPath: string): string {\n return this.normalizeRelPath(upath.relative(this.root, absPath));\n }\n\n /**\n * Returns true if a repo-relative path matches any configured exclusion glob.\n */\n private async shouldExclude(relPath: string): Promise<boolean> {\n const config = await this.loadConfig();\n const ignoreMatcher = await this.gitignore.buildMatcher(config);\n return ignoreMatcher.ignores(this.normalizeRelPath(relPath));\n }\n\n private async loadConfig(): Promise<DryConfig> {\n return await configStore.get(this.root);\n }\n\n /**\n * Normalizes repo-relative paths and strips leading \"./\" to keep matcher inputs consistent.\n */\n private normalizeRelPath(relPath: string): string {\n const normalized = upath.normalizeTrim(relPath);\n return normalized.startsWith(\"./\") ? normalized.slice(2) : normalized;\n }\n\n private async resolveTarget(dirPath: string): Promise<{ fullPath: string; baseRel: string; stat: Stats; }> {\n const fullPath = path.isAbsolute(dirPath) ? dirPath : path.join(this.root, dirPath);\n const stat = await fs.stat(fullPath).catch(() => null);\n if (!stat) {\n throw new Error(`Path not found: ${fullPath}`);\n }\n const baseRel = this.relPath(fullPath);\n log(\"Listing source files under %s\", fullPath);\n return { fullPath, baseRel, stat };\n }\n\n private async filterSingleFile(baseRel: string, ignoreMatcher: Ignore): Promise<string[]> {\n const relFile = this.normalizeRelPath(baseRel);\n if (ignoreMatcher.ignores(relFile)) return [];\n return this.extractors.some((ex) => ex.supports(relFile)) ? [relFile] : [];\n }\n\n private async globSourceFiles(baseRel: string): Promise<string[]> {\n const pattern = baseRel ? `${baseRel.replace(/\\\\/g, \"/\")}/**/*` : \"**/*\";\n const matches = await glob(pattern, {\n cwd: this.root,\n dot: false,\n nodir: true,\n });\n return matches.map((p: string) => this.normalizeRelPath(p));\n }\n\n private filterSupportedFiles(relPaths: string[], ignoreMatcher: Ignore): string[] {\n return relPaths\n .filter((relPath: string) => !ignoreMatcher.ignores(relPath))\n .filter((relPath: string) => this.extractors.some((ex) => ex.supports(relPath)));\n }\n}\n","import crypto from \"node:crypto\";\nimport Parser from \"tree-sitter\";\nimport Java from \"tree-sitter-java\";\nimport { LanguageExtractor } from \"./LanguageExtractor\";\nimport { IndexUnit, IndexUnitType } from \"../types\";\nimport { indexConfig } from \"../config/indexConfig\";\nimport { DryConfig } from \"../types\";\nimport { configStore } from \"../config/configStore\";\nimport { BLOCK_HASH_ALGO } from \"../const\";\n\nexport class JavaExtractor implements LanguageExtractor {\n readonly id = \"java\";\n readonly exts = [\".java\"];\n\n private parser: Parser;\n private readonly repoPath: string;\n private config?: DryConfig;\n\n constructor(repoPath: string) {\n this.repoPath = repoPath;\n this.parser = new Parser();\n this.parser.setLanguage(Java);\n }\n\n supports(filePath: string): boolean {\n const lower = filePath.toLowerCase();\n return this.exts.some((ext) => lower.endsWith(ext));\n }\n\n async extractFromText(fileRelPath: string, source: string): Promise<IndexUnit[]> {\n if (!source.trim()) return [];\n\n this.config = await configStore.get(this.repoPath);\n\n const tree = this.parser.parse(source);\n const units: IndexUnit[] = [];\n\n const visit = (node: Parser.SyntaxNode, currentClass?: IndexUnit) => {\n if (this.isClassNode(node)) {\n const className = this.getClassName(node, source) || \"<anonymous>\";\n if (this.isDtoClass(node, source, className)) {\n return;\n }\n const startLine = node.startPosition.row;\n const endLine = node.endPosition.row;\n const classLength = endLine - startLine;\n const skipClass = this.shouldSkip(IndexUnitType.CLASS, className, classLength);\n const classId = this.buildId(IndexUnitType.CLASS, className, startLine, endLine);\n const code = this.stripComments(this.stripClassBody(node, source));\n const classUnit: IndexUnit = {\n id: classId,\n name: className,\n filePath: fileRelPath,\n startLine,\n endLine,\n code,\n unitType: IndexUnitType.CLASS,\n children: [],\n };\n if (!skipClass) {\n units.push(classUnit);\n }\n\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (child) visit(child, skipClass ? undefined : classUnit);\n }\n return;\n }\n\n if (this.isFunctionNode(node)) {\n const fnUnit = this.buildFunctionUnit(node, source, fileRelPath, currentClass);\n const fnLength = fnUnit.endLine - fnUnit.startLine;\n const bodyNode = this.getFunctionBody(node);\n const skipFunction = this.shouldSkip(IndexUnitType.FUNCTION, fnUnit.name, fnLength);\n\n if (skipFunction) {\n return;\n }\n\n units.push(fnUnit);\n\n if (bodyNode) {\n const blocks = this.extractBlocks(bodyNode, source, fileRelPath, fnUnit);\n units.push(...blocks);\n }\n }\n\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (child) visit(child, currentClass);\n }\n };\n\n visit(tree.rootNode);\n\n //remove duplicates if any\n return this.removeDuplicates(units);\n }\n\n unitLabel(unit: IndexUnit): string | null {\n if (unit.unitType === IndexUnitType.CLASS) return unit.filePath;\n if (unit.unitType === IndexUnitType.FUNCTION) return this.canonicalFunctionSignature(unit);\n if (unit.unitType === IndexUnitType.BLOCK) return this.normalizedBlockHash(unit);\n return unit.name;\n }\n\n private isClassNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"class_declaration\";\n }\n\n private getClassName(node: Parser.SyntaxNode, source: string): string | null {\n const nameNode = node.childForFieldName?.(\"name\");\n return nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : null;\n }\n\n private isFunctionNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"method_declaration\" || node.type === \"constructor_declaration\";\n }\n\n private getFunctionName(node: Parser.SyntaxNode, source: string, parentClass?: IndexUnit): string | null {\n const nameNode = node.childForFieldName?.(\"name\");\n const nameText = nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : \"<anonymous>\";\n return parentClass ? `${parentClass.name}.${nameText}` : nameText;\n }\n\n private getFunctionBody(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n return node.childForFieldName?.(\"body\") ?? null;\n }\n\n private isBlockNode(node: Parser.SyntaxNode): boolean {\n return node.type === \"block\";\n }\n\n private getMethodBodiesForClass(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n const bodies: Parser.SyntaxNode[] = [];\n const classBody = node.children.find(child => child.type === \"class_body\");\n if (!classBody) return bodies;\n \n for (let i = 0; i < classBody.namedChildCount; i++) {\n const child = classBody.namedChild(i);\n if (!child) continue;\n if (child.type === \"method_declaration\" || child.type === \"constructor_declaration\") {\n const body = child.childForFieldName?.(\"body\");\n if (body) bodies.push(body);\n }\n }\n return bodies;\n }\n\n private canonicalFunctionSignature(unit: IndexUnit): string {\n const arity = this.extractArity(unit.code);\n return `${unit.name}(arity:${arity})`;\n }\n\n private normalizedBlockHash(unit: IndexUnit): string {\n const normalized = this.normalizeCode(unit.code);\n return crypto.createHash(BLOCK_HASH_ALGO).update(normalized).digest(\"hex\");\n }\n\n private shouldSkip(unitType: IndexUnitType, name: string, lineCount: number): boolean {\n if (!this.config) {\n throw new Error(\"Config not loaded before skip evaluation\");\n }\n const config = this.config;\n const minLines = unitType === IndexUnitType.BLOCK\n ? Math.max(indexConfig.blockMinLines, config.minBlockLines ?? 0)\n : config.minLines;\n const belowMin = minLines > 0 && lineCount < minLines;\n const trivial = unitType === IndexUnitType.FUNCTION && this.isTrivialFunction(name);\n return belowMin || trivial;\n }\n\n private isTrivialFunction(fullName: string): boolean {\n const simpleName = fullName.split(\".\").pop() || fullName;\n const isGetter = /^(get|is)[A-Z]/.test(simpleName);\n const isSetter = /^set[A-Z]/.test(simpleName);\n return isGetter || isSetter;\n }\n\n private isDtoClass(node: Parser.SyntaxNode, source: string, className: string): boolean {\n const classBody = node.children.find((child) => child.type === \"class_body\");\n if (!classBody) return false;\n\n let hasField = false;\n\n for (let i = 0; i < classBody.namedChildCount; i++) {\n const child = classBody.namedChild(i);\n if (!child) continue;\n\n if (child.type === \"field_declaration\") {\n hasField = true;\n continue;\n }\n\n if (child.type.includes(\"annotation\")) {\n continue;\n }\n\n if (child.type === \"method_declaration\" || child.type === \"constructor_declaration\") {\n const simpleName = this.getSimpleFunctionName(child, source);\n const fullName = `${className}.${simpleName}`;\n if (!this.isTrivialFunction(fullName)) {\n return false;\n }\n continue;\n }\n\n return false;\n }\n\n return hasField;\n }\n\n private getSimpleFunctionName(node: Parser.SyntaxNode, source: string): string {\n const nameNode = node.childForFieldName?.(\"name\");\n return nameNode ? source.slice(nameNode.startIndex, nameNode.endIndex) : \"<anonymous>\";\n }\n\n private buildFunctionUnit(\n node: Parser.SyntaxNode,\n source: string,\n file: string,\n parentClass?: IndexUnit\n ): IndexUnit {\n const name = this.getFunctionName(node, source, parentClass) || \"<anonymous>\";\n const startLine = node.startPosition.row;\n const endLine = node.endPosition.row;\n const id = this.buildId(IndexUnitType.FUNCTION, name, startLine, endLine);\n const unit: IndexUnit = {\n id,\n name,\n filePath: file,\n startLine,\n endLine,\n children: [],\n code: this.stripComments(source.slice(node.startIndex, node.endIndex)),\n unitType: IndexUnitType.FUNCTION,\n parentId: parentClass?.id,\n parent: parentClass,\n };\n if (parentClass) {\n parentClass.children = parentClass.children || [];\n parentClass.children.push(unit);\n }\n return unit;\n }\n\n private extractBlocks(\n bodyNode: Parser.SyntaxNode,\n source: string,\n file: string,\n parentFunction: IndexUnit\n ): IndexUnit[] {\n const blocks: IndexUnit[] = [];\n\n const visit = (n: Parser.SyntaxNode) => {\n if (this.isBlockNode(n)) {\n const startLine = n.startPosition.row;\n const endLine = n.endPosition.row;\n const lineCount = endLine - startLine;\n if (this.shouldSkip(IndexUnitType.BLOCK, parentFunction.name, lineCount)) {\n return;\n }\n if (lineCount >= indexConfig.blockMinLines) {\n const id = this.buildId(IndexUnitType.BLOCK, parentFunction.name, startLine, endLine);\n const blockUnit: IndexUnit = {\n id,\n name: parentFunction.name,\n filePath: file,\n startLine,\n endLine,\n code: this.stripComments(source.slice(n.startIndex, n.endIndex)),\n unitType: IndexUnitType.BLOCK,\n parentId: parentFunction.id,\n parent: parentFunction,\n };\n const contextLength = this.config?.contextLength ?? 2048;\n const splitBlocks = this.textSplitBlockIfOverContextLimit(blockUnit, contextLength);\n parentFunction.children = parentFunction.children || [];\n parentFunction.children.push(...splitBlocks);\n blocks.push(...splitBlocks);\n }\n }\n\n for (let i = 0; i < n.namedChildCount; i++) {\n const child = n.namedChild(i);\n if (child) visit(child);\n }\n };\n\n visit(bodyNode);\n return blocks;\n }\n\n private stripClassBody(node: Parser.SyntaxNode, source: string): string {\n const classStart = node.startIndex;\n let code = source.slice(classStart, node.endIndex);\n\n const methodBodies: Array<{ start: number; end: number }> = [];\n const candidates = this.getMethodBodiesForClass(node);\n\n for (const body of candidates) {\n methodBodies.push({ start: body.startIndex - classStart, end: body.endIndex - classStart });\n }\n\n methodBodies.sort((a, b) => b.start - a.start);\n for (const body of methodBodies) {\n code = code.slice(0, body.start) + \" { }\" + code.slice(body.end);\n }\n\n return code;\n }\n\n private buildId(type: IndexUnitType, name: string, startLine: number, endLine: number): string {\n return `${type}:${name}:${startLine}-${endLine}`;\n }\n\n private extractArity(code: string): number {\n const match = code.match(/^[^{]*?\\(([^)]*)\\)/s);\n if (!match) return 0;\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n return params.length;\n }\n\n private normalizeCode(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n const withoutLineComments = withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/g, \"\");\n return withoutLineComments.replace(/\\s+/g, \"\");\n }\n\n private stripComments(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, (match) => match.replace(/[^\\n\\r]/g, \"\"));\n return withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/g, \"\");\n }\n\n private removeDuplicates(units: IndexUnit[]): IndexUnit[] | PromiseLike<IndexUnit[]> {\n return Array.from(new Map(units.map(u => [u.id, u])).values());\n }\n\n /** Splits a block unit's code into chunks if it exceeds the context length limit. */\n private textSplitBlockIfOverContextLimit(unit: IndexUnit, contextLength: number): IndexUnit[] {\n if (unit.code.length <= contextLength) return [unit];\n\n const chunks: IndexUnit[] = [];\n let chunkIndex = 0;\n for (let i = 0; i < unit.code.length; i += contextLength) {\n chunks.push({\n ...unit,\n id: `${unit.id}:chunk${chunkIndex}`,\n code: unit.code.slice(i, i + contextLength),\n });\n chunkIndex++;\n }\n return chunks;\n }\n}\n\n","export const indexConfig = {\n blockMinLines: 5,\n thresholds: {\n class: 0.88,\n function: 0.88,\n block: 0.88,\n },\n weights: {\n class: { self: 1 },\n function: { self: 0.8, parentClass: 0.2 },\n block: { self: 0.7, parentFunction: 0.2, parentClass: 0.1 },\n },\n};\n","import upath from \"upath\";\nimport { DryConfig } from \"../types\";\nimport { ensureDefaultConfig, resolveDryConfig, saveDryConfig } from \"./dryconfig\";\n\nclass ConfigStore {\n private readonly cache = new Map<string, DryConfig>();\n private readonly loading = new Map<string, Promise<DryConfig>>();\n\n async init(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n return this.load(key, repoPath);\n }\n\n async get(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n const cached = this.cache.get(key);\n if (cached) return cached;\n return this.load(key, repoPath);\n }\n\n async refresh(repoPath: string): Promise<DryConfig> {\n const key = this.normalize(repoPath);\n this.cache.delete(key);\n return this.load(key, repoPath);\n }\n\n async save(repoPath: string, config: DryConfig): Promise<void> {\n const key = this.normalize(repoPath);\n await saveDryConfig(repoPath, config);\n this.cache.set(key, config);\n }\n\n private async load(key: string, repoPath: string): Promise<DryConfig> {\n const existing = this.loading.get(key);\n if (existing) return existing;\n\n const promise = ensureDefaultConfig(repoPath).then(() => resolveDryConfig(repoPath)).then((config) => {\n this.cache.set(key, config);\n this.loading.delete(key);\n return config;\n }).catch((err) => {\n this.loading.delete(key);\n throw err;\n });\n\n this.loading.set(key, promise);\n return promise;\n }\n\n private normalize(repoPath: string): string {\n return upath.normalizeTrim(upath.resolve(repoPath));\n }\n}\n\nexport const configStore = new ConfigStore();\n","import fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { Validator, Schema } from \"jsonschema\";\nimport { DryConfig } from \"../types\";\n\n// Baseline config used when no file is present; exported so tests and constructors can seed defaults.\nexport const DEFAULT_CONFIG: DryConfig = {\n excludedPaths: [\n \"**/test/**\",\n ],\n excludedPairs: [],\n minLines: 3,\n minBlockLines: 5,\n threshold: 0.88,\n embeddingSource: \"http://localhost:11434\",\n contextLength: 2048,\n};\n\nconst validator = new Validator();\n\nconst partialConfigSchema: Schema = {\n type: \"object\",\n properties: {\n excludedPaths: { type: \"array\", items: { type: \"string\" } },\n excludedPairs: { type: \"array\", items: { type: \"string\" } },\n minLines: { type: \"number\" },\n minBlockLines: { type: \"number\" },\n threshold: { type: \"number\" },\n embeddingSource: { type: \"string\" },\n contextLength: { type: \"number\" },\n },\n};\n\nconst fullConfigSchema: Schema = {\n ...partialConfigSchema,\n required: [\n \"excludedPaths\",\n \"excludedPairs\",\n \"minLines\",\n \"minBlockLines\",\n \"threshold\",\n \"embeddingSource\",\n \"contextLength\",\n ],\n};\n\nfunction validateConfig(raw: unknown, schema: Schema, source: string): any {\n const result = validator.validate(raw, schema);\n if (!result.valid) {\n const details = result.errors.map((e) => e.stack).join(\"; \");\n throw new Error(`${source} config is invalid: ${details}`);\n }\n return raw;\n}\n\nasync function readConfigFile(repoPath: string): Promise<Partial<DryConfig>> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n try {\n const content = await fs.readFile(configPath, \"utf8\");\n let parsed: Partial<DryConfig> = {};\n try {\n parsed = JSON.parse(content) as Partial<DryConfig>;\n } catch (parseErr) {\n throw new Error(`Invalid JSON in ${configPath}: ${(parseErr as Error).message}`);\n }\n return parsed;\n } catch (err: any) {\n if (err?.code === \"ENOENT\") {\n return {};\n }\n throw err;\n }\n}\n\n/**\n * Resolves the effective config for a repo using defaults merged with any file config.\n */\nexport async function resolveDryConfig(repoPath: string): Promise<DryConfig> {\n const fileConfigRaw = await readConfigFile(repoPath);\n validateConfig(fileConfigRaw, partialConfigSchema, \"Config file\");\n\n const merged = { ...DEFAULT_CONFIG, ...fileConfigRaw };\n validateConfig(merged, fullConfigSchema, \"Merged\");\n return merged as DryConfig;\n}\n\n// Backwards-compatible helper used by existing callers (file + defaults).\nexport async function loadDryConfig(repoPath: string): Promise<DryConfig> {\n return resolveDryConfig(repoPath);\n}\n\nexport async function saveDryConfig(repoPath: string, config: DryConfig): Promise<void> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n validateConfig(config, fullConfigSchema, \"Config to save\");\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), \"utf8\");\n}\n\nexport async function ensureDefaultConfig(repoPath: string): Promise<void> {\n const configPath = upath.join(repoPath, \"dryconfig.json\");\n const repoExists = await fs.stat(repoPath).then((s) => s.isDirectory()).catch((err: any) => {\n if (err?.code === \"ENOENT\") return false;\n throw err;\n });\n\n if (!repoExists) return;\n\n const exists = await fs.stat(configPath).then(() => true).catch((err: any) => {\n if (err?.code === \"ENOENT\") return false;\n throw err;\n });\n\n if (!exists) {\n await saveDryConfig(repoPath, DEFAULT_CONFIG);\n }\n}\n","import path from \"path\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { glob } from \"glob-gitignore\";\nimport ignore, { Ignore } from \"ignore\";\nimport { DryConfig } from \"./types\";\n\n/**\n * Gitignore helper that builds ignore matchers by combining default rules,\n * repo .gitignore files, and config-driven exclusions.\n */\nexport class Gitignore {\n private readonly defaultIgnores = [\".git/**\", \".dry/**\"];\n\n constructor(private readonly root: string) {}\n\n async buildMatcher(config: DryConfig): Promise<Ignore> {\n const rules = await this.resolveRules(config);\n return ignore({ allowRelativePaths: true }).add(rules);\n }\n\n private async resolveRules(config: DryConfig): Promise<string[]> {\n const gitignoreRules = await this.loadGitignoreRules();\n const configRules = config.excludedPaths || [];\n return [...this.defaultIgnores, ...gitignoreRules, ...configRules];\n }\n\n private async loadGitignoreRules(): Promise<string[]> {\n const gitignoreFiles = await glob(\"**/.gitignore\", {\n cwd: this.root,\n dot: true,\n nodir: true,\n ignore: this.defaultIgnores,\n });\n\n const rules: string[] = [];\n\n for (const file of gitignoreFiles) {\n const absPath = path.join(this.root, file);\n const dir = upath.normalizeTrim(upath.dirname(file));\n const content = await fs.readFile(absPath, \"utf8\").catch(() => \"\");\n const lines = content.split(/\\r?\\n/);\n\n for (const raw of lines) {\n const trimmed = raw.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n\n const negated = trimmed.startsWith(\"!\");\n const body = negated ? trimmed.slice(1) : trimmed;\n\n const scoped = this.scopeRule(body, dir);\n if (!scoped) continue;\n\n rules.push(negated ? `!${scoped}` : scoped);\n }\n }\n\n return rules;\n }\n\n private scopeRule(rule: string, gitignoreDir: string): string | null {\n const cleaned = rule.replace(/^\\//, \"\");\n if (!cleaned) return null;\n\n if (!gitignoreDir || gitignoreDir === \".\") {\n return cleaned;\n }\n\n return upath.normalizeTrim(upath.join(gitignoreDir, cleaned));\n }\n}\n","import \"reflect-metadata\";\nimport fs from \"fs/promises\";\nimport upath from \"upath\";\nimport { DataSource, Repository, In } from \"typeorm\";\nimport { FileEntity } from \"./entities/FileEntity\";\nimport { IndexUnit } from \"../types\";\nimport { IndexUnitEntity } from \"./entities/IndexUnitEntity\";\n\nexport class DryScanDatabase {\n private dataSource?: DataSource;\n private unitRepository?: Repository<IndexUnitEntity>;\n private fileRepository?: Repository<FileEntity>;\n\n isInitialized(): boolean {\n return !!this.dataSource?.isInitialized;\n }\n\n async init(dbPath: string): Promise<void> {\n await fs.mkdir(upath.dirname(dbPath), { recursive: true });\n\n this.dataSource = new DataSource({\n type: \"sqlite\",\n database: dbPath,\n entities: [IndexUnitEntity, FileEntity],\n synchronize: true,\n logging: false,\n });\n\n await this.dataSource.initialize();\n this.unitRepository = this.dataSource.getRepository(IndexUnitEntity);\n this.fileRepository = this.dataSource.getRepository(FileEntity);\n }\n\n async saveUnit(unit: IndexUnit): Promise<void> {\n await this.saveUnits(unit);\n }\n\n async saveUnits(units: IndexUnit | IndexUnit[]): Promise<void> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n const payload = Array.isArray(units) ? units : [units];\n const BATCH_SIZE = 500;\n for (let i = 0; i < payload.length; i += BATCH_SIZE) {\n console.debug(`[DryScanDatabase] Saving units ${i + 1}-${Math.min(i + BATCH_SIZE, payload.length)} of ${payload.length}...`);\n const batch = payload.slice(i, i + BATCH_SIZE);\n await this.unitRepository.save(batch);\n }\n }\n\n async getUnit(id: string): Promise<IndexUnit | null> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.findOne({\n where: { id },\n relations: [\"children\", \"parent\"]\n });\n }\n\n async getAllUnits(): Promise<IndexUnit[]> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.find({ relations: [\"children\", \"parent\"] });\n }\n\n async updateUnit(unit: IndexUnit): Promise<void> {\n await this.saveUnits(unit);\n }\n\n async updateUnits(units: IndexUnit | IndexUnit[]): Promise<void> {\n await this.saveUnits(units);\n }\n\n /**\n * Returns total count of indexed units.\n */\n async countUnits(): Promise<number> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n return this.unitRepository.count();\n }\n\n /**\n * Removes index units by their file paths.\n * Used during incremental updates when files change.\n */\n async removeUnitsByFilePaths(filePaths: string[]): Promise<void> {\n if (!this.unitRepository) throw new Error(\"Database not initialized\");\n await this.unitRepository.delete({ filePath: In(filePaths) });\n }\n\n /**\n * Saves file metadata (path, checksum, mtime) to track changes.\n */\n async saveFile(file: FileEntity): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.save(file);\n }\n\n /**\n * Saves multiple file metadata entries.\n */\n async saveFiles(files: FileEntity[]): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.save(files);\n }\n\n /**\n * Gets file metadata by file path.\n */\n async getFile(filePath: string): Promise<FileEntity | null> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n return this.fileRepository.findOne({ where: { filePath } });\n }\n\n /**\n * Gets all tracked files.\n */\n async getAllFiles(): Promise<FileEntity[]> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n return this.fileRepository.find();\n }\n\n /**\n * Removes file metadata entries by file paths.\n * Used when files are deleted from repository.\n */\n async removeFilesByFilePaths(filePaths: string[]): Promise<void> {\n if (!this.fileRepository) throw new Error(\"Database not initialized\");\n await this.fileRepository.delete({ filePath: In(filePaths) });\n }\n\n async close(): Promise<void> {\n if (this.dataSource?.isInitialized) {\n await this.dataSource.destroy();\n }\n }\n}\n","import { Entity, PrimaryColumn, Column } from \"typeorm\";\n\n/**\n * Represents a tracked source file in the repository.\n * Used to detect changes via checksum and mtime for incremental updates.\n */\n@Entity(\"files\")\nexport class FileEntity {\n /**\n * Relative path to the file from repository root.\n * Used as primary key for uniqueness.\n */\n @PrimaryColumn(\"text\")\n filePath!: string;\n\n /**\n * MD5 checksum of file content.\n * Used to detect content changes.\n */\n @Column(\"text\")\n checksum!: string;\n\n /**\n * Last modification time in milliseconds since epoch.\n * Used as fast sanity check before computing checksum.\n */\n @Column(\"integer\")\n mtime!: number;\n}\n","import {\n Column,\n Entity,\n JoinColumn,\n ManyToOne,\n OneToMany,\n PrimaryColumn,\n RelationId,\n} from \"typeorm\";\nimport { IndexUnit, IndexUnitType } from \"../../types\";\n\n@Entity(\"index_units\")\nexport class IndexUnitEntity implements IndexUnit {\n @PrimaryColumn(\"text\")\n id!: string;\n\n @Column(\"text\")\n name!: string;\n\n @Column(\"text\")\n filePath!: string;\n\n @Column(\"integer\")\n startLine!: number;\n\n @Column(\"integer\")\n endLine!: number;\n\n @Column(\"text\")\n code!: string;\n\n @Column(\"text\")\n unitType!: IndexUnitType;\n\n @ManyToOne(() => IndexUnitEntity, (unit) => unit.children, {\n nullable: true,\n onDelete: \"CASCADE\",\n })\n @JoinColumn({ name: \"parent_id\" })\n parent?: IndexUnitEntity | null;\n\n @RelationId((unit: IndexUnitEntity) => unit.parent)\n parentId?: string | null;\n\n @OneToMany(() => IndexUnitEntity, (unit) => unit.parent, { nullable: true })\n children?: IndexUnitEntity[];\n\n @Column(\"simple-array\", { nullable: true })\n embedding?: number[] | null;\n}\n","import path from \"path\";\nimport fs from \"fs/promises\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { ExclusionService } from \"./ExclusionService\";\nimport { IndexUnit } from \"../types\";\nimport { EmbeddingService } from \"./EmbeddingService\";\nimport { FileEntity } from \"../db/entities/FileEntity\";\nimport { IndexUnitExtractor } from \"../IndexUnitExtractor\";\n\nexport interface InitOptions {\n skipEmbeddings?: boolean;\n}\n\nexport class RepositoryInitializer {\n constructor(\n private readonly deps: DryScanServiceDeps,\n private readonly exclusionService: ExclusionService\n ) {}\n\n async init(options?: InitOptions): Promise<void> {\n const extractor = this.deps.extractor;\n\n console.log(\"[DryScan] Phase 1/3: Extracting code units...\");\n await this.initUnits(extractor);\n console.log(\"[DryScan] Phase 2/3: Computing embeddings (may be slow)...\");\n await this.computeEmbeddings(options?.skipEmbeddings === true);\n console.log(\"[DryScan] Phase 3/3: Tracking files...\");\n await this.trackFiles(extractor);\n await this.exclusionService.cleanupExcludedFiles();\n console.log(\"[DryScan] Initialization phases complete.\");\n }\n\n private async initUnits(extractor: IndexUnitExtractor): Promise<void> {\n const units = await extractor.scan(this.deps.repoPath);\n console.log(`[DryScan] Extracted ${units.length} index units.`);\n await this.deps.db.saveUnits(units);\n }\n\n private async computeEmbeddings(skipEmbeddings: boolean): Promise<void> {\n if (skipEmbeddings) {\n console.log(\"[DryScan] Skipping embedding computation by request.\");\n return;\n }\n const allUnits: IndexUnit[] = await this.deps.db.getAllUnits();\n const total = allUnits.length;\n console.log(`[DryScan] Computing embeddings for ${total} units...`);\n\n const updated: IndexUnit[] = [];\n const progressInterval = Math.max(1, Math.ceil(total / 10));\n const embeddingService = new EmbeddingService(this.deps.repoPath);\n\n for (let i = 0; i < total; i++) {\n const unit = allUnits[i];\n try {\n const enriched = await embeddingService.addEmbedding(unit);\n updated.push(enriched);\n } catch (err: any) {\n console.error(\n `[DryScan] Embedding failed for ${unit.filePath} (${unit.name}): ${err?.message || err}`\n );\n throw err;\n }\n\n const completed = i + 1;\n if (completed === total || completed % progressInterval === 0) {\n const pct = Math.floor((completed / total) * 100);\n console.log(`[DryScan] Embeddings ${completed}/${total} (${pct}%)`);\n }\n }\n\n await this.deps.db.updateUnits(updated);\n }\n\n private async trackFiles(extractor: IndexUnitExtractor): Promise<void> {\n const allFunctions = await extractor.listSourceFiles(this.deps.repoPath);\n const fileEntities: FileEntity[] = [];\n\n for (const relPath of allFunctions) {\n const fullPath = path.join(this.deps.repoPath, relPath);\n const stat = await fs.stat(fullPath);\n const checksum = await extractor.computeChecksum(fullPath);\n\n const fileEntity = new FileEntity();\n fileEntity.filePath = relPath;\n fileEntity.checksum = checksum;\n fileEntity.mtime = stat.mtimeMs;\n fileEntities.push(fileEntity);\n }\n\n await this.deps.db.saveFiles(fileEntities);\n console.log(`[DryScan] Tracked ${fileEntities.length} files.`);\n }\n}","import debug from \"debug\";\nimport { OllamaEmbeddings } from \"@langchain/ollama\";\nimport { HuggingFaceInferenceEmbeddings } from \"@langchain/community/embeddings/hf\";\nimport { IndexUnit } from \"../types\";\nimport { configStore } from \"../config/configStore\";\n\nconst log = debug(\"DryScan:EmbeddingService\");\n\n// Model names for each provider\nconst OLLAMA_MODEL = \"qwen3-embedding:0.6b\";\nconst HUGGINGFACE_MODEL = \"Qwen/Qwen3-Embedding-0.6B\";\n\nexport class EmbeddingService {\n constructor(private readonly repoPath: string) { }\n\n /**\n * Generates an embedding for the given index unit using the configured provider.\n * Skips embedding if code exceeds the configured context length.\n */\n async addEmbedding(fn: IndexUnit): Promise<IndexUnit> {\n const config = await configStore.get(this.repoPath);\n const maxContext = config?.contextLength ?? 2048;\n if (fn.code.length > maxContext) {\n log(\n \"Skipping embedding for %s (code length %d exceeds context %d)\",\n fn.id,\n fn.code.length,\n maxContext\n );\n return { ...fn, embedding: null };\n }\n\n const source = config.embeddingSource;\n if (!source) {\n const message = `Embedding source is not configured for repository at ${this.repoPath}`;\n log(message);\n throw new Error(message);\n }\n\n const embeddings = this.buildProvider(source);\n const embedding = await embeddings.embedQuery(fn.code);\n return { ...fn, embedding };\n }\n\n /**\n * Builds the embedding provider based on the source configuration.\n * - URL (http/https): Uses Ollama with \"embeddinggemma\" model\n * - \"huggingface\": Uses HuggingFace Inference API with \"embeddinggemma-300m\" model\n */\n private buildProvider(source: string) {\n // HuggingFace Inference API\n if (source.toLowerCase() === \"huggingface\") {\n log(\"Using HuggingFace Inference with model: %s\", HUGGINGFACE_MODEL);\n return new HuggingFaceInferenceEmbeddings({\n model: HUGGINGFACE_MODEL,\n provider: \"hf-inference\",\n });\n }\n\n // Ollama keyword or direct URL\n const ollamaBaseUrl = this.resolveOllamaBaseUrl(source);\n if (ollamaBaseUrl !== null) {\n log(\"Using Ollama%s with model: %s\", ollamaBaseUrl ? ` at ${ollamaBaseUrl}` : \"\", OLLAMA_MODEL);\n return new OllamaEmbeddings({ model: OLLAMA_MODEL, ...(ollamaBaseUrl && { baseUrl: ollamaBaseUrl }) });\n }\n\n const message = `Unsupported embedding source: ${source || \"(empty)\"}. Use \"huggingface\" or an Ollama URL.`;\n log(message);\n throw new Error(message);\n }\n\n /**\n * Returns the Ollama base URL if source is an HTTP URL, undefined if source is \"ollama\" (use default),\n * or null if source is not an Ollama provider at all.\n */\n private resolveOllamaBaseUrl(source: string): string | undefined | null {\n if (/^https?:\\/\\//i.test(source)) return source;\n if (source.toLowerCase() === \"ollama\") return undefined;\n return null;\n }\n}","import debug from \"debug\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { ExclusionService } from \"./ExclusionService\";\nimport { performIncrementalUpdate } from \"../DryScanUpdater\";\nimport { DuplicationCache } from \"./DuplicationCache\";\n\nconst log = debug(\"DryScan:UpdateService\");\n\nexport class UpdateService {\n constructor(\n private readonly deps: DryScanServiceDeps,\n private readonly exclusionService: ExclusionService\n ) {}\n\n async updateIndex(): Promise<void> {\n const extractor = this.deps.extractor;\n const cache = DuplicationCache.getInstance();\n\n try {\n const changeSet = await performIncrementalUpdate(this.deps.repoPath, extractor, this.deps.db);\n await this.exclusionService.cleanupExcludedFiles();\n await cache.invalidate([...changeSet.changed, ...changeSet.deleted]);\n } catch (err) {\n log(\"Error during index update:\", err);\n throw err;\n }\n }\n}","import path from \"path\";\nimport fs from \"fs/promises\";\nimport debug from \"debug\";\nimport { IndexUnit } from \"./types\";\nimport { IndexUnitExtractor } from \"./IndexUnitExtractor\";\nimport { DryScanDatabase } from \"./db/DryScanDatabase\";\nimport { FileEntity } from \"./db/entities/FileEntity\";\nimport { EmbeddingService } from \"./services/EmbeddingService\";\n\nconst log = debug(\"DryScan:Updater\");\n\n/**\n * DryScan Updater Module\n * \n * This module contains all incremental update logic for DryScan.\n * Separated from DryScan.ts to keep that file focused on core operations.\n * \n * Represents the result of change detection.\n * Categorizes files into added, changed, deleted, and unchanged.\n */\nexport interface FileChangeSet {\n added: string[];\n changed: string[];\n deleted: string[];\n unchanged: string[];\n}\n\n/**\n * Detects which files have been added, changed, or deleted since last scan.\n * Uses mtime as fast check, then checksum for verification.\n * \n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor instance for file operations\n * @param db - Database instance for retrieving tracked files\n * @returns Change set with categorized file paths\n */\nexport async function detectFileChanges(\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase\n): Promise<FileChangeSet> {\n // Get current files in repository\n const currentFiles = await extractor.listSourceFiles(repoPath);\n const currentFileSet = new Set(currentFiles);\n\n // Get tracked files from database\n const trackedFiles = await db.getAllFiles();\n const trackedFileMap = new Map(trackedFiles.map(f => [f.filePath, f]));\n\n const added: string[] = [];\n const changed: string[] = [];\n const unchanged: string[] = [];\n\n // Check each current file\n for (const filePath of currentFiles) {\n const tracked = trackedFileMap.get(filePath);\n \n if (!tracked) {\n // New file\n added.push(filePath);\n continue;\n }\n\n // Check if file changed using mtime first (fast check)\n const fullPath = path.join(repoPath, filePath);\n const stat = await fs.stat(fullPath);\n \n if (stat.mtimeMs !== tracked.mtime) {\n // Mtime changed, verify with checksum\n const currentChecksum = await extractor.computeChecksum(fullPath);\n if (currentChecksum !== tracked.checksum) {\n changed.push(filePath);\n } else {\n // Mtime changed but content same\n unchanged.push(filePath);\n }\n } else {\n unchanged.push(filePath);\n }\n }\n\n // Find deleted files\n const deleted = trackedFiles\n .map(f => f.filePath)\n .filter(fp => !currentFileSet.has(fp));\n\n return { added, changed, deleted, unchanged };\n}\n\n/**\n * Extracts index units from a list of files.\n * Used during incremental updates.\n * \n * @param filePaths - Array of relative file paths to extract from\n * @param extractor - Index unit extractor instance\n * @returns Array of extracted units\n */\nexport async function extractUnitsFromFiles(\n filePaths: string[],\n extractor: IndexUnitExtractor\n): Promise<IndexUnit[]> {\n const allUnits: IndexUnit[] = [];\n \n for (const relPath of filePaths) {\n const functions = await extractor.scan(relPath);\n allUnits.push(...functions);\n }\n \n return allUnits;\n}\n\n/**\n * Updates file tracking metadata after processing changes.\n * Removes deleted files, updates changed files, adds new files.\n * \n * @param changeSet - Set of file changes to apply\n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor for checksum computation\n * @param db - Database instance for file tracking\n */\nexport async function updateFileTracking(\n changeSet: FileChangeSet,\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase\n): Promise<void> {\n // Remove deleted files\n if (changeSet.deleted.length > 0) {\n if (typeof (db as any).removeFilesByFilePaths === \"function\") {\n await (db as any).removeFilesByFilePaths(changeSet.deleted);\n } else if (typeof (db as any).removeFiles === \"function\") {\n await (db as any).removeFiles(changeSet.deleted);\n }\n }\n\n // Create file entities for new and changed files\n const filesToTrack = [...changeSet.added, ...changeSet.changed];\n if (filesToTrack.length > 0) {\n const fileEntities: FileEntity[] = [];\n \n for (const relPath of filesToTrack) {\n const fullPath = path.join(repoPath, relPath);\n const stat = await fs.stat(fullPath);\n const checksum = await extractor.computeChecksum(fullPath);\n \n const fileEntity = new FileEntity();\n fileEntity.filePath = relPath;\n fileEntity.checksum = checksum;\n fileEntity.mtime = stat.mtimeMs;\n \n fileEntities.push(fileEntity);\n }\n \n await db.saveFiles(fileEntities);\n }\n}\n\n/**\n * Performs incremental update of the DryScan index.\n * Detects file changes and reprocesses only affected files.\n * \n * @param repoPath - Root path of the repository\n * @param extractor - Index unit extractor instance\n * @param db - Database instance (must be initialized)\n */\nexport async function performIncrementalUpdate(\n repoPath: string,\n extractor: IndexUnitExtractor,\n db: DryScanDatabase,\n): Promise<FileChangeSet> {\n log(\"Starting incremental update\");\n const embeddingService = new EmbeddingService(repoPath);\n \n // Step 1: Detect changes\n const changeSet = await detectFileChanges(repoPath, extractor, db);\n \n if (changeSet.changed.length === 0 && \n changeSet.added.length === 0 && \n changeSet.deleted.length === 0) {\n log(\"No changes detected. Index is up to date.\");\n return changeSet;\n }\n\n log(`Changes detected: ${changeSet.added.length} added, ${changeSet.changed.length} changed, ${changeSet.deleted.length} deleted`);\n\n // Step 2: Remove old data for changed/deleted files\n const filesToRemove = [...changeSet.changed, ...changeSet.deleted];\n if (filesToRemove.length > 0) {\n await db.removeUnitsByFilePaths(filesToRemove);\n log(`Removed units from ${filesToRemove.length} files`);\n }\n\n // Step 3: Extract functions from new/changed files\n const filesToProcess = [...changeSet.added, ...changeSet.changed];\n if (filesToProcess.length > 0) {\n const newUnits = await extractUnitsFromFiles(filesToProcess, extractor);\n await db.saveUnits(newUnits);\n log(`Extracted and saved ${newUnits.length} units from ${filesToProcess.length} files`);\n\n // Step 4: Recompute embeddings for affected units only\n const total = newUnits.length;\n if (total > 0) {\n log(`Recomputing embeddings for ${total} units`);\n const progressInterval = Math.max(1, Math.ceil(total / 10));\n const updatedWithEmbeddings = [] as IndexUnit[];\n\n for (let i = 0; i < total; i++) {\n const unit = newUnits[i];\n try {\n const enriched = await embeddingService.addEmbedding(unit);\n updatedWithEmbeddings.push(enriched);\n } catch (err: any) {\n console.error(\n `[DryScan] embedding failed for ${unit.filePath} (${unit.name}): ${err?.message || err}`\n );\n throw err;\n }\n\n const completed = i + 1;\n if (completed === total || completed % progressInterval === 0) {\n const pct = Math.floor((completed / total) * 100);\n console.log(`[DryScan] Incremental embeddings ${completed}/${total} (${pct}%)`);\n }\n }\n\n await db.updateUnits(updatedWithEmbeddings);\n log(`Recomputed embeddings for ${updatedWithEmbeddings.length} units`);\n }\n }\n\n // Step 5: Update file tracking\n await updateFileTracking(changeSet, repoPath, extractor, db);\n log(\"Incremental update complete\");\n\n return changeSet;\n}\n","import { DuplicateGroup } from \"../types\";\n\n/**\n * In-memory cache for duplicate comparison scores.\n * Stores a global map of comparison keys and a per-file index for fast invalidation.\n */\nexport class DuplicationCache {\n private static instance: DuplicationCache | null = null;\n\n private readonly comparisons = new Map<string, number>();\n private readonly fileIndex = new Map<string, Set<string>>();\n private initialized = false;\n\n static getInstance(): DuplicationCache {\n if (!DuplicationCache.instance) {\n DuplicationCache.instance = new DuplicationCache();\n }\n return DuplicationCache.instance;\n }\n\n /**\n * Updates the cache with fresh duplicate groups. Not awaited by callers to avoid blocking.\n */\n async update(groups: DuplicateGroup[]): Promise<void> {\n if (!groups) return;\n\n for (const group of groups) {\n const key = this.makeKey(group.left.id, group.right.id);\n this.comparisons.set(key, group.similarity);\n this.addKeyForFile(group.left.filePath, key);\n this.addKeyForFile(group.right.filePath, key);\n }\n\n this.initialized = this.initialized || groups.length > 0;\n }\n\n /**\n * Retrieves a cached similarity if present and valid for both file paths.\n * Returns null when the cache has not been initialized or when the pair is missing.\n */\n get(leftId: string, rightId: string, leftFilePath: string, rightFilePath: string): number | null {\n if (!this.initialized) return null;\n\n const key = this.makeKey(leftId, rightId);\n if (!this.fileHasKey(leftFilePath, key) || !this.fileHasKey(rightFilePath, key)) {\n return null;\n }\n\n const value = this.comparisons.get(key);\n return typeof value === \"number\" ? value : null;\n }\n\n /**\n * Invalidates all cached comparisons involving the provided file paths.\n */\n async invalidate(paths: string[]): Promise<void> {\n if (!this.initialized || !paths || paths.length === 0) return;\n\n const unique = new Set(paths);\n for (const filePath of unique) {\n const keys = this.fileIndex.get(filePath);\n if (!keys) continue;\n\n for (const key of keys) {\n this.comparisons.delete(key);\n for (const [otherPath, otherKeys] of this.fileIndex.entries()) {\n if (otherKeys.delete(key) && otherKeys.size === 0) {\n this.fileIndex.delete(otherPath);\n }\n }\n }\n\n this.fileIndex.delete(filePath);\n }\n\n if (this.comparisons.size === 0) {\n this.initialized = false;\n }\n }\n\n /**\n * Clears all cached data. Intended for test setup.\n */\n clear(): void {\n this.comparisons.clear();\n this.fileIndex.clear();\n this.initialized = false;\n }\n\n private addKeyForFile(filePath: string, key: string): void {\n const current = this.fileIndex.get(filePath) ?? new Set<string>();\n current.add(key);\n this.fileIndex.set(filePath, current);\n }\n\n private fileHasKey(filePath: string, key: string): boolean {\n const keys = this.fileIndex.get(filePath);\n return keys ? keys.has(key) : false;\n }\n\n private makeKey(leftId: string, rightId: string): string {\n return [leftId, rightId].sort().join(\"::\");\n }\n}\n","import debug from \"debug\";\nimport shortUuid from \"short-uuid\";\nimport { cosineSimilarity } from \"@langchain/core/utils/math\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { DuplicateAnalysisResult, DuplicateGroup, DuplicationScore, IndexUnit, IndexUnitType } from \"../types\";\nimport { indexConfig } from \"../config/indexConfig\";\nimport { DryConfig } from \"../types\";\nimport { DuplicationCache } from \"./DuplicationCache\";\n\nconst log = debug(\"DryScan:DuplicateService\");\n\nexport class DuplicateService {\n private config?: DryConfig;\n private readonly cache = DuplicationCache.getInstance();\n\n constructor(private readonly deps: DryScanServiceDeps) {}\n\n //todo vetter optimisation\n async findDuplicates(config: DryConfig): Promise<DuplicateAnalysisResult> {\n this.config = config;\n const t0 = performance.now();\n const allUnits = await this.deps.db.getAllUnits();\n log(\"Starting duplicate analysis on %d units\", allUnits.length);\n if (allUnits.length < 2) {\n log(\"Not enough units to compare, returning empty result\");\n const score = this.computeDuplicationScore([], allUnits);\n return { duplicates: [], score };\n }\n\n const thresholds = this.resolveThresholds(config.threshold);\n log(\"Resolved thresholds: function=%d, block=%d, class=%d\", thresholds.function, thresholds.block, thresholds.class);\n const duplicates = this.computeDuplicates(allUnits, thresholds);\n const filteredDuplicates = duplicates.filter((group) => !this.isGroupExcluded(group));\n log(\"Found %d duplicate groups (%d excluded)\", filteredDuplicates.length, duplicates.length - filteredDuplicates.length);\n\n // Update cache asynchronously; no need to block the main flow.\n this.cache.update(filteredDuplicates).catch((err) => log(\"Cache update failed: %O\", err));\n\n const score = this.computeDuplicationScore(filteredDuplicates, allUnits);\n log(\"findDuplicates completed in %dms\", (performance.now() - t0).toFixed(2));\n return { duplicates: filteredDuplicates, score };\n }\n\n private resolveThresholds(functionThreshold?: number): { function: number; block: number; class: number } {\n const defaults = indexConfig.thresholds;\n const clamp = (value: number) => Math.min(1, Math.max(0, value));\n\n const base = functionThreshold ?? defaults.function;\n const blockOffset = defaults.block - defaults.function;\n const classOffset = defaults.class - defaults.function;\n\n const functionThresholdValue = clamp(base);\n return {\n function: functionThresholdValue,\n block: clamp(functionThresholdValue + blockOffset),\n class: clamp(functionThresholdValue + classOffset),\n };\n }\n\n private computeDuplicates(\n units: IndexUnit[],\n thresholds: { function: number; block: number; class: number }\n ): DuplicateGroup[] {\n const duplicates: DuplicateGroup[] = [];\n const byType = new Map<IndexUnitType, IndexUnit[]>();\n\n for (const unit of units) {\n const list = byType.get(unit.unitType) ?? [];\n list.push(unit);\n byType.set(unit.unitType, list);\n }\n\n const t0 = performance.now();\n\n for (const [type, typedUnits] of byType.entries()) {\n const threshold = this.getThreshold(type, thresholds);\n log(\"Comparing %d units of type '%s' with threshold %d\", typedUnits.length, type, threshold);\n const typeStart = performance.now();\n\n for (let i = 0; i < typedUnits.length; i++) {\n for (let j = i + 1; j < typedUnits.length; j++) {\n const left = typedUnits[i];\n const right = typedUnits[j];\n\n if (this.shouldSkipComparison(left, right)) {\n log(\"Skipping nested block comparison: '%s' and '%s'\", left.name, right.name);\n continue;\n }\n\n const cached = this.cache.get(left.id, right.id, left.filePath, right.filePath);\n let similarity: number | null = null;\n\n if (cached !== null) {\n log(\"Cache hit for '%s' <-> '%s': similarity=%d\", left.name, right.name, cached);\n similarity = cached;\n } else {\n if (!left.embedding || !right.embedding) {\n log(\"Skipping '%s' <-> '%s': missing embedding\", left.name, right.name);\n continue;\n }\n similarity = this.computeWeightedSimilarity(left, right);\n log(\"Computed similarity for '%s' <-> '%s': %d\", left.name, right.name, similarity);\n }\n\n if (similarity === null) continue;\n\n if (similarity >= threshold) {\n const exclusionString = this.deps.pairing.pairKeyForUnits(left, right);\n if (!exclusionString) continue;\n\n log(\"Duplicate found: '%s' <-> '%s' (similarity=%d)\", left.name, right.name, similarity);\n duplicates.push({\n id: `${left.id}::${right.id}`,\n similarity,\n shortId: shortUuid.generate(),\n exclusionString,\n left: {\n id: left.id,\n name: left.name,\n filePath: left.filePath,\n startLine: left.startLine,\n endLine: left.endLine,\n code: left.code,\n unitType: left.unitType,\n },\n right: {\n id: right.id,\n name: right.name,\n filePath: right.filePath,\n startLine: right.startLine,\n endLine: right.endLine,\n code: right.code,\n unitType: right.unitType,\n },\n });\n }\n }\n }\n log(\"Type '%s' comparisons completed in %dms\", type, (performance.now() - typeStart).toFixed(2));\n }\n\n log(\"computeDuplicates completed in %dms, found %d raw duplicates\", (performance.now() - t0).toFixed(2), duplicates.length);\n return duplicates.sort((a, b) => b.similarity - a.similarity);\n }\n\n private isGroupExcluded(group: DuplicateGroup): boolean {\n const config = this.config;\n if (!config || !config.excludedPairs || config.excludedPairs.length === 0) return false;\n const key = this.deps.pairing.pairKeyForUnits(group.left, group.right);\n if (!key) return false;\n const actual = this.deps.pairing.parsePairKey(key);\n if (!actual) return false;\n return config.excludedPairs.some((entry) => {\n const parsed = this.deps.pairing.parsePairKey(entry);\n return parsed ? this.deps.pairing.pairKeyMatches(actual, parsed) : false;\n });\n }\n\n private getThreshold(type: IndexUnitType, thresholds: { function: number; block: number; class: number }): number {\n if (type === IndexUnitType.CLASS) return thresholds.class;\n if (type === IndexUnitType.BLOCK) return thresholds.block;\n return thresholds.function;\n }\n\n private computeWeightedSimilarity(left: IndexUnit, right: IndexUnit): number {\n const selfSimilarity = this.similarityWithFallback(left, right);\n\n if (left.unitType === IndexUnitType.CLASS) {\n return selfSimilarity * indexConfig.weights.class.self;\n }\n\n if (left.unitType === IndexUnitType.FUNCTION) {\n const weights = indexConfig.weights.function;\n const hasParentClass = !!this.findParentOfType(left, IndexUnitType.CLASS) && !!this.findParentOfType(right, IndexUnitType.CLASS);\n const parentClassSimilarity = hasParentClass ? this.parentSimilarity(left, right, IndexUnitType.CLASS) : 0;\n\n // Re-normalize weights when parent context is missing, so standalone units aren't penalized.\n const totalWeight = weights.self + (hasParentClass ? weights.parentClass : 0);\n return ((weights.self * selfSimilarity) + (hasParentClass ? (weights.parentClass * parentClassSimilarity) : 0)) / totalWeight;\n }\n\n const weights = indexConfig.weights.block;\n const hasParentFunction = !!this.findParentOfType(left, IndexUnitType.FUNCTION) && !!this.findParentOfType(right, IndexUnitType.FUNCTION);\n const hasParentClass = !!this.findParentOfType(left, IndexUnitType.CLASS) && !!this.findParentOfType(right, IndexUnitType.CLASS);\n const parentFuncSim = hasParentFunction ? this.parentSimilarity(left, right, IndexUnitType.FUNCTION) : 0;\n const parentClassSim = hasParentClass ? this.parentSimilarity(left, right, IndexUnitType.CLASS) : 0;\n\n // Re-normalize weights when some parent context is missing.\n const totalWeight =\n weights.self +\n (hasParentFunction ? weights.parentFunction : 0) +\n (hasParentClass ? weights.parentClass : 0);\n\n return (\n (weights.self * selfSimilarity) +\n (hasParentFunction ? (weights.parentFunction * parentFuncSim) : 0) +\n (hasParentClass ? (weights.parentClass * parentClassSim) : 0)\n ) / totalWeight;\n }\n\n private parentSimilarity(left: IndexUnit, right: IndexUnit, targetType: IndexUnitType): number {\n const leftParent = this.findParentOfType(left, targetType);\n const rightParent = this.findParentOfType(right, targetType);\n if (!leftParent || !rightParent) return 0;\n return this.similarityWithFallback(leftParent, rightParent);\n }\n\n private similarityWithFallback(left: IndexUnit, right: IndexUnit): number {\n const leftHasEmbedding = this.hasVector(left);\n const rightHasEmbedding = this.hasVector(right);\n\n if (leftHasEmbedding && rightHasEmbedding) {\n return cosineSimilarity([left.embedding as number[]], [right.embedding as number[]])[0][0];\n }\n\n return this.childSimilarity(left, right);\n }\n\n private childSimilarity(left: IndexUnit, right: IndexUnit): number {\n const leftChildren = left.children ?? [];\n const rightChildren = right.children ?? [];\n if (leftChildren.length === 0 || rightChildren.length === 0) return 0;\n\n let best = 0;\n for (const lChild of leftChildren) {\n for (const rChild of rightChildren) {\n if (lChild.unitType !== rChild.unitType) continue;\n const sim = this.similarityWithFallback(lChild, rChild);\n if (sim > best) best = sim;\n }\n }\n return best;\n }\n\n private hasVector(unit: IndexUnit): boolean {\n return Array.isArray(unit.embedding) && unit.embedding.length > 0;\n }\n\n private shouldSkipComparison(left: IndexUnit, right: IndexUnit): boolean {\n if (left.unitType !== IndexUnitType.BLOCK || right.unitType !== IndexUnitType.BLOCK) {\n return false;\n }\n\n if (left.filePath !== right.filePath) {\n return false;\n }\n\n const leftContainsRight = left.startLine <= right.startLine && left.endLine >= right.endLine;\n const rightContainsLeft = right.startLine <= left.startLine && right.endLine >= left.endLine;\n return leftContainsRight || rightContainsLeft;\n }\n\n private findParentOfType(unit: IndexUnit, targetType: IndexUnitType): IndexUnit | null {\n let current: IndexUnit | undefined | null = unit.parent;\n while (current) {\n if (current.unitType === targetType) return current;\n current = current.parent;\n }\n return null;\n }\n\n private computeDuplicationScore(duplicates: DuplicateGroup[], allUnits: IndexUnit[]): DuplicationScore {\n const totalLines = this.calculateTotalLines(allUnits);\n\n if (totalLines === 0 || duplicates.length === 0) {\n return {\n score: 0,\n grade: \"Excellent\",\n totalLines,\n duplicateLines: 0,\n duplicateGroups: 0,\n };\n }\n\n const weightedDuplicateLines = duplicates.reduce((sum, group) => {\n const leftLines = group.left.endLine - group.left.startLine + 1;\n const rightLines = group.right.endLine - group.right.startLine + 1;\n const avgLines = (leftLines + rightLines) / 2;\n return sum + group.similarity * avgLines;\n }, 0);\n\n const score = (weightedDuplicateLines / totalLines) * 100;\n const grade = this.getScoreGrade(score);\n\n return {\n score,\n grade,\n totalLines,\n duplicateLines: Math.round(weightedDuplicateLines),\n duplicateGroups: duplicates.length,\n };\n }\n\n private calculateTotalLines(units: IndexUnit[]): number {\n return units.reduce((sum, unit) => {\n const lines = unit.endLine - unit.startLine + 1;\n return sum + lines;\n }, 0);\n }\n\n private getScoreGrade(score: number): DuplicationScore[\"grade\"] {\n if (score < 5) return \"Excellent\";\n if (score < 15) return \"Good\";\n if (score < 30) return \"Fair\";\n if (score < 50) return \"Poor\";\n return \"Critical\";\n }\n}","import { DryConfig } from \"../types\";\nimport { configStore } from \"../config/configStore\";\nimport { DryScanServiceDeps } from \"./types\";\nimport { IndexUnitType } from \"../types\";\nimport { minimatch } from \"minimatch\";\nimport { ParsedPairKey } from \"./PairingService\";\n\nexport class ExclusionService {\n private config?: DryConfig;\n\n constructor(private readonly deps: DryScanServiceDeps) {}\n\n async cleanupExcludedFiles(): Promise<void> {\n const config = await this.loadConfig();\n if (!config.excludedPaths || config.excludedPaths.length === 0) return;\n\n const units = await this.deps.db.getAllUnits();\n const files = await this.deps.db.getAllFiles();\n\n const unitPathsToRemove = new Set<string>();\n for (const unit of units) {\n if (this.pathExcluded(unit.filePath)) {\n unitPathsToRemove.add(unit.filePath);\n }\n }\n\n const filePathsToRemove = new Set<string>();\n for (const file of files) {\n if (this.pathExcluded(file.filePath)) {\n filePathsToRemove.add(file.filePath);\n }\n }\n\n const paths = [...new Set([...unitPathsToRemove, ...filePathsToRemove])];\n if (paths.length > 0) {\n await this.deps.db.removeUnitsByFilePaths(paths);\n await this.deps.db.removeFilesByFilePaths(paths);\n }\n }\n\n async cleanExclusions(): Promise<{ removed: number; kept: number }> {\n const config = await this.loadConfig();\n const units = await this.deps.db.getAllUnits();\n\n const actualPairsByType = {\n [IndexUnitType.CLASS]: this.buildPairKeys(units, IndexUnitType.CLASS),\n [IndexUnitType.FUNCTION]: this.buildPairKeys(units, IndexUnitType.FUNCTION),\n [IndexUnitType.BLOCK]: this.buildPairKeys(units, IndexUnitType.BLOCK),\n };\n\n const kept: string[] = [];\n const removed: string[] = [];\n\n for (const entry of config.excludedPairs || []) {\n const parsed = this.deps.pairing.parsePairKey(entry);\n if (!parsed) {\n removed.push(entry);\n continue;\n }\n\n const candidates = actualPairsByType[parsed.type];\n const matched = candidates.some((actual) => this.deps.pairing.pairKeyMatches(actual, parsed));\n if (matched) {\n kept.push(entry);\n } else {\n removed.push(entry);\n }\n }\n\n const nextConfig: DryConfig = { ...config, excludedPairs: kept };\n await configStore.save(this.deps.repoPath, nextConfig);\n this.config = nextConfig;\n\n return { removed: removed.length, kept: kept.length };\n }\n\n private pathExcluded(filePath: string): boolean {\n const config = this.config;\n if (!config || !config.excludedPaths || config.excludedPaths.length === 0) return false;\n return config.excludedPaths.some((pattern) => minimatch(filePath, pattern, { dot: true }));\n }\n\n private buildPairKeys(units: any[], type: IndexUnitType): ParsedPairKey[] {\n const typed = units.filter((u) => u.unitType === type);\n const pairs: ParsedPairKey[] = [];\n for (let i = 0; i < typed.length; i++) {\n for (let j = i + 1; j < typed.length; j++) {\n const key = this.deps.pairing.pairKeyForUnits(typed[i], typed[j]);\n const parsed = key ? this.deps.pairing.parsePairKey(key) : null;\n if (parsed) {\n pairs.push(parsed);\n }\n }\n }\n return pairs;\n }\n\n private async loadConfig(): Promise<DryConfig> {\n this.config = await configStore.get(this.deps.repoPath);\n return this.config;\n }\n}","import crypto from \"node:crypto\";\nimport debug from \"debug\";\nimport { minimatch } from \"minimatch\";\nimport { LanguageExtractor } from \"../extractors/LanguageExtractor\";\nimport { IndexUnitExtractor } from \"../IndexUnitExtractor\";\nimport { IndexUnit, IndexUnitType } from \"../types\";\nimport { BLOCK_HASH_ALGO } from \"../const\";\n\nconst log = debug(\"DryScan:pairs\");\n\ntype UnitLike = Pick<IndexUnit, \"unitType\" | \"filePath\" | \"name\" | \"code\">;\n\nexport interface ParsedPairKey {\n type: IndexUnitType;\n left: string;\n right: string;\n key: string;\n}\n\n/**\n * Service for building and parsing pair keys with extractor-aware labeling.\n */\nexport class PairingService {\n constructor(private readonly indexUnitExtractor: IndexUnitExtractor) {}\n\n /**\n * Creates a stable, order-independent key for two units of the same type.\n * Returns null when units differ in type so callers can skip invalid pairs.\n */\n pairKeyForUnits(left: UnitLike, right: UnitLike): string | null {\n if (left.unitType !== right.unitType) {\n log(\"Skipping pair with mismatched types: %s vs %s\", left.unitType, right.unitType);\n return null;\n }\n const type = left.unitType;\n const leftLabel = this.unitLabel(left);\n const rightLabel = this.unitLabel(right);\n const [a, b] = [leftLabel, rightLabel].sort();\n return `${type}|${a}|${b}`;\n }\n\n /**\n * Parses a raw pair key into its components, returning null for malformed values.\n * Sorting is applied so callers can compare pairs without worrying about order.\n */\n parsePairKey(value: string): ParsedPairKey | null {\n const parts = value.split(\"|\");\n if (parts.length !== 3) {\n log(\"Invalid pair key format: %s\", value);\n return null;\n }\n const [typeRaw, leftRaw, rightRaw] = parts;\n const type = this.stringToUnitType(typeRaw);\n if (!type) {\n log(\"Unknown unit type in pair key: %s\", typeRaw);\n return null;\n }\n const [left, right] = [leftRaw, rightRaw].sort();\n return { type, left, right, key: `${type}|${left}|${right}` };\n }\n\n /**\n * Checks whether an actual pair key satisfies a pattern, with glob matching for class paths.\n */\n pairKeyMatches(actual: ParsedPairKey, pattern: ParsedPairKey): boolean {\n if (actual.type !== pattern.type) return false;\n if (actual.type === IndexUnitType.CLASS) {\n // Allow glob matching for class file paths.\n const forward =\n minimatch(actual.left, pattern.left, { dot: true }) &&\n minimatch(actual.right, pattern.right, { dot: true });\n const swapped =\n minimatch(actual.left, pattern.right, { dot: true }) &&\n minimatch(actual.right, pattern.left, { dot: true });\n return forward || swapped;\n }\n\n // Functions and blocks use exact matching on canonical strings.\n return (\n (actual.left === pattern.left && actual.right === pattern.right) ||\n (actual.left === pattern.right && actual.right === pattern.left)\n );\n }\n\n /**\n * Derives a reversible, extractor-aware label for a unit.\n * Extractors may override; fallback uses a fixed format per unit type.\n */\n unitLabel(unit: UnitLike): string {\n const extractor = this.findExtractor(unit.filePath);\n const customLabel = extractor?.unitLabel?.(unit as IndexUnit);\n if (customLabel) return customLabel;\n\n switch (unit.unitType) {\n case IndexUnitType.CLASS:\n return unit.filePath;\n case IndexUnitType.FUNCTION:\n return this.canonicalFunctionSignature(unit);\n case IndexUnitType.BLOCK:\n return this.normalizedBlockHash(unit);\n default:\n return unit.name;\n }\n }\n\n private findExtractor(filePath: string): LanguageExtractor | undefined {\n return this.indexUnitExtractor.extractors.find((ex) => ex.supports(filePath));\n }\n\n private canonicalFunctionSignature(unit: UnitLike): string {\n const arity = this.extractArity(unit.code);\n return `${unit.name}(arity:${arity})`;\n }\n\n /**\n * Normalizes block code (strips comments/whitespace) and hashes it for pair matching.\n */\n private normalizedBlockHash(unit: UnitLike): string {\n const normalized = this.normalizeCode(unit.code);\n return crypto.createHash(BLOCK_HASH_ALGO).update(normalized).digest(\"hex\");\n }\n\n private stringToUnitType(value: string): IndexUnitType | null {\n if (value === IndexUnitType.CLASS) return IndexUnitType.CLASS;\n if (value === IndexUnitType.FUNCTION) return IndexUnitType.FUNCTION;\n if (value === IndexUnitType.BLOCK) return IndexUnitType.BLOCK;\n return null;\n }\n\n private extractArity(code: string): number {\n const match = code.match(/^[^{]*?\\(([^)]*)\\)/s);\n if (!match) return 0;\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n return params.length;\n }\n\n private normalizeCode(code: string): string {\n const withoutBlockComments = code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n const withoutLineComments = withoutBlockComments.replace(/\\/\\/[^\\n\\r]*/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,MACpC,WAAW,OAAO;AAAA,MAClB,OAAO,SAAS,MAAM;AAAA,MACtB,OAAO,SAAS;AAAA,MAChB,YAAY,SAAS;AAAA,IACvB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAc,eAAe,QAAqD;AAChF,YAAQ,IAAI,4CAA4C,OAAO,SAAS,MAAM;AAC9E,UAAM,KAAK,eAAe;AAE1B,YAAQ,IAAI,6BAA6B;AACzC,UAAM,cAAc,KAAK,IAAI;AAC7B,UAAM,KAAK,YAAY;AACvB,UAAM,iBAAiB,KAAK,IAAI,IAAI;AACpC,YAAQ,IAAI,gCAAgC,cAAc,KAAK;AAE/D,YAAQ,IAAI,mCAAmC;AAC/C,UAAM,WAAW,KAAK,IAAI;AAC1B,UAAM,SAAS,MAAM,KAAK,SAAS,UAAU,eAAe,MAAM;AAClE,UAAM,cAAc,KAAK,IAAI,IAAI;AACjC,YAAQ,IAAI,sCAAsC,WAAW,KAAK;AAElE,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,kBAA8D;AAClE,UAAM,KAAK,YAAY;AACvB,WAAO,KAAK,SAAS,UAAU,gBAAgB;AAAA,EACjD;AAAA,EAEA,MAAc,iBAAgC;AAC5C,QAAI,KAAK,GAAG,cAAc,EAAG;AAC7B,UAAM,SAASA,OAAM,KAAK,KAAK,UAAU,aAAa,QAAQ;AAC9D,UAAMC,IAAG,MAAMD,OAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AACzD,UAAM,KAAK,GAAG,KAAK,MAAM;AAAA,EAC3B;AAAA,EAEA,MAAc,aAAiC;AAC7C,WAAO,YAAY,IAAI,KAAK,QAAQ;AAAA,EACtC;AAEF;","names":["upath","fs","path","fs","upath","crypto","glob","upath","upath","fs","upath","path","fs","crypto","upath","glob","fs","upath","Column","Entity","PrimaryColumn","PrimaryColumn","Column","Entity","fs","upath","path","fs","debug","log","debug","path","fs","debug","path","fs","debug","log","debug","path","fs","log","debug","debug","log","debug","score","weights","hasParentClass","totalWeight","crypto","debug","minimatch","log","debug","minimatch","crypto","upath","fs"]}
|
package/package.json
CHANGED
|
@@ -48,7 +48,7 @@ export class DryScanDatabase {
|
|
|
48
48
|
|
|
49
49
|
async getUnit(id: string): Promise<IndexUnit | null> {
|
|
50
50
|
if (!this.unitRepository) throw new Error("Database not initialized");
|
|
51
|
-
return this.unitRepository.findOne({
|
|
51
|
+
return this.unitRepository.findOne({
|
|
52
52
|
where: { id },
|
|
53
53
|
relations: ["children", "parent"]
|
|
54
54
|
});
|
package/src/extractors/java.ts
CHANGED
|
@@ -233,6 +233,7 @@ export class JavaExtractor implements LanguageExtractor {
|
|
|
233
233
|
filePath: file,
|
|
234
234
|
startLine,
|
|
235
235
|
endLine,
|
|
236
|
+
children: [],
|
|
236
237
|
code: this.stripComments(source.slice(node.startIndex, node.endIndex)),
|
|
237
238
|
unitType: IndexUnitType.FUNCTION,
|
|
238
239
|
parentId: parentClass?.id,
|
|
@@ -274,9 +275,11 @@ export class JavaExtractor implements LanguageExtractor {
|
|
|
274
275
|
parentId: parentFunction.id,
|
|
275
276
|
parent: parentFunction,
|
|
276
277
|
};
|
|
278
|
+
const contextLength = this.config?.contextLength ?? 2048;
|
|
279
|
+
const splitBlocks = this.textSplitBlockIfOverContextLimit(blockUnit, contextLength);
|
|
277
280
|
parentFunction.children = parentFunction.children || [];
|
|
278
|
-
parentFunction.children.push(
|
|
279
|
-
blocks.push(
|
|
281
|
+
parentFunction.children.push(...splitBlocks);
|
|
282
|
+
blocks.push(...splitBlocks);
|
|
280
283
|
}
|
|
281
284
|
}
|
|
282
285
|
|
|
@@ -334,8 +337,25 @@ export class JavaExtractor implements LanguageExtractor {
|
|
|
334
337
|
return withoutBlockComments.replace(/\/\/[^\n\r]*/g, "");
|
|
335
338
|
}
|
|
336
339
|
|
|
337
|
-
private removeDuplicates(units: IndexUnit[]): IndexUnit[] | PromiseLike<IndexUnit[]> {
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
+
private removeDuplicates(units: IndexUnit[]): IndexUnit[] | PromiseLike<IndexUnit[]> {
|
|
341
|
+
return Array.from(new Map(units.map(u => [u.id, u])).values());
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Splits a block unit's code into chunks if it exceeds the context length limit. */
|
|
345
|
+
private textSplitBlockIfOverContextLimit(unit: IndexUnit, contextLength: number): IndexUnit[] {
|
|
346
|
+
if (unit.code.length <= contextLength) return [unit];
|
|
347
|
+
|
|
348
|
+
const chunks: IndexUnit[] = [];
|
|
349
|
+
let chunkIndex = 0;
|
|
350
|
+
for (let i = 0; i < unit.code.length; i += contextLength) {
|
|
351
|
+
chunks.push({
|
|
352
|
+
...unit,
|
|
353
|
+
id: `${unit.id}:chunk${chunkIndex}`,
|
|
354
|
+
code: unit.code.slice(i, i + contextLength),
|
|
355
|
+
});
|
|
356
|
+
chunkIndex++;
|
|
357
|
+
}
|
|
358
|
+
return chunks;
|
|
359
|
+
}
|
|
340
360
|
}
|
|
341
361
|
|
|
@@ -15,23 +15,29 @@ export class DuplicateService {
|
|
|
15
15
|
|
|
16
16
|
constructor(private readonly deps: DryScanServiceDeps) {}
|
|
17
17
|
|
|
18
|
+
//todo vetter optimisation
|
|
18
19
|
async findDuplicates(config: DryConfig): Promise<DuplicateAnalysisResult> {
|
|
19
20
|
this.config = config;
|
|
21
|
+
const t0 = performance.now();
|
|
20
22
|
const allUnits = await this.deps.db.getAllUnits();
|
|
23
|
+
log("Starting duplicate analysis on %d units", allUnits.length);
|
|
21
24
|
if (allUnits.length < 2) {
|
|
25
|
+
log("Not enough units to compare, returning empty result");
|
|
22
26
|
const score = this.computeDuplicationScore([], allUnits);
|
|
23
27
|
return { duplicates: [], score };
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
const thresholds = this.resolveThresholds(config.threshold);
|
|
31
|
+
log("Resolved thresholds: function=%d, block=%d, class=%d", thresholds.function, thresholds.block, thresholds.class);
|
|
27
32
|
const duplicates = this.computeDuplicates(allUnits, thresholds);
|
|
28
33
|
const filteredDuplicates = duplicates.filter((group) => !this.isGroupExcluded(group));
|
|
29
|
-
log("Found %d duplicate groups", filteredDuplicates.length);
|
|
34
|
+
log("Found %d duplicate groups (%d excluded)", filteredDuplicates.length, duplicates.length - filteredDuplicates.length);
|
|
30
35
|
|
|
31
36
|
// Update cache asynchronously; no need to block the main flow.
|
|
32
37
|
this.cache.update(filteredDuplicates).catch((err) => log("Cache update failed: %O", err));
|
|
33
38
|
|
|
34
39
|
const score = this.computeDuplicationScore(filteredDuplicates, allUnits);
|
|
40
|
+
log("findDuplicates completed in %dms", (performance.now() - t0).toFixed(2));
|
|
35
41
|
return { duplicates: filteredDuplicates, score };
|
|
36
42
|
}
|
|
37
43
|
|
|
@@ -64,24 +70,36 @@ export class DuplicateService {
|
|
|
64
70
|
byType.set(unit.unitType, list);
|
|
65
71
|
}
|
|
66
72
|
|
|
73
|
+
const t0 = performance.now();
|
|
74
|
+
|
|
67
75
|
for (const [type, typedUnits] of byType.entries()) {
|
|
68
76
|
const threshold = this.getThreshold(type, thresholds);
|
|
77
|
+
log("Comparing %d units of type '%s' with threshold %d", typedUnits.length, type, threshold);
|
|
78
|
+
const typeStart = performance.now();
|
|
69
79
|
|
|
70
80
|
for (let i = 0; i < typedUnits.length; i++) {
|
|
71
81
|
for (let j = i + 1; j < typedUnits.length; j++) {
|
|
72
82
|
const left = typedUnits[i];
|
|
73
83
|
const right = typedUnits[j];
|
|
74
84
|
|
|
75
|
-
if (this.shouldSkipComparison(left, right))
|
|
85
|
+
if (this.shouldSkipComparison(left, right)) {
|
|
86
|
+
log("Skipping nested block comparison: '%s' and '%s'", left.name, right.name);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
76
89
|
|
|
77
90
|
const cached = this.cache.get(left.id, right.id, left.filePath, right.filePath);
|
|
78
91
|
let similarity: number | null = null;
|
|
79
92
|
|
|
80
93
|
if (cached !== null) {
|
|
94
|
+
log("Cache hit for '%s' <-> '%s': similarity=%d", left.name, right.name, cached);
|
|
81
95
|
similarity = cached;
|
|
82
96
|
} else {
|
|
83
|
-
if (!left.embedding || !right.embedding)
|
|
97
|
+
if (!left.embedding || !right.embedding) {
|
|
98
|
+
log("Skipping '%s' <-> '%s': missing embedding", left.name, right.name);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
84
101
|
similarity = this.computeWeightedSimilarity(left, right);
|
|
102
|
+
log("Computed similarity for '%s' <-> '%s': %d", left.name, right.name, similarity);
|
|
85
103
|
}
|
|
86
104
|
|
|
87
105
|
if (similarity === null) continue;
|
|
@@ -90,6 +108,7 @@ export class DuplicateService {
|
|
|
90
108
|
const exclusionString = this.deps.pairing.pairKeyForUnits(left, right);
|
|
91
109
|
if (!exclusionString) continue;
|
|
92
110
|
|
|
111
|
+
log("Duplicate found: '%s' <-> '%s' (similarity=%d)", left.name, right.name, similarity);
|
|
93
112
|
duplicates.push({
|
|
94
113
|
id: `${left.id}::${right.id}`,
|
|
95
114
|
similarity,
|
|
@@ -117,8 +136,10 @@ export class DuplicateService {
|
|
|
117
136
|
}
|
|
118
137
|
}
|
|
119
138
|
}
|
|
139
|
+
log("Type '%s' comparisons completed in %dms", type, (performance.now() - typeStart).toFixed(2));
|
|
120
140
|
}
|
|
121
141
|
|
|
142
|
+
log("computeDuplicates completed in %dms, found %d raw duplicates", (performance.now() - t0).toFixed(2), duplicates.length);
|
|
122
143
|
return duplicates.sort((a, b) => b.similarity - a.similarity);
|
|
123
144
|
}
|
|
124
145
|
|