Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1936 lines (1725 loc) · 67.3 KB
/
Copy pathbackground.js
File metadata and controls
1936 lines (1725 loc) · 67.3 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
// PrepPush - background.js (Milestone 4)
// Handles: LLM analysis, submission storage, GitHub push
console.log('[PrepPush] Background service worker started ✅');
const DEFAULT_GITHUB_REPO = 'hackerrank-solutions';
const HACKERRANK_TAB_URL = ['https://www.hackerrank.com/*'];
const CONTENT_SCRIPT_ID = 'preppush-content';
async function registerPrepPushContentScripts() {
try {
const existing = await chrome.scripting.getRegisteredContentScripts();
const current = existing?.find((s) => s.id === CONTENT_SCRIPT_ID);
if (
current &&
current.matches?.includes('https://www.hackerrank.com/*') &&
current.runAt === 'document_start' &&
current.allFrames === true
) {
return;
}
if (current) {
await chrome.scripting.unregisterContentScripts({ ids: [CONTENT_SCRIPT_ID] });
}
} catch (e) {
console.warn('[PrepPush] unregister content scripts:', e?.message || e);
}
await chrome.scripting.registerContentScripts([
{
id: CONTENT_SCRIPT_ID,
js: ['content.js'],
matches: HACKERRANK_TAB_URL,
runAt: 'document_start',
allFrames: true,
},
]);
}
async function tabHasContentScript(tabId) {
try {
const res = await chrome.tabs.sendMessage(tabId, { type: 'PING' });
return res?.status === 'alive';
} catch {
return false;
}
}
async function probeContentScriptInit(tabId) {
try {
const results = await chrome.scripting.executeScript({
target: { tabId, allFrames: true },
func: () => ({
hasInit: !!globalThis.__preppushContentInit,
hasListener: !!globalThis.__preppushRuntimeListener,
}),
});
return results?.some((r) => r.result?.hasInit || r.result?.hasListener) ?? false;
} catch {
return false;
}
}
async function injectContentScript(tabId) {
try {
await chrome.scripting.executeScript({
target: { tabId, allFrames: true },
files: ['content.js'],
});
return true;
} catch (e) {
const msg = e?.message || String(e);
if (/duplicate|already been injected|Cannot access/i.test(msg)) {
return false;
}
throw e;
}
}
/** Inject poll observer into all frames (fullscreen editor polls from iframes). */
async function injectPageInterceptor(tabId) {
await chrome.scripting.executeScript({
target: { tabId, allFrames: true },
world: 'MAIN',
files: ['interceptor.js'],
});
}
async function injectPageInterceptorFallback(tabId) {
await injectPageInterceptor(tabId);
}
async function ensurePageInterceptor(tabId) {
try {
await injectPageInterceptor(tabId);
return { ok: true, method: 'file' };
} catch (e) {
console.warn('[PrepPush] interceptor.js inject failed, using fallback:', e?.message);
try {
await injectPageInterceptorFallback(tabId);
return { ok: true, method: 'fallback' };
} catch (e2) {
return { ok: false, error: e2?.message || String(e2) };
}
}
}
async function wakeContentScript(tabId) {
try {
await chrome.tabs.sendMessage(tabId, { type: 'PREPPUSH_CONNECT' });
return true;
} catch {
return false;
}
}
/** Inject into HackerRank tabs (recovers stale tabs after extension reload). */
async function ensurePrepPushOnHackerRankTabs(onlyTabId = null) {
let injected = 0;
let connected = 0;
const tabs = onlyTabId != null
? [await chrome.tabs.get(onlyTabId).catch(() => null)].filter(Boolean)
: await chrome.tabs.query({ url: HACKERRANK_TAB_URL });
for (const tab of tabs) {
if (!tab?.id || !tab.url?.includes('hackerrank.com')) continue;
try {
// Prefer reconnect message + registered content script; only inject as last resort.
let alive = await tabHasContentScript(tab.id);
if (!alive) {
await wakeContentScript(tab.id);
await new Promise((r) => setTimeout(r, 150));
alive = await tabHasContentScript(tab.id);
}
if (!alive) {
const alreadyInit = await probeContentScriptInit(tab.id);
if (!alreadyInit) {
if (await injectContentScript(tab.id)) {
injected += 1;
console.log('[PrepPush] Injected content script into tab', tab.id);
}
await new Promise((r) => setTimeout(r, 250));
alive = await tabHasContentScript(tab.id);
}
}
await ensurePageInterceptor(tab.id);
if (await wakeContentScript(tab.id)) {
connected += 1;
continue;
}
// If connect failed but content script is already initialized, do NOT reinject.
const alreadyInit = alive || (await probeContentScriptInit(tab.id));
if (!alreadyInit && (await injectContentScript(tab.id))) {
injected += 1;
await new Promise((r) => setTimeout(r, 250));
}
if (await wakeContentScript(tab.id)) connected += 1;
} catch (e) {
console.warn('[PrepPush] Could not connect tab', tab.id, e?.message || e);
}
}
return { ok: true, injected, connected };
}
function scheduleHeartbeat() {
try {
chrome.alarms.create('preppush-heartbeat', { periodInMinutes: 1 });
} catch (e) {
console.warn('[PrepPush] alarms not available:', e?.message || e);
}
}
function onExtensionReady() {
scheduleHeartbeat();
registerPrepPushContentScripts()
.then(() => ensurePrepPushOnHackerRankTabs())
.catch((e) => console.warn('[PrepPush] Startup setup failed:', e?.message || e));
}
chrome.runtime.onInstalled.addListener(onExtensionReady);
chrome.runtime.onStartup.addListener(onExtensionReady);
onExtensionReady();
chrome.alarms?.onAlarm.addListener((alarm) => {
if (alarm.name === 'preppush-heartbeat') {
/* keep service worker reachable */
}
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status !== 'complete') return;
if (!tab?.url?.includes('hackerrank.com')) return;
ensurePrepPushOnHackerRankTabs(tabId).catch((e) =>
console.warn('[PrepPush] Tab injection failed:', e?.message || e)
);
});
// ─── LANGUAGE → FILE EXTENSION MAP ──────────────────────────────────────────
const EXTENSIONS = {
python3: 'py', python: 'py',
java: 'java', java8: 'java', java15: 'java',
javascript: 'js', javascript16: 'js', javascript20: 'js', node: 'js',
typescript: 'ts',
cpp: 'cpp', cpp14: 'cpp', cpp17: 'cpp', cpp20: 'cpp',
c: 'c',
csharp: 'cs',
ruby: 'rb',
swift: 'swift',
kotlin: 'kt',
go: 'go',
scala: 'scala',
rust: 'rs',
php: 'php',
r: 'r',
haskell: 'hs',
perl: 'pl',
bash: 'sh',
sql: 'sql',
db2: 'sql',
mysql: 'sql',
mariadb: 'sql',
oracle: 'sql',
postgresql: 'sql',
postgres: 'sql',
mssql: 'sql',
sqlite: 'sql',
plsql: 'sql',
};
function normalizeHrLanguage(raw) {
const t = String(raw || '')
.toLowerCase()
.trim()
.replace(/_/g, '-');
if (!t) return '';
if (EXTENSIONS[t]) return t;
const base = t.replace(/-v?\d+(\.\d+)*$/, '').replace(/-\d+$/, '');
if (EXTENSIONS[base]) return base;
if (/^(db2|mysql|oracle|postgresql|postgres|mssql|sqlite|mariadb|plsql|sql)/.test(base)) {
return base === 'postgres' ? 'postgresql' : base;
}
return t;
}
function looksLikeSql(code) {
const t = String(code || '').trim();
if (!t) return false;
if (/^\s*\/\*[\s\S]*?\*\/\s*(select|insert|update|delete|with)\b/i.test(t)) return true;
return /\b(select|insert|update|delete|with)\b[\s\S]*\b(from|into|set|values)\b/i.test(t);
}
function inferLanguage(submission) {
const raw = normalizeHrLanguage(submission?.language);
if (raw && EXTENSIONS[raw]) return raw;
const code = submission?.code || '';
if (looksLikeSql(code)) return raw && /^(db2|mysql|oracle|postgresql|mssql|sqlite|mariadb|plsql|sql)/.test(raw) ? raw : 'sql';
// Trust HackerRank's language slug when present (avoid mislabeling SQL/DB2 as Python).
if (raw) return raw;
if (/if\s+__name__/m.test(code) || /\binput\s*\(/m.test(code)) return 'python3';
if (/\bdef\s+\w+/m.test(code)) return 'python3';
if (/\bpublic\s+class\b/m.test(code)) return 'java';
if (/\b#include\s*</m.test(code)) return 'cpp';
if (/\bfunction\s+\w+/m.test(code) && /\bconst\s+/m.test(code)) return 'javascript';
if (/\bfn\s+\w+/m.test(code)) return 'rust';
return 'unknown';
}
function fileExtensionForLanguage(language, code = '') {
const lang = normalizeHrLanguage(language);
if (lang && EXTENSIONS[lang]) return EXTENSIONS[lang];
if (looksLikeSql(code)) return 'sql';
return 'txt';
}
// ─── LANGUAGE → COMMENT STYLE ────────────────────────────────────────────────
const COMMENT_STYLE = {
py: '#', js: '//', ts: '//', java: '//', cpp: '//', c: '//',
cs: '//', rb: '#', swift: '//', kt: '//', go: '//', scala: '//',
rs: '//', php: '//', r: '#', hs: '--', pl: '#', sh: '#', sql: '--',
};
// ─── PATH + SLUG HELPERS ─────────────────────────────────────────────────────
function slugify(text) {
if (!text || typeof text !== 'string') return '';
return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
// Interview-prep layout: language → difficulty → problem → solution-approachN per distinct code
const APPROACH_REGISTRY_KEY = 'approachRegistry';
function buildProblemDir(submission) {
const lang = slugify(submission.language) || 'unknown';
const difficulty = slugify(submission.difficulty) || 'uncategorized';
const slug = slugify(submission.problemSlug) || slugify(submission.problemName) || 'unknown';
return `solutions/${lang}/${difficulty}/${slug}`;
}
// Legacy normalizer (pre-0.6.3) — kept so existing approach registry entries still match.
function normalizeCodeLegacy(code) {
return String(code || '')
.replace(/\r\n/g, '\n')
.replace(/[ \t]+/g, ' ')
.trim();
}
// Compare from first `def` onward — ignores HackerRank boilerplate/import drift.
function extractCoreLines(code) {
const lines = String(code || '').replace(/\r\n/g, '\n').split('\n');
const defIdx = lines.findIndex((line) => /^\s*def \w+/.test(line));
return defIdx >= 0 ? lines.slice(defIdx) : lines;
}
// Ignores blank lines, comment-only lines, and spacing so formatting-only edits reuse approachN.
function normalizeCode(code) {
return extractCoreLines(code)
.map((line) => line.replace(/[ \t]+/g, ' ').trim())
.filter((line) => {
if (!line.length) return false;
if (line.startsWith('#')) return false;
return true;
})
.join('\n');
}
async function hashNormalized(normalized) {
if (!normalized) return null;
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(normalized));
return Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
async function hashCode(code) {
return hashNormalized(normalizeCode(code));
}
// Whitespace-stripped core — same algorithm with different blanks/comments → same fingerprint.
function codeFingerprint(code) {
return normalizeCode(code).replace(/\s+/g, '');
}
async function loadApproachRegistry() {
const local = await chrome.storage.local.get(APPROACH_REGISTRY_KEY);
if (local[APPROACH_REGISTRY_KEY]) return local[APPROACH_REGISTRY_KEY];
const sync = await chrome.storage.sync.get(APPROACH_REGISTRY_KEY);
if (sync[APPROACH_REGISTRY_KEY]) {
await chrome.storage.local.set({ [APPROACH_REGISTRY_KEY]: sync[APPROACH_REGISTRY_KEY] });
return sync[APPROACH_REGISTRY_KEY];
}
return {};
}
async function saveApproachRegistry(registry) {
await chrome.storage.local.set({ [APPROACH_REGISTRY_KEY]: registry });
}
function approachMatchesFingerprint(a, fingerprint, fpHash, norm, normHash, legacyHash, legacyCoreHash) {
if (fpHash && a.fpHash === fpHash) return true;
if (normHash && a.normHash === normHash) return true;
if (norm && a.norm === norm) return true;
if (a.lastNorm && codeFingerprint(a.lastNorm) === fingerprint) return true;
if (a.codeHash === normHash || a.codeHash === fpHash) return true;
if (legacyHash && a.codeHash === legacyHash) return true;
if (legacyCoreHash && a.codeHash === legacyCoreHash) return true;
return false;
}
function consolidateProblemApproaches(problem, matchId, fpHash, fingerprint) {
problem.byFp = problem.byFp || {};
problem.byFp[fpHash] = matchId;
problem.approaches = problem.approaches.filter((a) => {
if (a.id === matchId) return true;
if (a.fpHash === fpHash) return false;
if (a.lastNorm && codeFingerprint(a.lastNorm) === fingerprint) return false;
return true;
});
}
// Maps solution core → approach1, approach2, … (same logic = same number, even if formatting differs).
async function resolveApproachKey(submission) {
const problemKey = buildProblemDir(submission);
const norm = normalizeCode(submission.code);
const fingerprint = codeFingerprint(submission.code);
const normHash = await hashNormalized(norm);
const fpHash = await hashNormalized(fingerprint);
if (!fpHash) return 'approach1';
const registry = await loadApproachRegistry();
const problem = registry[problemKey] || { approaches: [], byFp: {} };
problem.byFp = problem.byFp || {};
const legacyHash = await hashNormalized(normalizeCodeLegacy(submission.code));
const legacyCoreHash = await hashNormalized(normalizeCodeLegacy(extractCoreLines(submission.code).join('\n')));
let match = null;
if (problem.byFp[fpHash] != null) {
match = problem.approaches.find((a) => a.id === problem.byFp[fpHash]) || { id: problem.byFp[fpHash] };
}
if (!match) {
const candidates = problem.approaches.filter((a) =>
approachMatchesFingerprint(a, fingerprint, fpHash, norm, normHash, legacyHash, legacyCoreHash),
);
if (candidates.length) {
match = candidates.reduce((best, a) => (a.id < best.id ? a : best));
}
}
// Same algorithm already filed under a higher approach number (e.g. approach7 = approach2).
if (!match) {
const withFp = problem.approaches.filter((a) => a.fpHash === fpHash);
const orphans = problem.approaches.filter((a) => !a.fpHash);
if (withFp.length && orphans.length) {
match = [...withFp, ...orphans].reduce((best, a) => (a.id < best.id ? a : best));
}
}
if (match) {
if (!problem.approaches.some((a) => a.id === match.id)) {
problem.approaches.push({ id: match.id, fpHash, normHash, norm, lastNorm: norm });
match = problem.approaches[problem.approaches.length - 1];
}
match.norm = norm;
match.normHash = normHash;
match.fpHash = fpHash;
match.lastNorm = norm;
match.codeHash = fpHash;
consolidateProblemApproaches(problem, match.id, fpHash, fingerprint);
registry[problemKey] = problem;
await saveApproachRegistry(registry);
console.log(`[PrepPush] Same logic → approach${match.id} (fp ${fpHash.slice(0, 8)}…)`);
} else {
const nextId = problem.approaches.reduce((max, a) => Math.max(max, a.id), 0) + 1;
match = { id: nextId, fpHash, normHash, norm, lastNorm: norm, codeHash: fpHash };
problem.approaches.push(match);
problem.byFp[fpHash] = nextId;
registry[problemKey] = problem;
await saveApproachRegistry(registry);
console.log(`[PrepPush] New approach for ${problemKey}: approach${nextId} (fp ${fpHash.slice(0, 8)}…)`);
}
return `approach${match.id}`;
}
async function buildFilePath(submission, ext) {
const dir = buildProblemDir(submission);
const approachKey = submission.approachKey || (await resolveApproachKey(submission));
return `${dir}/solution-${approachKey}.${ext}`;
}
// ─── LLM ANALYSIS (GOOGLE GEMINI — free tier, no card required) ─────────────
// Free tier: Flash Lite only (~500 analyses/day on typical Google AI Studio projects).
const GEMINI_MODELS = [
'gemini-3.1-flash-lite-preview',
'gemini-3.1-flash-lite',
];
const GEMINI_API_BASE = 'https://generativelanguage.googleapis.com/v1beta';
// Passed in each POST body as generationConfig (Gemini generateContent API).
// temperature: 0 = deterministic; 1+ = more random phrasing (bad for stable Big-O labels).
// topP / topK: nucleus sampling caps; kept conservative so quality stays high at temp 0.
const GEMINI_PARAMS = {
analysis: {
temperature: 0,
topP: 0.95,
topK: 40,
responseMimeType: 'application/json',
responseSchema: {
type: 'OBJECT',
properties: {
technique: {
type: 'STRING',
description:
'Short label for THIS implementation only (e.g. two-pointers-dummy-node, hash-map, isupper-scan)',
},
time_complexity: { type: 'STRING', description: 'Big-O time, short' },
space_complexity: { type: 'STRING', description: 'Big-O space, short' },
insight: {
type: 'STRING',
description:
'ONE complete sentence (≤40 words): invariant matching THIS code exactly. Third person only. Use "" if unsure — never guess. Never mid-sentence.',
},
interview: {
type: 'STRING',
description:
'Format: Before: "...". After: "...". Max 55 words, complete. Differ from insight; complexity in After. Use "" if unsure — never guess.',
},
pitfalls: {
type: 'ARRAY',
description:
'1–3 complete pitfalls matching THIS statement AND THIS code. Never contradict samples/guards. Use [] if unsure — never guess.',
items: {
type: 'STRING',
description: 'One complete pitfall, ≤30 words, names the exact rule — never truncated',
},
},
},
required: ['technique', 'time_complexity', 'space_complexity', 'insight', 'interview', 'pitfalls'],
},
},
test: {
temperature: 0,
topP: 1,
topK: 1,
},
};
function buildGenerationConfig(model, purpose, maxOutputTokens) {
const profile = GEMINI_PARAMS[purpose] || GEMINI_PARAMS.analysis;
const config = {
maxOutputTokens,
thinkingConfig: buildThinkingConfig(model),
temperature: profile.temperature,
};
if (profile.topP != null) config.topP = profile.topP;
if (profile.topK != null) config.topK = profile.topK;
if (profile.responseMimeType) config.responseMimeType = profile.responseMimeType;
if (profile.responseSchema) config.responseSchema = profile.responseSchema;
return config;
}
function isGeminiQuotaError(message) {
const m = String(message || '').toLowerCase();
return m.includes('quota') || m.includes('rate limit') || m.includes('limit: 0');
}
function formatGeminiError(message) {
const m = String(message || '');
if (!isGeminiQuotaError(m)) return m;
if (/gemini-3-flash/i.test(m) && /limit:\s*20/i.test(m)) {
return 'Gemini 3 Flash quota is separate (20/day). PrepPush uses Flash Lite only — reload the extension if you still see this.';
}
if (m.length > 160) {
return 'Gemini free quota or rate limit hit. Wait a minute, then retry. Usage: ai.dev/rate-limit';
}
return `${m.split('Please retry')[0].trim()} — wait and retry, or check ai.dev/rate-limit`;
}
function isGeminiModelUnavailable(message) {
const m = String(message || '').toLowerCase();
return m.includes('not found') || m.includes('not supported') || m.includes('invalid model');
}
function buildThinkingConfig(model) {
// Gemini 3 defaults to medium/high thinking and can burn the whole output budget.
if (/gemini-3/i.test(model)) {
return { thinkingLevel: 'minimal' };
}
return { thinkingBudget: 0 };
}
function extractVisibleText(candidate) {
const parts = candidate?.content?.parts;
if (!parts?.length) return '';
return parts
.filter((p) => typeof p.text === 'string' && !p.thought)
.map((p) => p.text)
.join('')
.trim();
}
function stripCodeForAnalysis(code) {
let t = String(code || '').trim();
if (!t) return t;
t = t.replace(/\r\n/g, '\n');
t = t.replace(/if\s+__name__\s*==\s*['"]__main__['"][\s\S]*$/m, '').trim();
if (/^\s*\/\*[\s\S]*?\*\//m.test(t)) {
t = t.replace(/^\s*\/\*[\s\S]*?\*\/\s*/m, '').trim();
}
return t || String(code || '').trim();
}
const GENERIC_AI_PHRASE =
/\b(practice more|edge cases?|interview tip|read carefully|test cases|think about|always remember|make sure|study more|good luck)\b/i;
function buildAnalysisPrompt({
code,
language,
problemName,
problemSlug,
problemUrl,
problemStatement,
}) {
const problemLine = problemUrl
? `Problem: ${problemName || problemSlug || 'Unknown'}\nLink: ${problemUrl}`
: `Problem: ${problemName || problemSlug || 'Unknown'}`;
const statementBlock = problemStatement
? `\nFULL PROBLEM STATEMENT (from HackerRank — treat definitions, samples, and constraints as ground truth):\n"""\n${problemStatement}\n"""\n`
: '\n(Problem statement unavailable — rely only on the code and problem title. Prefer empty pitfalls over generic DSA advice.)\n';
return `${problemLine}
Language: ${language || 'unknown'}
${statementBlock}
You help developers prep for coding interviews. Analyze the ACCEPTED solution below.
CRITICAL — ground truth order:
1) Read the PROBLEM STATEMENT definitions (especially parameters like k, indexing, invalid inputs, samples).
2) Read the CODE and note exact loop offsets (e.g. range(k) vs range(k+1)) and early-return guards (k < 0 vs k <= 0).
3) Write fields that agree with BOTH. Never invent "standard leetcode" rules that contradict this statement or this code.
ACCURACY POLICY (highest priority):
- Wrong notes are worse than missing notes. If you are not certain a claim matches THIS statement AND THIS code, omit it ("" or []).
- Never say k=0 is invalid if the code only rejects k < 0 (or otherwise handles k=0 as a real removal).
- If the code advances fast with k+1, insight/pitfalls must say k+1 — never a plain gap of k.
- Do not claim "k equals list length removes the head" unless that exact rule appears in THIS statement.
Field roles (do NOT blur them together):
- "insight" = silent-revision invariant in ONE third-person sentence. Never first person. Never "I will".
- "interview" = spoken script ONLY in this shape: Before: "...". After: "...". After must mention Big-O and the key edge from the statement. Must not copy insight.
- "pitfalls" = 1–3 concrete wrong-answer risks from THIS statement + THIS code. Each must name the exact rule. Ban vague "off-by-one with pointers".
Rules:
- "technique": 2–6 words for THIS file (e.g. two-pointers-dummy-node).
- "time_complexity" / "space_complexity": Big-O for THIS implementation only.
- "insight": max 40 words, complete sentence(s). "" if unsure.
- "interview": max 55 words, Before/After when non-trivial. "" if unsure.
- "pitfalls": 1–3 strings, each ≤30 words and a complete thought. [] if unsure.
- Never end a field mid-sentence. Short and complete beats long and cut off.
Respond with ONLY valid JSON (no markdown).
Code:
${code}`;
}
async function callGeminiOnModel({ apiKey, model, prompt, maxOutputTokens, purpose = 'analysis' }) {
const generationConfig = buildGenerationConfig(model, purpose, maxOutputTokens);
const url = `${GEMINI_API_BASE}/models/${model}:generateContent?key=${encodeURIComponent(apiKey)}`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig,
}),
});
if (!res.ok) {
let msg = `Gemini API error ${res.status}`;
try {
const err = await res.json();
msg = err.error?.message || msg;
} catch {}
const error = new Error(msg);
error.status = res.status;
throw error;
}
const data = await res.json();
const candidate = data.candidates?.[0];
const text = extractVisibleText(candidate);
const finishReason = candidate?.finishReason;
if (!text) {
const blockReason = finishReason || data.promptFeedback?.blockReason;
const error = new Error(
blockReason ? `Gemini blocked response: ${blockReason}` : 'Empty response from Gemini',
);
error.finishReason = finishReason;
error.retryable = finishReason === 'MAX_TOKENS';
throw error;
}
if (finishReason === 'MAX_TOKENS') {
console.warn(`[PrepPush] Gemini ${model} hit MAX_TOKENS; using partial output (${text.length} chars)`);
}
return text;
}
async function callGemini({
apiKey,
prompt,
maxOutputTokens = 1024,
purpose = 'analysis',
models = GEMINI_MODELS,
}) {
let lastError = null;
const tokenSteps = [maxOutputTokens, Math.min(maxOutputTokens * 2, 2048)];
for (const model of models) {
for (const tokens of tokenSteps) {
try {
const text = await callGeminiOnModel({
apiKey,
model,
prompt,
maxOutputTokens: tokens,
purpose,
});
return { text, model };
} catch (e) {
lastError = e;
const retryTokens = e.retryable && tokens === tokenSteps[0];
const retryable =
retryTokens ||
isGeminiQuotaError(e.message) ||
isGeminiModelUnavailable(e.message) ||
e.status === 429 ||
e.status === 404;
if (retryTokens) {
console.warn(`[PrepPush] Gemini ${model} retrying with ${tokenSteps[1]} tokens…`, e.message);
continue;
}
if (!retryable) throw e;
console.warn(`[PrepPush] Gemini model ${model} unavailable, trying next…`, e.message);
break;
}
}
}
throw lastError || new Error('All Gemini models failed');
}
function truncate(text, max = 140) {
if (!text) return '';
const s = String(text).trim();
return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
}
function truncateAtWord(text, max = 200) {
if (!text) return '';
const s = String(text).trim();
if (s.length <= max) return s;
const slice = s.slice(0, max);
const lastSpace = slice.lastIndexOf(' ');
const cut = lastSpace > max * 0.45 ? slice.slice(0, lastSpace) : slice;
return `${cut.trimEnd()}…`;
}
/**
* Keep full analysis text only — never mid-chop with "…".
* Over hardMax: omit (empty beats a truncated note).
*/
function keepCompleteAnalysisText(text, softMax, hardMax = softMax * 2) {
const s = String(text || '').trim().replace(/\s+/g, ' ');
if (!s) return '';
// Drop model output that already looks mid-truncated.
if (/…\s*$|\.\.\.\s*$/.test(s) && !/\bBefore:\s/i.test(s)) return '';
if (s.length <= hardMax) return s;
return '';
}
function normalizeForCompare(text) {
return String(text || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
}
function isUsefulAnalysisLine(text) {
const t = String(text || '').trim();
if (!t || t.length < 8) return false;
if (GENERIC_AI_PHRASE.test(t)) return false;
if (/^see implementation below\.?$/i.test(t)) return false;
return true;
}
function linesTooSimilar(a, b) {
const x = normalizeForCompare(a);
const y = normalizeForCompare(b);
if (!x || !y) return false;
if (x === y) return true;
if (x.includes(y) || y.includes(x)) return true;
const ax = new Set(x.split(/\s+/).filter((w) => w.length > 3));
const ay = new Set(y.split(/\s+/).filter((w) => w.length > 3));
if (!ax.size || !ay.size) return false;
let overlap = 0;
for (const w of ax) if (ay.has(w)) overlap++;
const ratio = overlap / Math.min(ax.size, ay.size);
return ratio >= 0.75;
}
/** Facts inferred from the solution code — used to drop contradictory AI claims. */
function extractCodeConsistencyFacts(code) {
const c = String(code || '');
const advancesKPlusOne =
/range\s*\(\s*k\s*\+\s*1\s*\)/.test(c) ||
/for\s*\([^)]*k\s*\+\s*1/.test(c) ||
/(?:fast|ptr|p2)[^\n]{0,48}k\s*\+\s*1/.test(c) ||
/k\s*\+\s*1[^\n]{0,48}(?:fast|times|steps)/.test(c);
const advancesKOnly =
/range\s*\(\s*k\s*\)/.test(c) && !/range\s*\(\s*k\s*\+\s*1\s*\)/.test(c);
const rejectsKLessOrEqualZero = /k\s*<=\s*0/.test(c);
const rejectsKStrictlyNegative = /k\s*<\s*0/.test(c) && !rejectsKLessOrEqualZero;
return {
advancesKPlusOne,
advancesKOnly,
// k=0 is a real case when we only bail on k < 0
k0Valid: rejectsKStrictlyNegative,
k0Invalid: rejectsKLessOrEqualZero,
};
}
function textContradictsCode(text, facts) {
const t = String(text || '');
if (!t.trim()) return false;
const lower = t.toLowerCase();
const claimsK0Invalid =
/k\s*=\s*0[^.\n]{0,40}invalid/i.test(t) ||
/invalid[^.\n]{0,40}k\s*=\s*0/i.test(t) ||
/k\s*=\s*0\s+is\s+treated\s+as\s+invalid/i.test(t) ||
/treat(?:s|ed)?\s+k\s*=\s*0\s+as\s+invalid/i.test(t);
const claimsK0RemovesOrValid =
/k\s*=\s*0[^.\n]{0,50}(removes?|last|valid)/i.test(t) ||
/(removes?|last)[^.\n]{0,50}k\s*=\s*0/i.test(t);
const mentionsGapOfK =
/\bgap of k\b(?!\s*\+\s*1)/i.test(t) ||
/\bfixed gap of k\b(?!\s*\+\s*1)/i.test(t) ||
/\boffset(?:ting)?(?:\s+the)?(?:\s+fast)?(?:\s+pointer)?\s+by k\b(?!\s*\+\s*1)/i.test(t) ||
/\badvance(?:s|ing)?(?:\s+the)?(?:\s+fast)?(?:\s+pointer)?\s+by k\b(?!\s*\+\s*1)/i.test(t);
const mentionsKPlusOne = /k\s*\+\s*1|k\s*plus\s*one/i.test(t);
const claimsKEqualsLengthRemovesHead =
/k equals (the )?list length/i.test(t) ||
/when k equals[^.]*length/i.test(t) ||
/k\s*==\s*n\b/i.test(t) ||
/k\s*=\s*(the )?list length/i.test(t);
if (facts.k0Valid && claimsK0Invalid) return true;
if (facts.k0Invalid && claimsK0RemovesOrValid) return true;
if (facts.advancesKPlusOne && mentionsGapOfK && !mentionsKPlusOne) return true;
if (facts.advancesKOnly && mentionsKPlusOne && /gap|advance|offset/i.test(t)) return true;
// Classic LeetCode confusion: k==n removes head — reject when this code uses 0-based k+1 pattern
if (facts.advancesKPlusOne && facts.k0Valid && claimsKEqualsLengthRemovesHead) return true;
// Vague "k=0 invalid" without saying why, when code shows k0 valid
if (facts.k0Valid && /k\s*=\s*0/i.test(t) && /invalid/i.test(lower)) return true;
return false;
}
function sanitizeAnalysisAgainstCode(fields, code) {
const facts = extractCodeConsistencyFacts(code);
let { insight, interview, pitfalls } = fields;
const dropped = [];
if (insight && textContradictsCode(insight, facts)) {
dropped.push('insight');
insight = null;
}
if (interview && textContradictsCode(interview, facts)) {
dropped.push('interview');
interview = null;
}
const keptPitfalls = [];
for (const p of pitfalls || []) {
if (textContradictsCode(p, facts)) {
dropped.push(`pitfall:${p.slice(0, 40)}`);
continue;
}
keptPitfalls.push(p);
}
if (dropped.length) {
console.warn('[PrepPush] Dropped inconsistent AI notes (prefer empty over wrong):', dropped);
}
return { ...fields, insight, interview, pitfalls: keptPitfalls };
}
function normalizePitfallsList(raw) {
let items = [];
if (Array.isArray(raw)) {
items = raw;
} else if (typeof raw === 'string' && raw.trim()) {
items = raw
.split(/\n|(?:\)\s*)(?=\()|;\s+/)
.map((s) => s.replace(/^\(?\s*\d+[\).\]]\s*/, '').replace(/^\(\d+\)\s*/, '').trim())
.filter(Boolean);
}
const out = [];
const seen = new Set();
for (const item of items) {
// Hard cap drops absurdly long lines instead of chopping with "…"
const line = keepCompleteAnalysisText(String(item || '').trim(), 220, 400);
if (!isUsefulAnalysisLine(line)) continue;
const key = normalizeForCompare(line);
if (!key || seen.has(key)) continue;
seen.add(key);
out.push(line);
if (out.length >= 3) break;
}
return out;
}
function parseAnalysisJson(text, code = '') {
const match = text.trim().match(/\{[\s\S]*\}/);
if (!match) throw new Error(`No JSON in model response (got: ${truncate(text, 120)})`);
let parsed;
try {
parsed = JSON.parse(match[0]);
} catch (e) {
throw new Error(`Invalid JSON from model: ${e.message}`);
}
const technique = truncate(parsed.technique || parsed.approach || 'unknown', 48);
// Prefer omitting weak/uncertain insight over filler or mid-chopped text.
let insight = keepCompleteAnalysisText(parsed.insight || parsed.trick || '', 280, 480);
if (!isUsefulAnalysisLine(insight)) insight = null;
let interview = keepCompleteAnalysisText(parsed.interview || '', 360, 560);
if (!isUsefulAnalysisLine(interview)) interview = null;
if (interview && insight && linesTooSimilar(insight, interview)) {
interview = null;
}
let pitfalls = normalizePitfallsList(parsed.pitfalls);
if (!pitfalls.length) {
const legacyHint = keepCompleteAnalysisText(parsed.code_hint || parsed.codeHint || '', 220, 400);
if (isUsefulAnalysisLine(legacyHint)) pitfalls = [legacyHint];
}
const insightKey = normalizeForCompare(insight);
const interviewKey = normalizeForCompare(interview);
pitfalls = pitfalls.filter((p) => {
const k = normalizeForCompare(p);
if (!k) return false;
if (insightKey && (k === insightKey || insightKey.includes(k) || k.includes(insightKey))) {
return false;
}
if (interviewKey && (k === interviewKey || interviewKey.includes(k) || k.includes(interviewKey))) {
return false;
}
return true;
});
return sanitizeAnalysisAgainstCode(
{
technique,
time_complexity: truncate(parsed.time_complexity || parsed.timeComplexity || 'N/A', 40),
space_complexity: truncate(parsed.space_complexity || parsed.spaceComplexity || 'N/A', 40),
insight,
interview,
pitfalls,
},
code,
);
}
async function analyzeCode({
code,
language,
problemName,
problemSlug,
contestSlug,
problemStatement,
apiKey,
}) {
let statement = String(problemStatement || '').trim();
if (!statement && problemSlug) {
try {
const details = await fetchChallengeDetails(problemSlug, contestSlug);
if (details.problemStatement) statement = details.problemStatement;
if (!problemName && details.problemName) problemName = details.problemName;
} catch (e) {
console.warn('[PrepPush] Could not load problem statement:', e?.message || e);
}
}
const stripped = stripCodeForAnalysis(code);
const prompt = buildAnalysisPrompt({
code: stripped,
language,
problemName,
problemSlug,
problemUrl: buildHackerRankProblemUrl({ problemSlug, contestSlug }),
problemStatement: statement || null,
});
// Full statements need a bit more output budget for grounded pitfalls.
const { text } = await callGemini({ apiKey, prompt, maxOutputTokens: 1280 });
return parseAnalysisJson(text, stripped);
}
async function testGeminiConnection(apiKey) {
try {
const { text, model } = await callGemini({
apiKey,
models: GEMINI_MODELS,
prompt: 'Reply with exactly: OK',
maxOutputTokens: 64,
purpose: 'test',
});
const reply = text.trim();
if (!reply) throw new Error('Empty response from Gemini');
if (/\bok\b/i.test(reply)) return { success: true, model };
throw new Error(`Unexpected test reply: ${truncate(reply, 80)}`);
} catch (e) {
return { success: false, error: formatGeminiError(e.message) };
}