@sirojar/tcgen 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # tcgen
2
+
3
+ AI-powered test case generator from git commits. Reads your commit diffs, combines them with a customizable prompt template, and uses Claude or Gemini to generate structured test cases as JSON.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g tcgen
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # In any git repository:
15
+ tcgen init # Creates prompt-template.md
16
+ # Edit prompt-template.md to describe your project
17
+
18
+ # Generate test cases (Claude - default)
19
+ ANTHROPIC_API_KEY=sk-... tcgen generate --all
20
+
21
+ # Generate test cases (Gemini)
22
+ GEMINI_API_KEY=... tcgen generate --all --provider gemini
23
+ ```
24
+
25
+ ## Commands
26
+
27
+ ### `tcgen init`
28
+
29
+ Creates a `prompt-template.md` in the current directory with a starter template. Edit this file to describe your project — the more specific you are, the better the generated test cases.
30
+
31
+ ### `tcgen generate [options]`
32
+
33
+ Generates test cases from git commits.
34
+
35
+ | Option | Description | Default |
36
+ |--------|-------------|---------|
37
+ | `--from <commit>` | Start from this commit (exclusive) | Last processed commit |
38
+ | `--to <commit>` | End at this commit (inclusive) | `HEAD` |
39
+ | `--all` | Process all commits from the beginning | `false` |
40
+ | `--output <dir>` | Output directory | `test-cases` |
41
+ | `--prompt <file>` | Prompt template file | `prompt-template.md` |
42
+ | `--provider <name>` | AI provider: `claude` or `gemini` | `claude` |
43
+ | `--model <model>` | Model to use | Per provider default |
44
+ | `--dry-run` | Preview prompt without calling AI | `false` |
45
+
46
+ ## Environment Variables
47
+
48
+ | Variable | Required for | Description |
49
+ |----------|-------------|-------------|
50
+ | `ANTHROPIC_API_KEY` | `--provider claude` | Your Claude API key |
51
+ | `GEMINI_API_KEY` | `--provider gemini` | Your Google Gemini API key |
52
+
53
+ ## AI Providers
54
+
55
+ ### Claude (default)
56
+
57
+ ```bash
58
+ ANTHROPIC_API_KEY=sk-... tcgen generate --all
59
+ ANTHROPIC_API_KEY=sk-... tcgen generate --all --model claude-sonnet-4-20250514
60
+ ```
61
+
62
+ Default model: `claude-sonnet-4-20250514`
63
+
64
+ ### Gemini
65
+
66
+ ```bash
67
+ GEMINI_API_KEY=... tcgen generate --all --provider gemini
68
+ GEMINI_API_KEY=... tcgen generate --all --provider gemini --model gemini-2.0-flash
69
+ ```
70
+
71
+ Default model: `gemini-2.0-flash`
72
+
73
+ ## Prompt Template
74
+
75
+ The `prompt-template.md` file is fully editable. It uses two placeholders that get replaced at runtime:
76
+
77
+ - `{{COMMIT_LOG}}` — list of commits being processed
78
+ - `{{DIFF}}` — the git diff of those commits
79
+
80
+ Everything else in the template is yours to customize: project description, instructions, emphasis on edge cases vs happy path, etc.
81
+
82
+ ### Example
83
+
84
+ ```markdown
85
+ # Project Context
86
+
87
+ This is a banking API with the following features:
88
+ - User accounts and KYC verification
89
+ - Fund transfers (domestic and international)
90
+ - Transaction history and statements
91
+
92
+ # Instructions
93
+
94
+ You are a QA engineer. Analyze the git diff below and generate test cases...
95
+
96
+ ## Changed commits:
97
+ {{COMMIT_LOG}}
98
+
99
+ ## Diff:
100
+ {{DIFF}}
101
+ ```
102
+
103
+ ## Output Format
104
+
105
+ Test cases are written as JSON files in the output directory (default: `test-cases/`):
106
+
107
+ ```json
108
+ {
109
+ "metadata": {
110
+ "generatedAt": "2026-04-07T14:30:22.000Z",
111
+ "fromCommit": "a1b2c3d",
112
+ "toCommit": "e4f5g6h",
113
+ "commitCount": 3,
114
+ "model": "claude-sonnet-4-20250514"
115
+ },
116
+ "testCases": [
117
+ {
118
+ "id": "TC-20260407-001",
119
+ "title": "Verify cart total updates when item quantity changes",
120
+ "description": "The commit modified the cart subtotal calculation...",
121
+ "preconditions": ["User is logged in", "At least one item in cart"],
122
+ "steps": [
123
+ {
124
+ "stepNumber": 1,
125
+ "action": "Navigate to the shopping cart page",
126
+ "expectedOutcome": "Cart page loads with item list"
127
+ }
128
+ ],
129
+ "expectedResult": "Cart total correctly reflects the updated quantity",
130
+ "priority": "high",
131
+ "tags": ["cart", "calculation"],
132
+ "relatedCommit": "e4f5g6h",
133
+ "generatedAt": "2026-04-07T14:30:22.000Z"
134
+ }
135
+ ]
136
+ }
137
+ ```
138
+
139
+ ## How It Works
140
+
141
+ 1. **Reads commits** — finds new commits since the last run (tracked in `.tcgen-state.json`)
142
+ 2. **Extracts diff** — gets the combined diff of those commits
143
+ 3. **Builds prompt** — loads your `prompt-template.md` and injects the diff + commit log
144
+ 4. **Calls AI** — sends the prompt to Claude or Gemini
145
+ 5. **Writes JSON** — saves structured test cases to the output directory
146
+ 6. **Updates state** — records the last processed commit for next run
147
+
148
+ ## Typical Workflow
149
+
150
+ ```bash
151
+ # First run — process all existing commits
152
+ tcgen generate --all
153
+
154
+ # After new commits — only processes what's new
155
+ tcgen generate
156
+
157
+ # Preview what would be sent to AI
158
+ tcgen generate --dry-run
159
+
160
+ # Use a different provider
161
+ tcgen generate --provider gemini
162
+ ```
163
+
164
+ ## License
165
+
166
+ MIT
package/dist/ai.js ADDED
@@ -0,0 +1,107 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { GoogleGenerativeAI } from "@google/generative-ai";
3
+ const SYSTEM_PROMPT = "You are a QA test case generator. Respond only with valid JSON — a JSON array of test case objects. No markdown, no explanation, just the JSON array.";
4
+ export async function generateTestCases(prompt, provider, model) {
5
+ let rawText;
6
+ if (provider === "gemini") {
7
+ rawText = await callGemini(prompt, model);
8
+ }
9
+ else {
10
+ rawText = await callClaude(prompt, model);
11
+ }
12
+ return parseTestCases(rawText);
13
+ }
14
+ async function callClaude(prompt, model) {
15
+ const apiKey = process.env.ANTHROPIC_API_KEY;
16
+ if (!apiKey) {
17
+ console.error("Error: ANTHROPIC_API_KEY environment variable is required.");
18
+ process.exit(1);
19
+ }
20
+ const client = new Anthropic({ apiKey });
21
+ let response;
22
+ try {
23
+ response = await client.messages.create({
24
+ model,
25
+ max_tokens: 4096,
26
+ system: SYSTEM_PROMPT,
27
+ messages: [{ role: "user", content: prompt }],
28
+ });
29
+ }
30
+ catch (error) {
31
+ if (error instanceof Anthropic.APIError) {
32
+ if (error.status === 401) {
33
+ console.error("Error: Claude API authentication failed. Check your ANTHROPIC_API_KEY.");
34
+ process.exit(1);
35
+ }
36
+ if (error.status === 429) {
37
+ console.error("Error: Rate limited by Claude API. Wait a moment and try again.");
38
+ process.exit(1);
39
+ }
40
+ console.error(`Error: Claude API returned status ${error.status}: ${error.message}`);
41
+ process.exit(1);
42
+ }
43
+ throw error;
44
+ }
45
+ const textBlock = response.content.find((block) => block.type === "text");
46
+ if (!textBlock || textBlock.type !== "text") {
47
+ console.error("Error: No text response from Claude API.");
48
+ process.exit(1);
49
+ }
50
+ return textBlock.text.trim();
51
+ }
52
+ async function callGemini(prompt, model) {
53
+ const apiKey = process.env.GEMINI_API_KEY;
54
+ if (!apiKey) {
55
+ console.error("Error: GEMINI_API_KEY environment variable is required.");
56
+ process.exit(1);
57
+ }
58
+ const genAI = new GoogleGenerativeAI(apiKey);
59
+ const genModel = genAI.getGenerativeModel({
60
+ model,
61
+ systemInstruction: SYSTEM_PROMPT,
62
+ });
63
+ let result;
64
+ try {
65
+ result = await genModel.generateContent(prompt);
66
+ }
67
+ catch (error) {
68
+ const err = error;
69
+ if (err.status === 401 || err.status === 403) {
70
+ console.error("Error: Gemini API authentication failed. Check your GEMINI_API_KEY.");
71
+ process.exit(1);
72
+ }
73
+ if (err.status === 429) {
74
+ console.error("Error: Rate limited by Gemini API. Wait a moment and try again.");
75
+ process.exit(1);
76
+ }
77
+ console.error(`Error: Gemini API error: ${err.message || error}`);
78
+ process.exit(1);
79
+ }
80
+ const text = result.response.text();
81
+ if (!text) {
82
+ console.error("Error: No text response from Gemini API.");
83
+ process.exit(1);
84
+ }
85
+ return text.trim();
86
+ }
87
+ function parseTestCases(raw) {
88
+ // Try direct JSON parse first
89
+ try {
90
+ return JSON.parse(raw);
91
+ }
92
+ catch {
93
+ // Try extracting from markdown code fences
94
+ const fenceMatch = raw.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
95
+ if (fenceMatch) {
96
+ try {
97
+ return JSON.parse(fenceMatch[1]);
98
+ }
99
+ catch {
100
+ // fall through
101
+ }
102
+ }
103
+ console.error("Error: Failed to parse AI response as JSON.");
104
+ console.error("Raw response:", raw);
105
+ process.exit(1);
106
+ }
107
+ }
package/dist/git.js ADDED
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { simpleGit } from "simple-git";
4
+ const STATE_FILE = ".tcgen-state.json";
5
+ const MAX_DIFF_CHARS = 90_000;
6
+ let git;
7
+ function getGit(cwd) {
8
+ if (!git) {
9
+ git = simpleGit(cwd);
10
+ }
11
+ return git;
12
+ }
13
+ export async function ensureGitRepo(cwd) {
14
+ const isRepo = await getGit(cwd).checkIsRepo();
15
+ if (!isRepo) {
16
+ console.error("Error: Not a git repository. Run this from a project with git initialized.");
17
+ process.exit(1);
18
+ }
19
+ }
20
+ export function getLastProcessedCommit() {
21
+ const statePath = path.resolve(STATE_FILE);
22
+ if (!fs.existsSync(statePath)) {
23
+ return null;
24
+ }
25
+ const content = fs.readFileSync(statePath, "utf-8");
26
+ return JSON.parse(content);
27
+ }
28
+ export function saveLastProcessedCommit(sha) {
29
+ const state = {
30
+ lastProcessedCommit: sha,
31
+ lastRunAt: new Date().toISOString(),
32
+ };
33
+ fs.writeFileSync(path.resolve(STATE_FILE), JSON.stringify(state, null, 2), "utf-8");
34
+ }
35
+ export async function getCommitRange(from, to) {
36
+ const g = getGit();
37
+ if (from) {
38
+ const log = await g.log({ from, to });
39
+ return log.all.map((c) => ({
40
+ hash: c.hash,
41
+ message: c.message,
42
+ author: c.author_name,
43
+ date: c.date,
44
+ }));
45
+ }
46
+ // No "from" means get all commits up to "to"
47
+ const log = await g.log([to]);
48
+ return log.all.map((c) => ({
49
+ hash: c.hash,
50
+ message: c.message,
51
+ author: c.author_name,
52
+ date: c.date,
53
+ }));
54
+ }
55
+ export async function getDiff(from, to) {
56
+ const g = getGit();
57
+ let diff;
58
+ if (from) {
59
+ diff = await g.diff([from, to]);
60
+ }
61
+ else {
62
+ // No "from" — show full tree diff from root
63
+ diff = await g.raw(["diff-tree", "-p", "--root", to]);
64
+ }
65
+ if (diff.length > MAX_DIFF_CHARS) {
66
+ console.warn(`Warning: Diff is ${diff.length} characters, truncating to ${MAX_DIFF_CHARS}.`);
67
+ diff = diff.substring(0, MAX_DIFF_CHARS) + "\n\n[DIFF TRUNCATED]";
68
+ }
69
+ return diff;
70
+ }
71
+ export function formatCommitLog(commits) {
72
+ return commits
73
+ .map((c) => `- ${c.hash.substring(0, 7)} ${c.message} (${c.author}, ${c.date})`)
74
+ .join("\n");
75
+ }
package/dist/index.js ADDED
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { Command } from "commander";
6
+ import { ensureGitRepo, getLastProcessedCommit, saveLastProcessedCommit, getCommitRange, getDiff, formatCommitLog, } from "./git.js";
7
+ import { loadTemplate, buildPrompt } from "./prompt.js";
8
+ import { generateTestCases } from "./ai.js";
9
+ import { writeTestCases } from "./output.js";
10
+ const DEFAULT_MODELS = {
11
+ claude: "claude-sonnet-4-20250514",
12
+ gemini: "gemini-2.0-flash",
13
+ };
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = path.dirname(__filename);
16
+ const program = new Command();
17
+ program
18
+ .name("tcgen")
19
+ .description("AI-powered test case generator from git commits")
20
+ .version("0.1.0");
21
+ // ---- init command ----
22
+ program
23
+ .command("init")
24
+ .description("Initialize prompt-template.md in the current directory")
25
+ .action(() => {
26
+ const dest = path.resolve("prompt-template.md");
27
+ if (fs.existsSync(dest)) {
28
+ console.log("prompt-template.md already exists. Skipping.");
29
+ return;
30
+ }
31
+ // Copy bundled template
32
+ const templateSrc = path.resolve(__dirname, "..", "templates", "prompt-template.md");
33
+ if (!fs.existsSync(templateSrc)) {
34
+ console.error("Error: Bundled template not found. Reinstall tcgen.");
35
+ process.exit(1);
36
+ }
37
+ fs.copyFileSync(templateSrc, dest);
38
+ console.log("Created prompt-template.md — edit it to describe your project.");
39
+ });
40
+ // ---- generate command ----
41
+ program
42
+ .command("generate")
43
+ .description("Generate test cases from git commits")
44
+ .option("--from <commit>", "Start from this commit (exclusive)")
45
+ .option("--to <commit>", "End at this commit (inclusive)", "HEAD")
46
+ .option("--all", "Process all commits from the beginning", false)
47
+ .option("--output <dir>", "Output directory", "test-cases")
48
+ .option("--prompt <file>", "Prompt template file", "prompt-template.md")
49
+ .option("--provider <provider>", "AI provider: claude or gemini", "claude")
50
+ .option("--model <model>", "Model to use (defaults per provider)")
51
+ .option("--dry-run", "Preview prompt without calling AI", false)
52
+ .action(async (opts) => {
53
+ await ensureGitRepo();
54
+ // Validate provider
55
+ const provider = opts.provider;
56
+ if (provider !== "claude" && provider !== "gemini") {
57
+ console.error(`Error: Unknown provider "${opts.provider}". Use "claude" or "gemini".`);
58
+ process.exit(1);
59
+ }
60
+ const model = opts.model || DEFAULT_MODELS[provider];
61
+ // Resolve from-commit
62
+ let fromCommit = opts.from || null;
63
+ if (!fromCommit && !opts.all) {
64
+ const state = getLastProcessedCommit();
65
+ if (state) {
66
+ fromCommit = state.lastProcessedCommit;
67
+ }
68
+ else {
69
+ console.error('Error: No previous run found. Use --all to process all commits or --from <commit> to specify a starting point.');
70
+ process.exit(1);
71
+ }
72
+ }
73
+ const config = {
74
+ fromCommit,
75
+ toCommit: opts.to,
76
+ outputDir: opts.output,
77
+ promptFile: opts.prompt,
78
+ provider,
79
+ model,
80
+ dryRun: opts.dryRun,
81
+ all: opts.all,
82
+ };
83
+ // Get commits
84
+ const commits = await getCommitRange(config.fromCommit, config.toCommit);
85
+ if (commits.length === 0) {
86
+ console.log(`No new commits${fromCommit ? ` since ${fromCommit.substring(0, 7)}` : ""}.`);
87
+ process.exit(0);
88
+ }
89
+ console.log(`Found ${commits.length} commit(s) to process.`);
90
+ // Get diff
91
+ const diff = await getDiff(config.fromCommit, config.toCommit);
92
+ if (!diff.trim()) {
93
+ console.log("No changes found in the diff. Nothing to generate.");
94
+ process.exit(0);
95
+ }
96
+ // Build prompt
97
+ const commitLog = formatCommitLog(commits);
98
+ const template = loadTemplate(path.resolve(config.promptFile));
99
+ const prompt = buildPrompt(template, diff, commitLog);
100
+ // Dry run — print and exit
101
+ if (config.dryRun) {
102
+ console.log("\n--- Constructed Prompt ---\n");
103
+ console.log(prompt);
104
+ console.log("\n--- End Prompt ---");
105
+ console.log(`\nCharacters: ${prompt.length}`);
106
+ return;
107
+ }
108
+ // Call AI
109
+ console.log(`Generating test cases with ${config.provider}/${config.model}...`);
110
+ const testCases = await generateTestCases(prompt, config.provider, config.model);
111
+ if (testCases.length === 0) {
112
+ console.log("AI returned no test cases (changes may be trivial).");
113
+ process.exit(0);
114
+ }
115
+ // Write output
116
+ const latestCommitHash = commits[0].hash;
117
+ const metadata = {
118
+ generatedAt: new Date().toISOString(),
119
+ fromCommit: config.fromCommit || "initial",
120
+ toCommit: latestCommitHash,
121
+ commitCount: commits.length,
122
+ model: config.model,
123
+ };
124
+ const filePath = writeTestCases(config, metadata, testCases);
125
+ console.log(`Generated ${testCases.length} test case(s) → ${filePath}`);
126
+ // Save state
127
+ saveLastProcessedCommit(latestCommitHash);
128
+ });
129
+ program.parse();
package/dist/output.js ADDED
@@ -0,0 +1,21 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ export function writeTestCases(config, metadata, testCases) {
4
+ const output = {
5
+ metadata,
6
+ testCases,
7
+ };
8
+ // Create output directory if it doesn't exist
9
+ const outputDir = path.resolve(config.outputDir);
10
+ fs.mkdirSync(outputDir, { recursive: true });
11
+ // Generate filename with timestamp
12
+ const timestamp = new Date()
13
+ .toISOString()
14
+ .replace(/[:.]/g, "-")
15
+ .replace("T", "-")
16
+ .substring(0, 19);
17
+ const fileName = `tc-${timestamp}.json`;
18
+ const filePath = path.join(outputDir, fileName);
19
+ fs.writeFileSync(filePath, JSON.stringify(output, null, 2), "utf-8");
20
+ return filePath;
21
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,13 @@
1
+ import fs from "node:fs";
2
+ export function loadTemplate(filePath) {
3
+ if (!fs.existsSync(filePath)) {
4
+ console.error(`Error: Prompt template not found at "${filePath}". Run "tcgen init" to create one or use --prompt to specify a path.`);
5
+ process.exit(1);
6
+ }
7
+ return fs.readFileSync(filePath, "utf-8");
8
+ }
9
+ export function buildPrompt(template, diff, commitLog) {
10
+ return template
11
+ .replace("{{COMMIT_LOG}}", commitLog)
12
+ .replace("{{DIFF}}", diff);
13
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@sirojar/tcgen",
3
+ "version": "0.1.0",
4
+ "description": "AI-powered test case generator from git commits",
5
+ "type": "module",
6
+ "bin": {
7
+ "tcgen": "./dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "templates"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "dev": "tsx src/index.ts",
16
+ "start": "node dist/index.js"
17
+ },
18
+ "keywords": [
19
+ "test",
20
+ "test-case",
21
+ "generator",
22
+ "qa",
23
+ "git",
24
+ "ai",
25
+ "claude"
26
+ ],
27
+ "license": "MIT",
28
+ "dependencies": {
29
+ "@anthropic-ai/sdk": "^0.39.0",
30
+ "@google/generative-ai": "^0.24.1",
31
+ "commander": "^12.1.0",
32
+ "simple-git": "^3.27.0"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^20.0.0",
36
+ "tsx": "^4.19.0",
37
+ "typescript": "^5.7.0"
38
+ }
39
+ }
@@ -0,0 +1,53 @@
1
+ # Project Context
2
+
3
+ This is an e-commerce application with the following features:
4
+ - User authentication (login, register, password reset)
5
+ - Product catalog with search and filtering
6
+ - Shopping cart and checkout flow
7
+ - Order management and history
8
+ - Payment processing
9
+
10
+ Edit this section to describe YOUR project. The more specific you are, the better the generated test cases will be.
11
+
12
+ ---
13
+
14
+ # Instructions
15
+
16
+ You are a QA engineer. Analyze the git diff below and generate test cases.
17
+
18
+ For each meaningful change, produce test cases that cover:
19
+ - Happy path (normal usage)
20
+ - Edge cases and boundary conditions
21
+ - Error/failure scenarios where relevant
22
+
23
+ Focus on **functional** test cases a manual QA tester could execute.
24
+ Do NOT generate test cases for trivial changes (typo fixes, comment-only changes, formatting).
25
+
26
+ If the diff contains no testable changes, return an empty JSON array `[]`.
27
+
28
+ ## Changed commits:
29
+ {{COMMIT_LOG}}
30
+
31
+ ## Diff:
32
+ {{DIFF}}
33
+
34
+ Respond ONLY with a JSON array of test case objects matching this schema:
35
+ [
36
+ {
37
+ "id": "TC-YYYYMMDD-NNN",
38
+ "title": "Short description of what is being tested",
39
+ "description": "Detailed explanation of what and why",
40
+ "preconditions": ["Setup needed before test"],
41
+ "steps": [
42
+ {
43
+ "stepNumber": 1,
44
+ "action": "What the tester does",
45
+ "expectedOutcome": "What should happen"
46
+ }
47
+ ],
48
+ "expectedResult": "Overall expected outcome",
49
+ "priority": "high | medium | low",
50
+ "tags": ["relevant", "tags"],
51
+ "relatedCommit": "short SHA"
52
+ }
53
+ ]