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
|
import { and, desc, eq, gte, inArray } from "drizzle-orm";
import { createHash } from "crypto";
import { db } from "../db";
import {
gateRuns,
issues,
pullRequests,
repositories,
} from "../db/schema";
import { getAnthropic, MODEL_SONNET, extractText, parseJsonResponse, isAiAvailable } from "./ai-client";
import { extractSymbols, detectLanguage } from "./symbols";
export interface PairContext {
openPrForFile?: {
prNumber: number;
title: string;
branch: string;
changedLines: string;
};
recentGateFailure?: {
runType: string;
errorSummary: string;
failedAt: Date;
};
fileSymbols?: string[];
relatedIssue?: {
issueNumber: number;
title: string;
};
}
export interface PairSuggestion {
type: "completion" | "warning" | "context_note" | "fix_available";
headline: string;
detail?: string;
actionLabel?: string;
actionPayload?: string;
}
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
const contextCache = new Map<string, CacheEntry<PairContext>>();
const CONTEXT_TTL_MS = 3 * 60 * 1000;
const prFilesCache = new Map<string, CacheEntry<string[]>>();
const PR_FILES_TTL_MS = 5 * 60 * 1000;
const suggestCache = new Map<string, CacheEntry<PairSuggestion>>();
const SUGGEST_TTL_MS = 30 * 1000;
function cacheGet<T>(store: Map<string, CacheEntry<T>>, key: string): T | undefined {
const entry = store.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
store.delete(key);
return undefined;
}
return entry.value;
}
function cacheSet<T>(store: Map<string, CacheEntry<T>>, key: string, value: T, ttlMs: number): void {
store.set(key, { value, expiresAt: Date.now() + ttlMs });
}
async function prChangedFiles(
prId: string,
repoPath: string,
baseBranch: string,
headBranch: string
): Promise<string[]> {
const cached = cacheGet(prFilesCache, prId);
if (cached !== undefined) return cached;
try {
const proc = Bun.spawn(
["git", "diff", "--name-only", `${baseBranch}...${headBranch}`],
{ cwd: repoPath, stdout: "pipe", stderr: "pipe" }
);
const text = await new Response(proc.stdout).text();
await proc.exited;
const files = text
.trim()
.split("\n")
.filter(Boolean);
cacheSet(prFilesCache, prId, files, PR_FILES_TTL_MS);
return files;
} catch {
return [];
}
}
async function fileDiffExcerpt(
repoPath: string,
baseBranch: string,
headBranch: string,
filePath: string
): Promise<string> {
try {
const proc = Bun.spawn(
["git", "diff", `${baseBranch}...${headBranch}`, "--", filePath],
{ cwd: repoPath, stdout: "pipe", stderr: "pipe" }
);
const text = await new Response(proc.stdout).text();
await proc.exited;
return text.slice(0, 2048);
} catch {
return "";
}
}
async function extractFileSymbols(
repoPath: string,
filePath: string,
defaultBranch: string
): Promise<string[]> {
try {
const proc = Bun.spawn(
["git", "show", `${defaultBranch}:${filePath}`],
{ cwd: repoPath, stdout: "pipe", stderr: "pipe" }
);
const content = await new Response(proc.stdout).text();
await proc.exited;
if (!content) return [];
const lang = detectLanguage(filePath);
if (!lang) return [];
const symbols = extractSymbols(content, lang);
const seen = new Set<string>();
const names: string[] = [];
for (const s of symbols) {
if (!seen.has(s.name)) {
seen.add(s.name);
names.push(s.name);
if (names.length >= 30) break;
}
}
return names;
} catch {
return [];
}
}
async function findOpenPrForFile(
repoId: string,
filePath: string,
userId: string,
repoPath: string
): Promise<PairContext["openPrForFile"] | undefined> {
try {
const prs = await db
.select()
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repoId),
eq(pullRequests.authorId, userId),
eq(pullRequests.state, "open")
)
)
.orderBy(desc(pullRequests.updatedAt))
.limit(10);
if (prs.length === 0) return undefined;
for (const pr of prs) {
const files = await prChangedFiles(
pr.id,
repoPath,
pr.baseBranch,
pr.headBranch
);
const touches = files.some(
(f) => f === filePath || filePath.endsWith(f) || f.endsWith(filePath)
);
if (!touches) continue;
const changedLines = await fileDiffExcerpt(
repoPath,
pr.baseBranch,
pr.headBranch,
filePath
);
return {
prNumber: pr.number,
title: pr.title,
branch: pr.headBranch,
changedLines,
};
}
return undefined;
} catch {
return undefined;
}
}
async function findRecentGateFailure(
repoId: string,
userId: string
): Promise<PairContext["recentGateFailure"] | undefined> {
try {
const cutoff = new Date(Date.now() - 30 * 60 * 1000);
const openPrs = await db
.select({ id: pullRequests.id })
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repoId),
eq(pullRequests.authorId, userId),
eq(pullRequests.state, "open")
)
)
.limit(20);
if (openPrs.length === 0) return undefined;
const prIds = openPrs.map((p) => p.id);
const [failed] = await db
.select()
.from(gateRuns)
.where(
and(
inArray(gateRuns.pullRequestId, prIds),
eq(gateRuns.status, "failed"),
gte(gateRuns.createdAt, cutoff)
)
)
.orderBy(desc(gateRuns.createdAt))
.limit(1);
if (!failed) return undefined;
const rawLog = failed.summary || failed.details || "";
const errorSummary = rawLog.slice(0, 500);
return {
runType: failed.gateName,
errorSummary,
failedAt: new Date(failed.createdAt),
};
} catch {
return undefined;
}
}
async function findRelatedIssue(
repoId: string,
filePath: string
): Promise<PairContext["relatedIssue"] | undefined> {
try {
const fileName = filePath.split("/").pop() || filePath;
const allOpen = await db
.select()
.from(issues)
.where(
and(
eq(issues.repositoryId, repoId),
eq(issues.state, "open")
)
)
.orderBy(desc(issues.updatedAt))
.limit(50);
for (const issue of allOpen) {
const haystack = `${issue.title} ${issue.body ?? ""}`.toLowerCase();
if (
haystack.includes(filePath.toLowerCase()) ||
haystack.includes(fileName.toLowerCase())
) {
return {
issueNumber: issue.number,
title: issue.title,
};
}
}
return undefined;
} catch {
return undefined;
}
}
export async function assemblePairContext(
repoId: string,
filePath: string,
userId: string
): Promise<PairContext> {
const cacheKey = `${repoId}:${filePath}:${userId}`;
const cached = cacheGet(contextCache, cacheKey);
if (cached !== undefined) return cached;
let repoPath = "";
let defaultBranch = "main";
try {
const [repo] = await db
.select({ diskPath: repositories.diskPath, defaultBranch: repositories.defaultBranch })
.from(repositories)
.where(eq(repositories.id, repoId))
.limit(1);
if (repo) {
repoPath = repo.diskPath;
defaultBranch = repo.defaultBranch || "main";
}
} catch {
}
const [openPrForFile, recentGateFailure, fileSymbols, relatedIssue] =
await Promise.all([
repoPath
? findOpenPrForFile(repoId, filePath, userId, repoPath)
: Promise.resolve(undefined),
findRecentGateFailure(repoId, userId),
repoPath
? extractFileSymbols(repoPath, filePath, defaultBranch)
: Promise.resolve([] as string[]),
findRelatedIssue(repoId, filePath),
]);
const context: PairContext = {};
if (openPrForFile) context.openPrForFile = openPrForFile;
if (recentGateFailure) context.recentGateFailure = recentGateFailure;
if (fileSymbols && fileSymbols.length > 0) context.fileSymbols = fileSymbols;
if (relatedIssue) context.relatedIssue = relatedIssue;
cacheSet(contextCache, cacheKey, context, CONTEXT_TTL_MS);
return context;
}
function hasInterestingContext(ctx: PairContext): boolean {
return !!(ctx.openPrForFile || ctx.recentGateFailure || ctx.relatedIssue);
}
function formatContext(ctx: PairContext): string {
const parts: string[] = [];
if (ctx.openPrForFile) {
parts.push(
`OPEN PR #${ctx.openPrForFile.prNumber}: "${ctx.openPrForFile.title}" (branch: ${ctx.openPrForFile.branch})`
);
if (ctx.openPrForFile.changedLines) {
parts.push(`Diff for this file:\n${ctx.openPrForFile.changedLines}`);
}
}
if (ctx.recentGateFailure) {
parts.push(
`RECENT CI FAILURE (${ctx.recentGateFailure.runType}):\n${ctx.recentGateFailure.errorSummary}`
);
}
if (ctx.relatedIssue) {
parts.push(
`RELATED ISSUE #${ctx.relatedIssue.issueNumber}: "${ctx.relatedIssue.title}"`
);
}
if (ctx.fileSymbols && ctx.fileSymbols.length > 0) {
parts.push(`File symbols: ${ctx.fileSymbols.join(", ")}`);
}
return parts.join("\n\n");
}
export async function generatePairSuggestion(
prefix: string,
suffix: string,
filePath: string,
context: PairContext
): Promise<PairSuggestion> {
const fallback: PairSuggestion = {
type: "completion",
headline: "Continue editing",
detail: undefined,
};
if (!isAiAvailable()) return fallback;
try {
const clippedPrefix = prefix.slice(-4000);
const clippedSuffix = (suffix || "").slice(0, 1000);
if (!hasInterestingContext(context)) {
const client = getAnthropic();
const response = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 256,
system:
"You are an expert pair programmer embedded in a code editor. " +
`The developer is editing ${filePath}. ` +
"Output ONLY the characters that should be inserted at the cursor. " +
"No explanations. No markdown fences.",
messages: [
{
role: "user",
content:
`PREFIX:\n${clippedPrefix}\n\nSUFFIX:\n${clippedSuffix}`,
},
],
});
const completion = extractText(response).replace(/^\s*```[A-Za-z0-9_+-]*\s*\n?/, "").replace(/\n?\s*```\s*$/, "");
return {
type: "completion",
headline: completion.split("\n")[0].slice(0, 120) || "Inline suggestion",
detail: completion,
};
}
const contextText = formatContext(context);
const client = getAnthropic();
const response = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 800,
system:
"You are an expert pair programmer embedded in a code editor. " +
`The developer is editing ${filePath}. ` +
"Analyse the context provided (open PRs, CI failures, related issues, file symbols) " +
"and return a single JSON object with the shape: " +
'{ "type": "completion"|"warning"|"context_note"|"fix_available", ' +
'"headline": "<one line, max 120 chars>", ' +
'"detail": "<optional expanded explanation>", ' +
'"actionLabel": "<optional button label>", ' +
'"actionPayload": "<optional diff or URL>" }. ' +
"Respond with ONLY the JSON object — no prose, no markdown fences.",
messages: [
{
role: "user",
content:
`CONTEXT:\n${contextText}\n\n` +
`PREFIX (last 4000 chars):\n${clippedPrefix}\n\n` +
`SUFFIX (first 1000 chars):\n${clippedSuffix}`,
},
],
});
const raw = extractText(response);
const parsed = parseJsonResponse<{
type?: string;
headline?: string;
detail?: string;
actionLabel?: string;
actionPayload?: string;
}>(raw);
if (!parsed || typeof parsed.headline !== "string") {
return {
type: "context_note",
headline: raw.split("\n")[0].slice(0, 120) || "Pair programmer note",
detail: raw.slice(0, 500),
};
}
const validTypes = new Set(["completion", "warning", "context_note", "fix_available"]);
const type = validTypes.has(parsed.type ?? "") ? (parsed.type as PairSuggestion["type"]) : "context_note";
return {
type,
headline: (parsed.headline || "").slice(0, 120),
detail: parsed.detail,
actionLabel: parsed.actionLabel,
actionPayload: parsed.actionPayload,
};
} catch (err) {
console.error(
"[ai-pair] generatePairSuggestion error:",
(err as Error)?.message || err
);
return fallback;
}
}
export function suggestCacheKey(
userId: string,
repoId: string,
filePath: string,
prefix: string
): string {
const prefixSlice = prefix.slice(-50);
return createHash("sha256")
.update(userId)
.update("\0")
.update(repoId)
.update("\0")
.update(filePath)
.update("\0")
.update(prefixSlice)
.digest("hex");
}
export { suggestCache, cacheGet, cacheSet, SUGGEST_TTL_MS };
|