{
 "name": "[HR/인사] 지원자 맞춤 면접 질문 생성 Agent",
 "nodes": [
  {
   "id": "1",
   "name": "면접 질문 생성 요청",
   "notes": "교육용 시작점입니다. 운영에서는 면접 일정 확정 이벤트 Webhook 또는 채용시스템 API 이벤트로 교체합니다.",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2.1,
   "onError": "continueRegularOutput",
   "position": [
    256,
    304
   ],
   "parameters": {
    "httpMethod": "POST",
    "path": "interview-questions-demo",
    "responseMode": "responseNode",
    "options": {}
   }
  },
  {
   "id": "2",
   "name": "입력 정규화 및 개인정보 최소화",
   "notes": "지원자 원문을 그대로 넘기지 않고 질문 생성에 필요한 최소 필드로 정규화합니다. 실무에서는 이 앞단에 파일 파싱/OCR/채용시스템 조회 노드를 둡니다.",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    480,
    304
   ],
   "parameters": {
    "jsCode": "const incoming = $input.first()?.json ?? {};\nconst body = incoming.body ?? incoming;\nconst now = new Date().toISOString();\n\nconst sample = {\n  candidate: {\n    candidate_id: 'C001',\n    application_id: 'A001',\n    name: '김지원',\n    total_years: 4,\n    domains: ['HR', 'Data Analysis'],\n    skills: ['SQL', 'Python', 'Tableau'],\n    projects: [\n      {\n        name: '채용 퍼널 데이터 분석',\n        role: '분석 담당',\n        impact: '서류-면접 전환율 개선 과제 도출',\n        evidence: '지원서: 채용 퍼널 데이터를 분석해 서류-면접 전환율 개선 과제를 도출'\n      }\n    ]\n  },\n  jd: {\n    job_id: 'J001',\n    position_name: 'HR Data Analyst',\n    responsibilities: ['채용 퍼널 분석', 'HR 대시보드 운영', '리포트 자동화'],\n    must_have: ['SQL', '데이터 해석', 'HR 도메인 이해'],\n    nice_to_have: ['자동화 경험', 'BI 도구 경험'],\n    interview_round: '1차'\n  },\n  question_library: [\n    {\n      question_id: 'Q001',\n      role_family: 'HR/Data',\n      competency: '문제정의',\n      difficulty: '중',\n      interview_round: '1차',\n      base_question: '채용 퍼널에서 가장 먼저 봐야 할 병목 지표는 무엇인가요?',\n      evaluation_points: ['지표 정의', '근거 설명', '개선 액션']\n    },\n    {\n      question_id: 'Q002',\n      role_family: 'HR/Data',\n      competency: '데이터해석',\n      difficulty: '중',\n      interview_round: '1차',\n      base_question: '데이터 분석 결과가 현업 의사결정으로 이어진 경험을 설명해주세요.',\n      evaluation_points: ['분석 맥락', '커뮤니케이션', '결과 검증']\n    },\n    {\n      question_id: 'Q003',\n      role_family: 'HR/Automation',\n      competency: '자동화설계',\n      difficulty: '중',\n      interview_round: '1차',\n      base_question: '반복 HR 업무를 자동화할 때 가장 먼저 확인해야 할 조건은 무엇인가요?',\n      evaluation_points: ['업무 범위화', '예외 처리', '운영 안정성']\n    },\n    {\n      question_id: 'Q004',\n      role_family: 'HR/Data',\n      competency: '이해관계자관리',\n      difficulty: '상',\n      interview_round: '2차',\n      base_question: '현업 리더와 채용 기준이 충돌할 때 어떤 근거로 조율하겠습니까?',\n      evaluation_points: ['기준 합의', '데이터 기반 설득', '리스크 관리']\n    }\n  ]\n};\n\nfunction asList(value) {\n  if (Array.isArray(value)) return value.map(v => String(v).trim()).filter(Boolean);\n  if (value === undefined || value === null || value === '') return [];\n  return String(value).split(/[,;\\n]/).map(v => v.trim()).filter(Boolean);\n}\n\nfunction maskName(name, fallback) {\n  const text = String(name || '').trim();\n  if (!text) return fallback || '지원자';\n  return `${text.charAt(0)}OO`;\n}\n\nconst rawCandidate = { ...sample.candidate, ...(body.candidate ?? {}) };\nconst rawJd = { ...sample.jd, ...(body.jd ?? {}) };\nconst library = Array.isArray(body.question_library) && body.question_library.length > 0\n  ? body.question_library\n  : sample.question_library;\n\nconst candidate = {\n  candidate_id: String(rawCandidate.candidate_id || rawCandidate.application_id || 'C001'),\n  application_id: String(rawCandidate.application_id || rawCandidate.candidate_id || 'A001'),\n  display_name: maskName(rawCandidate.name, rawCandidate.candidate_id),\n  total_years: Number(rawCandidate.total_years || 0),\n  domains: asList(rawCandidate.domains),\n  skills: asList(rawCandidate.skills),\n  projects: Array.isArray(rawCandidate.projects) ? rawCandidate.projects.map(project => ({\n    name: String(project.name || '주요 프로젝트'),\n    role: String(project.role || '역할 미확인'),\n    impact: String(project.impact || '성과 미확인'),\n    evidence: String(project.evidence || project.summary || '지원서 근거 확인 필요')\n  })) : []\n};\n\nconst jd = {\n  job_id: String(rawJd.job_id || 'J001'),\n  position_name: String(rawJd.position_name || rawJd.position || '직무 미확인'),\n  responsibilities: asList(rawJd.responsibilities),\n  must_have: asList(rawJd.must_have),\n  nice_to_have: asList(rawJd.nice_to_have),\n  interview_round: String(rawJd.interview_round || '1차')\n};\n\nconst validation_errors = [];\nif (!candidate.candidate_id) validation_errors.push('candidate_id가 필요합니다.');\nif (!jd.job_id) validation_errors.push('job_id가 필요합니다.');\nif (jd.must_have.length === 0 && jd.responsibilities.length === 0) validation_errors.push('JD 핵심 요건 또는 주요업무가 필요합니다.');\nif (library.length === 0) validation_errors.push('질문 라이브러리가 비어 있습니다.');\n\nreturn [{\n  json: {\n    run_id: `interview-question-demo-${Date.now()}`,\n    generated_at: now,\n    source_mode: body.candidate || body.jd ? 'request_payload' : 'built_in_sample',\n    candidate,\n    jd,\n    question_library: library,\n    validation_errors,\n    privacy_policy: {\n      minimized_fields: ['name', 'phone', 'email', 'birthdate', 'address', 'photo'],\n      note: '질문 생성에는 직무 경험, 프로젝트, 기술, JD 요건만 사용합니다.'\n    }\n  }\n}];"
   }
  },
  {
   "id": "3",
   "name": "질문 라이브러리 태그 검색",
   "notes": "교육용 RAG 대체 단계입니다. Google Sheets/DB의 질문 라이브러리를 태그로 검색하고, 실무에서는 vector DB 검색으로 교체합니다.",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    704,
    304
   ],
   "parameters": {
    "jsCode": "const data = $input.first().json;\nconst candidate = data.candidate;\nconst jd = data.jd;\n\nfunction norm(value) {\n  return String(value || '').toLowerCase().trim();\n}\n\nconst searchTerms = [\n  jd.position_name,\n  jd.interview_round,\n  ...jd.responsibilities,\n  ...jd.must_have,\n  ...jd.nice_to_have,\n  ...candidate.domains,\n  ...candidate.skills\n].map(norm).filter(Boolean);\n\nconst retrieved = data.question_library.map((question) => {\n  const haystack = norm([\n    question.question_id,\n    question.role_family,\n    question.competency,\n    question.difficulty,\n    question.interview_round,\n    question.base_question,\n    ...(Array.isArray(question.evaluation_points) ? question.evaluation_points : [])\n  ].join(' '));\n\n  let score = 0;\n  for (const term of searchTerms) {\n    if (term && haystack.includes(term)) score += 2;\n    if (term && term.includes('hr') && haystack.includes('hr')) score += 1;\n    if (term && term.includes('data') && haystack.includes('data')) score += 1;\n  }\n\n  if (norm(question.interview_round) === norm(jd.interview_round)) score += 3;\n  if (haystack.includes('hr')) score += 1;\n\n  return {\n    ...question,\n    retrieval_score: score,\n    retrieval_reason: score > 0\n      ? 'JD 요건, 지원자 경험, 면접 라운드와 태그가 매칭됨'\n      : '검색 조건과 직접 매칭되지 않음'\n  };\n}).filter(question => question.retrieval_score > 0)\n  .sort((a, b) => b.retrieval_score - a.retrieval_score)\n  .slice(0, 6);\n\nreturn [{\n  json: {\n    ...data,\n    retrieval_query: {\n      terms: searchTerms,\n      strategy: '교육용 태그 검색. 실무에서는 Vector Store RAG 또는 DB 검색으로 교체합니다.'\n    },\n    retrieved_questions: retrieved,\n    retrieval_warnings: retrieved.length === 0 ? ['질문 라이브러리 검색 결과가 없어 기본 질문 생성으로 진행합니다.'] : []\n  }\n}];"
   }
  },
  {
   "id": "4",
   "name": "맞춤 질문 세트 생성",
   "notes": "교육용 규칙 기반 질문 생성입니다. 운영에서는 이 노드를 AI Agent/OpenAI Chat Model로 교체하되 출력 JSON schema는 유지합니다.",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    928,
    304
   ],
   "parameters": {
    "jsCode": "const data = $input.first().json;\nconst { candidate, jd } = data;\nconst retrieved = data.retrieved_questions || [];\nconst project = candidate.projects?.[0] || { name: '주요 프로젝트', role: '역할 미확인', impact: '성과 미확인', evidence: '지원서 근거 확인 필요' };\nconst primarySkill = candidate.skills?.[0] || jd.must_have?.[0] || '핵심 역량';\nconst primaryResponsibility = jd.responsibilities?.[0] || '주요업무';\nconst primaryRequirement = jd.must_have?.[0] || '필수 요건';\n\nconst forbiddenPatterns = [\n  /나이|생년|출생|고향|출신지/,\n  /결혼|배우자|자녀|출산|임신|가족/,\n  /종교|정치|노조|질병|건강|장애/,\n  /군복무.*사유|부모|재산/\n];\n\nconst questionSet = [];\nfunction addQuestion(type, question, intent, evidence, evaluationPoints, followUps = [], riskNote = '') {\n  const flags = forbiddenPatterns\n    .filter(pattern => pattern.test(question))\n    .map(pattern => `민감 질문 가능성: ${pattern.source}`);\n\n  questionSet.push({\n    type,\n    question,\n    intent,\n    evidence,\n    evaluation_points: evaluationPoints,\n    follow_up_questions: followUps,\n    risk_note: riskNote || '지원서/JD에 없는 사실을 전제로 압박하지 말 것',\n    compliance_flags: flags\n  });\n}\n\naddQuestion(\n  'JD-fit',\n  `${jd.position_name} 역할에서 ${primaryResponsibility}을 수행한다고 가정할 때, 가장 먼저 확인해야 할 데이터나 업무 기준은 무엇이라고 보나요?`,\n  'JD 핵심업무에 대한 문제정의 방식 확인',\n  [`JD 주요업무: ${primaryResponsibility}`, `필수요건: ${primaryRequirement}`],\n  ['문제정의', '지표/기준 선택 근거', '업무 맥락 이해'],\n  ['그 기준을 선택한 이유를 실제 경험과 연결해 설명해주실 수 있나요?']\n);\n\naddQuestion(\n  'Candidate-experience',\n  `지원서에 적은 ${project.name} 경험에서 본인이 직접 맡은 역할과 의사결정한 기준은 무엇이었나요?`,\n  '지원자 프로젝트 경험의 실제 기여도 검증',\n  [`지원서 프로젝트: ${project.name}`, `지원서 역할: ${project.role}`, `근거: ${project.evidence}`],\n  ['본인 기여도', '실행 과정', '결과 검증'],\n  ['팀 산출물과 본인 산출물을 구분하면 무엇인가요?']\n);\n\naddQuestion(\n  'Skill-depth',\n  `${primarySkill}을 활용해 HR 업무 문제를 해결한 경험이 있다면, 데이터 준비부터 결과 공유까지 어떤 순서로 진행했나요?`,\n  '핵심 기술/역량의 실무 적용 깊이 확인',\n  [`지원자 스킬: ${candidate.skills.join(', ') || '미확인'}`, `JD 필수요건: ${jd.must_have.join(', ') || '미확인'}`],\n  ['기술 활용 맥락', '절차적 사고', '협업/공유 방식'],\n  ['그 과정에서 가장 많이 틀릴 수 있는 데이터나 전제는 무엇이었나요?']\n);\n\nfor (const base of retrieved.slice(0, 2)) {\n  addQuestion(\n    'RAG-adapted',\n    `${base.base_question} 이 질문을 ${candidate.display_name}님의 ${project.name} 경험과 연결해서 답변해 주세요.`,\n    '직무별 표준 질문을 지원자 경험에 맞게 재구성',\n    [`질문 라이브러리: ${base.question_id}`, `역량: ${base.competency}`, `검색점수: ${base.retrieval_score}`],\n    Array.isArray(base.evaluation_points) ? base.evaluation_points : ['답변 구조', '근거', '실행 가능성'],\n    ['답변에서 사용한 근거가 지원서의 어느 경험과 연결되나요?'],\n    '표준 질문을 그대로 읽기보다 지원자의 실제 경험과 연결해 질문할 것'\n  );\n}\n\naddQuestion(\n  'Risk-check',\n  `${project.impact}라는 결과가 실제로 확인되었다면, 어떤 지표나 피드백으로 검증했나요?`,\n  '지원서 성과 표현의 검증 가능성 확인',\n  [`지원서 성과 표현: ${project.impact}`],\n  ['성과 검증', '정량/정성 근거', '한계 인식'],\n  ['검증이 어려웠던 부분이나 당시의 한계는 무엇이었나요?']\n);\n\nreturn [{\n  json: {\n    ...data,\n    question_set: questionSet,\n    generation_policy: {\n      question_mix: 'JD-fit, Candidate-experience, Skill-depth, RAG-adapted, Risk-check',\n      output_status: 'draft_for_human_review',\n      llm_replacement_note: '이 Code 노드는 교육용 규칙 기반 생성입니다. 실무에서는 OpenAI/Azure OpenAI/사내 LLM 노드로 교체하고 동일 JSON schema를 유지합니다.'\n    }\n  }\n}];"
   }
  },
  {
   "id": "5",
   "name": "품질 검증 및 산출물 구성",
   "notes": "중복, 근거, 민감 질문 가능성을 점검하고 면접관 검토용 Markdown/JSON 산출물을 구성합니다.",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1152,
    304
   ],
   "parameters": {
    "jsCode": "const data = $input.first().json;\nconst seen = new Set();\nconst qualityWarnings = [...(data.validation_errors || []), ...(data.retrieval_warnings || [])];\n\nconst deduped = [];\nfor (const q of data.question_set || []) {\n  const key = String(q.question || '').replace(/\\s+/g, ' ').trim();\n  if (!key) continue;\n  if (seen.has(key)) {\n    qualityWarnings.push(`중복 질문 제거: ${key}`);\n    continue;\n  }\n  seen.add(key);\n  if (!q.evidence || q.evidence.length === 0) qualityWarnings.push(`근거 부족 질문: ${key}`);\n  if (q.compliance_flags?.length) qualityWarnings.push(`검토 필요 질문: ${key} / ${q.compliance_flags.join(', ')}`);\n  deduped.push(q);\n}\n\nconst markdownRows = [];\nfor (let index = 0; index < deduped.length; index += 1) {\n  const q = deduped[index];\n  markdownRows.push(`| ${index + 1} | ${q.type} | ${q.question} | ${q.intent} | ${q.evidence.join('<br>')} | ${q.evaluation_points.join(', ')} |`);\n}\n\nconst outputMarkdown = [\n  `# 지원자 맞춤 면접 질문 세트`,\n  ``,\n  `- 지원자: ${data.candidate.display_name} (${data.candidate.candidate_id})`,\n  `- 공고: ${data.jd.position_name} (${data.jd.job_id})`,\n  `- 면접 라운드: ${data.jd.interview_round}`,\n  `- 상태: HR/Assessor 검토 전 초안`,\n  ``,\n  `| No | 유형 | 질문 | 의도 | 근거 | 평가 포인트 |`,\n  `|---:|---|---|---|---|---|`,\n  ...markdownRows,\n  ``,\n  `## Human 검토 체크리스트`,\n  `- 지원서/JD에 없는 사실을 전제로 한 질문이 있는가?`,\n  `- 민감/차별 가능 질문이 섞여 있지 않은가?`,\n  `- 질문별 평가 포인트가 면접관에게 충분히 명확한가?`,\n  `- 같은 면접 라운드의 기존 질문과 중복되지 않는가?`\n].join('\\n');\n\nconst retrievedQuestionIds = [];\nfor (const q of data.retrieved_questions || []) {\n  retrievedQuestionIds.push({\n    question_id: q.question_id,\n    competency: q.competency,\n    retrieval_score: q.retrieval_score\n  });\n}\n\nreturn [{\n  json: {\n    status: qualityWarnings.length ? 'draft_ready_with_warnings' : 'draft_ready',\n    run_id: data.run_id,\n    generated_at: data.generated_at,\n    candidate_id: data.candidate.candidate_id,\n    job_id: data.jd.job_id,\n    interview_round: data.jd.interview_round,\n    question_set: deduped,\n    evidence_summary: {\n      jd_mapping: {\n        position_name: data.jd.position_name,\n        responsibilities: data.jd.responsibilities,\n        must_have: data.jd.must_have,\n        nice_to_have: data.jd.nice_to_have\n      },\n      candidate_mapping: {\n        display_name: data.candidate.display_name,\n        total_years: data.candidate.total_years,\n        domains: data.candidate.domains,\n        skills: data.candidate.skills,\n        projects: data.candidate.projects\n      },\n      retrieved_question_ids: retrievedQuestionIds\n    },\n    quality_warnings: qualityWarnings,\n    output_markdown: outputMarkdown,\n    human_review_checklist: [\n      '근거 부족 질문 제거 또는 보완',\n      '민감/차별 가능 질문 검토',\n      '질문 난이도와 면접 라운드 적합성 확인',\n      '최종 질문 세트 승인 후 final 폴더 저장'\n    ],\n    next_implementation_steps: [\n      '샘플 입력을 Google Sheets/채용시스템 API 조회로 교체',\n      '태그 검색 노드를 Vector Store RAG로 교체',\n      '규칙 기반 질문 생성 노드를 LLM 노드로 교체',\n      '검토 요청을 Slack/Teams/Email 승인 흐름으로 연결',\n      'draft/final 산출물 저장소와 실행 로그 테이블 연결'\n    ]\n  }\n}];"
   }
  },
  {
   "id": "6",
   "name": "결과 반환",
   "notes": "Webhook 테스트 결과를 JSON으로 반환합니다. 운영에서는 이 뒤에 문서 저장/승인 요청 노드를 붙입니다.",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.5,
   "position": [
    1376,
    304
   ],
   "parameters": {
    "options": {}
   }
  }
 ],
 "connections": {
  "면접 질문 생성 요청": {
   "main": [
    [
     {
      "node": "입력 정규화 및 개인정보 최소화",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "입력 정규화 및 개인정보 최소화": {
   "main": [
    [
     {
      "node": "질문 라이브러리 태그 검색",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "질문 라이브러리 태그 검색": {
   "main": [
    [
     {
      "node": "맞춤 질문 세트 생성",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "맞춤 질문 세트 생성": {
   "main": [
    [
     {
      "node": "품질 검증 및 산출물 구성",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "품질 검증 및 산출물 구성": {
   "main": [
    [
     {
      "node": "결과 반환",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "settings": {
  "executionOrder": "v1",
  "timezone": "Asia/Seoul"
 },
 "meta": {
  "source": "datapopcorn.ai/workflow"
 }
}