Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as Stream from "effect/Stream";

import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import * as TextGenerationPromptResolver from "../src/textGeneration/TextGenerationPromptResolver.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";
Expand All @@ -48,6 +49,7 @@ import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
import * as T3ProjectFileLoader from "../src/project/T3ProjectFileLoader.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
Expand Down Expand Up @@ -82,6 +84,7 @@ import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";

const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
Expand Down Expand Up @@ -332,10 +335,15 @@ export const makeOrchestrationIntegrationHarness = (
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const textGenerationPromptResolverLayer = TextGenerationPromptResolver.layer.pipe(
Layer.provide(T3ProjectFileLoader.layer),
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(textGenerationPromptResolverLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Expand Down
48 changes: 48 additions & 0 deletions apps/server/src/git/GeneratedBranchName.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { expect } from "vite-plus/test";

import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { validateGeneratedBranchName } from "./GeneratedBranchName.ts";

const TestLayer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "generated-branch-test-" })),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);

it.layer(TestLayer)(
"validates full generated branch names without changing their spelling",
(it) => {
it.effect("accepts a valid mixed-case nested name", () =>
Effect.gen(function* () {
const git = yield* GitVcsDriver.GitVcsDriver;
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "generated-branch-name-" });

expect(yield* validateGeneratedBranchName(git, cwd, " Theo/Fix.v2 ")).toBe("Theo/Fix.v2");
}).pipe(Effect.scoped),
);

it.effect("rejects invalid and reserved names", () =>
Effect.gen(function* () {
const git = yield* GitVcsDriver.GitVcsDriver;
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "generated-branch-name-" });

expect(yield* validateGeneratedBranchName(git, cwd, "bad..name")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "bad\nname")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "HEAD")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "@{-1}")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "refs/heads/feature/demo")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "-dangerous")).toBeNull();
expect(yield* validateGeneratedBranchName(git, cwd, "t3code/deadbeef")).toBeNull();
}).pipe(Effect.scoped),
);
},
);
32 changes: 32 additions & 0 deletions apps/server/src/git/GeneratedBranchName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
import * as Effect from "effect/Effect";

import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";

/**
* Validate a model-generated full branch name with Git while preserving its spelling.
* Internal temporary names and `refs/heads/` input are not valid user branch results.
*/
export const validateGeneratedBranchName = Effect.fn("validateGeneratedBranchName")(function* (
git: GitVcsDriver.GitVcsDriver["Service"],
cwd: string,
rawBranch: string,
) {
const branch = rawBranch.trim();
if (
branch.length === 0 ||
branch.startsWith("-") ||
branch.startsWith("refs/heads/") ||
isTemporaryWorktreeBranch(branch)
) {
return null;
}

const result = yield* git.execute({
operation: "validateGeneratedBranchName",
cwd,
args: ["check-ref-format", "--branch", branch],
allowNonZeroExit: true,
});
return result.exitCode === 0 && result.stdout.trim() === branch ? branch : null;
});
131 changes: 131 additions & 0 deletions apps/server/src/git/GitManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { expect } from "vite-plus/test";
import type {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
T3ProjectFileTextGenerationPrompts,
ThreadId,
} from "@t3tools/contracts";

Expand All @@ -31,12 +32,14 @@ import {
} from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as TextGenerationPromptResolver from "../textGeneration/TextGenerationPromptResolver.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitManager from "./GitManager.ts";
Expand Down Expand Up @@ -618,6 +621,7 @@ function preparePullRequestThread(
function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
prompts?: T3ProjectFileTextGenerationPrompts;
serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
}) {
Expand All @@ -628,6 +632,14 @@ function makeManager(input?: {
});

const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest(input?.serverSettings);
const promptResolverLayer = input?.prompts
? Layer.succeed(
TextGenerationPromptResolver.TextGenerationPromptResolver,
TextGenerationPromptResolver.TextGenerationPromptResolver.of({
resolve: () => Effect.succeed(input.prompts),
}),
)
: TextGenerationPromptResolver.layer.pipe(Layer.provide(T3ProjectFileLoader.layer));

const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Expand All @@ -651,6 +663,7 @@ function makeManager(input?: {

const managerLayer = Layer.mergeAll(
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
promptResolverLayer,
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.succeed([]),
}),
Expand Down Expand Up @@ -2143,6 +2156,124 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);

it.effect("resolves a custom branch namespace conflict and preserves custom commit output", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["branch", "Theo"]);
NodeFS.writeFileSync(
NodePath.join(repoDir, "t3.json"),
// @effect-diagnostics-next-line preferSchemaOverJson:off

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new preferSchemaOverJson:off directive has no adjacent explanation of why the diagnostic must be disabled here; the directive itself is not an explanation. Consider appending a short reason, as nearby suppressions in this repo do (for example bin.test.ts and bootService.test.ts).

Suggested change
// @effect-diagnostics-next-line preferSchemaOverJson:off
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed t3.json fixture written as raw JSON.

Posted via Macroscope — Effect Service Conventions

JSON.stringify({
textGeneration: {
prompts: {
commitMessage: "Return the exact commit format.",
branchName: "Return the complete branch name.",
},
},
}),
);
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\ncustom prompts\n");
const subject =
"Keep This Mixed-Case Commit Subject With Its Final Period And More Than Seventy-Two Characters.";

const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: (input) => {
expect(input.prompts).toMatchObject({
commitMessage: "Return the exact commit format.",
branchName: "Return the complete branch name.",
});
return Effect.succeed({ subject, body: "Exact body.", branch: "Theo/Fix.v2" });
},
},
});

const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
});

expect(result.branch).toEqual({ status: "created", name: "Theo-1/Fix.v2" });
expect(result.commit.subject).toBe(subject);
expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe(
"Theo-1/Fix.v2",
);
expect((yield* runGit(repoDir, ["log", "-1", "--pretty=%s"])).stdout.trim()).toBe(subject);
}),
);

it.effect("uses the custom branch task with a manual commit message", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nmanual custom branch\n");
let commitGenerationCount = 0;
let branchInput: TextGeneration.BranchNameGenerationInput | undefined;

const { manager } = yield* makeManager({
prompts: { branchName: "Return the complete branch name." },
textGeneration: {
generateCommitMessage: () => {
commitGenerationCount += 1;
return Effect.succeed({ subject: "unused", body: "" });
},
generateBranchName: (input) => {
branchInput = input;
return Effect.succeed({ branch: "Team/Manual.Change" });
},
},
});

const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
commitMessage: "feat: keep this manual message\n\nManual details.",
});

expect(commitGenerationCount).toBe(0);
expect(branchInput?.prompts?.branchName).toBe("Return the complete branch name.");
expect(branchInput?.message).toContain("feat: keep this manual message");
expect(branchInput?.message).toContain("README.md");
expect(branchInput?.message).toContain("manual custom branch");
expect(result.branch).toEqual({ status: "created", name: "Team/Manual.Change" });
expect(result.commit.subject).toBe("feat: keep this manual message");
}),
);

it.effect("rejects an invalid custom branch before creating a branch or commit", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\ninvalid branch\n");

const { manager } = yield* makeManager({
prompts: { branchName: "Return the complete branch name." },
textGeneration: {
generateCommitMessage: () =>
Effect.succeed({ subject: "Do not commit this", body: "", branch: "bad..branch" }),
},
});

const error = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
}).pipe(Effect.flip);

expect(error).toMatchObject({
_tag: "GitManagerError",
operation: "runFeatureBranchStep",
});
expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main");
expect((yield* runGit(repoDir, ["log", "--oneline"])).stdout.trim().split("\n")).toHaveLength(
1,
);
}),
);

it.effect("featureBranch uses custom commit message and derives branch name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
Expand Down
Loading
Loading