Add Review Sweep: one-click agentic review of unsettled work

Adds a sidebar-v2 button that reviews every unsettled thread across all
connected environments: an LLM summarizes each thread, suggests a
corrected title when the current one is misleading, and recommends
settling threads whose work has concluded. Results stream into a new
/review-sweep page with per-item Apply buttons and Apply All — nothing
applies without a click.

- contracts: ReviewThreadSummaryInput/Result, review.summarizeThread WS
  RPC, reviewSweep capability flag (old servers are skipped)
- server: generateThreadReview TextGeneration op across all five
  providers, conservative prompt with transcript capping, and
  ReviewService.summarizeThread reading the projection
- client-runtime: summarizeThread RPC command atom
- web: reviewSweepStore runner (concurrency 3, runId-guarded, survives
  navigation), /review-sweep view, SidebarV2 entry button

Settle recommendations are blocked for active threads at four layers:
prompt rules, normalizeThreadReview, a server-side projection re-check
(never trusts the client's canSettleNow), and a client canSettle
re-check at apply time.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 19:24:05 -07:00
1 parent 67a7b1a1d3
commit f8aa8450d1
26 files changed
+1457 -13

No files matched your search

@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
reviewSweep: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
+1
View File
@@ -365,6 +365,7 @@ function createTextGeneration(
}),
),
),
generateThreadReview: () => Effect.die("generateThreadReview is not used by GitManager tests"),
};
}
@@ -3,17 +3,59 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import {
ThreadId,
type OrchestrationThread,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as ReviewService from "./ReviewService.ts";
function makeShellFromThread(
thread: OrchestrationThread,
overrides: Partial<OrchestrationThreadShell> = {},
): OrchestrationThreadShell {
return {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
branch: thread.branch,
worktreePath: thread.worktreePath,
latestTurn: thread.latestTurn,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
session: thread.session,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...overrides,
};
}
function makeLayer(input: {
readonly workspaceRoot: string;
readonly baseDir: string;
readonly detectCalls?: Array<{ readonly cwd: string }>;
readonly thread?: OrchestrationThread;
readonly shellOverrides?: Partial<OrchestrationThreadShell>;
readonly generateThreadReview?: TextGeneration.TextGeneration["Service"]["generateThreadReview"];
readonly reviewCalls?: Array<TextGeneration.ThreadReviewGenerationInput>;
}) {
return ReviewService.layer.pipe(
Layer.provide(
@@ -28,11 +70,92 @@ function makeLayer(input: {
}),
),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
Layer.provide(
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
getThreadDetailById: (threadId) =>
Effect.succeed(
input.thread && input.thread.id === threadId
? Option.some(input.thread)
: Option.none(),
),
getThreadShellById: (threadId) =>
Effect.succeed(
input.thread && input.thread.id === threadId
? Option.some(makeShellFromThread(input.thread, input.shellOverrides))
: Option.none(),
),
getProjectShellById: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
Layer.mock(TextGeneration.TextGeneration)({
generateThreadReview: (reviewInput) => {
input.reviewCalls?.push(reviewInput);
return (
input.generateThreadReview?.(reviewInput) ??
Effect.succeed({
summary: "Did the thing.",
suggestedTitle: null,
recommendSettle: true,
settleReason: "Work concluded.",
})
);
},
}),
),
Layer.provide(ServerSettings.layerTest()),
Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)),
Layer.provideMerge(NodeServices.layer),
);
}
function makeThread(overrides: Partial<OrchestrationThread> = {}): OrchestrationThread {
return {
id: ThreadId.make("thread_review_1"),
projectId: "project_1" as OrchestrationThread["projectId"],
title: "New thread",
modelSelection: {
instanceId: "codex" as OrchestrationThread["modelSelection"]["instanceId"],
model: "gpt-5",
options: [],
},
runtimeMode: "local",
interactionMode: "chat",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-07-20T00:00:00.000Z",
updatedAt: "2026-07-20T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
...overrides,
} as OrchestrationThread;
}
function makeMessage(input: {
readonly id: string;
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly streaming?: boolean;
}): OrchestrationThread["messages"][number] {
return {
id: input.id as OrchestrationThread["messages"][number]["id"],
role: input.role,
text: input.text,
turnId: null,
streaming: input.streaming ?? false,
createdAt: "2026-07-20T00:00:00.000Z",
updatedAt: "2026-07-20T00:00:00.000Z",
};
}
describe("ReviewService", () => {
it.effect("rejects diff preview cwd outside the configured workspace roots", () =>
Effect.gen(function* () {
@@ -97,4 +220,153 @@ describe("ReviewService", () => {
assert.deepStrictEqual(detectCalls, []);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("summarizeThread fails with ReviewThreadNotFoundError for unknown threads", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const error = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
return yield* review
.summarizeThread({ threadId: ThreadId.make("thread_missing"), canSettleNow: true })
.pipe(Effect.flip);
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir })));
assert.strictEqual(error._tag, "ReviewThreadNotFoundError");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("summarizeThread passes transcript context and returns the review", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
const thread = makeThread({
messages: [
makeMessage({ id: "msg_1", role: "user", text: "Fix the settle default" }),
makeMessage({ id: "msg_2", role: "assistant", text: "Done, merged in PR #1" }),
makeMessage({ id: "msg_3", role: "assistant", text: "streaming...", streaming: true }),
],
});
const result = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
}).pipe(
Effect.provide(
makeLayer({
workspaceRoot,
baseDir,
thread,
reviewCalls,
generateThreadReview: () =>
Effect.succeed({
summary: "Bumped the settle default; PR merged.",
suggestedTitle: "Bump settle default",
recommendSettle: true,
settleReason: "PR merged, nothing pending.",
}),
}),
),
);
assert.strictEqual(result.threadId, thread.id);
assert.strictEqual(result.summary, "Bumped the settle default; PR merged.");
assert.strictEqual(result.suggestedTitle, "Bump settle default");
assert.strictEqual(result.recommendSettle, true);
assert.strictEqual(result.settleReason, "PR merged, nothing pending.");
assert.strictEqual(reviewCalls.length, 1);
const call = reviewCalls[0]!;
assert.strictEqual(call.title, "New thread");
assert.strictEqual(call.isActive, false);
assert.strictEqual(call.firstUserMessage, "Fix the settle default");
// Streaming messages are excluded from the transcript.
assert.deepStrictEqual(
call.recentMessages.map((message) => message.text),
["Fix the settle default", "Done, merged in PR #1"],
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("summarizeThread never recommends settling when canSettleNow is false", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
const thread = makeThread({});
const result = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: false });
}).pipe(
Effect.provide(
makeLayer({
workspaceRoot,
baseDir,
thread,
reviewCalls,
// Model misbehaves and recommends settle anyway.
generateThreadReview: () =>
Effect.succeed({
summary: "Still working.",
suggestedTitle: null,
recommendSettle: true,
settleReason: "Looks done to me.",
}),
}),
),
);
assert.strictEqual(reviewCalls[0]?.isActive, true);
assert.strictEqual(result.recommendSettle, false);
assert.strictEqual(result.settleReason, null);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect(
"summarizeThread overrides a stale client canSettleNow when the projection shows activity",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({
prefix: "t3-review-workspace-",
});
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
const thread = makeThread({});
const result = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
// Client believed the thread was settleable, but the server-side
// shell says approvals are pending.
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
}).pipe(
Effect.provide(
makeLayer({
workspaceRoot,
baseDir,
thread,
reviewCalls,
shellOverrides: { hasPendingApprovals: true },
generateThreadReview: () =>
Effect.succeed({
summary: "Looks finished.",
suggestedTitle: null,
recommendSettle: true,
settleReason: "Done.",
}),
}),
),
);
assert.strictEqual(reviewCalls[0]?.isActive, true);
assert.strictEqual(result.recommendSettle, false);
assert.strictEqual(result.settleReason, null);
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+98
View File
@@ -3,17 +3,27 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import {
ReviewThreadNotFoundError,
TextGenerationError,
VcsRepositoryDetectionError,
VcsUnsupportedOperationError,
type ReviewDiffPreviewError,
type ReviewDiffPreviewInput,
type ReviewDiffPreviewResult,
type ReviewThreadSummaryError,
type ReviewThreadSummaryInput,
type ReviewThreadSummaryResult,
} from "@t3tools/contracts";
import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -23,6 +33,9 @@ export class ReviewService extends Context.Service<
readonly getDiffPreview: (
input: ReviewDiffPreviewInput,
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
readonly summarizeThread: (
input: ReviewThreadSummaryInput,
) => Effect.Effect<ReviewThreadSummaryResult, ReviewThreadSummaryError>;
}
>()("t3/review/ReviewService") {}
@@ -32,6 +45,9 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const git = yield* GitVcsDriver.GitVcsDriver;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const textGeneration = yield* TextGeneration.TextGeneration;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const canonicalizePath = (value: string) => {
const resolvedPath = path.resolve(value);
@@ -106,8 +122,90 @@ export const make = Effect.gen(function* () {
return yield* getDriverDiffPreview(input);
});
const summarizeThread: ReviewService["Service"]["summarizeThread"] = Effect.fn(
"ReviewService.summarizeThread",
)(function* (input) {
const mapProjectionError = (cause: unknown) =>
new TextGenerationError({
operation: "generateThreadReview",
detail: "Failed to read the thread projection for review.",
cause,
});
const threadOption = yield* projectionSnapshotQuery
.getThreadDetailById(input.threadId)
.pipe(Effect.mapError(mapProjectionError));
if (Option.isNone(threadOption)) {
return yield* new ReviewThreadNotFoundError({ threadId: input.threadId });
}
const thread = threadOption.value;
const projectOption = yield* projectionSnapshotQuery
.getProjectShellById(thread.projectId)
.pipe(Effect.mapError(mapProjectionError));
const cwd =
resolveThreadWorkspaceCwd({
thread,
projects: Option.isSome(projectOption) ? [projectOption.value] : [],
}) ?? process.cwd();
const settled = thread.messages.filter((message) => !message.streaming);
const firstUserMessage = settled.find((message) => message.role === "user")?.text ?? null;
const recentMessages = settled.map((message) => ({
role: message.role,
text: message.text,
}));
// Never trust the client's canSettleNow alone: re-derive activity from the
// server's own projection so a session that started (or approval/input
// that appeared) after the client read its shell still blocks settling.
const shellOption = yield* projectionSnapshotQuery
.getThreadShellById(input.threadId)
.pipe(Effect.mapError(mapProjectionError));
const shell = Option.isSome(shellOption) ? shellOption.value : null;
const serverSideActive =
shell === null ||
shell.hasPendingApprovals ||
shell.hasPendingUserInput ||
shell.session?.status === "starting" ||
shell.session?.status === "running";
const canSettleNow = input.canSettleNow && !serverSideActive;
const isActive = !canSettleNow;
const { textGenerationModelSelection: modelSelection } = yield* serverSettings.getSettings.pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: "generateThreadReview",
detail: "Failed to load server settings for review generation.",
cause,
}),
),
);
const generated = yield* textGeneration.generateThreadReview({
cwd,
title: thread.title,
isActive,
firstUserMessage,
recentMessages,
modelSelection,
});
// Belt and braces on top of prompt rules + normalizeThreadReview: an
// active thread must never carry a settle recommendation.
const recommendSettle = generated.recommendSettle && canSettleNow;
return {
threadId: input.threadId,
summary: generated.summary,
suggestedTitle: generated.suggestedTitle,
recommendSettle,
settleReason: recommendSettle ? generated.settleReason : null,
};
});
return ReviewService.of({
getDiffPreview,
summarizeThread,
});
});
+14
View File
@@ -87,6 +87,7 @@ import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/provid
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
@@ -522,6 +523,19 @@ const buildAppUnderTest = (options?: {
: ReviewService.layer.pipe(
Layer.provideMerge(gitVcsDriverLayer),
Layer.provide(vcsDriverRegistryLayer),
Layer.provide(
Layer.mock(TextGeneration.TextGeneration)({
generateThreadReview: () => Effect.die("TextGeneration not stubbed in this test"),
}),
),
Layer.provide(
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
getThreadDetailById: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
...options?.layers?.projectionSnapshotQuery,
}),
),
Layer.provide(ServerSettings.layerTest()),
);
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
+1
View File
@@ -222,6 +222,7 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
const ReviewLayerLive = ReviewService.layer.pipe(
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provide(TextGeneration.layer),
);
const VcsLayerLive = Layer.empty.pipe(
@@ -23,10 +23,12 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
normalizeThreadReview,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -85,7 +87,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
| "generateThreadTitle"
| "generateThreadReview",
value: unknown,
detail: string,
): Effect.Effect<string, TextGenerationError> =>
@@ -115,7 +118,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -355,10 +359,31 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
};
});
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
Effect.fn("ClaudeTextGeneration.generateThreadReview")(function* (input) {
const { prompt, outputSchema } = buildThreadReviewPrompt({
title: input.title,
isActive: input.isActive,
firstUserMessage: input.firstUserMessage,
recentMessages: input.recentMessages,
});
const generated = yield* runClaudeJson({
operation: "generateThreadReview",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return normalizeThreadReview(generated, input.isActive);
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
generateThreadReview,
} satisfies TextGeneration.TextGeneration["Service"];
});
@@ -21,10 +21,12 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
normalizeThreadReview,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -98,7 +100,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
| "generateThreadTitle"
| "generateThreadReview",
value: unknown,
): Effect.Effect<string, TextGenerationError> =>
encodeJsonString(value).pipe(
@@ -117,7 +120,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
| "generateThreadTitle"
| "generateThreadReview",
attachments: TextGeneration.BranchNameGenerationInput["attachments"],
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
if (!attachments || attachments.length === 0) {
@@ -159,7 +163,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -398,10 +403,32 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
} satisfies TextGeneration.ThreadTitleGenerationResult;
});
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
Effect.fn("CodexTextGeneration.generateThreadReview")(function* (input) {
const { prompt, outputSchema } = buildThreadReviewPrompt({
title: input.title,
isActive: input.isActive,
firstUserMessage: input.firstUserMessage,
recentMessages: input.recentMessages,
});
const generated = yield* runCodexJson({
operation: "generateThreadReview",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths: [],
modelSelection: input.modelSelection,
});
return normalizeThreadReview(generated, input.isActive);
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
generateThreadReview,
} satisfies TextGeneration.TextGeneration["Service"];
});
@@ -15,9 +15,11 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
normalizeThreadReview,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -54,7 +56,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -255,10 +258,31 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
} satisfies TextGeneration.ThreadTitleGenerationResult;
});
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
Effect.fn("CursorTextGeneration.generateThreadReview")(function* (input) {
const { prompt, outputSchema } = buildThreadReviewPrompt({
title: input.title,
isActive: input.isActive,
firstUserMessage: input.firstUserMessage,
recentMessages: input.recentMessages,
});
const generated = yield* runCursorJson({
operation: "generateThreadReview",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return normalizeThreadReview(generated, input.isActive);
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
generateThreadReview,
} satisfies TextGeneration.TextGeneration["Service"];
});
@@ -16,9 +16,11 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
normalizeThreadReview,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -52,7 +54,8 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -247,10 +250,31 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
} satisfies TextGeneration.ThreadTitleGenerationResult;
});
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
Effect.fn("GrokTextGeneration.generateThreadReview")(function* (input) {
const { prompt, outputSchema } = buildThreadReviewPrompt({
title: input.title,
isActive: input.isActive,
firstUserMessage: input.firstUserMessage,
recentMessages: input.recentMessages,
});
const generated = yield* runGrokJson({
operation: "generateThreadReview",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return normalizeThreadReview(generated, input.isActive);
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
generateThreadReview,
} satisfies TextGeneration.TextGeneration["Service"];
});
@@ -22,10 +22,12 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import * as TextGeneration from "./TextGeneration.ts";
import {
normalizeThreadReview,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -39,6 +41,7 @@ const OpenCodeTextGenerationOperation = Schema.Literals([
"generatePrContent",
"generateBranchName",
"generateThreadTitle",
"generateThreadReview",
]);
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
@@ -253,7 +256,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
}) =>
sharedServerMutex.withPermit(
Effect.gen(function* () {
@@ -611,10 +615,31 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
};
});
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
Effect.fn("OpenCodeTextGeneration.generateThreadReview")(function* (input) {
const { prompt, outputSchema } = buildThreadReviewPrompt({
title: input.title,
isActive: input.isActive,
firstUserMessage: input.firstUserMessage,
recentMessages: input.recentMessages,
});
const generated = yield* runOpenCodeJson({
operation: "generateThreadReview",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return normalizeThreadReview(generated, input.isActive);
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
generateThreadReview,
} satisfies TextGeneration.TextGeneration["Service"];
});
@@ -21,6 +21,8 @@ const makeStubTextGeneration = (
generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),
generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),
generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),
generateThreadReview: () =>
Effect.die("generateThreadReview stub not configured for this test"),
...overrides,
});
@@ -67,6 +67,26 @@ export interface ThreadTitleGenerationResult {
title: string;
}
export interface ThreadReviewGenerationInput {
cwd: string;
title: string;
/** Active threads (running session or awaiting the user) never get a settle
recommendation. */
isActive: boolean;
firstUserMessage: string | null;
recentMessages: ReadonlyArray<{ role: "user" | "assistant" | "system"; text: string }>;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface ThreadReviewGenerationResult {
summary: string;
/** Null when the current title is still accurate. */
suggestedTitle: string | null;
recommendSettle: boolean;
settleReason: string | null;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
@@ -74,6 +94,7 @@ export interface TextGenerationService {
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
generateThreadReview(input: ThreadReviewGenerationInput): Promise<ThreadReviewGenerationResult>;
}
/**
@@ -109,6 +130,14 @@ export class TextGeneration extends Context.Service<
readonly generateThreadTitle: (
input: ThreadTitleGenerationInput,
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
/**
* Review a thread transcript for the work-review sweep: summary,
* optional corrected title, and a settle recommendation.
*/
readonly generateThreadReview: (
input: ThreadReviewGenerationInput,
) => Effect.Effect<ThreadReviewGenerationResult, TextGenerationError>;
}
>()("t3/textGeneration/TextGeneration") {}
@@ -119,7 +148,8 @@ type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
| "generateThreadTitle"
| "generateThreadReview";
const resolveInstance = (
registry: ProviderInstanceRegistry.ProviderInstanceRegistry["Service"],
@@ -159,6 +189,10 @@ export const makeTextGenerationFromRegistry = (
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
),
generateThreadReview: (input) =>
resolveInstance(registry, "generateThreadReview", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateThreadReview(input)),
),
});
export const make = Effect.gen(function* () {
@@ -4,9 +4,14 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadReviewPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import {
normalizeCliError,
normalizeThreadReview,
sanitizeThreadTitle,
} from "./TextGenerationUtils.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
@@ -136,6 +141,89 @@ describe("buildThreadTitlePrompt", () => {
});
});
describe("buildThreadReviewPrompt", () => {
it("includes title, first user message, and transcript", () => {
const result = buildThreadReviewPrompt({
title: "New thread",
isActive: false,
firstUserMessage: "Fix the settle default",
recentMessages: [
{ role: "user", text: "Fix the settle default" },
{ role: "assistant", text: "Done, merged." },
],
});
expect(result.prompt).toContain("Current title: New thread");
expect(result.prompt).toContain("Fix the settle default");
expect(result.prompt).toContain("[assistant] Done, merged.");
expect(result.prompt).not.toContain("ACTIVE");
});
it("adds the never-settle rule for active threads", () => {
const result = buildThreadReviewPrompt({
title: "Working thread",
isActive: true,
firstUserMessage: "Do a thing",
recentMessages: [],
});
expect(result.prompt).toContain("recommendSettle must be false");
expect(result.prompt).toContain("(no messages)");
});
it("caps the transcript to the most recent 20 messages", () => {
const result = buildThreadReviewPrompt({
title: "Long thread",
isActive: false,
firstUserMessage: "start",
recentMessages: Array.from({ length: 30 }, (_, index) => ({
role: "assistant" as const,
text: `message-${index}`,
})),
});
expect(result.prompt).not.toContain("message-9\n");
expect(result.prompt).toContain("message-10");
expect(result.prompt).toContain("message-29");
});
});
describe("normalizeThreadReview", () => {
const raw = {
summary: " Work finished. ",
suggestedTitle: '"Ship settle default"',
recommendSettle: true,
settleReason: " PR merged. ",
};
it("sanitizes fields and keeps settle recommendation for inactive threads", () => {
expect(normalizeThreadReview(raw, false)).toEqual({
summary: "Work finished.",
suggestedTitle: "Ship settle default",
recommendSettle: true,
settleReason: "PR merged.",
});
});
it("forces recommendSettle off for active threads even if the model says settle", () => {
const result = normalizeThreadReview(raw, true);
expect(result.recommendSettle).toBe(false);
expect(result.settleReason).toBeNull();
});
it("drops empty and placeholder title suggestions", () => {
expect(
normalizeThreadReview({ ...raw, suggestedTitle: " " }, false).suggestedTitle,
).toBeNull();
expect(
normalizeThreadReview({ ...raw, suggestedTitle: "New thread" }, false).suggestedTitle,
).toBeNull();
expect(
normalizeThreadReview({ ...raw, suggestedTitle: null }, false).suggestedTitle,
).toBeNull();
});
});
describe("sanitizeThreadTitle", () => {
it("truncates long titles with the shared sidebar-safe limit", () => {
expect(
@@ -216,3 +216,67 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
return { prompt, outputSchema };
}
// ---------------------------------------------------------------------------
// Thread review (work-review sweep)
// ---------------------------------------------------------------------------
export interface ThreadReviewMessage {
role: "user" | "assistant" | "system";
text: string;
}
export interface ThreadReviewPromptInput {
title: string;
/** True when the thread has a running session or pending approvals/input.
Active threads must never get a settle recommendation. */
isActive: boolean;
firstUserMessage: string | null;
recentMessages: ReadonlyArray<ThreadReviewMessage>;
}
const THREAD_REVIEW_RECENT_MESSAGE_COUNT = 20;
const THREAD_REVIEW_MESSAGE_CHAR_LIMIT = 2_000;
export function buildThreadReviewPrompt(input: ThreadReviewPromptInput) {
const recent = input.recentMessages.slice(-THREAD_REVIEW_RECENT_MESSAGE_COUNT);
const transcript = recent
.map(
(message) =>
`[${message.role}] ${limitSection(message.text, THREAD_REVIEW_MESSAGE_CHAR_LIMIT)}`,
)
.join("\n\n");
const prompt = [
"You review a coding-agent conversation thread and report its state.",
"Return a JSON object with keys: summary, suggestedTitle, recommendSettle, settleReason.",
"Rules:",
"- summary: 1-2 sentences covering what was asked and where the work landed",
"- suggestedTitle: a corrected 3-8 word title ONLY if the current title is misleading or a placeholder like 'New thread'; otherwise null",
"- recommendSettle: true ONLY when the work clearly concluded (done, abandoned, or superseded) and nothing awaits the user",
"- settleReason: one short sentence justifying recommendSettle, or null when recommendSettle is false",
"- be conservative: when in doubt, do not suggest a title change and do not recommend settling",
...(input.isActive
? [
"- this thread is still ACTIVE (running or awaiting the user): recommendSettle must be false",
]
: []),
"",
`Current title: ${input.title}`,
"",
"First user message:",
limitSection(input.firstUserMessage ?? "(none)", THREAD_REVIEW_MESSAGE_CHAR_LIMIT),
"",
`Most recent messages (up to ${THREAD_REVIEW_RECENT_MESSAGE_COUNT}):`,
limitSection(transcript.length > 0 ? transcript : "(no messages)", 24_000),
].join("\n");
const outputSchema = Schema.Struct({
summary: Schema.String,
suggestedTitle: Schema.NullOr(Schema.String),
recommendSettle: Schema.Boolean,
settleReason: Schema.NullOr(Schema.String),
});
return { prompt, outputSchema };
}
@@ -63,6 +63,43 @@ export function sanitizeThreadTitle(raw: string): string {
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/**
* Normalise a raw thread-review generation into the service result shape:
* collapse whitespace, drop empty/no-op title suggestions, and force
* `recommendSettle` off for active threads regardless of model output.
*/
export function normalizeThreadReview(
raw: {
summary: string;
suggestedTitle: string | null;
recommendSettle: boolean;
settleReason: string | null;
},
isActive: boolean,
): {
summary: string;
suggestedTitle: string | null;
recommendSettle: boolean;
settleReason: string | null;
} {
const summary = raw.summary.trim().replace(/\s+/g, " ");
const suggestedTitle =
raw.suggestedTitle && raw.suggestedTitle.trim().length > 0
? sanitizeThreadTitle(raw.suggestedTitle)
: null;
const recommendSettle = raw.recommendSettle && !isActive;
const settleReason =
recommendSettle && raw.settleReason && raw.settleReason.trim().length > 0
? raw.settleReason.trim().replace(/\s+/g, " ")
: null;
return {
summary: summary.length > 0 ? summary : "No summary available.",
suggestedTitle: suggestedTitle === "New thread" ? null : suggestedTitle,
recommendSettle,
settleReason,
};
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
+5
View File
@@ -332,6 +332,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],
[WS_METHODS.vcsInit, AuthOrchestrationOperateScope],
[WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope],
[WS_METHODS.reviewSummarizeThread, AuthReviewWriteScope],
[WS_METHODS.terminalOpen, AuthTerminalOperateScope],
[WS_METHODS.terminalAttach, AuthTerminalOperateScope],
[WS_METHODS.terminalWrite, AuthTerminalOperateScope],
@@ -1852,6 +1853,10 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
"rpc.aggregate": "review",
}),
[WS_METHODS.reviewSummarizeThread]: (input) =>
observeRpcEffect(WS_METHODS.reviewSummarizeThread, review.summarizeThread(input), {
"rpc.aggregate": "review",
}),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",