Issue/90 fix windows (#91)
* Window対応および Codexが.gitを必要とする問題があるので.gitがみつからない場合はエラーとする fix #90 * 文字化け修正
This commit is contained in:
parent
54ade15dcb
commit
8e509e13c6
@ -476,9 +476,6 @@ model: sonnet # Default model (optional)
|
||||
anthropic_api_key: sk-ant-... # For Claude (Anthropic)
|
||||
# openai_api_key: sk-... # For Codex (OpenAI)
|
||||
|
||||
trusted_directories:
|
||||
- /path/to/trusted/dir
|
||||
|
||||
# Pipeline execution configuration (optional)
|
||||
# Customize branch names, commit messages, and PR body.
|
||||
# pipeline:
|
||||
@ -490,6 +487,8 @@ trusted_directories:
|
||||
# Closes #{issue}
|
||||
```
|
||||
|
||||
**Note:** The Codex SDK requires running inside a Git repository. `--skip-git-repo-check` is only available in the Codex CLI.
|
||||
|
||||
**API Key Configuration Methods:**
|
||||
|
||||
1. **Set via environment variables**:
|
||||
|
||||
5
bin/takt
5
bin/takt
@ -9,7 +9,7 @@
|
||||
* - npm exec takt
|
||||
*/
|
||||
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
@ -19,7 +19,8 @@ const __dirname = dirname(__filename);
|
||||
const cliPath = join(__dirname, '..', 'dist', 'app', 'cli', 'index.js');
|
||||
|
||||
try {
|
||||
await import(cliPath);
|
||||
const cliUrl = pathToFileURL(cliPath).href;
|
||||
await import(cliUrl);
|
||||
} catch (err) {
|
||||
console.error('Failed to load TAKT CLI. Have you run "npm run build"?');
|
||||
console.error(err.message);
|
||||
|
||||
@ -472,9 +472,6 @@ model: sonnet # デフォルトモデル(オプション)
|
||||
anthropic_api_key: sk-ant-... # Claude (Anthropic) を使う場合
|
||||
# openai_api_key: sk-... # Codex (OpenAI) を使う場合
|
||||
|
||||
trusted_directories:
|
||||
- /path/to/trusted/dir
|
||||
|
||||
# パイプライン実行設定(オプション)
|
||||
# ブランチ名、コミットメッセージ、PRの本文をカスタマイズできます。
|
||||
# pipeline:
|
||||
@ -486,6 +483,8 @@ trusted_directories:
|
||||
# Closes #{issue}
|
||||
```
|
||||
|
||||
**注意:** Codex SDK は Git 管理下のディレクトリでのみ動作します。`--skip-git-repo-check` は Codex CLI 専用です。
|
||||
|
||||
**API Key の設定方法:**
|
||||
|
||||
1. **環境変数で設定**:
|
||||
|
||||
734
package-lock.json
generated
734
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,9 +4,6 @@
|
||||
# Language setting (en or ja)
|
||||
language: en
|
||||
|
||||
# Trusted directories - projects in these directories skip confirmation prompts
|
||||
trusted_directories: []
|
||||
|
||||
# Default piece to use when no piece is specified
|
||||
default_piece: default
|
||||
|
||||
|
||||
@ -4,10 +4,7 @@
|
||||
# 言語設定 (en または ja)
|
||||
language: ja
|
||||
|
||||
# 信頼済みディレクトリ - これらのディレクトリ内のプロジェクトは確認プロンプトをスキップします
|
||||
trusted_directories: []
|
||||
|
||||
# デフォルトピース - ピースが指定されていない場合に使用します
|
||||
# デフォルトのピース - 指定がない場合に使用します
|
||||
default_piece: default
|
||||
|
||||
# ログレベル: debug, info, warn, error
|
||||
|
||||
@ -1,292 +1,282 @@
|
||||
/**
|
||||
* Tests for API key authentication feature
|
||||
*
|
||||
* Tests the resolution logic for Anthropic and OpenAI API keys:
|
||||
* - Environment variable priority over config.yaml
|
||||
* - Config.yaml fallback when env var is not set
|
||||
* - Undefined when neither is set
|
||||
* - Schema validation for API key fields
|
||||
* - GlobalConfig load/save round-trip with API keys
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { GlobalConfigSchema } from '../core/models/index.js';
|
||||
|
||||
// Mock paths module to redirect config to temp directory
|
||||
const testId = randomUUID();
|
||||
const testDir = join(tmpdir(), `takt-api-key-test-${testId}`);
|
||||
const taktDir = join(testDir, '.takt');
|
||||
const configPath = join(taktDir, 'config.yaml');
|
||||
|
||||
vi.mock('../infra/config/paths.js', async (importOriginal) => {
|
||||
const original = await importOriginal() as Record<string, unknown>;
|
||||
return {
|
||||
...original,
|
||||
getGlobalConfigPath: () => configPath,
|
||||
getTaktDir: () => taktDir,
|
||||
};
|
||||
});
|
||||
|
||||
// Import after mocking
|
||||
const { loadGlobalConfig, saveGlobalConfig, resolveAnthropicApiKey, resolveOpenaiApiKey, invalidateGlobalConfigCache } = await import('../infra/config/global/globalConfig.js');
|
||||
|
||||
describe('GlobalConfigSchema API key fields', () => {
|
||||
it('should accept config without API keys', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBeUndefined();
|
||||
expect(result.openai_api_key).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should accept config with anthropic_api_key', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
anthropic_api_key: 'sk-ant-test-key',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBe('sk-ant-test-key');
|
||||
});
|
||||
|
||||
it('should accept config with openai_api_key', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
openai_api_key: 'sk-openai-test-key',
|
||||
});
|
||||
expect(result.openai_api_key).toBe('sk-openai-test-key');
|
||||
});
|
||||
|
||||
it('should accept config with both API keys', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
anthropic_api_key: 'sk-ant-key',
|
||||
openai_api_key: 'sk-openai-key',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBe('sk-ant-key');
|
||||
expect(result.openai_api_key).toBe('sk-openai-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobalConfig load/save with API keys', () => {
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should load config with API keys from YAML', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
expect(config.anthropicApiKey).toBe('sk-ant-from-yaml');
|
||||
expect(config.openaiApiKey).toBe('sk-openai-from-yaml');
|
||||
});
|
||||
|
||||
it('should load config without API keys', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
expect(config.anthropicApiKey).toBeUndefined();
|
||||
expect(config.openaiApiKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save and reload config with API keys', () => {
|
||||
// Write initial config
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
config.anthropicApiKey = 'sk-ant-saved';
|
||||
config.openaiApiKey = 'sk-openai-saved';
|
||||
saveGlobalConfig(config);
|
||||
|
||||
const reloaded = loadGlobalConfig();
|
||||
expect(reloaded.anthropicApiKey).toBe('sk-ant-saved');
|
||||
expect(reloaded.openaiApiKey).toBe('sk-openai-saved');
|
||||
});
|
||||
|
||||
it('should not persist API keys when not set', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
saveGlobalConfig(config);
|
||||
|
||||
const content = readFileSync(configPath, 'utf-8');
|
||||
expect(content).not.toContain('anthropic_api_key');
|
||||
expect(content).not.toContain('openai_api_key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveAnthropicApiKey', () => {
|
||||
const originalEnv = process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env['TAKT_ANTHROPIC_API_KEY'] = originalEnv;
|
||||
} else {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
}
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return env var when set', () => {
|
||||
process.env['TAKT_ANTHROPIC_API_KEY'] = 'sk-ant-from-env';
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBe('sk-ant-from-env');
|
||||
});
|
||||
|
||||
it('should fall back to config when env var is not set', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBe('sk-ant-from-yaml');
|
||||
});
|
||||
|
||||
it('should return undefined when neither env var nor config is set', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when config file does not exist', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
// No config file created
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveOpenaiApiKey', () => {
|
||||
const originalEnv = process.env['TAKT_OPENAI_API_KEY'];
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env['TAKT_OPENAI_API_KEY'] = originalEnv;
|
||||
} else {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
}
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return env var when set', () => {
|
||||
process.env['TAKT_OPENAI_API_KEY'] = 'sk-openai-from-env';
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBe('sk-openai-from-env');
|
||||
});
|
||||
|
||||
it('should fall back to config when env var is not set', () => {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBe('sk-openai-from-yaml');
|
||||
});
|
||||
|
||||
it('should return undefined when neither env var nor config is set', () => {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'trusted_directories: []',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
});
|
||||
/**
|
||||
* Tests for API key authentication feature
|
||||
*
|
||||
* Tests the resolution logic for Anthropic and OpenAI API keys:
|
||||
* - Environment variable priority over config.yaml
|
||||
* - Config.yaml fallback when env var is not set
|
||||
* - Undefined when neither is set
|
||||
* - Schema validation for API key fields
|
||||
* - GlobalConfig load/save round-trip with API keys
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { GlobalConfigSchema } from '../core/models/index.js';
|
||||
|
||||
// Mock paths module to redirect config to temp directory
|
||||
const testId = randomUUID();
|
||||
const testDir = join(tmpdir(), `takt-api-key-test-${testId}`);
|
||||
const taktDir = join(testDir, '.takt');
|
||||
const configPath = join(taktDir, 'config.yaml');
|
||||
|
||||
vi.mock('../infra/config/paths.js', async (importOriginal) => {
|
||||
const original = await importOriginal() as Record<string, unknown>;
|
||||
return {
|
||||
...original,
|
||||
getGlobalConfigPath: () => configPath,
|
||||
getTaktDir: () => taktDir,
|
||||
};
|
||||
});
|
||||
|
||||
// Import after mocking
|
||||
const { loadGlobalConfig, saveGlobalConfig, resolveAnthropicApiKey, resolveOpenaiApiKey, invalidateGlobalConfigCache } = await import('../infra/config/global/globalConfig.js');
|
||||
|
||||
describe('GlobalConfigSchema API key fields', () => {
|
||||
it('should accept config without API keys', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBeUndefined();
|
||||
expect(result.openai_api_key).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should accept config with anthropic_api_key', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
anthropic_api_key: 'sk-ant-test-key',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBe('sk-ant-test-key');
|
||||
});
|
||||
|
||||
it('should accept config with openai_api_key', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
openai_api_key: 'sk-openai-test-key',
|
||||
});
|
||||
expect(result.openai_api_key).toBe('sk-openai-test-key');
|
||||
});
|
||||
|
||||
it('should accept config with both API keys', () => {
|
||||
const result = GlobalConfigSchema.parse({
|
||||
language: 'en',
|
||||
anthropic_api_key: 'sk-ant-key',
|
||||
openai_api_key: 'sk-openai-key',
|
||||
});
|
||||
expect(result.anthropic_api_key).toBe('sk-ant-key');
|
||||
expect(result.openai_api_key).toBe('sk-openai-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobalConfig load/save with API keys', () => {
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should load config with API keys from YAML', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
expect(config.anthropicApiKey).toBe('sk-ant-from-yaml');
|
||||
expect(config.openaiApiKey).toBe('sk-openai-from-yaml');
|
||||
});
|
||||
|
||||
it('should load config without API keys', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
expect(config.anthropicApiKey).toBeUndefined();
|
||||
expect(config.openaiApiKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save and reload config with API keys', () => {
|
||||
// Write initial config
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
config.anthropicApiKey = 'sk-ant-saved';
|
||||
config.openaiApiKey = 'sk-openai-saved';
|
||||
saveGlobalConfig(config);
|
||||
|
||||
const reloaded = loadGlobalConfig();
|
||||
expect(reloaded.anthropicApiKey).toBe('sk-ant-saved');
|
||||
expect(reloaded.openaiApiKey).toBe('sk-openai-saved');
|
||||
});
|
||||
|
||||
it('should not persist API keys when not set', () => {
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const config = loadGlobalConfig();
|
||||
saveGlobalConfig(config);
|
||||
|
||||
const content = readFileSync(configPath, 'utf-8');
|
||||
expect(content).not.toContain('anthropic_api_key');
|
||||
expect(content).not.toContain('openai_api_key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveAnthropicApiKey', () => {
|
||||
const originalEnv = process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env['TAKT_ANTHROPIC_API_KEY'] = originalEnv;
|
||||
} else {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
}
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return env var when set', () => {
|
||||
process.env['TAKT_ANTHROPIC_API_KEY'] = 'sk-ant-from-env';
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBe('sk-ant-from-env');
|
||||
});
|
||||
|
||||
it('should fall back to config when env var is not set', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'anthropic_api_key: sk-ant-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBe('sk-ant-from-yaml');
|
||||
});
|
||||
|
||||
it('should return undefined when neither env var nor config is set', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when config file does not exist', () => {
|
||||
delete process.env['TAKT_ANTHROPIC_API_KEY'];
|
||||
// No config file created
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
|
||||
const key = resolveAnthropicApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveOpenaiApiKey', () => {
|
||||
const originalEnv = process.env['TAKT_OPENAI_API_KEY'];
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateGlobalConfigCache();
|
||||
mkdirSync(taktDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env['TAKT_OPENAI_API_KEY'] = originalEnv;
|
||||
} else {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
}
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return env var when set', () => {
|
||||
process.env['TAKT_OPENAI_API_KEY'] = 'sk-openai-from-env';
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBe('sk-openai-from-env');
|
||||
});
|
||||
|
||||
it('should fall back to config when env var is not set', () => {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
'openai_api_key: sk-openai-from-yaml',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBe('sk-openai-from-yaml');
|
||||
});
|
||||
|
||||
it('should return undefined when neither env var nor config is set', () => {
|
||||
delete process.env['TAKT_OPENAI_API_KEY'];
|
||||
const yaml = [
|
||||
'language: en',
|
||||
'default_piece: default',
|
||||
'log_level: info',
|
||||
'provider: claude',
|
||||
].join('\n');
|
||||
writeFileSync(configPath, yaml, 'utf-8');
|
||||
|
||||
const key = resolveOpenaiApiKey();
|
||||
expect(key).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
37
src/__tests__/cli-wrapper.test.ts
Normal file
37
src/__tests__/cli-wrapper.test.ts
Normal file
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Tests for the CLI wrapper URL handling.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { posix, win32, resolve } from 'node:path';
|
||||
|
||||
describe('cli wrapper import URL', () => {
|
||||
it('builds a file URL for Windows paths', () => {
|
||||
const winPath = win32.join('C:\\', 'work', 'git', 'takt', 'dist', 'app', 'cli', 'index.js');
|
||||
const url = pathToFileURL(winPath).href;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
expect(url).toBe('file:///C:/work/git/takt/dist/app/cli/index.js');
|
||||
return;
|
||||
}
|
||||
|
||||
expect(url).toMatch(/C:%5Cwork%5Cgit%5Ctakt%5Cdist%5Capp%5Ccli%5Cindex\.js$/);
|
||||
});
|
||||
|
||||
it('builds a file URL for POSIX paths', () => {
|
||||
const posixPath = posix.join('/', 'usr', 'local', 'lib', 'takt', 'dist', 'app', 'cli', 'index.js');
|
||||
const url = pathToFileURL(posixPath).href;
|
||||
|
||||
expect(url).toBe('file:///usr/local/lib/takt/dist/app/cli/index.js');
|
||||
});
|
||||
|
||||
it('uses pathToFileURL in the npm wrapper', async () => {
|
||||
const wrapperPath = resolve('bin', 'takt');
|
||||
const wrapperContents = await readFile(wrapperPath, 'utf8');
|
||||
|
||||
expect(wrapperContents).toContain('pathToFileURL');
|
||||
expect(wrapperContents).toContain('pathToFileURL(cliPath)');
|
||||
});
|
||||
});
|
||||
@ -39,7 +39,6 @@ describe('loadGlobalConfig', () => {
|
||||
const config = loadGlobalConfig();
|
||||
|
||||
expect(config.language).toBe('en');
|
||||
expect(config.trustedDirectories).toEqual([]);
|
||||
expect(config.defaultPiece).toBe('default');
|
||||
expect(config.logLevel).toBe('info');
|
||||
expect(config.provider).toBe('claude');
|
||||
|
||||
@ -156,6 +156,12 @@ describe('worktree branch deletion', () => {
|
||||
});
|
||||
|
||||
it('should delete regular (non-worktree) branches normally', () => {
|
||||
const defaultBranch = execFileSync('git', ['branch', '--show-current'], {
|
||||
cwd: testDir,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe',
|
||||
}).trim();
|
||||
|
||||
// Create a regular local branch
|
||||
const branchName = 'takt/20260203T1002-regular-branch';
|
||||
execFileSync('git', ['checkout', '-b', branchName], { cwd: testDir });
|
||||
@ -166,7 +172,7 @@ describe('worktree branch deletion', () => {
|
||||
execFileSync('git', ['commit', '-m', 'Test change'], { cwd: testDir });
|
||||
|
||||
// Switch back to main
|
||||
execFileSync('git', ['checkout', 'master'], { cwd: testDir });
|
||||
execFileSync('git', ['checkout', defaultBranch || 'main'], { cwd: testDir });
|
||||
|
||||
// Verify branch exists
|
||||
const branchesBefore = listTaktBranches(testDir);
|
||||
|
||||
@ -201,7 +201,6 @@ describe('GlobalConfigSchema', () => {
|
||||
const config = {};
|
||||
const result = GlobalConfigSchema.parse(config);
|
||||
|
||||
expect(result.trusted_directories).toEqual([]);
|
||||
expect(result.default_piece).toBe('default');
|
||||
expect(result.log_level).toBe('info');
|
||||
expect(result.provider).toBe('claude');
|
||||
@ -209,13 +208,11 @@ describe('GlobalConfigSchema', () => {
|
||||
|
||||
it('should accept valid config', () => {
|
||||
const config = {
|
||||
trusted_directories: ['/home/user/projects'],
|
||||
default_piece: 'custom',
|
||||
log_level: 'debug' as const,
|
||||
};
|
||||
|
||||
const result = GlobalConfigSchema.parse(config);
|
||||
expect(result.trusted_directories).toHaveLength(1);
|
||||
expect(result.log_level).toBe('debug');
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,438 +1,434 @@
|
||||
/**
|
||||
* Tests for pipeline execution
|
||||
*
|
||||
* Tests the orchestration logic with mocked dependencies.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock all external dependencies
|
||||
const mockFetchIssue = vi.fn();
|
||||
const mockCheckGhCli = vi.fn().mockReturnValue({ available: true });
|
||||
vi.mock('../infra/github/issue.js', () => ({
|
||||
fetchIssue: mockFetchIssue,
|
||||
formatIssueAsTask: vi.fn((issue: { title: string; body: string; number: number }) =>
|
||||
`## GitHub Issue #${issue.number}: ${issue.title}\n\n${issue.body}`
|
||||
),
|
||||
checkGhCli: mockCheckGhCli,
|
||||
}));
|
||||
|
||||
const mockCreatePullRequest = vi.fn();
|
||||
const mockPushBranch = vi.fn();
|
||||
const mockBuildPrBody = vi.fn(() => 'Default PR body');
|
||||
vi.mock('../infra/github/pr.js', () => ({
|
||||
createPullRequest: mockCreatePullRequest,
|
||||
pushBranch: mockPushBranch,
|
||||
buildPrBody: mockBuildPrBody,
|
||||
}));
|
||||
|
||||
const mockExecuteTask = vi.fn();
|
||||
vi.mock('../features/tasks/index.js', () => ({
|
||||
executeTask: mockExecuteTask,
|
||||
}));
|
||||
|
||||
// Mock loadGlobalConfig
|
||||
const mockLoadGlobalConfig = vi.fn();
|
||||
vi.mock('../infra/config/global/globalConfig.js', async (importOriginal) => ({ ...(await importOriginal<Record<string, unknown>>()),
|
||||
loadGlobalConfig: mockLoadGlobalConfig,
|
||||
}));
|
||||
|
||||
// Mock execFileSync for git operations
|
||||
const mockExecFileSync = vi.fn();
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFileSync: mockExecFileSync,
|
||||
}));
|
||||
|
||||
// Mock UI
|
||||
vi.mock('../shared/ui/index.js', () => ({
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
status: vi.fn(),
|
||||
blankLine: vi.fn(),
|
||||
header: vi.fn(),
|
||||
section: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}));
|
||||
// Mock debug logger
|
||||
vi.mock('../shared/utils/index.js', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const { executePipeline } = await import('../features/pipeline/index.js');
|
||||
|
||||
describe('executePipeline', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: git operations succeed
|
||||
mockExecFileSync.mockReturnValue('abc1234\n');
|
||||
// Default: no pipeline config
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return exit code 2 when neither --issue nor --task is specified', async () => {
|
||||
const exitCode = await executePipeline({
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 2 when gh CLI is not available', async () => {
|
||||
mockCheckGhCli.mockReturnValueOnce({ available: false, error: 'gh not found' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 99,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 2 when issue fetch fails', async () => {
|
||||
mockFetchIssue.mockImplementationOnce(() => {
|
||||
throw new Error('Issue not found');
|
||||
});
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 999,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 3 when piece fails', async () => {
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 99,
|
||||
title: 'Test issue',
|
||||
body: 'Test body',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(false);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 99,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(3);
|
||||
});
|
||||
|
||||
it('should return exit code 0 on successful task-only execution', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('passes provider/model overrides to task execution', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
provider: 'codex',
|
||||
model: 'codex-model',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: { provider: 'codex', model: 'codex-model' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should return exit code 5 when PR creation fails', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: false, error: 'PR failed' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(5);
|
||||
});
|
||||
|
||||
it('should create PR with correct branch when --auto-pr', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/test/pr/1' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
branch: 'fix/my-branch',
|
||||
autoPr: true,
|
||||
repo: 'owner/repo',
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
branch: 'fix/my-branch',
|
||||
repo: 'owner/repo',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use --task when both --task and positional task are provided', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'From --task flag',
|
||||
piece: 'magi',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'From --task flag',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'magi',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
describe('PipelineConfig template expansion', () => {
|
||||
it('should use commit_message_template when configured', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
commitMessageTemplate: 'fix: {title} (#{issue})',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 42,
|
||||
title: 'Login broken',
|
||||
body: 'Cannot login.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 42,
|
||||
piece: 'default',
|
||||
branch: 'test-branch',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Verify commit was called with expanded template
|
||||
const commitCall = mockExecFileSync.mock.calls.find(
|
||||
(call: unknown[]) => call[0] === 'git' && (call[1] as string[])[0] === 'commit',
|
||||
);
|
||||
expect(commitCall).toBeDefined();
|
||||
expect((commitCall![1] as string[])[2]).toBe('fix: Login broken (#42)');
|
||||
});
|
||||
|
||||
it('should use default_branch_prefix when configured', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
defaultBranchPrefix: 'feat/',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 10,
|
||||
title: 'Add feature',
|
||||
body: 'Please add.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 10,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Verify checkout -b was called with prefix
|
||||
const checkoutCall = mockExecFileSync.mock.calls.find(
|
||||
(call: unknown[]) => call[0] === 'git' && (call[1] as string[])[0] === 'checkout' && (call[1] as string[])[1] === '-b',
|
||||
);
|
||||
expect(checkoutCall).toBeDefined();
|
||||
const branchName = (checkoutCall![1] as string[])[2];
|
||||
expect(branchName).toMatch(/^feat\/issue-10-\d+$/);
|
||||
});
|
||||
|
||||
it('should use pr_body_template when configured for PR creation', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
prBodyTemplate: '## Summary\n{issue_body}\n\nCloses #{issue}',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 50,
|
||||
title: 'Fix auth',
|
||||
body: 'Auth is broken.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/pr/1' });
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 50,
|
||||
piece: 'default',
|
||||
branch: 'fix-auth',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// When prBodyTemplate is set, buildPrBody (mock) should NOT be called
|
||||
// Instead, the template is expanded directly
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
body: '## Summary\nAuth is broken.\n\nCloses #50',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should fall back to buildPrBody when no template is configured', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/pr/1' });
|
||||
|
||||
await executePipeline({
|
||||
task: 'Fix bug',
|
||||
piece: 'default',
|
||||
branch: 'fix-branch',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Should use buildPrBody (the mock)
|
||||
expect(mockBuildPrBody).toHaveBeenCalled();
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
body: 'Default PR body',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('--skip-git', () => {
|
||||
it('should skip branch creation, commit, push when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
|
||||
// No git operations should have been called
|
||||
const gitCalls = mockExecFileSync.mock.calls.filter(
|
||||
(call: unknown[]) => call[0] === 'git',
|
||||
);
|
||||
expect(gitCalls).toHaveLength(0);
|
||||
expect(mockPushBranch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore --auto-pr when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: true,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockCreatePullRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should still return piece failure exit code when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(false);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
/**
|
||||
* Tests for pipeline execution
|
||||
*
|
||||
* Tests the orchestration logic with mocked dependencies.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock all external dependencies
|
||||
const mockFetchIssue = vi.fn();
|
||||
const mockCheckGhCli = vi.fn().mockReturnValue({ available: true });
|
||||
vi.mock('../infra/github/issue.js', () => ({
|
||||
fetchIssue: mockFetchIssue,
|
||||
formatIssueAsTask: vi.fn((issue: { title: string; body: string; number: number }) =>
|
||||
`## GitHub Issue #${issue.number}: ${issue.title}\n\n${issue.body}`
|
||||
),
|
||||
checkGhCli: mockCheckGhCli,
|
||||
}));
|
||||
|
||||
const mockCreatePullRequest = vi.fn();
|
||||
const mockPushBranch = vi.fn();
|
||||
const mockBuildPrBody = vi.fn(() => 'Default PR body');
|
||||
vi.mock('../infra/github/pr.js', () => ({
|
||||
createPullRequest: mockCreatePullRequest,
|
||||
pushBranch: mockPushBranch,
|
||||
buildPrBody: mockBuildPrBody,
|
||||
}));
|
||||
|
||||
const mockExecuteTask = vi.fn();
|
||||
vi.mock('../features/tasks/index.js', () => ({
|
||||
executeTask: mockExecuteTask,
|
||||
}));
|
||||
|
||||
// Mock loadGlobalConfig
|
||||
const mockLoadGlobalConfig = vi.fn();
|
||||
vi.mock('../infra/config/global/globalConfig.js', async (importOriginal) => ({ ...(await importOriginal<Record<string, unknown>>()),
|
||||
loadGlobalConfig: mockLoadGlobalConfig,
|
||||
}));
|
||||
|
||||
// Mock execFileSync for git operations
|
||||
const mockExecFileSync = vi.fn();
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFileSync: mockExecFileSync,
|
||||
}));
|
||||
|
||||
// Mock UI
|
||||
vi.mock('../shared/ui/index.js', () => ({
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
status: vi.fn(),
|
||||
blankLine: vi.fn(),
|
||||
header: vi.fn(),
|
||||
section: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}));
|
||||
// Mock debug logger
|
||||
vi.mock('../shared/utils/index.js', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const { executePipeline } = await import('../features/pipeline/index.js');
|
||||
|
||||
describe('executePipeline', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: git operations succeed
|
||||
mockExecFileSync.mockReturnValue('abc1234\n');
|
||||
// Default: no pipeline config
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return exit code 2 when neither --issue nor --task is specified', async () => {
|
||||
const exitCode = await executePipeline({
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 2 when gh CLI is not available', async () => {
|
||||
mockCheckGhCli.mockReturnValueOnce({ available: false, error: 'gh not found' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 99,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 2 when issue fetch fails', async () => {
|
||||
mockFetchIssue.mockImplementationOnce(() => {
|
||||
throw new Error('Issue not found');
|
||||
});
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 999,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(2);
|
||||
});
|
||||
|
||||
it('should return exit code 3 when piece fails', async () => {
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 99,
|
||||
title: 'Test issue',
|
||||
body: 'Test body',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(false);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
issueNumber: 99,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(3);
|
||||
});
|
||||
|
||||
it('should return exit code 0 on successful task-only execution', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('passes provider/model overrides to task execution', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
provider: 'codex',
|
||||
model: 'codex-model',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: { provider: 'codex', model: 'codex-model' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should return exit code 5 when PR creation fails', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: false, error: 'PR failed' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(5);
|
||||
});
|
||||
|
||||
it('should create PR with correct branch when --auto-pr', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/test/pr/1' });
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
branch: 'fix/my-branch',
|
||||
autoPr: true,
|
||||
repo: 'owner/repo',
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
branch: 'fix/my-branch',
|
||||
repo: 'owner/repo',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use --task when both --task and positional task are provided', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'From --task flag',
|
||||
piece: 'magi',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'From --task flag',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'magi',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
describe('PipelineConfig template expansion', () => {
|
||||
it('should use commit_message_template when configured', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
commitMessageTemplate: 'fix: {title} (#{issue})',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 42,
|
||||
title: 'Login broken',
|
||||
body: 'Cannot login.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 42,
|
||||
piece: 'default',
|
||||
branch: 'test-branch',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Verify commit was called with expanded template
|
||||
const commitCall = mockExecFileSync.mock.calls.find(
|
||||
(call: unknown[]) => call[0] === 'git' && (call[1] as string[])[0] === 'commit',
|
||||
);
|
||||
expect(commitCall).toBeDefined();
|
||||
expect((commitCall![1] as string[])[2]).toBe('fix: Login broken (#42)');
|
||||
});
|
||||
|
||||
it('should use default_branch_prefix when configured', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
defaultBranchPrefix: 'feat/',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 10,
|
||||
title: 'Add feature',
|
||||
body: 'Please add.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 10,
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Verify checkout -b was called with prefix
|
||||
const checkoutCall = mockExecFileSync.mock.calls.find(
|
||||
(call: unknown[]) => call[0] === 'git' && (call[1] as string[])[0] === 'checkout' && (call[1] as string[])[1] === '-b',
|
||||
);
|
||||
expect(checkoutCall).toBeDefined();
|
||||
const branchName = (checkoutCall![1] as string[])[2];
|
||||
expect(branchName).toMatch(/^feat\/issue-10-\d+$/);
|
||||
});
|
||||
|
||||
it('should use pr_body_template when configured for PR creation', async () => {
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'en',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
pipeline: {
|
||||
prBodyTemplate: '## Summary\n{issue_body}\n\nCloses #{issue}',
|
||||
},
|
||||
});
|
||||
|
||||
mockFetchIssue.mockReturnValueOnce({
|
||||
number: 50,
|
||||
title: 'Fix auth',
|
||||
body: 'Auth is broken.',
|
||||
labels: [],
|
||||
comments: [],
|
||||
});
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/pr/1' });
|
||||
|
||||
await executePipeline({
|
||||
issueNumber: 50,
|
||||
piece: 'default',
|
||||
branch: 'fix-auth',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// When prBodyTemplate is set, buildPrBody (mock) should NOT be called
|
||||
// Instead, the template is expanded directly
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
body: '## Summary\nAuth is broken.\n\nCloses #50',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should fall back to buildPrBody when no template is configured', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
mockCreatePullRequest.mockReturnValueOnce({ success: true, url: 'https://github.com/pr/1' });
|
||||
|
||||
await executePipeline({
|
||||
task: 'Fix bug',
|
||||
piece: 'default',
|
||||
branch: 'fix-branch',
|
||||
autoPr: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
// Should use buildPrBody (the mock)
|
||||
expect(mockBuildPrBody).toHaveBeenCalled();
|
||||
expect(mockCreatePullRequest).toHaveBeenCalledWith(
|
||||
'/tmp/test',
|
||||
expect.objectContaining({
|
||||
body: 'Default PR body',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('--skip-git', () => {
|
||||
it('should skip branch creation, commit, push when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockExecuteTask).toHaveBeenCalledWith({
|
||||
task: 'Fix the bug',
|
||||
cwd: '/tmp/test',
|
||||
pieceIdentifier: 'default',
|
||||
projectCwd: '/tmp/test',
|
||||
agentOverrides: undefined,
|
||||
});
|
||||
|
||||
// No git operations should have been called
|
||||
const gitCalls = mockExecFileSync.mock.calls.filter(
|
||||
(call: unknown[]) => call[0] === 'git',
|
||||
);
|
||||
expect(gitCalls).toHaveLength(0);
|
||||
expect(mockPushBranch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore --auto-pr when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(true);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: true,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(mockCreatePullRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should still return piece failure exit code when skipGit is true', async () => {
|
||||
mockExecuteTask.mockResolvedValueOnce(false);
|
||||
|
||||
const exitCode = await executePipeline({
|
||||
task: 'Fix the bug',
|
||||
piece: 'default',
|
||||
autoPr: false,
|
||||
skipGit: true,
|
||||
cwd: '/tmp/test',
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,273 +1,271 @@
|
||||
/**
|
||||
* Tests for summarizeTaskName
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('../infra/providers/index.js', () => ({
|
||||
getProvider: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../infra/config/global/globalConfig.js', () => ({
|
||||
loadGlobalConfig: vi.fn(),
|
||||
getBuiltinPiecesEnabled: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
vi.mock('../shared/utils/index.js', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
import { getProvider } from '../infra/providers/index.js';
|
||||
import { loadGlobalConfig } from '../infra/config/global/globalConfig.js';
|
||||
import { summarizeTaskName } from '../infra/task/summarize.js';
|
||||
|
||||
const mockGetProvider = vi.mocked(getProvider);
|
||||
const mockLoadGlobalConfig = vi.mocked(loadGlobalConfig);
|
||||
|
||||
const mockProviderCall = vi.fn();
|
||||
const mockProvider = {
|
||||
call: mockProviderCall,
|
||||
callCustom: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockGetProvider.mockReturnValue(mockProvider);
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'ja',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
model: 'haiku',
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeTaskName', () => {
|
||||
it('should return AI-generated slug for Japanese task name', async () => {
|
||||
// Given: AI returns a slug for Japanese input
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'add-auth',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('認証機能を追加する', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('add-auth');
|
||||
expect(mockGetProvider).toHaveBeenCalledWith('claude');
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
'認証機能を追加する',
|
||||
expect.objectContaining({
|
||||
cwd: '/project',
|
||||
model: 'haiku',
|
||||
allowedTools: [],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should return AI-generated slug for English task name', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'fix-login-bug',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('Fix the login bug', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('fix-login-bug');
|
||||
});
|
||||
|
||||
it('should clean up AI response with extra characters', async () => {
|
||||
// Given: AI response has extra whitespace or formatting
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: ' Add-User-Auth! \n',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('ユーザー認証を追加', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('add-user-auth');
|
||||
});
|
||||
|
||||
it('should truncate long slugs to 30 characters without trailing hyphen', async () => {
|
||||
// Given: AI returns a long slug
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'this-is-a-very-long-slug-that-exceeds-thirty-characters',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('長いタスク名', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result.length).toBeLessThanOrEqual(30);
|
||||
expect(result).toBe('this-is-a-very-long-slug-that');
|
||||
expect(result).not.toMatch(/-$/); // No trailing hyphen
|
||||
});
|
||||
|
||||
it('should return "task" as fallback for empty AI response', async () => {
|
||||
// Given: AI returns empty string
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: '',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('task');
|
||||
});
|
||||
|
||||
it('should use custom model if specified in options', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'custom-task',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
await summarizeTaskName('test', { cwd: '/project', model: 'sonnet' });
|
||||
|
||||
// Then
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
model: 'sonnet',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should use provider from config.yaml', async () => {
|
||||
// Given: config has codex provider
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'ja',
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'codex',
|
||||
model: 'gpt-4',
|
||||
});
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'codex-task',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(mockGetProvider).toHaveBeenCalledWith('codex');
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
model: 'gpt-4',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should remove consecutive hyphens', async () => {
|
||||
// Given: AI response has consecutive hyphens
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'fix---multiple---hyphens',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('fix-multiple-hyphens');
|
||||
});
|
||||
|
||||
it('should remove leading and trailing hyphens', async () => {
|
||||
// Given: AI response has leading/trailing hyphens
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: '-leading-trailing-',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('leading-trailing');
|
||||
});
|
||||
|
||||
it('should throw error when config load fails', async () => {
|
||||
// Given: config loading throws error
|
||||
mockLoadGlobalConfig.mockImplementation(() => {
|
||||
throw new Error('Config not found');
|
||||
});
|
||||
|
||||
// When/Then
|
||||
await expect(summarizeTaskName('test', { cwd: '/project' })).rejects.toThrow('Config not found');
|
||||
});
|
||||
|
||||
it('should use romanization when useLLM is false', async () => {
|
||||
// When: useLLM is explicitly false
|
||||
const result = await summarizeTaskName('認証機能を追加する', { cwd: '/project', useLLM: false });
|
||||
|
||||
// Then: should not call provider, should return romaji
|
||||
expect(mockProviderCall).not.toHaveBeenCalled();
|
||||
expect(result).toMatch(/^[a-z0-9-]+$/);
|
||||
expect(result.length).toBeLessThanOrEqual(30);
|
||||
});
|
||||
|
||||
it('should handle mixed Japanese/English with romanization', async () => {
|
||||
// When
|
||||
const result = await summarizeTaskName('Add 認証機能', { cwd: '/project', useLLM: false });
|
||||
|
||||
// Then
|
||||
expect(result).toMatch(/^[a-z0-9-]+$/);
|
||||
expect(result).not.toMatch(/^-|-$/); // No leading/trailing hyphens
|
||||
});
|
||||
|
||||
it('should use LLM by default', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'add-auth',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When: useLLM not specified (defaults to true)
|
||||
await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then: should call provider
|
||||
expect(mockProviderCall).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
/**
|
||||
* Tests for summarizeTaskName
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('../infra/providers/index.js', () => ({
|
||||
getProvider: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../infra/config/global/globalConfig.js', () => ({
|
||||
loadGlobalConfig: vi.fn(),
|
||||
getBuiltinPiecesEnabled: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
vi.mock('../shared/utils/index.js', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
import { getProvider } from '../infra/providers/index.js';
|
||||
import { loadGlobalConfig } from '../infra/config/global/globalConfig.js';
|
||||
import { summarizeTaskName } from '../infra/task/summarize.js';
|
||||
|
||||
const mockGetProvider = vi.mocked(getProvider);
|
||||
const mockLoadGlobalConfig = vi.mocked(loadGlobalConfig);
|
||||
|
||||
const mockProviderCall = vi.fn();
|
||||
const mockProvider = {
|
||||
call: mockProviderCall,
|
||||
callCustom: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockGetProvider.mockReturnValue(mockProvider);
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'ja',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
model: 'haiku',
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeTaskName', () => {
|
||||
it('should return AI-generated slug for task name', async () => {
|
||||
// Given: AI returns a slug for input
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'add-auth',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('add-auth');
|
||||
expect(mockGetProvider).toHaveBeenCalledWith('claude');
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
'long task name for testing',
|
||||
expect.objectContaining({
|
||||
cwd: '/project',
|
||||
model: 'haiku',
|
||||
allowedTools: [],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should return AI-generated slug for English task name', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'fix-login-bug',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('fix-login-bug');
|
||||
});
|
||||
|
||||
it('should clean up AI response with extra characters', async () => {
|
||||
// Given: AI response has extra whitespace or formatting
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: ' Add-User-Auth! \n',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('add-user-auth');
|
||||
});
|
||||
|
||||
it('should truncate long slugs to 30 characters without trailing hyphen', async () => {
|
||||
// Given: AI returns a long slug
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'this-is-a-very-long-slug-that-exceeds-thirty-characters',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result.length).toBeLessThanOrEqual(30);
|
||||
expect(result).toBe('this-is-a-very-long-slug-that');
|
||||
expect(result).not.toMatch(/-$/); // No trailing hyphen
|
||||
});
|
||||
|
||||
it('should return "task" as fallback for empty AI response', async () => {
|
||||
// Given: AI returns empty string
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: '',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('task');
|
||||
});
|
||||
|
||||
it('should use custom model if specified in options', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'custom-task',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
await summarizeTaskName('test', { cwd: '/project', model: 'sonnet' });
|
||||
|
||||
// Then
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
model: 'sonnet',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should use provider from config.yaml', async () => {
|
||||
// Given: config has codex provider
|
||||
mockLoadGlobalConfig.mockReturnValue({
|
||||
language: 'ja',
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'codex',
|
||||
model: 'gpt-4',
|
||||
});
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'codex-task',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(mockGetProvider).toHaveBeenCalledWith('codex');
|
||||
expect(mockProviderCall).toHaveBeenCalledWith(
|
||||
'summarizer',
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
model: 'gpt-4',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should remove consecutive hyphens', async () => {
|
||||
// Given: AI response has consecutive hyphens
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'fix---multiple---hyphens',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('fix-multiple-hyphens');
|
||||
});
|
||||
|
||||
it('should remove leading and trailing hyphens', async () => {
|
||||
// Given: AI response has leading/trailing hyphens
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: '-leading-trailing-',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await summarizeTaskName('long task name for testing', { cwd: '/project' });
|
||||
|
||||
// Then
|
||||
expect(result).toBe('leading-trailing');
|
||||
});
|
||||
|
||||
it('should throw error when config load fails', async () => {
|
||||
// Given: config loading throws error
|
||||
mockLoadGlobalConfig.mockImplementation(() => {
|
||||
throw new Error('Config not found');
|
||||
});
|
||||
|
||||
// When/Then
|
||||
await expect(summarizeTaskName('test', { cwd: '/project' })).rejects.toThrow('Config not found');
|
||||
});
|
||||
|
||||
it('should use romanization when useLLM is false', async () => {
|
||||
// When: useLLM is explicitly false
|
||||
const result = await summarizeTaskName('romanization test', { cwd: '/project', useLLM: false });
|
||||
|
||||
// Then: should not call provider, should return romaji
|
||||
expect(mockProviderCall).not.toHaveBeenCalled();
|
||||
expect(result).toMatch(/^[a-z0-9-]+$/);
|
||||
expect(result.length).toBeLessThanOrEqual(30);
|
||||
});
|
||||
|
||||
it('should handle mixed Japanese/English with romanization', async () => {
|
||||
// When
|
||||
const result = await summarizeTaskName('Add romanization', { cwd: '/project', useLLM: false });
|
||||
|
||||
// Then
|
||||
expect(result).toMatch(/^[a-z0-9-]+$/);
|
||||
expect(result).not.toMatch(/^-|-$/); // No leading/trailing hyphens
|
||||
});
|
||||
|
||||
it('should use LLM by default', async () => {
|
||||
// Given
|
||||
mockProviderCall.mockResolvedValue({
|
||||
agent: 'summarizer',
|
||||
status: 'done',
|
||||
content: 'add-auth',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// When: useLLM not specified (defaults to true)
|
||||
await summarizeTaskName('test', { cwd: '/project' });
|
||||
|
||||
// Then: should call provider
|
||||
expect(mockProviderCall).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -36,7 +36,6 @@ export interface PipelineConfig {
|
||||
/** Global configuration for takt */
|
||||
export interface GlobalConfig {
|
||||
language: Language;
|
||||
trustedDirectories: string[];
|
||||
defaultPiece: string;
|
||||
logLevel: 'debug' | 'info' | 'warn' | 'error';
|
||||
provider?: 'claude' | 'codex' | 'mock';
|
||||
|
||||
@ -216,7 +216,6 @@ export const PieceCategoryConfigSchema = z.record(z.string(), PieceCategoryConfi
|
||||
/** Global config schema */
|
||||
export const GlobalConfigSchema = z.object({
|
||||
language: LanguageSchema.optional().default(DEFAULT_LANGUAGE),
|
||||
trusted_directories: z.array(z.string()).optional().default([]),
|
||||
default_piece: z.string().optional().default('default'),
|
||||
log_level: z.enum(['debug', 'info', 'warn', 'error']).optional().default('info'),
|
||||
provider: z.enum(['claude', 'codex', 'mock']).optional().default('claude'),
|
||||
|
||||
@ -285,6 +285,11 @@ export async function interactiveMode(
|
||||
|
||||
const result = await callAIWithRetry(initialInput, prompts.systemPrompt);
|
||||
if (result) {
|
||||
if (!result.success) {
|
||||
error(result.content);
|
||||
blankLine();
|
||||
return { confirmed: false, task: '' };
|
||||
}
|
||||
history.push({ role: 'assistant', content: result.content });
|
||||
blankLine();
|
||||
} else {
|
||||
@ -332,6 +337,11 @@ export async function interactiveMode(
|
||||
info(prompts.ui.summarizeFailed);
|
||||
continue;
|
||||
}
|
||||
if (!summaryResult.success) {
|
||||
error(summaryResult.content);
|
||||
blankLine();
|
||||
return { confirmed: false, task: '' };
|
||||
}
|
||||
const task = summaryResult.content.trim();
|
||||
const confirmed = await confirmTask(
|
||||
task,
|
||||
@ -362,6 +372,12 @@ export async function interactiveMode(
|
||||
|
||||
const result = await callAIWithRetry(trimmed, prompts.systemPrompt);
|
||||
if (result) {
|
||||
if (!result.success) {
|
||||
error(result.content);
|
||||
blankLine();
|
||||
history.pop();
|
||||
return { confirmed: false, task: '' };
|
||||
}
|
||||
history.push({ role: 'assistant', content: result.content });
|
||||
blankLine();
|
||||
} else {
|
||||
|
||||
@ -6,7 +6,6 @@
|
||||
*/
|
||||
|
||||
import { readFileSync, existsSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
import { GlobalConfigSchema } from '../../../core/models/index.js';
|
||||
import type { GlobalConfig, DebugConfig, Language } from '../../../core/models/index.js';
|
||||
@ -17,7 +16,6 @@ import { DEFAULT_LANGUAGE } from '../../../shared/constants.js';
|
||||
function createDefaultGlobalConfig(): GlobalConfig {
|
||||
return {
|
||||
language: DEFAULT_LANGUAGE,
|
||||
trustedDirectories: [],
|
||||
defaultPiece: 'default',
|
||||
logLevel: 'info',
|
||||
provider: 'claude',
|
||||
@ -68,7 +66,6 @@ export class GlobalConfigManager {
|
||||
const parsed = GlobalConfigSchema.parse(raw);
|
||||
const config: GlobalConfig = {
|
||||
language: parsed.language,
|
||||
trustedDirectories: parsed.trusted_directories,
|
||||
defaultPiece: parsed.default_piece,
|
||||
logLevel: parsed.log_level,
|
||||
provider: parsed.provider,
|
||||
@ -100,7 +97,6 @@ export class GlobalConfigManager {
|
||||
const configPath = getGlobalConfigPath();
|
||||
const raw: Record<string, unknown> = {
|
||||
language: config.language,
|
||||
trusted_directories: config.trustedDirectories,
|
||||
default_piece: config.defaultPiece,
|
||||
log_level: config.logLevel,
|
||||
provider: config.provider,
|
||||
@ -203,23 +199,6 @@ export function setProvider(provider: 'claude' | 'codex'): void {
|
||||
saveGlobalConfig(config);
|
||||
}
|
||||
|
||||
export function addTrustedDirectory(dir: string): void {
|
||||
const config = loadGlobalConfig();
|
||||
const resolvedDir = join(dir);
|
||||
if (!config.trustedDirectories.includes(resolvedDir)) {
|
||||
config.trustedDirectories.push(resolvedDir);
|
||||
saveGlobalConfig(config);
|
||||
}
|
||||
}
|
||||
|
||||
export function isDirectoryTrusted(dir: string): boolean {
|
||||
const config = loadGlobalConfig();
|
||||
const resolvedDir = join(dir);
|
||||
return config.trustedDirectories.some(
|
||||
(trusted) => resolvedDir === trusted || resolvedDir.startsWith(trusted + '/')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Anthropic API key.
|
||||
* Priority: TAKT_ANTHROPIC_API_KEY env var > config.yaml > undefined (CLI auth fallback)
|
||||
@ -290,4 +269,3 @@ export function getEffectiveDebugConfig(projectDir?: string): DebugConfig | unde
|
||||
|
||||
return debugConfig;
|
||||
}
|
||||
|
||||
|
||||
@ -12,8 +12,6 @@ export {
|
||||
getLanguage,
|
||||
setLanguage,
|
||||
setProvider,
|
||||
addTrustedDirectory,
|
||||
isDirectoryTrusted,
|
||||
resolveAnthropicApiKey,
|
||||
resolveOpenaiApiKey,
|
||||
loadProjectDebugConfig,
|
||||
|
||||
@ -28,8 +28,6 @@ export {
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
invalidateGlobalConfigCache,
|
||||
addTrustedDirectory,
|
||||
isDirectoryTrusted,
|
||||
loadProjectDebugConfig,
|
||||
getEffectiveDebugConfig,
|
||||
} from '../global/globalConfig.js';
|
||||
|
||||
@ -2,14 +2,40 @@
|
||||
* Codex provider implementation
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { callCodex, callCodexCustom, type CodexCallOptions } from '../codex/index.js';
|
||||
import { resolveOpenaiApiKey } from '../config/index.js';
|
||||
import type { AgentResponse } from '../../core/models/index.js';
|
||||
import type { Provider, ProviderCallOptions } from './types.js';
|
||||
|
||||
const NOT_GIT_REPO_MESSAGE =
|
||||
'Codex をご利用の場合 Git 管理下のディレクトリでのみ動作します。';
|
||||
|
||||
function isInsideGitRepo(cwd: string): boolean {
|
||||
try {
|
||||
const result = execFileSync('git', ['rev-parse', '--is-inside-work-tree'], {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe',
|
||||
}).trim();
|
||||
return result === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Codex provider - wraps existing Codex client */
|
||||
export class CodexProvider implements Provider {
|
||||
async call(agentName: string, prompt: string, options: ProviderCallOptions): Promise<AgentResponse> {
|
||||
if (!isInsideGitRepo(options.cwd)) {
|
||||
return {
|
||||
agent: agentName,
|
||||
status: 'blocked',
|
||||
content: NOT_GIT_REPO_MESSAGE,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
const callOptions: CodexCallOptions = {
|
||||
cwd: options.cwd,
|
||||
sessionId: options.sessionId,
|
||||
@ -24,6 +50,15 @@ export class CodexProvider implements Provider {
|
||||
}
|
||||
|
||||
async callCustom(agentName: string, prompt: string, systemPrompt: string, options: ProviderCallOptions): Promise<AgentResponse> {
|
||||
if (!isInsideGitRepo(options.cwd)) {
|
||||
return {
|
||||
agent: agentName,
|
||||
status: 'blocked',
|
||||
content: NOT_GIT_REPO_MESSAGE,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
const callOptions: CodexCallOptions = {
|
||||
cwd: options.cwd,
|
||||
sessionId: options.sessionId,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user