-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdoc2vec.ts
More file actions
1537 lines (1302 loc) · 70.8 KB
/
doc2vec.ts
File metadata and controls
1537 lines (1302 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import axios from 'axios';
import crypto from 'crypto';
import * as yaml from 'js-yaml';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { exec } from 'child_process';
import { promisify } from 'util';
import { Buffer } from 'buffer';
import { OpenAI, AzureOpenAI } from "openai";
import * as dotenv from "dotenv";
import { Logger, LogLevel } from './logger';
import { Utils } from './utils';
import { DatabaseManager } from './database';
import { ContentProcessor } from './content-processor';
import {
Config,
SourceConfig,
GithubSourceConfig,
WebsiteSourceConfig,
LocalDirectorySourceConfig,
CodeSourceConfig,
ZendeskSourceConfig,
DatabaseConnection,
DocumentChunk,
BrokenLink,
EmbeddingConfig,
MarkdownStoreConfig
} from './types';
import { MarkdownStore } from './markdown-store';
const GITHUB_TOKEN = process.env.GITHUB_PERSONAL_ACCESS_TOKEN;
const execAsync = promisify(exec);
dotenv.config();
export class Doc2Vec {
private config: Config;
private openai: OpenAI | AzureOpenAI;
private embeddingModel: string;
private embeddingDimension: number;
private contentProcessor: ContentProcessor;
private logger: Logger;
private configDir: string;
private brokenLinksByWebsite: Record<string, BrokenLink[]> = {};
private markdownStore: MarkdownStore | undefined;
constructor(configPath: string) {
this.logger = new Logger('Doc2Vec', {
level: LogLevel.DEBUG,
useTimestamp: true,
useColor: true,
prettyPrint: true
});
this.logger.info('Initializing Doc2Vec');
this.config = this.loadConfig(configPath);
this.configDir = path.dirname(path.resolve(configPath));
// Initialize OpenAI or Azure OpenAI based on configuration
// Check environment variable if not specified in config
const embeddingProvider = this.config.embedding?.provider || (process.env.EMBEDDING_PROVIDER as 'openai' | 'azure') || 'openai';
const embeddingConfig = this.config.embedding || { provider: embeddingProvider };
this.embeddingDimension = this.resolveEmbeddingDimension(embeddingConfig);
if (embeddingProvider === 'azure') {
const azureApiKey = embeddingConfig.azure?.api_key || process.env.AZURE_OPENAI_KEY;
const azureEndpoint = embeddingConfig.azure?.endpoint || process.env.AZURE_OPENAI_ENDPOINT;
const azureDeploymentName = embeddingConfig.azure?.deployment_name || process.env.AZURE_OPENAI_DEPLOYMENT_NAME || 'text-embedding-3-large';
const azureApiVersion = embeddingConfig.azure?.api_version || process.env.AZURE_OPENAI_API_VERSION || '2024-10-21';
if (!azureApiKey || !azureEndpoint) {
this.logger.error('Azure OpenAI requires api_key and endpoint to be configured');
process.exit(1);
}
this.openai = new AzureOpenAI({
apiKey: azureApiKey,
endpoint: azureEndpoint,
deployment: azureDeploymentName,
apiVersion: azureApiVersion,
});
this.embeddingModel = azureDeploymentName;
this.logger.info(`Using Azure OpenAI with deployment: ${azureDeploymentName} (${this.embeddingDimension} dimensions)`);
} else {
const openaiApiKey = embeddingConfig.openai?.api_key || process.env.OPENAI_API_KEY;
const openaiModel = embeddingConfig.openai?.model || process.env.OPENAI_MODEL || 'text-embedding-3-large';
if (!openaiApiKey) {
this.logger.error('OpenAI requires api_key to be configured');
process.exit(1);
}
this.openai = new OpenAI({ apiKey: openaiApiKey });
this.embeddingModel = openaiModel;
this.logger.info(`Using OpenAI with model: ${openaiModel} (${this.embeddingDimension} dimensions)`);
}
this.contentProcessor = new ContentProcessor(this.logger);
// Initialize Postgres markdown store if configured
if (this.config.markdown_store) {
this.markdownStore = new MarkdownStore(this.config.markdown_store, this.logger);
}
}
private loadConfig(configPath: string): Config {
try {
const logger = this.logger.child('config');
logger.info(`Loading configuration from ${configPath}`);
let configFile = fs.readFileSync(configPath, 'utf8');
// Substitute environment variables in the format ${VAR_NAME}
configFile = configFile.replace(/\$\{([^}]+)\}/g, (match, varName) => {
const envValue = process.env[varName];
if (envValue === undefined) {
logger.warn(`Environment variable ${varName} not found, keeping placeholder ${match}`);
return match;
}
logger.debug(`Substituted ${match} with environment variable value`);
return envValue;
});
let config = yaml.load(configFile) as any;
const typedConfig = config as Config;
for (const source of typedConfig.sources) {
if (source.type === 'code') {
if (!source.version || String(source.version).trim().length === 0) {
if (source.branch && String(source.branch).trim().length > 0) {
source.version = source.branch;
} else {
source.version = 'local';
}
}
} else if (!source.version || String(source.version).trim().length === 0) {
logger.error(`Missing required version for ${source.type} source: ${source.product_name}`);
process.exit(1);
}
}
logger.info(`Configuration loaded successfully, found ${typedConfig.sources.length} sources`);
return typedConfig;
} catch (error) {
this.logger.error(`Failed to load or parse config file at ${configPath}:`, error);
process.exit(1);
}
}
private resolveEmbeddingDimension(embeddingConfig: EmbeddingConfig | undefined): number {
const defaultDimension = 3072;
const rawConfigValue = embeddingConfig?.dimension;
const rawEnvValue = process.env.EMBEDDING_DIMENSION;
const candidate = rawConfigValue ?? (rawEnvValue ? Number(rawEnvValue) : undefined);
if (candidate === undefined) {
return defaultDimension;
}
const parsedValue = typeof candidate === 'string' ? Number(candidate) : candidate;
if (!Number.isFinite(parsedValue) || parsedValue <= 0 || !Number.isInteger(parsedValue)) {
this.logger.warn(`Invalid embedding dimension provided (${candidate}), falling back to ${defaultDimension}`);
return defaultDimension;
}
return parsedValue;
}
public async run(): Promise<void> {
// Initialize Postgres markdown store table if configured
if (this.markdownStore) {
await this.markdownStore.init();
}
this.logger.section('PROCESSING SOURCES');
for (const sourceConfig of this.config.sources) {
const sourceLogger = this.logger.child(`source:${sourceConfig.product_name}`);
sourceLogger.info(`Processing ${sourceConfig.type} source for ${sourceConfig.product_name}@${sourceConfig.version}`);
if (sourceConfig.type === 'github') {
await this.processGithubRepo(sourceConfig, sourceLogger);
} else if (sourceConfig.type === 'website') {
await this.processWebsite(sourceConfig, sourceLogger);
} else if (sourceConfig.type === 'local_directory') {
await this.processLocalDirectory(sourceConfig, sourceLogger);
} else if (sourceConfig.type === 'code') {
await this.processCodeSource(sourceConfig, sourceLogger);
} else if (sourceConfig.type === 'zendesk') {
await this.processZendesk(sourceConfig, sourceLogger);
} else {
sourceLogger.error(`Unknown source type: ${(sourceConfig as any).type}`);
}
}
// Close the Postgres markdown store connection pool
if (this.markdownStore) {
await this.markdownStore.close();
}
this.logger.section('PROCESSING COMPLETE');
}
private async fetchAndProcessGitHubIssues(repo: string, sourceConfig: GithubSourceConfig, dbConnection: DatabaseConnection, logger: Logger): Promise<void> {
const [owner, repoName] = repo.split('/');
const GITHUB_API_URL = `https://api.github.com/repos/${owner}/${repoName}/issues`;
// Initialize metadata storage if needed
await DatabaseManager.initDatabaseMetadata(dbConnection, logger);
// Get the last run date from the database
const startDate = sourceConfig.start_date || '2025-01-01';
const lastRunDate = await DatabaseManager.getLastRunDate(dbConnection, repo, `${startDate}T00:00:00Z`, logger);
const fetchWithRetry = async (url: string, params = {}, retries = 5, delay = 5000): Promise<any> => {
for (let attempt = 0; attempt < retries; attempt++) {
try {
// Only log on retries to reduce noise during pagination
if (attempt > 0) {
logger.debug(`GitHub API retry: ${url} (attempt ${attempt + 1}/${retries})`);
}
const response = await axios.get(url, {
headers: {
Authorization: `token ${GITHUB_TOKEN}`,
Accept: 'application/vnd.github.v3+json',
},
params,
timeout: 30000, // 30 second timeout
});
return response.data;
} catch (error: any) {
// Enhanced error logging for debugging
const errorDetails = {
code: error.code,
message: error.message,
status: error.response?.status,
isTimeout: error.code === 'ECONNABORTED' || error.message?.includes('timeout'),
isNetworkError: !error.response && error.code,
};
logger.debug(`GitHub API error details: ${JSON.stringify(errorDetails)}`);
if (error.response && error.response.status === 403) {
// Check if this is actually a rate limit error
const rateLimitRemaining = error.response.headers['x-ratelimit-remaining'];
const resetTime = error.response.headers['x-ratelimit-reset'];
if (rateLimitRemaining === '0' && resetTime) {
const currentTime = Math.floor(Date.now() / 1000);
const resetTimestamp = parseInt(resetTime, 10);
let waitTime = (resetTimestamp - currentTime) * 1000;
// Ensure waitTime is at least 1 second (in case resetTime is in the past)
if (waitTime < 1000) {
waitTime = 1000;
}
logger.warn(`GitHub rate limit exceeded. Waiting ${Math.ceil(waitTime / 1000)}s (attempt ${attempt + 1}/${retries})`);
await new Promise(res => setTimeout(res, waitTime));
// Retry the request after waiting
continue;
} else {
// Other 403 errors (e.g., forbidden access)
logger.error(`GitHub API returned 403 (not rate limit): ${error.message}`);
throw error;
}
} else {
// For non-403 errors, wait before retrying (exponential backoff)
if (attempt < retries - 1) {
const backoffDelay = delay * Math.pow(2, attempt);
logger.warn(`GitHub fetch failed (attempt ${attempt + 1}/${retries}): ${error.message}. Retrying in ${backoffDelay}ms`);
await new Promise(res => setTimeout(res, backoffDelay));
} else {
logger.error(`GitHub fetch failed after ${retries} attempts: ${error.message} (code: ${error.code || 'unknown'})`);
throw error;
}
}
}
}
throw new Error('Max retries reached');
};
const fetchAllIssues = async (sinceDate: string): Promise<any[]> => {
let issues: any[] = [];
let page = 1;
const perPage = 100;
const sinceTimestamp = new Date(sinceDate);
while (true) {
// Log progress every 10 pages to reduce noise
if (page === 1 || page % 10 === 0) {
logger.debug(`Fetching issues page ${page}... (${issues.length} issues so far)`);
}
const data = await fetchWithRetry(GITHUB_API_URL, {
per_page: perPage,
page,
state: 'all',
since: sinceDate,
});
if (data.length === 0) break;
const filtered = data.filter((issue: any) => new Date(issue.created_at) >= sinceTimestamp);
issues = issues.concat(filtered);
if (filtered.length < data.length) break;
page++;
}
return issues;
};
const fetchIssueComments = async (issueNumber: number): Promise<any[]> => {
const url = `${GITHUB_API_URL}/${issueNumber}/comments`;
return await fetchWithRetry(url);
};
const generateMarkdownForIssue = async (issue: any): Promise<string> => {
const comments = await fetchIssueComments(issue.number);
let md = `# Issue #${issue.number}: ${issue.title}\n\n`;
md += `- **Author:** ${issue.user.login}\n`;
md += `- **State:** ${issue.state}\n`;
md += `- **Created on:** ${new Date(issue.created_at).toDateString()}\n`;
md += `- **Updated on:** ${new Date(issue.updated_at).toDateString()}\n`;
md += `- **Labels:** ${issue.labels.map((l: any) => `\`${l.name}\``).join(', ') || 'None'}\n\n`;
md += `## Description\n\n${issue.body || '_No description._'}\n\n## Comments\n\n`;
if (comments.length === 0) {
md += '_No comments._\n';
} else {
for (const c of comments) {
md += `### ${c.user.login} - ${new Date(c.created_at).toDateString()}\n\n${c.body}\n\n---\n\n`;
}
}
return md;
};
// Process a single issue and store its chunks
const processIssue = async (issue: any): Promise<void> => {
const issueNumber = issue.number;
const url = `https://github.com/${repo}/issues/${issueNumber}`;
logger.info(`Processing issue #${issueNumber}`);
// Generate markdown for the issue
const markdown = await generateMarkdownForIssue(issue);
// Chunk the markdown content
const issueConfig = {
...sourceConfig,
product_name: sourceConfig.product_name || repo,
max_size: sourceConfig.max_size || Infinity
};
const chunks = await this.contentProcessor.chunkMarkdown(markdown, issueConfig, url);
logger.info(`Issue #${issueNumber}: Created ${chunks.length} chunks`);
// Process and store each chunk immediately
for (const chunk of chunks) {
const chunkHash = Utils.generateHash(chunk.content);
const chunkId = chunk.metadata.chunk_id.substring(0, 8) + '...';
if (dbConnection.type === 'sqlite') {
const { checkHashStmt } = DatabaseManager.prepareSQLiteStatements(dbConnection.db);
const existing = checkHashStmt.get(chunk.metadata.chunk_id) as { hash: string } | undefined;
if (existing && existing.hash === chunkHash) {
logger.info(`Skipping unchanged chunk: ${chunkId}`);
continue;
}
const embeddings = await this.createEmbeddings([chunk.content]);
if (embeddings.length) {
DatabaseManager.insertVectorsSQLite(dbConnection.db, chunk, embeddings[0], logger, chunkHash);
logger.debug(`Stored chunk ${chunkId} in SQLite`);
} else {
logger.error(`Embedding failed for chunk: ${chunkId}`);
}
} else if (dbConnection.type === 'qdrant') {
try {
let pointId: string;
try {
pointId = chunk.metadata.chunk_id;
if (!Utils.isValidUuid(pointId)) {
pointId = Utils.hashToUuid(chunk.metadata.chunk_id);
}
} catch (e) {
pointId = crypto.randomUUID();
}
const existingPoints = await dbConnection.client.retrieve(dbConnection.collectionName, {
ids: [pointId],
with_payload: true,
with_vector: false,
});
if (existingPoints.length > 0 && existingPoints[0].payload && existingPoints[0].payload.hash === chunkHash) {
logger.info(`Skipping unchanged chunk: ${chunkId}`);
continue;
}
const embeddings = await this.createEmbeddings([chunk.content]);
if (embeddings.length) {
await DatabaseManager.storeChunkInQdrant(dbConnection, chunk, embeddings[0], chunkHash);
logger.debug(`Stored chunk ${chunkId} in Qdrant (${dbConnection.collectionName})`);
} else {
logger.error(`Embedding failed for chunk: ${chunkId}`);
}
} catch (error) {
logger.error(`Error processing chunk in Qdrant:`, error);
}
}
}
};
logger.info(`Fetching GitHub issues for ${repo} since ${lastRunDate}`);
const issues = await fetchAllIssues(lastRunDate);
logger.info(`Found ${issues.length} updated/new issues`);
// Process each issue individually, one at a time
for (let i = 0; i < issues.length; i++) {
logger.info(`Processing issue ${i + 1}/${issues.length}`);
await processIssue(issues[i]);
}
// Update the last run date in the database after processing all issues
await DatabaseManager.updateLastRunDate(dbConnection, repo, logger, this.embeddingDimension);
logger.info(`Successfully processed ${issues.length} issues`);
}
private async processGithubRepo(config: GithubSourceConfig, parentLogger: Logger): Promise<void> {
const logger = parentLogger.child('process');
logger.info(`Starting processing for GitHub repo: ${config.repo}`);
const dbConnection = await DatabaseManager.initDatabase(config, logger, this.embeddingDimension);
// Initialize metadata storage
await DatabaseManager.initDatabaseMetadata(dbConnection, logger);
logger.section('GITHUB ISSUES');
// Process GitHub issues
await this.fetchAndProcessGitHubIssues(config.repo, config, dbConnection, logger);
logger.info(`Finished processing GitHub repo: ${config.repo}`);
}
private async processWebsite(config: WebsiteSourceConfig, parentLogger: Logger): Promise<void> {
const logger = parentLogger.child('process');
logger.info(`Starting processing for website: ${config.url}`);
const dbConnection = await DatabaseManager.initDatabase(config, logger, this.embeddingDimension);
await DatabaseManager.initDatabaseMetadata(dbConnection, logger);
const validChunkIds: Set<string> = new Set();
const visitedUrls: Set<string> = new Set();
const urlPrefix = Utils.getUrlPrefix(config.url);
logger.section('CRAWL AND EMBEDDING');
// Pre-load known URLs from the database so the queue includes pages from
// previous runs. This ensures link discovery isn't lost when pages are
// skipped via ETag matching.
let knownUrls: Set<string> | undefined;
if (dbConnection.type === 'sqlite') {
const urls = DatabaseManager.getStoredUrlsByPrefixSQLite(dbConnection.db, urlPrefix);
if (urls.length > 0) {
knownUrls = new Set(urls);
logger.info(`Found ${urls.length} known URLs in database for pre-seeding`);
}
} else if (dbConnection.type === 'qdrant') {
const urls = await DatabaseManager.getStoredUrlsByPrefixQdrant(dbConnection, urlPrefix);
if (urls.length > 0) {
knownUrls = new Set(urls);
logger.info(`Found ${urls.length} known URLs in Qdrant for pre-seeding`);
}
}
// ETag store for caching page ETags across runs
const etagStore = {
get: async (url: string): Promise<string | undefined> => {
return DatabaseManager.getMetadataValue(dbConnection, `etag:${url}`, undefined, logger);
},
set: async (url: string, etag: string): Promise<void> => {
await DatabaseManager.setMetadataValue(dbConnection, `etag:${url}`, etag, logger, this.embeddingDimension);
},
};
const lastmodStore = {
get: async (url: string): Promise<string | undefined> => {
return DatabaseManager.getMetadataValue(dbConnection, `lastmod:${url}`, undefined, logger);
},
set: async (url: string, lastmod: string): Promise<void> => {
await DatabaseManager.setMetadataValue(dbConnection, `lastmod:${url}`, lastmod, logger, this.embeddingDimension);
},
};
// If Postgres markdown store is enabled for this source, load URLs that
// already have markdown stored. URLs NOT in this set will bypass
// lastmod/ETag skip logic so that the store is fully populated on the
// first sync.
const useMarkdownStore = config.markdown_store === true && this.markdownStore != null;
let markdownStoreUrls: Set<string> | undefined;
if (useMarkdownStore) {
markdownStoreUrls = await this.markdownStore!.getUrlsWithMarkdown(urlPrefix);
logger.info(`Markdown store: ${markdownStoreUrls.size} URLs already stored for prefix ${urlPrefix}`);
}
// Check whether a full sync has ever completed successfully for this
// source. If not, bypass all lastmod/ETag skip logic so that every
// page is processed at least once. This handles the case where a
// previous sync was interrupted (killed mid-crawl) — the stored
// ETags/lastmods from the partial run would otherwise cause the
// remaining pages to be skipped indefinitely.
const syncCompleteKey = `sync_complete:${urlPrefix}`;
const syncCompleteValue = await DatabaseManager.getMetadataValue(dbConnection, syncCompleteKey, undefined, logger);
const forceFullSync = syncCompleteValue !== 'true';
if (forceFullSync) {
logger.info('Full sync has not yet completed for this source — forcing processing of all pages (bypassing lastmod/ETag skip)');
}
const crawlResult = await this.contentProcessor.crawlWebsite(config.url, config, async (url, content) => {
visitedUrls.add(url);
logger.info(`Processing content from ${url} (${content.length} chars markdown)`);
try {
const chunks = await this.contentProcessor.chunkMarkdown(content, config, url);
logger.info(`Created ${chunks.length} chunks`);
for (const chunk of chunks) {
validChunkIds.add(chunk.metadata.chunk_id);
}
await this.processChunksForUrl(chunks, url, dbConnection, logger);
// Store the generated markdown in Postgres
if (useMarkdownStore) {
try {
await this.markdownStore!.upsertMarkdown(url, config.product_name, content);
} catch (pgError) {
logger.error(`Failed to store markdown in Postgres for ${url}:`, pgError);
}
}
return true;
} catch (error) {
logger.error(`Error during chunking or embedding for ${url}:`, error);
return false;
}
}, logger, visitedUrls, { knownUrls, etagStore, lastmodStore, markdownStoreUrls, forceFullSync });
this.recordBrokenLinks(config.url, crawlResult.brokenLinks);
this.writeBrokenLinksReport();
logger.info(`Found ${validChunkIds.size} valid chunks across processed pages for ${config.url}`);
logger.section('CLEANUP');
// Remove 404 URLs from the Postgres markdown store
if (useMarkdownStore && crawlResult.notFoundUrls && crawlResult.notFoundUrls.size > 0) {
logger.info(`Removing ${crawlResult.notFoundUrls.size} not-found URLs from markdown store`);
for (const url of crawlResult.notFoundUrls) {
try {
await this.markdownStore!.deleteMarkdown(url);
} catch (pgError) {
logger.error(`Failed to delete markdown from Postgres for ${url}:`, pgError);
}
}
}
if (crawlResult.hasNetworkErrors) {
logger.warn('Skipping cleanup due to network errors encountered during crawling. This prevents removal of valid chunks when the site is temporarily unreachable.');
} else {
// Mark this source as having completed a full sync. On subsequent
// runs, lastmod/ETag skip logic will function normally. If the
// process is killed before reaching this point, the flag stays
// unset and the next run will force-process all pages again.
if (forceFullSync) {
await DatabaseManager.setMetadataValue(dbConnection, syncCompleteKey, 'true', logger, this.embeddingDimension);
logger.info('Full sync completed successfully — subsequent runs will use normal caching');
}
if (dbConnection.type === 'sqlite') {
logger.info(`Running SQLite cleanup for ${urlPrefix}`);
DatabaseManager.removeObsoleteChunksSQLite(dbConnection.db, visitedUrls, urlPrefix, logger);
} else if (dbConnection.type === 'qdrant') {
logger.info(`Running Qdrant cleanup for ${urlPrefix} in collection ${dbConnection.collectionName}`);
await DatabaseManager.removeObsoleteChunksQdrant(dbConnection, visitedUrls, urlPrefix, logger);
}
}
logger.info(`Finished processing website: ${config.url}`);
}
private recordBrokenLinks(baseUrl: string, brokenLinks: BrokenLink[]): void {
const uniqueByKey = new Map<string, BrokenLink>();
for (const link of brokenLinks) {
const key = `${link.source} -> ${link.target}`;
if (!uniqueByKey.has(key)) {
uniqueByKey.set(key, link);
}
}
const unique = Array.from(uniqueByKey.values()).sort((a, b) => {
const sourceCompare = a.source.localeCompare(b.source);
if (sourceCompare !== 0) return sourceCompare;
return a.target.localeCompare(b.target);
});
this.brokenLinksByWebsite[baseUrl] = unique;
}
private writeBrokenLinksReport(): void {
const reportPath = path.join(this.configDir, '404.yaml');
const orderedEntries = Object.entries(this.brokenLinksByWebsite)
.sort(([a], [b]) => a.localeCompare(b));
const reportPayload = orderedEntries.map(([website, links]) => ({
website,
'broken-links': links
}));
try {
fs.writeFileSync(reportPath, yaml.dump(reportPayload, { noRefs: true }), 'utf8');
this.logger.info(`Wrote broken link report to ${reportPath}`);
} catch (error) {
this.logger.error(`Failed to write broken link report to ${reportPath}:`, error);
}
}
private async processLocalDirectory(config: LocalDirectorySourceConfig, parentLogger: Logger): Promise<void> {
const logger = parentLogger.child('process');
logger.info(`Starting processing for local directory: ${config.path}`);
const dbConnection = await DatabaseManager.initDatabase(config, logger, this.embeddingDimension);
const validChunkIds: Set<string> = new Set();
const processedFiles: Set<string> = new Set();
logger.section('FILE SCANNING AND EMBEDDING');
await this.contentProcessor.processDirectory(
config.path,
config,
async (filePath, content) => {
processedFiles.add(filePath);
logger.info(`Processing content from ${filePath} (${content.length} chars)`);
try {
// Generate URL based on configuration
let fileUrl: string;
if (config.url_rewrite_prefix) {
// Replace local path with URL prefix
const relativePath = path.relative(config.path, filePath).replace(/\\/g, '/');
// If relativePath starts with '..', it means the file is outside the base directory
if (relativePath.startsWith('..')) {
// For files outside the configured path, use the default file:// scheme
fileUrl = `file://${filePath}`;
logger.debug(`File outside configured path, using default URL: ${fileUrl}`);
} else {
// For files inside the configured path, rewrite the URL
// Handle trailing slashes in the URL prefix to avoid double slashes
const prefix = config.url_rewrite_prefix.endsWith('/')
? config.url_rewrite_prefix.slice(0, -1)
: config.url_rewrite_prefix;
fileUrl = `${prefix}/${relativePath}`;
logger.debug(`URL rewritten: ${filePath} -> ${fileUrl}`);
}
} else {
// Use default file:// URL
fileUrl = `file://${filePath}`;
}
const chunks = await this.contentProcessor.chunkMarkdown(content, config, fileUrl);
logger.info(`Created ${chunks.length} chunks`);
for (const chunk of chunks) {
validChunkIds.add(chunk.metadata.chunk_id);
}
await this.processChunksForUrl(chunks, fileUrl, dbConnection, logger);
} catch (error) {
logger.error(`Error during chunking or embedding for ${filePath}:`, error);
}
},
logger
);
logger.section('CLEANUP');
if (dbConnection.type === 'sqlite') {
logger.info(`Running SQLite cleanup for local directory ${config.path}`);
DatabaseManager.removeObsoleteFilesSQLite(dbConnection.db, processedFiles, config, logger);
} else if (dbConnection.type === 'qdrant') {
logger.info(`Running Qdrant cleanup for local directory ${config.path} in collection ${dbConnection.collectionName}`);
await DatabaseManager.removeObsoleteFilesQdrant(dbConnection, processedFiles, config, logger);
}
logger.info(`Finished processing local directory: ${config.path}`);
}
private async processCodeSource(config: CodeSourceConfig, parentLogger: Logger): Promise<void> {
const logger = parentLogger.child('process');
logger.info(`Starting processing for code source (${config.source})`);
const dbConnection = await DatabaseManager.initDatabase(config, logger, this.embeddingDimension);
const validChunkIds: Set<string> = new Set();
const processedFiles: Set<string> = new Set();
let basePath: string | undefined;
let cleanupPathConfig: { path: string; url_rewrite_prefix?: string } | string;
let tempDir: string | null = null;
let repoUrlPrefix: string | undefined;
let repoBranch: string | undefined;
let incrementalMode = false;
let deleteUrls: string[] = [];
let allowedFiles: Set<string> | undefined;
let mtimeCutoff: number | undefined;
let fileListKey: string | undefined;
let lastMtimeKey: string | undefined;
let trackedFiles: Set<string> | undefined;
let maxObservedMtime = 0;
if (config.source === 'local_directory') {
if (!config.path) {
logger.error('Code source type local_directory requires a path.');
return;
}
basePath = config.path;
cleanupPathConfig = config.url_rewrite_prefix
? { path: basePath, url_rewrite_prefix: config.url_rewrite_prefix }
: basePath;
const resolvedPath = path.resolve(basePath);
const pathKey = resolvedPath.replace(/[^a-zA-Z0-9]+/g, '_');
lastMtimeKey = `code_last_mtime_${pathKey}`;
fileListKey = `code_filelist_${pathKey}`;
await DatabaseManager.initDatabaseMetadata(dbConnection, logger);
const lastMtimeValue = await DatabaseManager.getMetadataValue(dbConnection, lastMtimeKey, '0', logger);
mtimeCutoff = lastMtimeValue ? parseFloat(lastMtimeValue) : 0;
trackedFiles = new Set<string>();
incrementalMode = true;
} else if (config.source === 'github') {
if (!config.repo) {
logger.error('Code source type github requires a repo in owner/repo format.');
return;
}
const cloneResult = await this.cloneGithubRepo(config, logger);
basePath = cloneResult.path;
tempDir = cloneResult.path;
repoUrlPrefix = cloneResult.urlPrefix;
repoBranch = cloneResult.branch;
cleanupPathConfig = { path: basePath, url_rewrite_prefix: repoUrlPrefix };
await DatabaseManager.initDatabaseMetadata(dbConnection, logger);
const shaKey = this.buildCodeShaMetadataKey(config.repo, repoBranch);
const lastSha = await DatabaseManager.getMetadataValue(dbConnection, shaKey, undefined, logger);
const headSha = await this.getRepoHeadSha(basePath, logger);
if (lastSha && headSha) {
if (headSha === lastSha) {
incrementalMode = true;
allowedFiles = new Set();
deleteUrls = [];
} else {
const diffResult = await this.getGitChangedFiles(basePath, lastSha, repoBranch, logger);
if (diffResult.mode === 'incremental') {
incrementalMode = true;
allowedFiles = diffResult.changedFiles;
deleteUrls = diffResult.deletedPaths
.map((relativePath) => this.buildCodeFileUrl(path.join(basePath as string, relativePath), basePath as string, config, repoUrlPrefix));
} else {
logger.warn('Falling back to full scan for GitHub code source.');
}
}
}
} else {
logger.error(`Unknown code source: ${config.source}`);
return;
}
logger.section('CODE SCANNING AND EMBEDDING');
try {
const scanResult = await this.contentProcessor.processCodeDirectory(
basePath,
config,
async (filePath, content) => {
processedFiles.add(filePath);
const relativePath = path.relative(basePath as string, filePath).replace(/\\/g, '/');
const fileUrl = this.buildCodeFileUrl(filePath, basePath as string, config, repoUrlPrefix);
logger.info(`Processing code from ${relativePath || filePath} (${content.length} chars)`);
try {
const chunks = await this.contentProcessor.chunkCode(
content,
config,
fileUrl,
relativePath || filePath,
repoBranch || config.branch,
config.repo
);
logger.info(`Created ${chunks.length} chunks`);
for (const chunk of chunks) {
validChunkIds.add(chunk.metadata.chunk_id);
}
await this.processChunksForUrl(chunks, fileUrl, dbConnection, logger);
} catch (error) {
logger.error(`Error during code chunking or embedding for ${filePath}:`, error);
}
},
logger,
undefined,
{
allowedFiles,
mtimeCutoff,
trackFiles: trackedFiles
}
);
if (trackedFiles) {
maxObservedMtime = scanResult.maxMtime;
}
} finally {
logger.section('CLEANUP');
if (incrementalMode) {
if (deleteUrls.length > 0) {
logger.info(`Cleaning up ${deleteUrls.length} deleted/renamed files`);
for (const url of deleteUrls) {
if (dbConnection.type === 'sqlite') {
DatabaseManager.removeChunksByUrlSQLite(dbConnection.db, url, logger);
} else if (dbConnection.type === 'qdrant') {
await DatabaseManager.removeChunksByUrlQdrant(dbConnection, url, logger);
}
}
} else {
logger.info('No deleted/renamed files to clean up.');
}
if (trackedFiles && fileListKey) {
const previousListValue = await DatabaseManager.getMetadataValue(dbConnection, fileListKey, '[]', logger);
const previousList = previousListValue ? JSON.parse(previousListValue) as string[] : [];
const currentList = Array.from(trackedFiles);
const deletedFiles = previousList.filter((filePath) => !trackedFiles?.has(filePath));
for (const deletedFile of deletedFiles) {
const url = this.buildCodeFileUrl(deletedFile, basePath as string, config, repoUrlPrefix);
if (dbConnection.type === 'sqlite') {
DatabaseManager.removeChunksByUrlSQLite(dbConnection.db, url, logger);
} else if (dbConnection.type === 'qdrant') {
await DatabaseManager.removeChunksByUrlQdrant(dbConnection, url, logger);
}
}
await DatabaseManager.setMetadataValue(dbConnection, fileListKey, JSON.stringify(currentList), logger, this.embeddingDimension);
if (lastMtimeKey) {
const nextMtime = maxObservedMtime > 0 ? maxObservedMtime : Date.now();
await DatabaseManager.setMetadataValue(dbConnection, lastMtimeKey, `${nextMtime}`, logger, this.embeddingDimension);
}
}
} else {
if (dbConnection.type === 'sqlite') {
logger.info(`Running SQLite cleanup for code source ${basePath}`);
DatabaseManager.removeObsoleteFilesSQLite(dbConnection.db, processedFiles, cleanupPathConfig, logger);
} else if (dbConnection.type === 'qdrant') {
logger.info(`Running Qdrant cleanup for code source ${basePath} in collection ${dbConnection.collectionName}`);
await DatabaseManager.removeObsoleteFilesQdrant(dbConnection, processedFiles, cleanupPathConfig, logger);
}
}
if (config.source === 'github' && basePath && repoBranch) {
const headSha = await this.getRepoHeadSha(basePath, logger);
if (headSha) {
const shaKey = this.buildCodeShaMetadataKey(config.repo as string, repoBranch);
await DatabaseManager.setMetadataValue(dbConnection, shaKey, headSha, logger, this.embeddingDimension);
}
}
if (tempDir) {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
logger.debug(`Removed temporary repo at ${tempDir}`);
} catch (error) {
logger.warn(`Failed to remove temporary repo at ${tempDir}:`, error);
}
}
}
logger.info(`Finished processing code source (${config.source})`);
}
private buildCodeShaMetadataKey(repo: string, branch: string): string {
const normalizedRepo = repo.replace(/[^a-zA-Z0-9]+/g, '_');
const normalizedBranch = branch.replace(/[^a-zA-Z0-9]+/g, '_');
return `code_last_sha_${normalizedRepo}_${normalizedBranch}`;
}
private async getRepoHeadSha(repoPath: string, logger: Logger): Promise<string | undefined> {
try {
const { stdout } = await execAsync(`git -C "${repoPath}" rev-parse HEAD`);
return stdout.trim() || undefined;
} catch (error) {
logger.warn(`Failed to resolve HEAD sha for ${repoPath}:`, error);
return undefined;
}
}
private async getGitChangedFiles(
repoPath: string,
lastSha: string,
branch: string,
logger: Logger
): Promise<{ mode: 'incremental' | 'full'; changedFiles: Set<string>; deletedPaths: string[] }> {
const diffCommand = `git -C "${repoPath}" diff --name-status ${lastSha}..HEAD`;
const attemptDiff = async () => {
const { stdout } = await execAsync(diffCommand);
return stdout;
};
let diffOutput: string | undefined;
try {
diffOutput = await attemptDiff();
} catch (error) {
logger.warn(`Failed to diff against ${lastSha}. Fetching more history...`);
const fetchDepths = [200, 1000, 5000];
let fetched = false;
for (const depth of fetchDepths) {
try {
logger.info(`Fetching with --depth=${depth}...`);
await execAsync(`git -C "${repoPath}" fetch --depth=${depth} origin "${branch}"`);
diffOutput = await attemptDiff();
fetched = true;
break;
} catch (fetchError) {
logger.warn(`Diff still failed at --depth=${depth}.`);
}
}
if (!fetched) {
try {
logger.info(`Attempting full unshallow fetch...`);
await execAsync(`git -C "${repoPath}" fetch --unshallow origin "${branch}"`);
diffOutput = await attemptDiff();
} catch (unshallowError) {
logger.warn(`Failed to diff even after full unshallow. Falling back to full scan.`, unshallowError);
return { mode: 'full', changedFiles: new Set(), deletedPaths: [] };
}
}
}
if (!diffOutput) {
logger.warn('No diff output available. Falling back to full scan.');
return { mode: 'full', changedFiles: new Set(), deletedPaths: [] };
}
const changedFiles = new Set<string>();
const deletedPaths: string[] = [];
for (const line of diffOutput.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
const parts = trimmed.split('\t');
const status = parts[0];
if (status.startsWith('R')) {
const oldPath = parts[1];
const newPath = parts[2];
if (oldPath) deletedPaths.push(oldPath);
if (newPath) changedFiles.add(path.join(repoPath, newPath));
} else if (status === 'D') {
const deletedPath = parts[1];
if (deletedPath) deletedPaths.push(deletedPath);
} else if (status === 'A' || status === 'M') {
const changedPath = parts[1];
if (changedPath) changedFiles.add(path.join(repoPath, changedPath));
}
}
logger.info(`Git diff changes: ${changedFiles.size} modified/added, ${deletedPaths.length} deleted/renamed.`);
return { mode: 'incremental', changedFiles, deletedPaths };
}
private buildCodeFileUrl(
filePath: string,
basePath: string,
config: CodeSourceConfig,
repoUrlPrefix?: string
): string {
const relativePath = path.relative(basePath, filePath).replace(/\\/g, '/');
if (repoUrlPrefix) {
return `${repoUrlPrefix}/${relativePath}`;