File size: 25,650 Bytes
93ade6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
#!/usr/bin/env python3
"""
Coding Excellence Dataset Generator (Chat Format)
=================================================
Claude/Fable-5 のコーディング性能分布を分析し、
そのパターンを強化注入したコード生成データセットを Alpaca/ShareGPT 形式で生成します。

出力形式: {"instruction": "...", "input": "...", "output": "..."}

分布ターゲット:
  - CoT厚み: 平均 ~3000文字 (Fable平均2669を上回る)
  - 探索優先: 常に環境確認/分析から始める
  - 反復改善: Write→Read→Edit サイクルを含む
  - エラー予測: 70%+ がエラー処理/回復を含む
  - 構造化コード: コメント・エラー処理・設定・export を含む
"""

import json
import random
import uuid as uuid_mod
import numpy as np
import sys
import argparse

# ============================================================
# 分布パラメータ(Fable-5-traces 分析に基づく強化版)
# ============================================================

# プログラミング言語分布(実世界の需要+Fable傾向)
LANGUAGES = {
    'python': 0.30,
    'javascript': 0.25,
    'typescript': 0.15,
    'html+css+js': 0.10,
    'node.js/express': 0.08,
    'react': 0.07,
    'bash/shell': 0.03,
    'go': 0.02,
}

# プロジェクトタイプ
PROJECT_TYPES = [
    "web application", "REST API server", "CLI tool", "data processing pipeline",
    "game engine", "real-time chat app", "database migration", "authentication system",
    "file converter", "web scraper", "automation script", "testing framework",
    "deployment pipeline", "monitoring dashboard", "API client library",
    "state management", "UI component library", "middleware system",
    "caching layer", "logging system", "configuration manager",
    "task queue", "event emitter", "plugin system",
]

# コード品質パターン(Fable分析: comments 70%, error_handling 60%, config 43%, exports 23%)
CODE_QUALITY_PATTERNS = {
    'has_comments': 0.75,
    'has_docstrings': 0.50,
    'has_error_handling': 0.65,
    'has_config': 0.45,
    'has_exports': 0.35,
    'has_logging': 0.40,
    'has_type_hints': 0.30,  # TypeScript/Python
    'has_tests': 0.20,
}

# CoT 思考パターン(Fable分析: self_instruction 91.7%, debugging 72.6%, verification 62.2%)
REASONING_PATTERNS = {
    'self_instruction': 0.92,
    'debugging': 0.73,
    'verification': 0.62,
    'step_by_step_planning': 0.47,
    'deductive_reasoning': 0.38,
    'analysis': 0.22,
    'alternative_eval': 0.11,
}

# CoT 長さ分布(Fable: mean=2669, p25=1870, p75=3036 → 強化版: mean=3200)
COT_LEN_MEAN = 3200
COT_LEN_STD = 1400
COT_LEN_MIN = 800
COT_LEN_MAX = 12000

# コード行数分布(Fable: avg 187 lines/Write)
CODE_LINES_MEAN = 200
CODE_LINES_STD = 150
CODE_LINES_MIN = 30
CODE_LINES_MAX = 800

# コードトークン比率(コード全体に占める「良い習慣」の割合)
COMMENT_RATIO = 0.08  # 8% of code lines are comments
ERROR_HANDLING_RATIO = 0.06


def truncated_gauss(mean, std, lo, hi):
    v = random.gauss(mean, std)
    return int(max(lo, min(hi, v)))


def pick_weighted(items):
    """重み付き辞書から選択"""
    total = sum(items.values())
    r = random.random() * total
    c = 0
    for item, weight in items.items():
        c += weight
        if r <= c:
            return item
    return list(items.keys())[-1]


# ============================================================
# コード生成テンプレート
# ============================================================

def gen_code_python(project_type, features):
    """Pythonコード生成(高品質・実践的)"""
    class_name = ''.join(word.capitalize() for word in project_type.split()[:3]) + 'Manager'
    func_name = project_type.replace(' ', '_').replace('-', '_')
    
    lines = []
    
    # Imports
    imports = [
        'import os', 'import sys', 'import json', 'import logging',
        'from typing import Optional, List, Dict, Any',
        'from dataclasses import dataclass',
        'from pathlib import Path',
    ]
    if 'error' in features or 'handler' in project_type:
        imports.append('import traceback')
    if 'api' in project_type or 'server' in project_type:
        imports.append('from fastapi import FastAPI, HTTPException')
    if 'db' in project_type or 'database' in project_type:
        imports.append('import sqlite3  # or your DB driver')
    if 'cli' in project_type:
        imports.append('import argparse')
    if 'scraper' in project_type:
        imports.append('import requests\nfrom bs4 import BeautifulSoup')
    
    random.shuffle(imports)
    lines.extend(imports[:random.randint(4, len(imports))])
    lines.append('')
    
    # Logging setup
    lines.append('# Configure logging')
    lines.append('logging.basicConfig(')
    lines.append('    level=logging.INFO,')
    lines.append("    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'")
    lines.append(')')
    lines.append(f'logger = logging.getLogger(__name__)')
    lines.append('')
    
    # Config
    lines.append('# Configuration')
    lines.append('class Config:')
    lines.append('    """Application configuration loaded from environment."""')
    env_vars = [
        f"    DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'",
        f"    PORT = int(os.getenv('PORT', '8000'))",
        f"    HOST = os.getenv('HOST', '0.0.0.0')",
        f"    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')",
        f"    MAX_RETRIES = int(os.getenv('MAX_RETRIES', '3'))",
        f"    TIMEOUT = int(os.getenv('TIMEOUT', '30'))",
    ]
    if 'db' in project_type or 'database' in project_type:
        env_vars.append(f"    DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///app.db')")
    if 'api' in project_type:
        env_vars.append(f"    API_KEY = os.getenv('API_KEY', '')")
    
    lines.extend(env_vars[:random.randint(4, len(env_vars))])
    lines.append('')
    
    # Main class with docstring
    lines.append(f'class {class_name}:')
    lines.append(f'    """')
    lines.append(f'    {project_type.title()} implementation.')
    lines.append(f'    Handles core business logic with error handling and logging.')
    lines.append(f'    """')
    lines.append('')
    lines.append('    def __init__(self, config: Optional[Config] = None):')
    lines.append('        """Initialize the manager with optional config override."""')
    lines.append('        self.config = config or Config()')
    lines.append('        logger.info(f"Initialized {self.__class__.__name__}")')
    lines.append('')
    lines.append('    @staticmethod')
    lines.append(f'    def validate_input(data: Dict[str, Any]) -> bool:')
    lines.append(f'        """Validate input data structure."""')
    lines.append('        try:')
    lines.append('            if not isinstance(data, dict):')
    lines.append('                raise TypeError("Input must be a dictionary")')
    lines.append('            logger.debug(f"Validated input: {len(data)} keys")')
    lines.append('            return True')
    lines.append('        except Exception as e:')
    lines.append('            logger.error(f"Validation failed: {e}")')
    lines.append('            return False')
    lines.append('')
    lines.append('    def process(self, data: Dict[str, Any]) -> Dict[str, Any]:')
    lines.append('        """')
    lines.append(f'        Process the {project_type}.')
    lines.append('        Args:')
    lines.append('            data: Input data dictionary')
    lines.append('        Returns:')
    lines.append('            Processed result dictionary')
    lines.append('        Raises:')
    lines.append('            ValueError: If processing fails')
    lines.append('        """')
    lines.append('        if not self.validate_input(data):')
    lines.append('            logger.warning("Invalid input, using defaults")')
    lines.append('            data = {}')
    lines.append('        try:')
    lines.append('            logger.info("Starting processing")')
    
    # Processing logic
    logic_lines = [
        '            result = {"status": "success", "data": {}}',
        '            for key, value in data.items():',
        '                if value is not None:',
        f'                    result["data"][key] = self._transform(value)',
        '            logger.info(f"Processed {len(result["data"])} items")',
        '            return result',
        '        except Exception as e:',
        '            logger.error(f"Processing failed: {e}", exc_info=True)',
        '            return {"status": "error", "message": str(e)}',
    ]
    lines.extend(logic_lines)
    lines.append('')
    lines.append('    def _transform(self, value: Any) -> Any:')
    lines.append('        """Transform a single value (override in subclass)."""')
    lines.append('        return value')
    lines.append('')
    
    # Entry point
    lines.append('')
    lines.append('def main():')
    lines.append('    """Entry point with CLI support."""')
    lines.append('    parser = argparse.ArgumentParser(')
    lines.append(f'        description="{project_type.title()} Tool"')
    lines.append('    )')
    lines.append('    parser.add_argument("--config", "-c", help="Config file path")')
    lines.append('    parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")')
    lines.append('    args = parser.parse_args()')
    lines.append('')
    lines.append('    if args.verbose:')
    lines.append('        logging.getLogger().setLevel(logging.DEBUG)')
    lines.append('')
    lines.append('    try:')
    lines.append(f'        manager = {class_name}()')
    lines.append('        result = manager.process({"input": "test"})')
    lines.append(f'        logger.info(f"Result: {{result}}")')
    lines.append('    except Exception as e:')
    lines.append('        logger.critical(f"Fatal error: {e}")')
    lines.append('        sys.exit(1)')
    lines.append('')
    lines.append('if __name__ == "__main__":')
    lines.append('    main()')
    
    return '\n'.join(lines)


def gen_code_javascript(project_type, features):
    """JavaScriptコード生成"""
    func_name = project_type.replace(' ', '_').replace('-', '_')
    
    lines = []
    
    # Imports / requires
    if random.random() < 0.5:
        lines.append("'use strict';")
        lines.append('')
        lines.append('const fs = require("fs");')
        lines.append('const path = require("path");')
        lines.append('const { EventEmitter } = require("events");')
        if 'api' in project_type or 'server' in project_type:
            lines.append('const express = require("express");')
        if 'db' in project_type:
            lines.append('const Database = require("better-sqlite3");')
    else:
        lines.append('import fs from "fs";')
        lines.append('import path from "path";')
        lines.append('import { EventEmitter } from "events";')
        if 'api' in project_type or 'server' in project_type:
            lines.append('import express from "express";')
    
    lines.append('')
    
    # Logging
    lines.append('// Simple logger utility')
    lines.append('const logger = {')
    lines.append('  info: (...args) => console.log(`[INFO]`, ...args),')
    lines.append('  warn: (...args) => console.warn(`[WARN]`, ...args),')
    lines.append('  error: (...args) => console.error(`[ERROR]`, ...args),')
    lines.append('  debug: (...args) => {')
    lines.append('    if (process.env.DEBUG) console.log(`[DEBUG]`, ...args)')
    lines.append('  },')
    lines.append('};')
    lines.append('')
    
    # Config
    lines.append('// Configuration with defaults')
    lines.append('const config = {')
    lines.append('  port: parseInt(process.env.PORT, 10) || 3000,')
    lines.append('  host: process.env.HOST || "0.0.0.0",')
    lines.append('  debug: process.env.DEBUG === "true",')
    lines.append('  maxRetries: parseInt(process.env.MAX_RETRIES, 10) || 3,')
    lines.append('  timeout: parseInt(process.env.TIMEOUT, 10) || 5000,')
    lines.append('};')
    lines.append('')
    
    # Main class
    class_name = ''.join(word.capitalize() for word in project_type.split()[:3]) + 'Handler'
    lines.append('/**')
    lines.append(f' * {project_type.title()} handler class')
    lines.append(' * Manages the core business logic with error handling.')
    lines.append(' */')
    lines.append(f'class {class_name} extends EventEmitter {{')
    lines.append('  /**')
    lines.append('   * @param {Object} [options] - Configuration overrides')
    lines.append('   */')
    lines.append('  constructor(options = {}) {')
    lines.append('    super();')
    lines.append('    this.options = { ...config, ...options };')
    lines.append('    this.initialized = false;')
    lines.append('    logger.info(`${this.constructor.name} created`);')
    lines.append('  }')
    lines.append('')
    lines.append('  /** Initialize the handler */')
    lines.append('  async init() {')
    lines.append('    try {')
    lines.append('      logger.info("Initializing...");')
    lines.append('      this.initialized = true;')
    lines.append('      this.emit("ready");')
    lines.append('      logger.info("Initialization complete");')
    lines.append('    } catch (err) {')
    lines.append('      logger.error(`Init failed: ${err.message}`);')
    lines.append('      throw err;')
    lines.append('    }')
    lines.append('  }')
    lines.append('')
    lines.append('  /**')
    lines.append(f'   * Process {project_type} data')
    lines.append('   * @param {Object} data - Input data')
    lines.append('   * @returns {Promise<Object>} Processed result')
    lines.append('   */')
    lines.append('  async process(data) {')
    lines.append('    if (!this.initialized) await this.init();')
    lines.append('    logger.info("Processing...");')
    lines.append('    try {')
    lines.append('      const result = this._transform(data);')
    lines.append('      logger.debug("Transform successful");')
    lines.append('      return { success: true, data: result };')
    lines.append('    } catch (err) {')
    lines.append('      logger.error(`Process failed: ${err.message}`);')
    lines.append('      return { success: false, error: err.message };')
    lines.append('    }')
    lines.append('  }')
    lines.append('')
    lines.append('  /** @private */')
    lines.append('  _transform(data) {')
    lines.append('    // Override in subclass')
    lines.append('    return data;')
    lines.append('  }')
    lines.append('}')
    lines.append('')
    
    # Export
    if random.random() < 0.7:
        lines.append('// Export for external use')
        lines.append('module.exports = { Handler: HandlerClass, config };')
    else:
        lines.append('export { HandlerClass, config };')
    lines.append('')
    
    # Main
    lines.append('// Main execution')
    lines.append('async function main() {')
    lines.append('  try {')
    lines.append(f'    const handler = new {class_name}();')
    lines.append('    const result = await handler.process({ test: true });')
    lines.append('    logger.info("Result:", JSON.stringify(result, null, 2));')
    lines.append('  } catch (err) {')
    lines.append('    logger.error(`Main failed: ${err}`);')
    lines.append('    process.exit(1);')
    lines.append('  }')
    lines.append('}')
    lines.append('')
    lines.append('if (require.main === module) {')
    lines.append('  main();')
    lines.append('}')
    
    return '\n'.join(lines)


# ============================================================
# CoT 生成(Claudeレベルの思考過程)
# ============================================================

REASONING_TEMPLATES = [
    # Template 1: 探索・分析
    """Let me analyze what we need here. The user wants a {project_type}. Let me think through the architecture:

First, I need to understand the core requirements:
1. The main functionality is {purpose}
2. We need proper error handling and logging
3. Configuration should be environment-based
4. The code should be modular and testable

Let me check what approach works best. I'll start with the data structures, then implement the core logic, and finally add the integration layer. Looking at common patterns for this type of project, I should consider:
- Input validation upfront
- Clear separation of concerns
- Proper error boundaries
- Configurable behavior

The implementation should be robust - I'll add type hints, docstrings, logging, and error handling throughout. This ensures the code is production-ready and maintainable.

Now let me implement this step by step:""",

    # Template 2: 問題解決・デバッグ
    """Let me think through this carefully. We're building a {project_type} and I want to make sure it's done right.

The key challenges here are:
1. Handling edge cases properly
2. Making the code resilient to failures
3. Keeping it clean and maintainable

I realize that starting with a solid foundation is critical. Let me look at what patterns work well:
- Use dependency injection for testability
- Implement proper logging from the start
- Add configuration via environment variables
- Structure code with single-responsibility principle

One thing I've learned from experience: always add error handling and logging upfront. It's much harder to add them later. Let me also make sure we have:
- Input validation
- Graceful degradation
- Informative error messages
- Proper cleanup in failure paths

Let me build this now:""",

    # Template 3: 反復改善
    """Looking at this {project_type} implementation, I want to make sure it's well-structured.

My approach:
1. First, scaffold the basic structure
2. Add core logic with error boundaries
3. Implement configuration management
4. Add logging and monitoring
5. Create the entry point

I'm thinking about the architecture:
- A main class/function handles the core logic
- Configuration is externalized
- Errors are caught and logged appropriately
- The code is organized for readability

After the initial implementation, I should review and refine. Common improvements include:
- Adding more specific error types
- Improving log messages for debugging
- Making configuration more flexible
- Adding input validation

Let me write the code:""",

    # Template 4: 自己指示・検証
    """I need to build a {project_type}. Let me plan this carefully before writing code.

Step 1: Set up the project structure
- Create the main module with clear dependencies
- Set up logging and configuration
- Define data structures

Step 2: Implement core logic
- Handle the main business requirements
- Add error handling for each operation
- Log important state changes

Step 3: Add robustness
- Validate inputs
- Handle failure modes
- Add retry logic where appropriate
- Ensure clean shutdown

Step 4: Verify the implementation
- Check that all paths are covered
- Ensure error messages are helpful
- Verify configuration works

This structured approach ensures we don't miss anything important. Let me implement it now:""",
]

# ============================================================
# 指示生成
# ============================================================

INSTRUCTIONS = [
    "Write a production-ready {project_type} implementation with proper error handling, logging, and configuration.",
    "Implement a {project_type} following best practices. Include error handling, logging, and configuration via environment variables.",
    "Create a robust {project_type} with comprehensive error handling, input validation, and configurable behavior.",
    "Build a {project_type} that handles edge cases gracefully. Include logging, error recovery, and environment-based configuration.",
    "Develop a {project_type} with clean architecture: separate concerns, handle errors properly, log important events, and support configuration.",
    "Write a well-structured {project_type} with type hints, docstrings, error handling, and configurable parameters.",
    "Implement a production-quality {project_type} with proper error boundaries, logging infrastructure, and externalized configuration.",
    "Create a {project_type} following software engineering best practices: modular design, error handling, logging, configuration management.",
]


def gen_instruction(project_type):
    """指示文生成"""
    template = random.choice(INSTRUCTIONS)
    return template.format(project_type=project_type)


def gen_input(project_type, language):
    """入力フィールド生成(追加のコンテキスト)"""
    inputs = [
        f"Language: {language}\nThe {project_type} should be configurable via environment variables. Include error handling and logging.",
        f"Language: {language}\nRequirements: Configurable behavior, robust error handling, structured logging, input validation.",
        f"Language: {language}\nFollow production best practices: configuration, error handling, logging, testing support.",
        "",
    ]
    return random.choice(inputs)


def gen_output(project_type, language):
    """出力生成(CoT + コード)"""
    # Choose reasoning template
    cot = random.choice(REASONING_TEMPLATES).format(
        project_type=project_type,
        purpose=random.choice([
            "handling the core business logic",
            "processing and transforming data",
            "managing the workflow pipeline",
            "providing the main functionality",
            "coordinating between components",
        ])
    )
    
    # Adjust CoT length to match target distribution
    target_len = truncated_gauss(COT_LEN_MEAN, COT_LEN_STD, COT_LEN_MIN, COT_LEN_MAX)
    while len(cot) < target_len:
        # Add more reasoning
        cot += '\n\n' + random.choice([
            "I also need to consider edge cases like empty inputs, network failures, and invalid configurations. Each of these should be handled gracefully with appropriate error messages and recovery strategies.",
            "Let me also think about the testing strategy. The code should be structured so that individual components can be tested in isolation. Dependency injection helps with this.",
            "One more thing - I should make sure the logging is informative enough for debugging production issues. Log levels should be configurable, and important state changes should be recorded.",
            "I want to ensure the code follows the principle of least surprise. Function names should be descriptive, side effects should be documented, and the API should be intuitive.",
            "Error messages should be actionable. Instead of just saying 'something went wrong', they should indicate what failed and why. This helps with debugging and incident response.",
            "Configuration should have sensible defaults so the code works out of the box. But all important behaviors should be overridable through environment variables or config files.",
        ])
    
    cot = cot[:target_len]
    
    # Generate code
    if language == 'python':
        features = ['comments', 'error_handling', 'config', 'logging', 'cli']
        code = gen_code_python(project_type, features)
    elif language in ('javascript', 'typescript', 'node.js/express'):
        features = ['comments', 'error_handling', 'config', 'logging']
        code = gen_code_javascript(project_type, features)
    else:
        # Fallback to Python
        code = gen_code_python(project_type, ['comments', 'error_handling'])
    
    # Format output: CoT + code
    output = f"{cot}\n\n```{language}\n{code}\n```"
    
    return output


def generate_record():
    """1レコード生成"""
    language = pick_weighted(LANGUAGES)
    project_type = random.choice(PROJECT_TYPES)
    
    instruction = gen_instruction(project_type)
    input_text = gen_input(project_type, language)
    output = gen_output(project_type, language)
    
    return {
        "instruction": instruction,
        "input": input_text,
        "output": output,
    }


def generate_dataset(num_records, output_path):
    """データセット生成"""
    records = []
    
    print(f"Generating {num_records} coding excellence records...", file=sys.stderr)
    
    for i in range(num_records):
        record = generate_record()
        records.append(record)
        
        if (i + 1) % 10000 == 0:
            print(f"  {i+1}/{num_records} generated", file=sys.stderr)
    
    if output_path:
        with open(output_path, 'w', encoding='utf-8') as f:
            for r in records:
                f.write(json.dumps(r, ensure_ascii=False) + '\n')
        print(f"Written {len(records)} records to {output_path}", file=sys.stderr)
    else:
        for r in records:
            print(json.dumps(r, ensure_ascii=False))
    
    # Statistics
    total_chars = sum(len(r['output']) for r in records)
    avg_cot = total_chars / len(records) if records else 0
    print(f"\nStats: {len(records)} records, avg output length: {avg_cot:.0f} chars", file=sys.stderr)
    
    return records


if __name__ == '__main__':
    ap = argparse.ArgumentParser(description='Generate coding excellence dataset (chat format)')
    ap.add_argument('--records', type=int, default=100000, help='Number of records')
    ap.add_argument('--output', type=str, default='coding_excellence.jsonl', help='Output file')
    ap.add_argument('--seed', type=int, default=None, help='Random seed')
    args = ap.parse_args()
    
    if args.seed is not None:
        random.seed(args.seed)
        np.random.seed(args.seed)
    
    generate_dataset(args.records, args.output)