diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 41381bfce4..8945294555 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -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"; diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index 3a8123f198..cb0f3fe9a3 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.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"; diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index 4c88f9dc11..69867bd254 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -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"; diff --git a/apps/server/src/git/Layers/TextGenerationLive.ts b/apps/server/src/git/Layers/TextGenerationLive.ts deleted file mode 100644 index 58e1541d55..0000000000 --- a/apps/server/src/git/Layers/TextGenerationLive.ts +++ /dev/null @@ -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 => - 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); - }), -); diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index 15015e8cda..6faf3e99c7 100644 --- a/apps/server/src/git/Utils.ts +++ b/apps/server/src/git/Utils.ts @@ -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, - }); -} diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index d0f1a1df3e..09252571c3 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -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"; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 974400c377..998475f611 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.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 { diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index feddd3b86b..311f495865 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -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"; diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 13598ab5f6..26fffd5e21 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.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"; diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index b7eda591bc..cd058800f2 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.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 { diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index 29f74ead02..27f98a9830 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -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"; diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts index 05735f3a50..eeba158ab4 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.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"; diff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts index bedfd61194..e7d3e40cd8 100644 --- a/apps/server/src/provider/ProviderDriver.ts +++ b/apps/server/src/provider/ProviderDriver.ts @@ -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"; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 6120077787..c39f56a82b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -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( diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts similarity index 97% rename from apps/server/src/git/Layers/ClaudeTextGeneration.test.ts rename to apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index eb7bf62ad4..19cff6f034 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -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( }).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( { diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts similarity index 97% rename from apps/server/src/git/Layers/ClaudeTextGeneration.ts rename to apps/server/src/textGeneration/ClaudeTextGeneration.ts index 33bf7bc014..2f0cbc509b 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -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; diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts similarity index 99% rename from apps/server/src/git/Layers/CodexTextGeneration.test.ts rename to apps/server/src/textGeneration/CodexTextGeneration.test.ts index f38d6a68a8..07123e921b 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -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( }).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( { diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts similarity index 96% rename from apps/server/src/git/Layers/CodexTextGeneration.ts rename to apps/server/src/textGeneration/CodexTextGeneration.ts index d4bc8f1632..786a0be4c4 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -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. diff --git a/apps/server/src/git/Layers/CursorTextGeneration.test.ts b/apps/server/src/textGeneration/CursorTextGeneration.test.ts similarity index 92% rename from apps/server/src/git/Layers/CursorTextGeneration.test.ts rename to apps/server/src/textGeneration/CursorTextGeneration.test.ts index 3718557664..0de135c846 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.test.ts @@ -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 { }); } -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", diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts similarity index 94% rename from apps/server/src/git/Layers/CursorTextGeneration.ts rename to apps/server/src/textGeneration/CursorTextGeneration.ts index c94c6dd180..1cde82d61b 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.ts @@ -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. diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts similarity index 97% rename from apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts rename to apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts index c3bdd6035e..907c749355 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts @@ -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) => diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts similarity index 98% rename from apps/server/src/git/Layers/OpenCodeTextGeneration.ts rename to apps/server/src/textGeneration/OpenCodeTextGeneration.ts index f2d0b4b272..d646e4f2e5 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts @@ -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"; diff --git a/apps/server/src/git/Layers/TextGenerationLive.test.ts b/apps/server/src/textGeneration/TextGeneration.test.ts similarity index 93% rename from apps/server/src/git/Layers/TextGenerationLive.test.ts rename to apps/server/src/textGeneration/TextGeneration.test.ts index 3b03696eb4..4f3d44f925 100644 --- a/apps/server/src/git/Layers/TextGenerationLive.test.ts +++ b/apps/server/src/textGeneration/TextGeneration.test.ts @@ -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 => ({ generateCommitMessage: () => diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts similarity index 57% rename from apps/server/src/git/Services/TextGeneration.ts rename to apps/server/src/textGeneration/TextGeneration.ts index 78d37a0108..51796faf8a 100644 --- a/apps/server/src/git/Services/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -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()( - "t3/git/Services/TextGeneration", + "t3/text-generation/TextGeneration", ) {} + +type TextGenerationOp = + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; + +const resolveInstance = ( + registry: ProviderInstanceRegistryShape, + operation: TextGenerationOp, + instanceId: ProviderInstanceId, +): Effect.Effect => + 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); + }), +); diff --git a/apps/server/src/textGeneration/TextGenerationPolicy.ts b/apps/server/src/textGeneration/TextGenerationPolicy.ts new file mode 100644 index 0000000000..b0e020fa4f --- /dev/null +++ b/apps/server/src/textGeneration/TextGenerationPolicy.ts @@ -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; diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.ts new file mode 100644 index 0000000000..7095574214 --- /dev/null +++ b/apps/server/src/textGeneration/TextGenerationPresets.ts @@ -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, "kind">, +): TextGenerationPolicy => ({ + kind: "custom", + inferRepositoryConventions: false, + ...overrides, +}); + +export const textGenerationPresets: Record< + Exclude, + TextGenerationPolicy +> = { + default: defaultTextGenerationPolicy, + conventional_commits: conventionalCommitsTextGenerationPolicy, + repo_conventions: repositoryConventionsTextGenerationPolicy, +}; diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts similarity index 98% rename from apps/server/src/git/Prompts.test.ts rename to apps/server/src/textGeneration/TextGenerationPrompts.test.ts index d8d079c0cf..25fed64227 100644 --- a/apps/server/src/git/Prompts.test.ts +++ b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts @@ -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", () => { diff --git a/apps/server/src/git/Prompts.ts b/apps/server/src/textGeneration/TextGenerationPrompts.ts similarity index 87% rename from apps/server/src/git/Prompts.ts rename to apps/server/src/textGeneration/TextGenerationPrompts.ts index 4092358825..43ae62047b 100644 --- a/apps/server/src/git/Prompts.ts +++ b/apps/server/src/textGeneration/TextGenerationPrompts.ts @@ -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 { + 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 | undefined; + policy?: TextGenerationPolicy | undefined; } interface PromptFromMessageInput { @@ -125,6 +136,7 @@ interface PromptFromMessageInput { rules: ReadonlyArray; message: string; attachments?: ReadonlyArray | 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 | 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, diff --git a/apps/server/src/textGeneration/TextGenerationUtils.ts b/apps/server/src/textGeneration/TextGenerationUtils.ts new file mode 100644 index 0000000000..fcd8cc8b68 --- /dev/null +++ b/apps/server/src/textGeneration/TextGenerationUtils.ts @@ -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, + }); +}