Skip to content

Commit 801093b

Browse files
fix(pull-requests): review guide fixes from review
- A late run for an older head no longer clears a newer run's state or writes over its guide; completion only applies while the run still owns the PR. - The base branch is fetched into a ref of the run's own, not the shared FETCH_HEAD, and its name is checked before it reaches the refspec. - A removed or added line that looks like a `---`/`+++` header is read as a source line, not a new file. - Claude investigations deny `git … --output`/`-o`, which would write a file; probed against the CLI: writes are refused, plain `git diff` still runs. - Guide RPCs stay on the pull request's own server instead of being routed, since each server stores its own guides. - The prompt tags the pull request's own text as data, not instructions. - Web: excerpts read the diff of the guide's head; a reveal pages forward to its file; a failed start stops being watched; "Ask agent" is offered only where a thread can open, and keeps the guide beside it for line asks too; removed-code ranges are labelled base-side; the guide model setting validates on enable, shows mixed values and its own model options; settings search lands on the beta switch while the guide rows are hidden. - The unsupported-provider message names the review guide model. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 63556ce commit 801093b

19 files changed

Lines changed: 302 additions & 53 deletions

‎apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts‎

Lines changed: 105 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Deferred from "effect/Deferred";
55
import * as Effect from "effect/Effect";
66
import * as FileSystem from "effect/FileSystem";
77
import * as Layer from "effect/Layer";
8+
import * as Ref from "effect/Ref";
89
import * as Schedule from "effect/Schedule";
910
import {
1011
ProjectId,
@@ -148,6 +149,8 @@ const makeLayer = (input: {
148149
readonly stored: Deferred.Deferred<void>;
149150
/** The server's beta switch; on unless a test is about it being off. */
150151
readonly enabled?: boolean;
152+
/** The head the host reports now, for a test that pushes between runs. */
153+
readonly currentHead?: Ref.Ref<string>;
151154
}) =>
152155
PullRequestReviewGuideService.layer.pipe(
153156
Layer.provide(
@@ -167,7 +170,11 @@ const makeLayer = (input: {
167170
),
168171
Layer.provide(
169172
Layer.succeed(PullRequestService.PullRequestService, {
170-
detail: () => Effect.succeed(detail(input.workspace, input.headSha)),
173+
detail: () =>
174+
(input.currentHead === undefined
175+
? Effect.succeed(input.headSha)
176+
: Ref.get(input.currentHead)
177+
).pipe(Effect.map((head) => detail(input.workspace, head))),
171178
activity: () => Effect.succeed(activity),
172179
stack: () => Effect.succeed(stack(input)),
173180
} as unknown as PullRequestService.PullRequestService["Service"]),
@@ -199,7 +206,8 @@ const layerBase = Layer.mergeAll(
199206
SqlitePersistence.layerMemory,
200207
).pipe(Layer.provideMerge(NodeServices.layer));
201208

202-
it.layer(layerBase)("PullRequestReviewGuideService", (it) => {
209+
// Runs drive real git, which the test clock does not advance, so waits use real time.
210+
it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
203211
it.effect("briefs the change against its own base in a checkout it then removes", () =>
204212
Effect.scoped(
205213
Effect.gen(function* () {
@@ -348,4 +356,99 @@ it.layer(layerBase)("PullRequestReviewGuideService", (it) => {
348356
}),
349357
),
350358
);
359+
360+
it.effect(
361+
"keeps a newer run's guide when an older run for the same pull request finishes late",
362+
() =>
363+
Effect.scoped(
364+
Effect.gen(function* () {
365+
const repositories = yield* makeRepositories;
366+
const stored = yield* Deferred.make<void>();
367+
const currentHead = yield* Ref.make(repositories.headSha);
368+
// The old run waits on this; the new one answers at once.
369+
const releaseOld = yield* Deferred.make<void>();
370+
const oldStarted = yield* Deferred.make<void>();
371+
const answer = (title: string) => ({
372+
stops: [
373+
{
374+
title,
375+
summary: "",
376+
attention: null,
377+
excerpts: [],
378+
files: [],
379+
notes: [],
380+
questions: [],
381+
},
382+
],
383+
});
384+
const context = yield* Layer.build(
385+
makeLayer({
386+
...repositories,
387+
stored,
388+
currentHead,
389+
generate: (input) =>
390+
input.cwd.length > 0 && input.baseCommit.length > 0
391+
? Ref.get(currentHead).pipe(
392+
Effect.flatMap((head) =>
393+
head === repositories.headSha
394+
? Deferred.succeed(oldStarted, undefined).pipe(
395+
Effect.andThen(Deferred.await(releaseOld)),
396+
Effect.as(answer("old head")),
397+
)
398+
: Effect.succeed(answer("new head")),
399+
),
400+
)
401+
: Effect.die("unreachable"),
402+
}),
403+
);
404+
const service = Context.get(
405+
context,
406+
PullRequestReviewGuideService.PullRequestReviewGuideService,
407+
);
408+
409+
yield* service.generate(reference);
410+
const firstFailed = service.get(reference).pipe(
411+
Effect.flatMap((result) =>
412+
result.run?._tag === "Failed"
413+
? Effect.die(`first run failed: ${result.run.detail}`)
414+
: Effect.fail("still running" as const),
415+
),
416+
Effect.retry(Schedule.spaced("20 millis")),
417+
);
418+
yield* Effect.raceFirst(Deferred.await(oldStarted), firstFailed);
419+
// A push: the host reports the upper layer's commit as the head now, and a new run starts.
420+
yield* Ref.set(currentHead, repositories.upperSha);
421+
const second = yield* service.generate(reference);
422+
assert.strictEqual(second.run?._tag, "Running");
423+
assert.strictEqual(second.run?.headSha, repositories.upperSha);
424+
// A run that fails reports why rather than leaving this waiting.
425+
const failedRun = service.get(reference).pipe(
426+
Effect.flatMap((result) =>
427+
result.run?._tag === "Failed"
428+
? Effect.die(`run failed: ${result.run.detail}`)
429+
: Effect.fail("still running" as const),
430+
),
431+
Effect.retry(Schedule.spaced("20 millis")),
432+
);
433+
yield* Effect.raceFirst(Deferred.await(stored), failedRun);
434+
435+
// The old run finishes last. Its guide is for a head nobody is looking at any more.
436+
yield* Deferred.succeed(releaseOld, undefined);
437+
const settled = yield* service.get(reference).pipe(
438+
Effect.filterOrFail(
439+
(result) => result.run === null,
440+
() => "still running" as const,
441+
),
442+
Effect.retry({ schedule: Schedule.spaced("20 millis"), times: 250 }),
443+
);
444+
assert.strictEqual(settled.guide?.headSha, repositories.upperSha);
445+
// Give the late run every chance to write over the newer guide; it must not.
446+
yield* Effect.sleep("200 millis");
447+
const after = yield* service.get(reference);
448+
assert.isNull(after.run);
449+
assert.strictEqual(after.guide?.headSha, repositories.upperSha);
450+
assert.strictEqual(after.guide?.stops[0]?.title, "new head");
451+
}),
452+
),
453+
);
351454
});

‎apps/server/src/pullRequest/PullRequestReviewGuideService.ts‎

Lines changed: 63 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ const make = Effect.gen(function* () {
8585
const serviceScope = yield* Effect.scope;
8686
// In memory on purpose: a restart drops a run in progress, and a reader presses Generate again.
8787
const runs = yield* Ref.make<ReadonlyMap<string, PullRequestReviewGuideRun>>(new Map());
88+
// Names each run's private git refs; unique for the server's lifetime, like the runs map.
89+
let runCounter = 0;
8890

8991
const keyFor = Effect.fn("PullRequestReviewGuideService.keyFor")(function* (
9092
input: PullRequestRef,
@@ -115,14 +117,6 @@ const make = Effect.gen(function* () {
115117
Effect.map(Option.getOrNull),
116118
);
117119

118-
const setRun = (key: string, run: PullRequestReviewGuideRun | null) =>
119-
Ref.update(runs, (current) => {
120-
const next = new Map(current);
121-
if (run === null) next.delete(key);
122-
else next.set(key, run);
123-
return next;
124-
});
125-
126120
const get: PullRequestReviewGuideService["Service"]["get"] = Effect.fn(
127121
"PullRequestReviewGuideService.get",
128122
)(function* (input) {
@@ -148,6 +142,7 @@ const make = Effect.gen(function* () {
148142
detail: PullRequestDetail,
149143
headSha: string,
150144
stack: PullRequestStack | null,
145+
runId: string,
151146
) {
152147
const remote = yield* git.resolvePrimaryRemoteName(workspaceRoot);
153148
const fetch = (args: ReadonlyArray<string>) =>
@@ -160,8 +155,38 @@ const make = Effect.gen(function* () {
160155
// The base branch is what the change is measured from; the head commit is the change. Hosts
161156
// that do not serve an unadvertised commit still serve their pull refs, which GitHub and
162157
// Forgejo name the same way.
163-
yield* fetch([`refs/heads/${detail.baseBranch}`]);
164-
const baseTip = yield* git.resolveCommit({ cwd: workspaceRoot, revision: "FETCH_HEAD" });
158+
// The host names the base branch. A name git rejects, or one that would change the refspec
159+
// (a leading `+`, a `:`), is refused before it reaches `git fetch`.
160+
yield* git
161+
.execute({
162+
operation: "PullRequestReviewGuideService.checkBaseBranch",
163+
cwd: workspaceRoot,
164+
args: ["check-ref-format", "--branch", detail.baseBranch],
165+
})
166+
.pipe(
167+
Effect.filterOrFail(
168+
() => !detail.baseBranch.startsWith("+") && !detail.baseBranch.includes(":"),
169+
() =>
170+
new PullRequestOperationError({
171+
operation: "generateReviewGuide",
172+
detail: "The pull request's base branch name is not one git can fetch.",
173+
}),
174+
),
175+
);
176+
// Fetched into a ref of this run's own: FETCH_HEAD is shared by every fetch in the
177+
// workspace, so a concurrent run could otherwise measure this change from its base.
178+
const baseRef = `refs/t3/review-guide/${runId}/base`;
179+
yield* fetch([`+refs/heads/${detail.baseBranch}:${baseRef}`]);
180+
yield* Effect.addFinalizer(() =>
181+
git
182+
.execute({
183+
operation: "PullRequestReviewGuideService.dropBaseRef",
184+
cwd: workspaceRoot,
185+
args: ["update-ref", "-d", baseRef],
186+
})
187+
.pipe(Effect.ignore({ log: true })),
188+
);
189+
const baseTip = yield* git.resolveCommit({ cwd: workspaceRoot, revision: baseRef });
165190
const fetchHead = (number: number, sha: string) =>
166191
fetch([sha]).pipe(Effect.catch(() => fetch([`refs/pull/${number}/head`])));
167192
yield* fetchHead(detail.number, headSha);
@@ -237,6 +262,8 @@ const make = Effect.gen(function* () {
237262
workspaceRoot: string,
238263
detail: PullRequestDetail,
239264
headSha: string,
265+
runId: string,
266+
owns: Effect.Effect<boolean>,
240267
) {
241268
const [activity, settings, providers, stack] = yield* Effect.all(
242269
[
@@ -255,7 +282,13 @@ const make = Effect.gen(function* () {
255282
);
256283
// The checkout lives only as long as the model is reading it. The change's hunks are read
257284
// from it too, so the guide can be held to the lines the change actually touched.
258-
const { generated, change } = yield* checkoutHead(workspaceRoot, detail, headSha, stack).pipe(
285+
const { generated, change } = yield* checkoutHead(
286+
workspaceRoot,
287+
detail,
288+
headSha,
289+
stack,
290+
runId,
291+
).pipe(
259292
Effect.flatMap((checkout) =>
260293
Effect.all(
261294
{
@@ -279,7 +312,9 @@ const make = Effect.gen(function* () {
279312
modelSelection,
280313
...normalizeReviewGuide(generated, change),
281314
};
282-
yield* guides.put(key, guide);
315+
// A newer run for this pull request, say after a push, owns its guide now; this one's result
316+
// is for an older head and is dropped rather than written over it.
317+
if (yield* owns) yield* guides.put(key, guide);
283318
});
284319

285320
/** What a reader is told when a run fails; the full cause goes to the log. */
@@ -338,18 +373,30 @@ const make = Effect.gen(function* () {
338373
});
339374
if (claimed !== running) return { guide: stored, run: claimed, currentHeadSha };
340375

341-
yield* write(input, key, workspaceRoot, detail, currentHeadSha).pipe(
342-
Effect.andThen(setRun(runKey, null)),
376+
// The run is identified by its own Running value: a later claim replaces it, and from then
377+
// on this run's completion leaves the newer run's state and guide alone.
378+
const owns = Ref.get(runs).pipe(Effect.map((current) => current.get(runKey) === running));
379+
const finish = (next: PullRequestReviewGuideRun | null) =>
380+
Ref.update(runs, (current) => {
381+
if (current.get(runKey) !== running) return current;
382+
const updated = new Map(current);
383+
if (next === null) updated.delete(runKey);
384+
else updated.set(runKey, next);
385+
return updated;
386+
});
387+
const runId = `${runCounter++}`;
388+
yield* write(input, key, workspaceRoot, detail, currentHeadSha, runId, owns).pipe(
389+
Effect.andThen(finish(null)),
343390
Effect.catchCause((cause) =>
344391
Cause.hasInterruptsOnly(cause)
345-
? setRun(runKey, null)
392+
? finish(null)
346393
: Effect.logWarning("Review guide generation failed", {
347394
key: runKey,
348395
cause: Cause.pretty(cause),
349396
}).pipe(
350397
Effect.andThen(nowIso),
351398
Effect.flatMap((failedAt) =>
352-
setRun(runKey, {
399+
finish({
353400
_tag: "Failed",
354401
headSha: currentHeadSha,
355402
failedAt,

‎apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,30 @@ const excerpt = (path: string, start: number, end: number, side: "new" | "old" =
5757
});
5858

5959
describe("parseReviewGuideChange", () => {
60+
it("reads a removed or added line that looks like a file header as a source line", () => {
61+
const tricky = [
62+
"diff --git a/notes.md b/notes.md",
63+
"--- a/notes.md",
64+
"+++ b/notes.md",
65+
"@@ -3,1 +3,2 @@",
66+
"--- a/old-heading",
67+
"+++ b/other.ts",
68+
"+tail",
69+
"@@ -9,0 +10,1 @@",
70+
"+later",
71+
"",
72+
].join("\n");
73+
const parsed = parseReviewGuideChange("notes.md\0", tricky);
74+
expect([...parsed.hunks.keys()]).toEqual(["notes.md"]);
75+
expect(parsed.hunks.get("notes.md")).toEqual({
76+
new: [
77+
{ start: 3, end: 4 },
78+
{ start: 10, end: 10 },
79+
],
80+
old: [{ start: 3, end: 3 }],
81+
});
82+
});
83+
6084
it("reads each side's hunks, keying a deleted file by its old path", () => {
6185
expect(change.files).toEqual(["src/a.ts", "src/gone.ts", "docs/readme.md"]);
6286
expect(change.hunks.get("src/a.ts")).toEqual({

‎apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,20 +38,24 @@ export function parseReviewGuideChange(nameOnly: string, patch: string): ReviewG
3838
const hunks = new Map<string, FileHunks>();
3939
let oldPath: string | null = null;
4040
let current: FileHunks | null = null;
41+
// Inside a file's hunks a `--- ` or `+++ ` line is a removed or added source line, not a header.
42+
let inHunks = false;
4143
for (const line of patch.split("\n")) {
4244
if (line.startsWith("diff --git ")) {
4345
oldPath = null;
4446
current = null;
45-
} else if (line.startsWith("--- ")) {
47+
inHunks = false;
48+
} else if (!inHunks && line.startsWith("--- ")) {
4649
oldPath = line.startsWith("--- a/") ? line.slice(6) : null;
47-
} else if (line.startsWith("+++ ")) {
50+
} else if (!inHunks && line.startsWith("+++ ")) {
4851
const path = line.startsWith("+++ b/") ? line.slice(6) : oldPath;
4952
if (path === null) continue;
5053
current = hunks.get(path) ?? { new: [], old: [] };
5154
hunks.set(path, current);
5255
} else if (current !== null) {
5356
const header = HUNK_HEADER.exec(line);
5457
if (header === null) continue;
58+
inHunks = true;
5559
const removed = hunkRange(header[1]!, header[2]);
5660
const added = hunkRange(header[3]!, header[4]);
5761
if (removed !== null) current.old.push(removed);

‎apps/server/src/textGeneration/ClaudeTextGeneration.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ const CLAUDE_INVESTIGATION_ALLOWED = [
5151
"Bash(git log:*)",
5252
"Bash(git show:*)",
5353
].join(",");
54+
/**
55+
* The allowed git commands accept any trailing arguments, and `--output` makes each of them write
56+
* a file anywhere. Deny rules win over allow rules, so this keeps the investigation read-only.
57+
*/
58+
const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(",");
5459

5560
/**
5661
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
@@ -209,6 +214,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
209214
CLAUDE_INVESTIGATION_TOOLS,
210215
"--allowedTools",
211216
CLAUDE_INVESTIGATION_ALLOWED,
217+
"--disallowedTools",
218+
CLAUDE_INVESTIGATION_DENIED,
212219
]
213220
: ["--tools", ""]),
214221
"--disable-slash-commands",

‎apps/web/src/components/pullRequest/PullRequestCodeTab.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -685,10 +685,14 @@ function PullRequestCodeTab({
685685
const answeredReveal = useRef<number | null>(null);
686686
useEffect(() => {
687687
if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
688-
if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) return;
688+
if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
689+
// The reader is not scrolling toward it, so the sentinel would never ask for its slice.
690+
if (canLoadNextSlice) loadNextSlice();
691+
return;
692+
}
689693
answeredReveal.current = revealRequest.nonce;
690694
revealFile(revealRequest.path);
691-
}, [items, revealFile, revealRequest]);
695+
}, [canLoadNextSlice, items, loadNextSlice, revealFile, revealRequest]);
692696

693697
const toggleAllFiles = () => {
694698
// Held as an override of the default rather than as the file keys on screen: a diff that is

0 commit comments

Comments
 (0)