Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import { Effect, FileSystem, Layer, Path } from "effect";
4import { expect } from "vitest";
5
6import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
7import { TextGenerationError } from "../Errors.ts";
8import { TextGeneration } from "../Services/TextGeneration.ts";
9
10function makeFakeCodexBinary(dir: string) {
11 return Effect.gen(function* () {
12 const fs = yield* FileSystem.FileSystem;
13 const path = yield* Path.Path;
14 const binDir = path.join(dir, "bin");
15 const codexPath = path.join(binDir, "codex");
16 yield* fs.makeDirectory(binDir, { recursive: true });
17
18 yield* fs.writeFileString(
19 codexPath,
20 [
21 "#!/bin/sh",
22 'output_path=""',
23 "while [ $# -gt 0 ]; do",
24 ' if [ "$1" = "--output-last-message" ]; then',
25 " shift",
26 ' output_path="$1"',
27 " fi",
28 " shift",
29 "done",
30 "cat >/dev/null",
31 'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
32 ' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
33 "fi",
34 'if [ -n "$output_path" ]; then',
35 ' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
36 "fi",
37 'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
38 "",
39 ].join("\n"),
40 );
41 yield* fs.chmod(codexPath, 0o755);
42 return binDir;
43 });
44}
45
46function withFakeCodexEnv<A, E, R>(
47 input: {
48 output: string;
49 exitCode?: number;
50 stderr?: string;
51 },
52 effect: Effect.Effect<A, E, R>,
53) {
54 return Effect.acquireUseRelease(
55 Effect.gen(function* () {
56 const fs = yield* FileSystem.FileSystem;
57 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
58 const binDir = yield* makeFakeCodexBinary(tempDir);
59 const previousPath = process.env.PATH;
60 const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
61 const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
62 const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
63
64 yield* Effect.sync(() => {
65 process.env.PATH = `${binDir}:${previousPath ?? ""}`;
66 process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
67
68 if (input.exitCode !== undefined) {
69 process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
70 } else {
71 delete process.env.T3_FAKE_CODEX_EXIT_CODE;
72 }
73
74 if (input.stderr !== undefined) {
75 process.env.T3_FAKE_CODEX_STDERR = input.stderr;
76 } else {
77 delete process.env.T3_FAKE_CODEX_STDERR;
78 }
79 });
80
81 return {
82 previousPath,
83 previousOutput,
84 previousExitCode,
85 previousStderr,
86 };
87 }),
88 () => effect,
89 (previous) =>
90 Effect.sync(() => {
91 process.env.PATH = previous.previousPath;
92
93 if (previous.previousOutput === undefined) {
94 delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
95 } else {
96 process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
97 }
98
99 if (previous.previousExitCode === undefined) {
100 delete process.env.T3_FAKE_CODEX_EXIT_CODE;
101 } else {
102 process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
103 }
104
105 if (previous.previousStderr === undefined) {
106 delete process.env.T3_FAKE_CODEX_STDERR;
107 } else {
108 process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
109 }
110 }),
111 );
112}
113
114const CodexTextGenerationTestLayer = Layer.provideMerge(
115 CodexTextGenerationLive,
116 NodeServices.layer,
117);
118
119it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
120 it.effect("generates and sanitizes commit messages", () =>
121 withFakeCodexEnv(
122 {
123 output: JSON.stringify({
124 subject:
125 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
126 body: "\n- added migration\n- updated tests\n",
127 }),
128 },
129 Effect.gen(function* () {
130 const textGeneration = yield* TextGeneration;
131
132 const generated = yield* textGeneration.generateCommitMessage({
133 cwd: process.cwd(),
134 branch: "feature/codex-effect",
135 stagedSummary: "M README.md",
136 stagedPatch: "diff --git a/README.md b/README.md",
137 });
138
139 expect(generated.subject.length).toBeLessThanOrEqual(72);
140 expect(generated.subject.endsWith(".")).toBe(false);
141 expect(generated.body).toBe("- added migration\n- updated tests");
142 }),
143 ),
144 );
145
146 it.effect("generates PR content and trims markdown body", () =>
147 withFakeCodexEnv(
148 {
149 output: JSON.stringify({
150 title: " Improve orchestration flow\nwith ignored suffix",
151 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
152 }),
153 },
154 Effect.gen(function* () {
155 const textGeneration = yield* TextGeneration;
156
157 const generated = yield* textGeneration.generatePrContent({
158 cwd: process.cwd(),
159 baseBranch: "main",
160 headBranch: "feature/codex-effect",
161 commitSummary: "feat: improve orchestration flow",
162 diffSummary: "2 files changed",
163 diffPatch: "diff --git a/a.ts b/a.ts",
164 });
165
166 expect(generated.title).toBe("Improve orchestration flow");
167 expect(generated.body.startsWith("## Summary")).toBe(true);
168 expect(generated.body.endsWith("\n\n")).toBe(false);
169 }),
170 ),
171 );
172
173 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
174 withFakeCodexEnv(
175 {
176 output: JSON.stringify({ subject: "ignored", body: "" }),
177 exitCode: 1,
178 stderr: "codex execution failed",
179 },
180 Effect.gen(function* () {
181 const textGeneration = yield* TextGeneration;
182
183 const result = yield* textGeneration
184 .generateCommitMessage({
185 cwd: process.cwd(),
186 branch: "feature/codex-error",
187 stagedSummary: "M README.md",
188 stagedPatch: "diff --git a/README.md b/README.md",
189 })
190 .pipe(
191 Effect.match({
192 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
193 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
194 }),
195 );
196
197 expect(result._tag).toBe("Left");
198 if (result._tag === "Left") {
199 expect(result.left).toBeInstanceOf(TextGenerationError);
200 expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
201 }
202 }),
203 ),
204 );
205});