Extract text generation into dedicated server module

- Move git text-generation layers and tests under `src/textGeneration`
- Route server and provider drivers to the new module
- Replace the old git-scoped `TextGenerationLive` registry layer
This commit is contained in:
Julius Marminge committed 2026-05-02 00:03:12 -07:00
1 parent e21b1514a5
commit dcbb182f82
29 files changed
+358 -352

No files matched your search

@@ -25,7 +25,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -20,7 +20,7 @@ import {
type GitHubPullRequestSummary,
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { type TextGenerationShape, TextGeneration } from "../../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../../sourceControl/GitHubSourceControlProvider.ts";
+1 -1
View File
@@ -40,7 +40,7 @@ import {
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -1,101 +0,0 @@
/**
* TextGenerationLive — registry-backed implementation of the `TextGeneration`
* service tag.
*
* The `TextGeneration` tag is kept as a thin facade over
* `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`,
* looks up the matching `ProviderInstance`, and delegates to that instance's
* own `textGeneration` closure (built by its driver's `create()`).
*
* There is deliberately no per-driver dispatch here — the registry already
* knows which driver backs each instance, and each `ProviderInstance`
* carries the fully-bound `TextGenerationShape` produced by its driver.
* That means:
*
* - Multiple instances of the same driver (e.g. `codex_personal`,
* `codex_work`) each get their own text-generation closure bound to
* their own settings — the routing is by instance, not by driver.
* - Unknown or disabled instances surface a `TextGenerationError` with
* the missing `instanceId`, instead of silently falling back to a
* default.
*
* This replaces the old `RoutingTextGenerationLive`, which tried to route
* by driver-kind and misused `modelSelection.instanceId` as a driver-id
* literal.
*
* @module git/Layers/TextGenerationLive
*/
import { Effect, Layer } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import type { ProviderInstanceId } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
/**
* Build a `TextGenerationShape` that routes every call through the
* registry. Exposed separately from the Layer so tests can construct it
* against a stub registry without layering gymnastics.
*/
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateThreadTitle(input)),
),
});
/**
* `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest
* of the server keeps using `yield* TextGeneration` — only the underlying
* wiring changed from kind-based routing to instance-based routing.
*/
export const TextGenerationLive = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
-165
View File
@@ -1,171 +1,6 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** 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);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
@@ -33,7 +33,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -19,7 +19,7 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -16,7 +16,7 @@ import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tool
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../git/Layers/ClaudeTextGeneration.ts";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
@@ -25,7 +25,7 @@ import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../git/Layers/CodexTextGeneration.ts";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
@@ -17,7 +17,7 @@ import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeCursorTextGeneration } from "../../git/Layers/CursorTextGeneration.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
import {
@@ -16,7 +16,7 @@ import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3to
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../git/Layers/OpenCodeTextGeneration.ts";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
@@ -14,7 +14,7 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import type { TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
+1 -1
View File
@@ -28,7 +28,7 @@ import type {
} from "@t3tools/contracts";
import type { Effect, Schema, Scope } from "effect";
import type { TextGenerationShape } from "../git/Services/TextGeneration.ts";
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
+2 -2
View File
@@ -26,7 +26,7 @@ import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
import { GitHubCliLive } from "./git/Layers/GitHubCli.ts";
import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
import { GitManagerLive } from "./git/Layers/GitManager.ts";
@@ -159,7 +159,7 @@ const GitManagerLayerLive = GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistry.layer.pipe(Layer.provide(GitHubCliLive))),
Layer.provideMerge(TextGenerationLive),
Layer.provideMerge(TextGeneration.layer),
);
const GitLayerLive = Layer.empty.pipe(
@@ -5,9 +5,9 @@ import { Effect, FileSystem, Layer, Path, Schema } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
@@ -184,7 +184,7 @@ function withFakeClaudeEnv<A, E, R>(
}).pipe(Effect.scoped);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
@@ -14,20 +14,20 @@ import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
@@ -37,8 +37,8 @@ import {
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "../../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
} from "../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -6,8 +6,8 @@ import { expect } from "vitest";
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
@@ -168,7 +168,7 @@ function withFakeCodexEnv<A, E, R>(
}).pipe(Effect.scoped);
}
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
@@ -4,28 +4,28 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
} from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
@@ -386,7 +386,3 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
generateThreadTitle,
} satisfies TextGenerationShape;
});
// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed.
// `makeCodexTextGeneration(codexConfig)` is now invoked directly by
// `CodexDriver.create()` for each configured instance.
@@ -11,12 +11,12 @@ import { expect } from "vitest";
import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -82,7 +82,7 @@ function waitForFileContent(path: string): Effect.Effect<string> {
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
@@ -100,9 +100,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
@@ -243,9 +243,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
modelSelection: {
instanceId: ProviderInstanceId.make("cursor"),
model: "composer-2",
@@ -5,26 +5,23 @@ import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../../provider/acp/CursorAcpSupport.ts";
} from "../provider/acp/CursorAcpSupport.ts";
const CURSOR_TIMEOUT_MS = 180_000;
@@ -277,7 +274,3 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
generateThreadTitle,
} satisfies TextGenerationShape;
});
// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed.
// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by
// `CursorDriver.create()` so each provider instance owns its own closure.
@@ -6,13 +6,13 @@ import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerConfig } from "../config.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
} from "../provider/opencodeRuntime.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
@@ -158,7 +158,7 @@ const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
@@ -306,7 +306,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
"OpenCodeTextGeneration with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
@@ -10,21 +10,21 @@ import {
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
} from "./TextGenerationPrompts.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
OpenCodeRuntime,
type OpenCodeServerConnection,
@@ -32,7 +32,7 @@ import {
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
toOpenCodeFileParts,
} from "../../provider/opencodeRuntime.ts";
} from "../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
@@ -5,11 +5,11 @@ import { describe, expect } from "vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { TextGenerationShape } from "../Services/TextGeneration.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import type { ProviderInstanceRegistryShape } from "../provider/Services/ProviderInstanceRegistry.ts";
import type { TextGenerationShape } from "./TextGeneration.ts";
import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts";
import { makeTextGenerationFromRegistry } from "./TextGeneration.ts";
const makeStubTextGeneration = (overrides: Partial<TextGenerationShape>): TextGenerationShape => ({
generateCommitMessage: () =>
@@ -1,18 +1,13 @@
/**
* TextGeneration - Effect service contract for AI-generated Git content.
*
* Generates commit messages and pull request titles/bodies from repository
* context prepared by Git services.
*
* @module TextGeneration
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import { Context, Effect, Layer } from "effect";
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import { TextGenerationError } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export interface CommitMessageGenerationInput {
@@ -119,5 +114,58 @@ export interface TextGenerationShape {
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
"t3/git/Services/TextGeneration",
"t3/text-generation/TextGeneration",
) {}
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
),
});
export const layer = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
@@ -0,0 +1,19 @@
import { Schema } from "effect";
export const TextGenerationPolicyKind = Schema.Literals([
"default",
"conventional_commits",
"repo_conventions",
"custom",
]);
export type TextGenerationPolicyKind = typeof TextGenerationPolicyKind.Type;
export const TextGenerationPolicy = Schema.Struct({
kind: TextGenerationPolicyKind,
commitInstructions: Schema.optional(Schema.String),
changeRequestInstructions: Schema.optional(Schema.String),
branchInstructions: Schema.optional(Schema.String),
threadTitleInstructions: Schema.optional(Schema.String),
inferRepositoryConventions: Schema.Boolean,
});
export type TextGenerationPolicy = typeof TextGenerationPolicy.Type;
@@ -0,0 +1,41 @@
import type { TextGenerationPolicy, TextGenerationPolicyKind } from "./TextGenerationPolicy.ts";
export const defaultTextGenerationPolicy: TextGenerationPolicy = {
kind: "default",
inferRepositoryConventions: false,
};
export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = {
kind: "conventional_commits",
commitInstructions:
"Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff.",
changeRequestInstructions:
"Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.",
inferRepositoryConventions: false,
};
export const repositoryConventionsTextGenerationPolicy: TextGenerationPolicy = {
kind: "repo_conventions",
commitInstructions:
"Follow the repository's established commit message style when examples are available.",
changeRequestInstructions:
"Follow the repository's established change request title and body style when examples are available.",
inferRepositoryConventions: true,
};
export const customTextGenerationPolicy = (
overrides: Omit<Partial<TextGenerationPolicy>, "kind">,
): TextGenerationPolicy => ({
kind: "custom",
inferRepositoryConventions: false,
...overrides,
});
export const textGenerationPresets: Record<
Exclude<TextGenerationPolicyKind, "custom">,
TextGenerationPolicy
> = {
default: defaultTextGenerationPolicy,
conventional_commits: conventionalCommitsTextGenerationPolicy,
repo_conventions: repositoryConventionsTextGenerationPolicy,
};
@@ -5,8 +5,8 @@ import {
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
} from "./TextGenerationPrompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
@@ -9,7 +9,13 @@
import { Schema } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./Utils.ts";
import { limitSection } from "./TextGenerationUtils.ts";
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
const trimmed = instruction?.trim();
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
}
// ---------------------------------------------------------------------------
// Commit message
@@ -20,6 +26,7 @@ export interface CommitMessagePromptInput {
stagedSummary: string;
stagedPatch: string;
includeBranch: boolean;
policy?: TextGenerationPolicy | undefined;
}
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
@@ -37,6 +44,7 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
...policyInstruction(input.policy?.commitInstructions),
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
@@ -77,6 +85,7 @@ export interface PrContentPromptInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
policy?: TextGenerationPolicy | undefined;
}
export function buildPrContentPrompt(input: PrContentPromptInput) {
@@ -88,6 +97,7 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
...policyInstruction(input.policy?.changeRequestInstructions),
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
@@ -117,6 +127,7 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
export interface BranchNamePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
interface PromptFromMessageInput {
@@ -125,6 +136,7 @@ interface PromptFromMessageInput {
rules: ReadonlyArray<string>;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
additionalInstructions?: string | undefined;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
@@ -140,6 +152,7 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
"",
"User message:",
limitSection(input.message, 8_000),
...policyInstruction(input.additionalInstructions),
];
if (attachmentLines.length > 0) {
promptSections.push(
@@ -164,6 +177,7 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.branchInstructions,
});
const outputSchema = Schema.Struct({
branch: Schema.String,
@@ -179,6 +193,7 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
export interface ThreadTitlePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
@@ -193,6 +208,7 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.threadTitleInstructions,
});
const outputSchema = Schema.Struct({
title: Schema.String,
@@ -0,0 +1,159 @@
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** 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);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}