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
|
import { and, eq, gt, sql } from "drizzle-orm";
import { db } from "../db";
import { prComments, prVisits } from "../db/schema";
import {
getAnthropic,
isAiAvailable,
MODEL_SONNET,
extractText,
} from "./ai-client";
import { commitsBetween } from "../git/repository";
export interface ReviewContext {
lastVisitedAt: string;
commitsSince: number;
newComments: number;
unresolvedThreads: number;
summary: string;
suggestedStartLine?: string;
}
const MIN_STALENESS_HOURS = 4;
export async function recordPrVisit(
prId: string,
userId: string
): Promise<void> {
try {
await db
.insert(prVisits)
.values({ prId, userId, visitedAt: new Date() })
.onConflictDoUpdate({
target: [prVisits.prId, prVisits.userId],
set: { visitedAt: new Date() },
});
} catch (err) {
console.error("[review-context] recordPrVisit error:", err);
}
}
export async function getReviewContext(
prId: string,
userId: string,
opts?: {
ownerName?: string;
repoName?: string;
baseBranch?: string;
headBranch?: string;
}
): Promise<ReviewContext | null> {
try {
const [visit] = await db
.select()
.from(prVisits)
.where(and(eq(prVisits.prId, prId), eq(prVisits.userId, userId)))
.limit(1);
if (!visit) return null;
const lastVisitedAt = new Date(visit.visitedAt);
const hoursSince =
(Date.now() - lastVisitedAt.getTime()) / 3_600_000;
if (hoursSince < MIN_STALENESS_HOURS) return null;
let newComments = 0;
try {
const [countRow] = await db
.select({ count: sql<number>`count(*)::int` })
.from(prComments)
.where(
and(
eq(prComments.pullRequestId, prId),
gt(prComments.createdAt, lastVisitedAt)
)
);
newComments = countRow?.count || 0;
} catch {
}
let commitsSince = 0;
let changedFiles: string[] = [];
if (opts?.ownerName && opts?.repoName && opts?.baseBranch && opts?.headBranch) {
try {
const allCommits = await commitsBetween(
opts.ownerName,
opts.repoName,
opts.baseBranch,
opts.headBranch
);
const newCommits = allCommits.filter(
(c) => new Date(c.date) > lastVisitedAt
);
commitsSince = newCommits.length;
changedFiles = newCommits
.flatMap((c) => (c.message || "").split("\n"))
.filter((l) => l.startsWith("M\t") || l.startsWith("A\t") || l.startsWith("D\t"))
.map((l) => l.slice(2))
.filter(Boolean)
.slice(0, 5);
} catch {
}
}
if (commitsSince === 0 && newComments === 0) return null;
let summary = buildFallbackSummary(commitsSince, newComments, hoursSince);
let suggestedStartLine: string | undefined;
if (isAiAvailable() && (commitsSince > 0 || newComments > 0)) {
try {
const aiResult = await callClaudeForContext({
commitsSince,
newComments,
changedFiles,
hoursSince,
lastVisitedAt: lastVisitedAt.toISOString(),
});
if (aiResult) {
summary = aiResult.summary;
suggestedStartLine = aiResult.suggestedStartLine;
}
} catch (err) {
console.error("[review-context] Claude call failed:", err);
}
}
const unresolvedThreads = newComments;
return {
lastVisitedAt: lastVisitedAt.toISOString(),
commitsSince,
newComments,
unresolvedThreads,
summary,
suggestedStartLine,
};
} catch (err) {
console.error("[review-context] getReviewContext error:", err);
return null;
}
}
function buildFallbackSummary(
commitsSince: number,
newComments: number,
hoursSince: number
): string {
const parts: string[] = [];
const hoursLabel =
hoursSince >= 24
? `${Math.floor(hoursSince / 24)} day${Math.floor(hoursSince / 24) === 1 ? "" : "s"}`
: `${Math.round(hoursSince)} hour${Math.round(hoursSince) === 1 ? "" : "s"}`;
if (commitsSince > 0) {
parts.push(
`${commitsSince} new commit${commitsSince === 1 ? " was" : "s were"} pushed since your last visit ${hoursLabel} ago`
);
}
if (newComments > 0) {
parts.push(
`${newComments} new comment${newComments === 1 ? " was" : "s were"} added`
);
}
return parts.join(". ") + ".";
}
interface ClaudeContextResponse {
summary: string;
suggestedStartLine?: string;
}
async function callClaudeForContext(input: {
commitsSince: number;
newComments: number;
changedFiles: string[];
hoursSince: number;
lastVisitedAt: string;
}): Promise<ClaudeContextResponse | null> {
const client = getAnthropic();
const hoursLabel =
input.hoursSince >= 24
? `${Math.floor(input.hoursSince / 24)} day${Math.floor(input.hoursSince / 24) === 1 ? "" : "s"}`
: `${Math.round(input.hoursSince)} hours`;
const prompt = `A developer is returning to a pull request they last reviewed ${hoursLabel} ago.
Changes since their last visit:
- New commits pushed: ${input.commitsSince}
- New comments added: ${input.newComments}
${input.changedFiles.length > 0 ? `- Files changed: ${input.changedFiles.join(", ")}` : ""}
Write a brief 2-3 sentence "welcome back" summary telling the reviewer what happened.
If there are changed files, suggest one as the best starting point.
Respond with JSON:
{"summary": "...", "suggestedStartLine": "src/foo.ts:42 — reason (optional, omit if no files)"}
Rules:
- summary must be specific and human, not generic
- No more than 3 sentences
- If no changed files, omit suggestedStartLine
- Return only valid JSON, no prose`;
const msg = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 500,
messages: [{ role: "user", content: prompt }],
});
const text = extractText(msg);
try {
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]) as ClaudeContextResponse;
if (typeof parsed.summary === "string") return parsed;
}
} catch {
}
return null;
}
|