Skip to content

Commit 87e941b

Browse files
author
James
committed
Implement CodeRabbit review integration
1 parent 7e47aec commit 87e941b

27 files changed

Lines changed: 3383 additions & 179 deletions

‎apps/server/src/coderabbit/Layers/CodeRabbitService.ts‎

Lines changed: 651 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import type {
2+
CodeRabbitCancelReviewInput,
3+
CodeRabbitGetReviewInput,
4+
CodeRabbitGetStatusInput,
5+
CodeRabbitReviewEvent,
6+
CodeRabbitReviewSnapshot,
7+
CodeRabbitReviewStatus,
8+
CodeRabbitRpcError,
9+
CodeRabbitStartReviewInput,
10+
CodeRabbitStartReviewResult,
11+
} from "@t3tools/contracts";
12+
import { ServiceMap } from "effect";
13+
import type { Effect, Stream } from "effect";
14+
15+
export interface CodeRabbitServiceShape {
16+
/**
17+
* Review lifecycle only. `fixWithAI` is intentionally handled in the WS/orchestration
18+
* bridge so this service stays focused on CodeRabbit subprocess state.
19+
*/
20+
readonly startReview: (
21+
input: CodeRabbitStartReviewInput,
22+
) => Effect.Effect<CodeRabbitStartReviewResult, CodeRabbitRpcError>;
23+
readonly cancelReview: (
24+
input: CodeRabbitCancelReviewInput,
25+
) => Effect.Effect<void, CodeRabbitRpcError>;
26+
readonly getStatus: (
27+
input: CodeRabbitGetStatusInput,
28+
) => Effect.Effect<CodeRabbitReviewStatus, CodeRabbitRpcError>;
29+
readonly getReview: (
30+
input: CodeRabbitGetReviewInput,
31+
) => Effect.Effect<CodeRabbitReviewSnapshot, CodeRabbitRpcError>;
32+
readonly streamReviewEvents: (
33+
input: CodeRabbitGetReviewInput,
34+
) => Stream.Stream<CodeRabbitReviewEvent, CodeRabbitRpcError>;
35+
}
36+
37+
export class CodeRabbitService extends ServiceMap.Service<
38+
CodeRabbitService,
39+
CodeRabbitServiceShape
40+
>()("t3/coderabbit/Services/CodeRabbitService") {}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"type":"status","phase":"auth","status":"authenticated","authenticated":true,"user":{"name":"James Cadena","email":"[email protected]","username":"james-a-cadena"},"provider":"github","currentOrg":{"id":"b84405ef-e644-4bec-8ce1-3425eb40ea26","name":"Cadena-Labs"},"organizations":[{"id":"b84405ef-e644-4bec-8ce1-3425eb40ea26","name":"Cadena-Labs"},{"id":"90351ccd-19a7-4813-8420-dd237e2770ed","name":"james-a-cadena"}]}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{"type":"review_context","reviewType":"all","currentBranch":"main","baseBranch":"main","workingDirectory":"/Users/james/dev/t3code"}
2+
{"type":"status","phase":"connecting","status":"connecting_to_review_service"}
3+
{"type":"status","phase":"setup","status":"setting_up"}
4+
{"type":"status","phase":"analyzing","status":"summarizing"}
5+
{"type":"status","phase":"analyzing","status":"reviewing"}
6+
{"type":"finding","severity":"trivial","fileName":"apps/server/src/coderabbit/Services/CodeRabbitService.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/coderabbit/Services/CodeRabbitService.ts around lines 15 - 31, The interface CodeRabbitServiceShape is missing the fixWithAI method present on NativeApi.coderabbit and the RPC surface; either add a fixWithAI entry to CodeRabbitServiceShape (matching the signature used by rpc.ts/NativeApi.coderabbit) or add a clear comment above CodeRabbitServiceShape explaining that fixWithAI is intentionally handled externally via dispatchCodeRabbitFixWithAI (and therefore excluded). Update the interface to include the method name and matching effect/stream types if you choose the stub approach, or add the explanatory comment referencing dispatchCodeRabbitFixWithAI and the RPC symbol names to keep intent clear and consistent.","suggestions":[]}
7+
{"type":"finding","severity":"trivial","fileName":"apps/server/src/ws.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/ws.ts around lines 139 - 180, The buildCodeRabbitFixPrompt function is embedding user-controlled fields (e.g., input.snapshot.cwd, input.snapshot.scope, finding.filePath, finding.summary, finding.suggestions, finding.codegenInstructions) directly into the prompt; sanitize or escape those values before concatenation to prevent parsing issues (for example normalize or escape newlines, backticks, and other control characters or wrap values with a safe encoding like JSON.stringify) while keeping the existing prompt shape and the findingSections logic intact; update the map that builds findingSections to run each user field through a single helper sanitizer (e.g., sanitizePromptValue) and use the sanitized values for location, suggestions, summary, id, and codegenInstructions, and also sanitize snapshot fields when embedding them.","suggestions":[]}
8+
{"type":"finding","severity":"trivial","fileName":"packages/contracts/src/coderabbit.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @packages/contracts/src/coderabbit.ts around lines 42 - 45, The CodeRabbitFindingLineRange schema currently allows any positive start and end independently; add a refinement/validation to ensure start <= end by wrapping or extending the existing Schema.Struct({ start: PositiveInt, end: PositiveInt }) with a check that compares the two fields and rejects (or throws) if start > end so the invariant is enforced whenever CodeRabbitFindingLineRange is parsed/validated.","suggestions":["const CodeRabbitFindingLineRange = Schema.Struct({\n start: PositiveInt,\n end: PositiveInt,\n}).pipe(\n Schema.filter((range) => range.start <= range.end, {\n message: () => \"Line range start must be less than or equal to end\",\n }),\n);"]}
9+
{"type":"finding","severity":"minor","fileName":"apps/server/src/ws.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/ws.ts around lines 484 - 503, The thread creation is not rolled back if the subsequent turn start fails; update the logic around dispatchNormalizedCommand({... type: \"thread.create\", ...}) and the follow-up dispatchNormalizedCommand({... type: \"thread.turn.start\", ...}) so that if the turn start call rejects/errors you perform a compensating cleanup (dispatch a \"thread.delete\" or \"thread.terminate\" command using the same threadId via serverCommandId(\"coderabbit-thread-delete\") or similar) and surface the original turn-start error; locate the create call and wrap the turn start in a try/catch or Effect.chain error handler that on failure runs a dispatchNormalizedCommand for deletion (mapping errors with toCodeRabbitRpcError consistent with existing mapError usage) before rethrowing the turn-start failure.","suggestions":[]}
10+
{"type":"finding","severity":"trivial","fileName":"apps/server/src/coderabbit/Layers/CodeRabbitService.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/coderabbit/Layers/CodeRabbitService.ts around lines 369 - 381, The attachLineReader currently calls void onLine(line) which launches line handlers fire-and-forget and can process lines out of order; change the listener to ensure sequential handling by awaiting each onLine call (make the \"line\" event handler async and await onLine(line)) or implement a simple per-stream queue/promise-chain (e.g., track lastPromise and chain lastPromise = lastPromise.then(()=>onLine(line))) so each line is fully processed before the next begins; update attachLineReader and any callers relying on onLine to accommodate the awaited behavior (function attachLineReader, the onLine callback reference).","suggestions":[]}
11+
{"type":"finding","severity":"trivial","fileName":"apps/server/src/coderabbit/parser.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/coderabbit/parser.ts around lines 179 - 214, In parseCodeRabbitFinding, normalizeSeverity(raw.severity) is called twice—once for createCodeRabbitFindingId and again when constructing the finding object; compute const normalizedSeverity = normalizeSeverity(raw.severity) once near the top (before calling createCodeRabbitFindingId) and use normalizedSeverity in both createCodeRabbitFindingId(...) and the finding.severity field to avoid redundant computation.","suggestions":[]}
12+
{"type":"finding","severity":"trivial","fileName":"apps/server/src/coderabbit/Layers/CodeRabbitService.ts","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @apps/server/src/coderabbit/Layers/CodeRabbitService.ts around lines 582 - 589, The cleanup in the Effect.catchAll unintentionally deletes a newer review entry for the same cwd; modify the handler so that before calling latestReviewIdByCwd.delete(input.cwd) you check that latestReviewIdByCwd.get(input.cwd) === reviewId (i.e., only remove if the stored latest ID still matches the failed reviewId), keep closing via closeActiveReviewForCwd(record) and removing from recordsById as-is, and apply the same guarded check if you ever set or clear related state elsewhere to avoid the race.","suggestions":[]}
13+
{"type":"complete","status":"review_completed","findings":7}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
{"type":"review_context","reviewType":"committed","currentBranch":"main","baseBranch":"main","workingDirectory":"/Users/james/dev/t3code"}
2+
{"type":"error","errorType":"review","message":"Review failed: No files found for review","recoverable":false,"details":{}}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{"type":"review_context","reviewType":"uncommitted","currentBranch":"main","baseBranch":"main","workingDirectory":"/Users/james/dev/t3code"}
2+
{"type":"status","phase":"connecting","status":"connecting_to_review_service"}
3+
{"type":"status","phase":"setup","status":"setting_up"}
4+
{"type":"status","phase":"analyzing","status":"summarizing"}
5+
{"type":"status","phase":"analyzing","status":"reviewing"}
6+
{"type":"finding","severity":"trivial","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md around lines 351 - 353, Add an explicit enumeration of terminal thread states to the spec (e.g., TerminalThreadState = { completed, error, cancelled, timed_out }) and reference it in the \"track file-group or request-level fix sessions\" and \"UI should count\" sections so implementers know which states increment the progress total; also clarify that only a subsequent review-rerun that passes transitions a session from terminal-but-not-fixed into \"fixed\" status to be counted as resolved.","suggestions":[]}
7+
{"type":"finding","severity":"trivial","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md around lines 118 - 147, Add explicit schema examples or an implementation task note for the normalized model: provide a short TypeScript/Zod example (or state as a required follow-up) for each symbol listed (CodeRabbitReviewScope, CodeRabbitReviewPhase, CodeRabbitFindingSeverity, CodeRabbitFindingLocation, CodeRabbitFinding, CodeRabbitReviewSnapshot) that clarifies which fields are required vs optional, expected types (e.g., date strings vs Date), and validation constraints; alternatively add a clear \"Implementation tasks\" bullet in the file inventory requiring creation of concrete TypeScript/Zod schemas and validation rules for those exact symbols so implementers know to enforce nullability and type constraints.","suggestions":[]}
8+
{"type":"finding","severity":"trivial","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md at line 192, Add a short design note or separate mini-spec that explains how to upgrade the current WebSocket RPC helper (wsRpcClient.ts) to support parameterized stream subscriptions: describe extending the subscribe API to accept an input payload type and correlation id, how to encode/decode payloads on send/receive, how the client should open/close streams (e.g., subscribe/unsubscribe messages with id), and how the server should route messages back to the matching subscription id; include the concrete function signatures to change (e.g., subscribe -> subscribe<TInput, TOutput>(input: TInput, onMessage: (msg: TOutput) => void): Subscription) and note required server-side contract changes and error/timeout handling as a prerequisite task before landing the integration.","suggestions":[]}
9+
{"type":"finding","severity":"trivial","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md at line 166, Document the exact pinned CodeRabbit CLI version and upgrade policy: add a concrete version identifier (e.g., \"CodeRabbit CLI vX.Y.Z\") wherever the spec mentions \"pinned CodeRabbit CLI version\" (search for that phrase) and record it in the project metadata (README, package.json under \"engines\" or \"devDependencies\", and CI config used for builds/tests); explicitly state the upgrade strategy and parser compatibility policy (strict pin vs acceptable semver range, rollback/testing steps, and who approves upgrades) so the schema derivation step (from captured CLI fixtures) always targets a reproducible CLI binary and outlines how/when to update that binary and regenerate fixtures.","suggestions":[]}
10+
{"type":"finding","severity":"major","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md at line 46, The document docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md contains user-specific absolute paths (e.g., /Users/james/dev/t3code/apps/web/src/routes/_chat.$threadId.tsx); update every absolute path occurrence to repository-relative paths such as apps/web/src/routes/_chat.$threadId.tsx (also fix the other listed occurrences referencing the same user-rooted prefix at the indicated spots) so all file references are project-root-relative and portable for other developers and CI.","suggestions":[]}
11+
{"type":"finding","severity":"trivial","fileName":"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md","codegenInstructions":"Verify each finding against the current code and only fix it if needed.\n\nIn @docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md around lines 76 - 78, The spec's \"Allow at most one active review per project `cwd`\" rule needs explicit review replacement semantics: update the document to define whether startReview for a `cwd` performs cancelReview on the existing active review before or after creating the new review, specify a cancellation timeout and retry/backoff behavior if cancelReview fails, mandate an atomic replacement strategy (e.g., compare-and-swap or leader-election) to prevent races when two clients call startReview concurrently for the same `cwd`, and state whether a transient \"replacing\" transition state is allowed (both exist briefly) or must be prevented; reference the entities \"startReview\", \"cancelReview\", \"active review\", \"review snapshot\", and \"cwd\" in the spec so implementers can follow exact ordering, error handling, and concurrency guarantees.","suggestions":[]}
12+
{"type":"complete","status":"review_completed","findings":6}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { readFileSync } from "node:fs";
2+
import { describe, expect, it } from "vitest";
3+
4+
import { parseCodeRabbitAuthStatusOutput, parseCodeRabbitCliLine } from "./parser";
5+
6+
function readFixture(name: string) {
7+
return readFileSync(new URL(`./__fixtures__/${name}`, import.meta.url), "utf8");
8+
}
9+
10+
describe("CodeRabbit parser", () => {
11+
it("parses auth status fixtures", () => {
12+
const result = parseCodeRabbitAuthStatusOutput(readFixture("auth-status.ndjson"));
13+
14+
expect(result).toEqual({
15+
authenticated: true,
16+
rawStatus: "authenticated",
17+
});
18+
});
19+
20+
it("parses uncommitted review fixtures", () => {
21+
const events = readFixture("review-uncommitted.ndjson")
22+
.trim()
23+
.split("\n")
24+
.map((line) => parseCodeRabbitCliLine(line));
25+
26+
expect(events.map((event) => event?.kind)).toEqual([
27+
"review_context",
28+
"status",
29+
"status",
30+
"status",
31+
"status",
32+
"finding",
33+
"finding",
34+
"finding",
35+
"finding",
36+
"finding",
37+
"finding",
38+
"complete",
39+
]);
40+
41+
const firstFinding = events.find((event) => event?.kind === "finding");
42+
expect(firstFinding?.kind).toBe("finding");
43+
if (firstFinding?.kind === "finding") {
44+
expect(firstFinding.finding.filePath).toBe(
45+
"docs/superpowers/specs/2026-04-05-coderabbit-integration-design.md",
46+
);
47+
expect(firstFinding.finding.location.type).toBe("file");
48+
expect(firstFinding.finding.summary).toContain("TerminalThreadState");
49+
}
50+
});
51+
52+
it("parses committed review fixture errors", () => {
53+
const events = readFixture("review-committed.ndjson")
54+
.trim()
55+
.split("\n")
56+
.map((line) => parseCodeRabbitCliLine(line));
57+
58+
expect(events.map((event) => event?.kind)).toEqual(["review_context", "error"]);
59+
expect(events[1]).toMatchObject({
60+
kind: "error",
61+
message: "Review failed: No files found for review",
62+
});
63+
});
64+
});

0 commit comments

Comments
 (0)