const fs = require('fs'); const path = require('path'); /** * Inserts default samples (harnesses, batch tasks, and workflows) into the database. * @param {string} projectId * @param {object} dbInstance The database instance (SqliteDb or JsonFallbackDb) */ function insertDefaultSamples(projectId, dbInstance) { const isPackaged = (() => { try { const { app } = require('electron'); return app && app.isPackaged; } catch (e) { return false; } })(); if (process.env.SKIP_DEFAULT_SAMPLES || isPackaged || process.env.NODE_ENV === 'production') { return; } if (!dbInstance) { console.error('[DefaultSamplesLoader] Cannot insert samples: dbInstance is undefined'); return; } // 1. 하네스 샘플 3종 const harnesses = [ { id: 'cell-design-lint', name: '셀 설계 정적 린터 검증', description: '배터리 anode/cathode 레시피 설정 및 두께 범위(0.05 ~ 0.15mm) 등 물리 스펙 기본 규칙 위반 여부를 검증하는 린터 스크립트입니다.', validation_command: 'npm run lint', max_retries: 3, trigger_pattern: 'src/**/*.js', success_criteria: '{"regex_match": "PASS"}', tool_chain: '["node", "npm"]' }, { id: 'battery-spec-test', name: '배터리 용량 시뮬레이터 검증', description: '설계된 배터리 셀 사양에 대한 에너지 밀도(Wh/kg) 및 수명 예측 검증용 단위 테스트를 가동합니다.', validation_command: 'npm test', max_retries: 5, trigger_pattern: 'tests/**/*.js', success_criteria: '{"regex_match": "OK"}', tool_chain: '["node", "npm"]' }, { id: 'integrity-config-validator', name: '무결성 설정 파일 검증', description: '프로젝트 내 주요 환경 변수 및 설정 사양 데이터 파일(JSON)의 스키마 구조 정합성을 검증합니다.', validation_command: 'node scripts/validate-spec.js', max_retries: 2, trigger_pattern: 'config/*.json', success_criteria: '{"regex_match": "valid"}', tool_chain: '["node"]' } ]; for (const h of harnesses) { try { const existing = dbInstance.getHarness(h.id); if (!existing) { dbInstance.saveHarness(projectId, h); } } catch (e) { console.error('[SampleHarness] Failed to insert harness sample:', e.message); } } // 2. 배치 작업 샘플 2종 const batchTasks = [ { id: 'task_daily_build_and_lint', name: '매일 빌드 및 린트 검증', project_id: projectId, cron_expr: '0 3 * * *', is_active: 0, is_tested_success: 0, steps_json: JSON.stringify([ { id: 'lint', type: 'cli', name: '린트 분석 (Mocked)', config: { command: 'echo "Running mock linter..." && echo "PASS"' }, on_failure: 'abort' }, { id: 'test', type: 'cli', name: '단위 테스트 (Mocked)', config: { command: 'echo "Running mock battery spec tests..." && echo "OK"' }, on_failure: 'continue' } ]) }, { id: 'task_rag_indexing', name: '위키 온톨로지 지식 인덱싱 스케줄', project_id: projectId, cron_expr: '0 1 * * *', is_active: 0, is_tested_success: 0, steps_json: JSON.stringify([ { id: 'wiki_index', type: 'cli', name: '위키 색인 빌드 (Mocked)', config: { command: 'echo "Building project ontology graph..." && echo "Done"' }, on_failure: 'abort' } ]) } ]; for (const t of batchTasks) { try { const tasks = dbInstance.getBatchTasks(projectId); const existing = tasks ? tasks.find(x => x.id === t.id) : null; if (!existing) { dbInstance.saveBatchTask(projectId, t); } } catch (e) { console.error('[SampleBatch] Failed to insert batch sample:', e.message); } } // 3. 배터리 역설계 오케스트레이션 워크플로우 샘플 (Mocked) const workflowObj = { id: 'wf_battery_redesign', name: '🔋 배터리 역설계 오케스트레이션 워크플로우 (Mocked)', description: '목업 모델 및 시뮬레이터 API를 연동하여 기획 사양에 따른 전극 레시피 및 설계를 반복 루프로 조율하는 의사결정 인과 체인 워크플로우 예시입니다.', graph_json: JSON.stringify({ nodes: [ { id: 'input_init', name: '1. Input Gateway', type: 'input', config: { filePath: 'cell_data.csv', targetSpec: { energy_density: 250 } } }, { id: 'cell_gen', name: '2. Cell Design Sub-Agent', type: 'agent', config: { agentProfileId: 'cell_gen', prompt: 'Target spec: energy_density={{nodes.input_init.output.targetSpec.energy_density}} Wh/kg. Run mock redesign model and output anode recipe config.' } }, { id: 'spec_eval', name: '3. Spec Validator', type: 'validator', config: { target: { energy_density: { type: 'lower_bound', value: 250 } }, predictions: '{{nodes.cell_gen.output.new_cell_design}}' } }, { id: 'loop_gate', name: '4. Loop Gate', type: 'loop', config: { overallResult: '{{nodes.spec_eval.output.overallResult}}' } } ], edges: [ { source: 'input_init', target: 'cell_gen' }, { source: 'cell_gen', target: 'spec_eval' }, { source: 'spec_eval', target: 'loop_gate' } ] }) }; // 4. 배터리 고도화 제어 워크플로우 샘플 (Mocked) const workflowAdvancedObj = { id: 'wf_battery_advanced', name: '🔋 배터리 고도화 제어 워크플로우 (Mocked)', description: '조건 분기, 다중 에이전트, 루프백, 그리고 지식 생성(보고서/노트) 노드가 포함된 고도화된 자동화 최적화 시나리오입니다.', graph_json: JSON.stringify({ nodes: [ { id: 'input_init', name: '1. Input Gateway', type: 'input', config: { filePath: 'cell_data.csv', targetSpec: { energy_density: 250 } } }, { id: 'cell_gen', name: '2. Cell Design Sub-Agent', type: 'agent', config: { agentProfileId: 'cell_gen', prompt: 'Target spec: energy_density={{nodes.input_init.output.targetSpec.energy_density}} Wh/kg. Run mock redesign model.' } }, { id: 'spec_eval', name: '3. Spec Validator', type: 'validator', config: { target: { energy_density: { type: 'lower_bound', value: 250 } }, predictions: '{{nodes.cell_gen.output.new_cell_design}}' } }, { id: 'temp_check', name: '4. Temp/Thickness Check (Condition)', type: 'condition', config: { expression: '{{nodes.cell_gen.output.new_cell_design.anode_thickness}} > 0.09', trueNodeId: 'cooling_gen', falseNodeId: 'loop_gate' } }, { id: 'cooling_gen', name: '5. Cooling Design Sub-Agent', type: 'agent', config: { agentProfileId: 'cooling_agent', prompt: 'Anode thickness is {{nodes.cell_gen.output.new_cell_design.anode_thickness}} (> 0.09). Design cooling pack.' } }, { id: 'loop_gate', name: '6. Loop Gate', type: 'loop', config: { overallResult: '{{nodes.spec_eval.output.overallResult}}', loopTargetNodeId: 'cell_gen' } }, { id: 'note_gen', name: '7. Wiki Knowledge Note Writer', type: 'note', config: { title: '배터리 설계 지식노트 - {{runId}}', tags: ['battery', 'knowledge', 'recipe'], content: '### 배터리 최적화 설계 완료\n- 에너지 밀도: {{nodes.cell_gen.output.new_cell_design.energy_density}} Wh/kg\n- 음극 두께: {{nodes.cell_gen.output.new_cell_design.anode_thickness}} mm\n- 최종 판정: {{nodes.spec_eval.output.overallResult}}' } }, { id: 'report_gen', name: '8. PDF/Markdown Report Generator', type: 'report', config: { filePath: 'wiki/workflows/reports/battery_final_{{runId}}.md', template: '# 최종 배터리 최적화 보고서\n\n- Run ID: {{runId}}\n- 최종 판정: {{nodes.spec_eval.output.overallResult}}\n- 상세 스펙: {{nodes.cell_gen.output.new_cell_design}}' } } ], edges: [ { source: 'input_init', target: 'cell_gen' }, { source: 'cell_gen', target: 'spec_eval' }, { source: 'spec_eval', target: 'temp_check' }, { source: 'temp_check', target: 'cooling_gen' }, { source: 'cooling_gen', target: 'loop_gate' }, { source: 'temp_check', target: 'loop_gate' }, { source: 'loop_gate', target: 'note_gen' }, { source: 'note_gen', target: 'report_gen' }, { source: 'loop_gate', target: 'cell_gen', loopback: true } ] }) }; try { const existing = dbInstance.getWorkflow(workflowObj.id); if (!existing) { dbInstance.saveWorkflow(projectId, workflowObj); } } catch (e) { console.error('[SampleWorkflow] Failed to insert workflow sample:', e.message); } try { const existing = dbInstance.getWorkflow(workflowAdvancedObj.id); if (!existing) { dbInstance.saveWorkflow(projectId, workflowAdvancedObj); } } catch (e) { console.error('[SampleWorkflow] Failed to insert advanced workflow sample:', e.message); } } module.exports = { insertDefaultSamples };