feat: 카드뉴스 포스트(관리자 admin/, /v1/card API, 피드 이미지 슬라이드), 인스타 홍보 기획 문서

This commit is contained in:
minaChoi committed 2026-10-23 15:38:07 +09:00
1 parent 96cbd19c61
commit 739a8c59eb
107 files changed
+17684 -19

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
// 인스타 카드를 템플릿대로 JPEG로 만든다. 웹 화면(/render)을 헤드리스 Chrome으로 찍는다.
// 사용: npm run card -- <tarot|ootd> [--topic 주제] [--feedback 피드백] [--copy <웹 화면 '대화로 만들기'의 값>] [--out <폴더>]
// --topic·--feedback 이 있으면 Claude가 먼저 문구를 기획하고(관리자 서버 /api/plan), 기획안을 출력한 뒤 그 문구로 그린다.
// 날씨 타로는 --copy 가 없으면 주제 없이도 Claude가 기획한다. --color <테마>로 색을 고르고, 없으면 무작위.
// 그리기 전에 그날 카드에 없는 그림만 Codex로 만든다 (--no-images 로 건너뜀).
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
import { resolve } from 'node:path'
const SLIDES = { tarot: 5, ootd: 6 }
// 기본 문구가 서비스 데이터 그대로라 Claude 기획이 꼭 필요한 템플릿 (src/cards/templates.tsx autoPlan)
const AUTO_PLAN = ['tarot']
// src/cards/themes.ts THEMES 의 id
const THEMES = ['sunset', 'sky', 'mint', 'berry', 'lemon', 'lavender']
const ADMIN_URL = process.env.ADMIN_URL ?? 'http://localhost:5175'
const API_URL = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
function fail(message) {
console.error(message)
process.exit(1)
}
const args = process.argv.slice(2)
const flag = (name) => {
const i = args.indexOf(name)
if (i < 0) return null
const [, value] = args.splice(i, 2)
return value
}
let copy = flag('--copy')
const topic = flag('--topic')
const feedback = flag('--feedback')
const color = flag('--color')
const outArg = flag('--out')
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
const noImages = take('--no-images')
const postNow = take('--post')
const postWait = take('--post-wait')
const [template] = args
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
if (color && !THEMES.includes(color)) fail(`색은 ${THEMES.join(', ')} 중 하나예요.`)
if (!existsSync(CHROME)) fail(`Chrome을 찾지 못했어요: ${CHROME}\nCHROME_PATH 환경변수로 경로를 알려 주세요.`)
await fetch(`${API_URL}/v1/region/list`).catch((e) => fail(`날씨각 API(${API_URL})에 연결하지 못했어요. 백엔드가 켜져 있는지 확인하세요. (${e.message})`))
await fetch(ADMIN_URL).catch(() => fail(`관리자 화면(${ADMIN_URL})이 꺼져 있어요. admin 폴더에서 npm run dev 를 먼저 켜 주세요.`))
const decode = (value) => (value ? JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) : {})
if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template))) {
const current = decode(copy)
console.log('Claude가 기획하는 중…')
const res = await fetch(`${ADMIN_URL}/api/plan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template, topic: topic ?? '', feedback: feedback ?? '', current }),
})
const body = await res.json()
if (!res.ok) fail(`기획하지 못했어요: ${body.error}`)
console.log(`주제: ${body.topic}`)
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
}
{
const current = decode(copy)
const theme = color ?? current.theme ?? THEMES[Math.floor(Math.random() * THEMES.length)]
copy = Buffer.from(JSON.stringify({ ...current, theme })).toString('base64url')
console.log(`색: ${theme}`)
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
}
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
if (!noImages) {
const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template, copy: decode(copy) }),
}).then((r) => r.json())
if (start.error) fail(`그림을 만들지 못했어요: ${start.error}`)
if (start.status === 'running') {
console.log(`그림 ${start.total}장 만드는 중 (Codex, 한 장에 1~2분)…`)
let state = start
while (state.status === 'running') {
await new Promise((r) => setTimeout(r, 5000))
state = await fetch(`${ADMIN_URL}/api/gen-image`).then((r) => r.json())
}
for (const line of state.log) console.log(` ${line}`)
if (state.status === 'failed') console.log('일부 그림을 못 만들어 그 장은 아이콘·옷 이름으로 나가요.')
// 새 그림이 화면에 반영될 시간
await new Promise((r) => setTimeout(r, 3000))
}
}
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const outDir = resolve(outArg ?? `out/${day}`)
mkdirSync(outDir, { recursive: true })
const files = []
for (let slide = 1; slide <= SLIDES[template]; slide++) {
const query = new URLSearchParams({ template, slide: String(slide) })
if (copy) query.set('copy', copy)
const png = resolve(outDir, `${day}_${template}_${slide}.png`)
const jpg = png.replace(/\.png$/, '.jpg')
execFileSync(CHROME, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=1',
'--window-size=1080,1350',
'--virtual-time-budget=20000',
`--screenshot=${png}`,
`${ADMIN_URL}/render?${query}`,
], { stdio: 'ignore' })
execFileSync('sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', '92', png, '--out', jpg], { stdio: 'ignore' })
rmSync(png)
files.push(jpg)
}
console.log(`${template} · ${files.length}장`)
for (const f of files) console.log(f)
if (postNow || postWait) {
const images = files.map((f) => readFileSync(f).toString('base64'))
const res = await fetch(`${ADMIN_URL}/api/post`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template, texts: decode(copy), images, publish: postNow }),
})
const body = await res.json()
if (!res.ok || body.result?.success === false) fail(`날씨각에 올리지 못했어요: ${body.error ?? body.result?.desc}`)
console.log(postNow ? `날씨각 오늘 피드에 올렸어요: 카드 ${body.card_id}, 포스트 ${body.post_id}` : `승인 대기로 저장했어요: 카드 ${body.card_id}`)
}
+91
View File
@@ -0,0 +1,91 @@
// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-luna'
function fail(message) {
console.error(message)
process.exit(1)
}
const args = process.argv.slice(2)
const force = args.includes('--force')
const [kind, target, ...more] = args.filter((a) => !a.startsWith('--'))
const styleFilter = more[0]
const promptFile = resolve(`image-prompts/${kind}.json`)
if (!kind || !target || !existsSync(promptFile)) fail('사용: npm run gen-image -- <ootd|tarot> <id|missing> [--force]')
const spec = JSON.parse(readFileSync(promptFile, 'utf8'))
// 각 카드는 그림 목록을 따로 적지 않고 서비스의 각 목록에서 만든다
if (spec.deck === 'gak') {
const defs = JSON.parse(readFileSync(resolve('../backend/seed/index_definition.json'), 'utf8'))
spec.items = defs.map((g) => ({ id: g.code, motif: spec.scene.replaceAll('{name}', g.name).replaceAll('{meaning}', g.description), name: g.name, meaning: g.description }))
}
const outDir = resolve(`src/assets/${kind}`)
mkdirSync(outDir, { recursive: true })
const outPath = (id) => join(outDir, `${id}.webp`)
// 그림 한 장 = { id, 프롬프트 }. ootd 는 구간 × 스타일 × 사람, tarot 은 주제 꾸밈(skin)마다
const jobs = spec.bands
? spec.bands.flatMap((b) =>
Object.entries(b.outfits).flatMap(([style, byPersona]) =>
Object.entries(byPersona).map(([persona, outfit]) => ({
id: `${b.id}-${persona}-${style}`,
band: b.id,
style,
prompt: spec.style
.replace('{items}', outfit.items)
.replace('{persona}', spec.personas[persona].prompt)
.replace('{style}', spec.styles[style].prompt)
.replace('{trend}', spec.styles[style].trends?.[persona] ?? '')
.replace('{layering}', b.layering ?? ''),
})),
),
)
: spec.items.map((it) => ({
id: it.id,
band: it.id,
prompt: spec.style.replace('{motif}', it.motif).replace('{scene}', it.motif).replaceAll('{name}', it.name ?? '').replaceAll('{meaning}', it.meaning ?? '').replace('{card}', it.card ?? ''),
}))
// 카드에 필요한 그림만: 정확한 id 를 여러 개 받거나(npm run card·관리자 서버가 씀), 구간·스타일로 좁힌다
const exact = [target, ...more].filter((t) => jobs.some((j) => j.id === t))
const picked =
exact.length > 0 ? jobs.filter((j) => exact.includes(j.id))
: target === 'missing' ? jobs.filter((j) => !existsSync(outPath(j.id)))
: jobs.filter((j) => j.id === target || j.band === target || j.style === target)
const bands = exact.length === 0 && styleFilter ? picked.filter((j) => j.style === styleFilter) : picked
if (bands.length === 0) fail(target === 'missing' ? '빠진 그림이 없어요.' : `'${target}' 은 ${promptFile} 에 없어요.${spec.bands ? ` 구간: ${spec.bands.map((b) => b.id).join(', ')} / 스타일: ${Object.keys(spec.styles).join(', ')} / 사람: ${Object.keys(spec.personas).join(', ')}` : ` id: ${spec.items.map((i) => i.id).join(', ')}`}`)
for (const band of bands) {
if (existsSync(outPath(band.id)) && !force) {
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
continue
}
const prompt = band.prompt
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
const task = [
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
'',
prompt,
].join('\n')
console.log(`${band.id}: Codex로 그리는 중…`)
try {
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 한 번 보는 역할뿐이라 가장 싼 모델·낮은 추론으로 고정한다 (기본 설정의 gpt-6-astra·xhigh 를 쓰지 않는다)
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', task], { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (e) {
rmSync(work, { recursive: true, force: true })
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
}
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
if (!png) fail(`${band.id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath(band.id)])
rmSync(work, { recursive: true, force: true })
console.log(`${band.id}: ${outPath(band.id)}`)
}
+7
View File
@@ -0,0 +1,7 @@
export type PlanContext = {
template: { id: string; name: string; about: string; how: string[] }
fields: { key: string; label: string }[]
current: Record<string, string>
weather: unknown
}
export function runPlan(ctx: PlanContext, opts?: { topic?: string; feedback?: string; fixed?: { question?: string; cards?: string[] } }): Promise<{ topic: string; copy: Record<string, string> }>
+138
View File
@@ -0,0 +1,138 @@
// 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다.
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
import { execFile } from 'node:child_process'
import { readdirSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { resolve } from 'node:path'
const pngNames = (dir) =>
readdirSync(resolve(import.meta.dirname, dir))
.filter((f) => f.endsWith('.png'))
.map((f) => f.replace(/\.png$/, ''))
// 서비스 각·날씨 아이콘
const ICONS = pngNames('../../frontend/public/icons')
const TOPICS = JSON.parse(readFileSync(resolve(import.meta.dirname, '../topics.json'), 'utf8')).categories
const questionOf = (topic) => {
const c = categoryOf(topic)
if (!c) return null
const sub = c.subtopics.find((x) => topic.includes(x))
return c.questions[sub ?? ''] ?? c.questions['']
}
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s)))
const RULES = [
'너는 한국 날씨 서비스 "날씨각"의 인스타그램 카드 문구 담당이다.',
'오늘 날씨 사실(아래 데이터)을 근거로, 주제와 엮어 재미있게 쓴다. 날씨 사실을 지어내지 않는다.',
'날씨를 모르는 사람도 바로 알아듣는 쉬운 말로 쓴다. 숫자만 나열하거나 전문 용어, 점수, 판정 이름을 쓰지 않는다.',
'좋은 말과 나쁜 말을 한 문장에 섞지 않는다. 뜻 없는 비교("더 나아요")를 쓰지 않는다.',
'카드에 들어가야 하니 칸마다 지금 문구와 비슷한 길이(최대 1.3배)로 쓴다(날씨 타로 리딩은 아래 길이 규칙을 따른다). 줄바꿈은 " ⏎ "로 표시하고, 개수를 지금 문구와 맞춘다.',
'강조할 말은 *별표*로 감싼다. 지금 문구에 별표가 있으면 같은 자리에 둔다.',
`아이콘 칸(i1·i2·i3)은 다음 중 하나의 파일 이름만 쓴다: ${ICONS.join(', ')}`,
'쓰지 않는 것: 투자 권유(종목, 매수·매도, 수익·손실 단정), 건강·의료 단정, 사고·재난·정치, 특정 집단 비하, 욕설.',
'"재미로"라는 말이 지금 문구에 있으면 남긴다.',
'주제가 있으면 제목·카드 이름·문장을 모두 그 주제의 말로 바꾼다. 오늘 날씨 사실은 주제에 빗대는 근거로만 쓴다.',
'날씨각의 각 요약 문장("오전 10시 14°, 바람 조금")을 그대로 옮기지 않는다. 날씨 사실은 쉬운 말로 다시 쓴다.',
'템플릿 설명(아래 ## 템플릿 목록)을 반드시 따른다.',
].join('\n')
const isTarot = (ctx) => ctx.template.id === 'tarot'
// 각 카드(이름·그림)는 Claude가 쓰지 않고 고른 카드(card1~3)로 채운다
const DECK_KEY = /^[cni]\d$/
// 실제 타로 리더(온도타로·타로하는 아율·가문비타로·알라딘타로 등 유튜브 설명란) 말투에서 뽑은 규칙. 2026-10-23 조사, admin/AGENTS.md 참고
const TAROT_TONE = [
'## 리딩 말투 (반드시)',
'진짜 타로 리더가 한 사람에게 말하듯 쓴다. 질문자는 "님"이라 부르거나 생략하고, 상대는 "그 사람"이라 부른다. "당신·그대"는 쓰지 않는다.',
'해요체가 기본이고, 단정할 땐 합니다체 한 문장을 섞는다("~하고 있습니다", "~꺼낼 겁니다"). 카드를 보는 중인 느낌으로 "~네요/~거든요/~죠" 같은 어미를 섞는다.',
'구조: ① 그 사람(또는 님)의 지금 상태를 겉모습과 속마음을 대비해서 한 문장("겉으론 평소랑 똑같이 굴어도 말 걸 타이밍만 재는 중이거든요") ② "다만/그런데"로 한 번 꺾기 ③ 오늘 할 행동 딱 하나, 타이밍과 함께. 각 카드의 활동(걷기·커피·바깥 자리)이 그 행동이 된다.',
'폰에서 확인할 수 있는 신호(답장 길이, 읽씹, 프사, 말끝 흐림)나 대사 한 줄("잠깐 걸을래?")처럼 구체적인 디테일을 하나 넣는다.',
'길이: 3문장, 전체 70~95자. 줄바꿈 없음. 별표 강조는 쓰지 않는다.',
'세 장이 같은 틀로 시작하지 않는다. "겉으론 ~ 속으론" 대비는 한 장에만, 다른 장은 상대의 상태 묘사·질문으로 붙잡기("요즘 답장 짧아졌죠?")·단정 한 줄 등으로 다르게 연다. "다만"도 세 장에 다 쓰지 않는다.',
'하지 않는 것: "~이면 ~해요/~하면 ~돼요" 공식, 모든 문장이 같은 어미("~해요"만 세 번), "~할 수 있어요/~일 수 있어요" 두 번 이상, "~것이 중요합니다", "도움이 되길", 명사 나열형 조언, 설명조("이 카드는 ~을 뜻해요"는 세 장 통틀어 한 번만), 이모지, 느낌표 두 개 이상, 리딩 본문에 기온·시각 숫자(숫자는 행운 포인트에만), 뻔한 덕담("기대해도 좋은 하루").',
'좋은 예: "오늘 그 사람, 님 생각보다 가까이 와 있어요. 겉으론 평소랑 똑같이 굴어도 말 걸 타이밍만 재는 중이거든요. 해 지고 선선해질 때 \'잠깐 걸을래?\' 한마디면 돼요."',
'나쁜 예(쓰지 말 것): "커피 한 잔이면 말문이 열려요. 아침 인사부터 먼저 건네요." / "걷다 보면 거리가 가까워져요. 저녁 산책을 먼저 제안해요."',
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
]
function tarotSection(topic) {
return [
'',
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 각(오늘 실제로 하기 좋은 각) 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
...TAROT_TONE,
'',
...DECK.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
]
}
function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
// 줄바꿈은 ⏎ 로 보여 주고 받을 때 되돌린다 (JSON 안의 \\n 을 글자로 따라 쓰는 일을 막는다)
const fields = ctx.fields.map((f) => `- ${f.key} (${f.label}): ${String(ctx.current[f.key] ?? '').replaceAll('\n', ' ⏎ ')}`).join('\n')
return [
RULES,
'',
`## 템플릿: ${ctx.template.name} — ${ctx.template.about}`,
...ctx.template.how.map((h) => `- ${h}`),
'',
'## 오늘 날씨 (서울)',
JSON.stringify(ctx.weather, null, 1),
'',
'## 지금 문구 (칸 이름: 값)',
fields,
'',
topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`,
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
'',
...(isTarot(ctx) ? tarotSection(topic) : []),
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
].join('\n')
}
function schema(ctx) {
const properties = { topic: { type: 'string' } }
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: DECK.map((c) => c.id) }
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
}
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
return new Promise((done, fail) => {
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
let out
try {
out = JSON.parse(stdout)
} catch {
return fail(new Error(`Claude 답을 읽지 못했어요: ${stdout.slice(0, 300)}`))
}
const result = out.structured_output ?? (typeof out.result === 'string' ? JSON.parse(out.result) : null)
if (out.is_error || !result) return fail(new Error(`Claude가 기획안을 주지 못했어요: ${String(out.result ?? '').slice(0, 300)}`))
const copy = {}
if (isTarot(ctx)) {
if (fixed.question) result.question = fixed.question
fixed.cards?.forEach((code, i) => (result[`card${i + 1}`] = code))
;['card1', 'card2', 'card3'].forEach((k, i) => {
const card = DECK.find((c) => c.id === result[k])
if (card) Object.assign(result, { [`c${i + 1}`]: card.id, [`n${i + 1}`]: card.name, [`i${i + 1}`]: card.icon })
})
}
for (const f of ctx.fields) {
const value = String(result[f.key] ?? '').replace(/\s*⏎\s*/g, '\n').replace(/\\n/g, '\n').trim()
const badIcon = /^i\d$/.test(f.key) && !ICONS.includes(value)
copy[f.key] = value && !badIcon ? value : ctx.current[f.key]
}
const finalTopic = String(result.topic || topic)
copy.skin = categoryOf(finalTopic)?.skin ?? 'star'
// 각 카드 id·그림은 화면 칸이 아니라 덱에서 채운 값 그대로
if (isTarot(ctx)) for (const k of ['c1', 'c2', 'c3', 'i1', 'i2', 'i3']) if (result[k]) copy[k] = result[k]
done({ topic: finalTopic, copy })
})
})
}