bot commited on
Commit
8214b38
·
1 Parent(s): fbe6540

母题库 v2:按人物查/检索/组稿(读取 R2 motif_v2,29310 条第二次提炼)

Browse files
fanqie/motif2.js ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+ // 母题库 v2:直接从 R2 的 motif_v2/ 读取第二次提炼后的素材卡(按批次增量加载),
3
+ // 提供按人物原型 / 母题 / 情绪 / 场景检索,以及带逻辑校验的自动组稿。
4
+ // 只读:不修改 R2 上的任何数据,也不影响旧的母题库接口。
5
+ const crypto = require('crypto')
6
+ const fs = require('fs')
7
+ const path = require('path')
8
+ const zlib = require('zlib')
9
+ const ENDPOINT = process.env.R2_ENDPOINT
10
+ const BUCKET = process.env.R2_BUCKET
11
+ const AK = process.env.R2_ACCESS_KEY_ID
12
+ const SK = process.env.R2_SECRET_ACCESS_KEY
13
+ const PREFIX = 'motif_v2/'
14
+ const DATA_DIR = process.env.FANQIE_DATA || path.join(__dirname, 'data')
15
+
16
+ /* ---------------- R2 只读访问(SigV4,UNSIGNED-PAYLOAD) ---------------- */
17
+ const sha = v => crypto.createHash('sha256').update(v).digest('hex')
18
+ const hm = (k, v, enc) => crypto.createHmac('sha256', k).update(v).digest(enc)
19
+ const enc = v => encodeURIComponent(String(v)).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
20
+ async function r2get(key) {
21
+ if (!ENDPOINT || !BUCKET || !AK || !SK) throw new Error('R2 未配置')
22
+ const url = new URL(ENDPOINT)
23
+ url.pathname = '/' + [url.pathname.replace(/^\/+|\/+$/g, ''), BUCKET, ...key.split('/')].filter(Boolean).map(enc).join('/')
24
+ const amz = new Date().toISOString().replace(/[:-]|\.\d{3}/g, '')
25
+ const day = amz.slice(0, 8)
26
+ const headers = { host: url.host.toLowerCase(), 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD', 'x-amz-date': amz }
27
+ const names = Object.keys(headers).sort()
28
+ const creq = ['GET', url.pathname, '', names.map(k => `${k}:${headers[k]}`).join('\n') + '\n', names.join(';'), 'UNSIGNED-PAYLOAD'].join('\n')
29
+ const scope = `${day}/auto/s3/aws4_request`
30
+ const sts = ['AWS4-HMAC-SHA256', amz, scope, sha(creq)].join('\n')
31
+ const kS = hm(hm(hm(hm(`AWS4${SK}`, day), 'auto'), 's3'), 'aws4_request')
32
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${AK}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hm(kS, sts, 'hex')}`
33
+ for (let i = 0; i < 3; i++) {
34
+ try {
35
+ const r = await fetch(url, { headers })
36
+ if (r.status === 404) return null
37
+ if (r.ok) return Buffer.from(await r.arrayBuffer())
38
+ } catch (e) { if (i === 2) throw e }
39
+ await new Promise(ok => setTimeout(ok, 400 * (i + 1)))
40
+ }
41
+ throw new Error('R2 读取失败:' + key)
42
+ }
43
+
44
+ /* ---------------- 数据加载(增量 + 定时刷新) ---------------- */
45
+ const S = { tax: null, progress: null, batches: new Map(), cards: [], byUid: new Map(), loadedAt: 0, loading: null, error: '' }
46
+ let src = null
47
+ function source() {
48
+ if (src) return src
49
+ src = new Map()
50
+ try {
51
+ const raw = zlib.gunzipSync(fs.readFileSync(path.join(DATA_DIR, 'materials.jsonl.gz'))).toString('utf8')
52
+ for (const l of raw.split('\n')) if (l) { const x = JSON.parse(l); src.set(x.uid, { sum: x.sum, text: x.text, ch: x.ch, k: x.k, g: x.g, at: x.at }) }
53
+ } catch (e) { console.error('motif2: 原文索引加载失败', e.message) }
54
+ return src
55
+ }
56
+ function docOf(c) {
57
+ const parts = [c.log, c.arc, c.hook, c.twist, c.fit, c.risk, c.pov?.role]
58
+ for (const p of c.ppl || []) parts.push(p.role, p.trait, p.want)
59
+ for (const t of c.ties || []) parts.push(t.rel, ...(t.acts || []))
60
+ for (const e of c.ev || []) parts.push(e.e, e.why, e.then)
61
+ parts.push(...(c.lines || []), ...(c.det || []), ...(c.facts || []), ...(c.needs || []), ...(c.open || []), ...(c.roles || []))
62
+ return parts.filter(Boolean).join('|')
63
+ }
64
+ function rolesOf(c) { return c.lv === 'full' ? [...new Set((c.ppl || []).map(p => p.role))] : (c.roles || []) }
65
+ async function refresh(force = false) {
66
+ if (S.loading) return S.loading
67
+ if (!force && S.tax && Date.now() - S.loadedAt < 10 * 60 * 1000) return
68
+ S.loading = (async () => {
69
+ try {
70
+ const [tb, pb] = await Promise.all([r2get(PREFIX + 'taxonomy.json'), r2get(PREFIX + 'progress.json')])
71
+ if (tb) S.tax = JSON.parse(tb.toString('utf8'))
72
+ S.progress = pb ? JSON.parse(pb.toString('utf8')) : { batches: {} }
73
+ const want = Object.entries(S.progress.batches || {}).filter(([n, m]) => S.batches.get(n)?.at !== m.at)
74
+ for (let i = 0; i < want.length; i += 12) {
75
+ await Promise.all(want.slice(i, i + 12).map(async ([n, m]) => {
76
+ const buf = await r2get(`${PREFIX}batches/b${String(n).padStart(4, '0')}.jsonl.gz`)
77
+ if (!buf) return
78
+ const cards = zlib.gunzipSync(buf).toString('utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
79
+ S.batches.set(n, { at: m.at, cards })
80
+ }))
81
+ }
82
+ if (want.length || !S.cards.length) {
83
+ const all = []
84
+ for (const n of [...S.batches.keys()].sort((a, b) => a - b)) for (const c of S.batches.get(n).cards) if (c.use) {
85
+ c._b = Number(n); c._doc = docOf(c); c._roles = rolesOf(c); all.push(c)
86
+ }
87
+ S.cards = all
88
+ S.byUid = new Map(all.map(c => [c.uid, c]))
89
+ }
90
+ S.loadedAt = Date.now(); S.error = ''
91
+ } catch (e) { S.error = String(e.message || e); console.error('motif2 load failed', e) }
92
+ finally { S.loading = null }
93
+ })()
94
+ return S.loading
95
+ }
96
+ async function ready() { if (!S.tax || Date.now() - S.loadedAt > 10 * 60 * 1000) await refresh(); if (!S.tax) throw new Error('母题库 v2 尚未就绪:' + (S.error || '没有数据')) }
97
+ setTimeout(() => refresh().catch(() => {}), 3000)
98
+
99
+ /* ---------------- 工具 ---------------- */
100
+ const motifName = id => { for (const g of Object.values(S.tax?.motifs || {})) if (g[id]) return g[id]; return id }
101
+ const motifGroup = id => { for (const [k, g] of Object.entries(S.tax?.motifs || {})) if (g[id]) return k; return '' }
102
+ const arr = v => (v ? String(v).split(',').map(s => s.trim()).filter(Boolean) : [])
103
+ const terms = w => String(w || '').split(/[\s,,、;;]+/).map(s => s.trim()).filter(s => s.length >= 1).slice(0, 8)
104
+ const lite = c => { const { _doc, _roles, ...r } = c; return r }
105
+ function countBy(list, f) {
106
+ const m = {}
107
+ for (const c of list) for (const k of f(c) || []) if (k) m[k] = (m[k] || 0) + 1
108
+ return Object.entries(m).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n }))
109
+ }
110
+ function filterCards(q) {
111
+ const role = q.role ? String(q.role) : ''
112
+ const ms = arr(q.m), emo = arr(q.emo), place = arr(q.place)
113
+ const era = q.era ? String(q.era) : '', gen = q.gen ? String(q.gen) : '', lv = q.lv ? String(q.lv) : ''
114
+ const st = q.st ? String(q.st) : ''
115
+ const minQ = Number(q.q) || 0
116
+ const ws = terms(q.w)
117
+ return S.cards.filter(c =>
118
+ (!role || c._roles.includes(role)) &&
119
+ (!st || (c.ppl || []).some(p => p.role === role && p.st === st)) &&
120
+ (!ms.length || ms.every(m => (c.mot || []).includes(m) || (c.ev || []).some(e => e.m === m))) &&
121
+ (!emo.length || emo.some(e => (c.emo || []).includes(e))) &&
122
+ (!place.length || place.some(p => (c.place || []).includes(p))) &&
123
+ (!era || c.era === era) && (!gen || (c.gen || []).includes(gen)) && (!lv || c.lv === lv) &&
124
+ (c.q || 0) >= minQ && (!ws.length || ws.every(w => c._doc.includes(w))))
125
+ }
126
+ const sortCards = list => list.sort((a, b) => (b.q || 0) - (a.q || 0) || (b.lv === 'full') - (a.lv === 'full'))
127
+
128
+ /* ---------------- 接口 ---------------- */
129
+ module.exports = function buildMotif2(express) {
130
+ const router = express.Router()
131
+ const wrap = fn => async (req, res) => { try { await ready(); res.json(await fn(req, res)) } catch (e) { res.status(e.status || 500).json({ error: String(e.message || e) }) } }
132
+
133
+ router.get('/meta', wrap(() => {
134
+ const P = S.progress || {}
135
+ return {
136
+ taxonomy: S.tax,
137
+ progress: { done_batches: P.done_batches || 0, total_batches: P.total_batches || 0, done_items: P.done_items || 0, total_items: P.total_items || 0, counts: P.counts || {}, updated_at: P.updated_at, next_batch: P.next_batch },
138
+ cards: S.cards.length,
139
+ full: S.cards.filter(c => c.lv === 'full').length,
140
+ roles: countBy(S.cards, c => c._roles),
141
+ motifs: countBy(S.cards, c => [...new Set([...(c.mot || []), ...(c.ev || []).map(e => e.m)])]).map(x => ({ ...x, t: motifName(x.k), grp: motifGroup(x.k) })),
142
+ emo: countBy(S.cards, c => c.emo), era: countBy(S.cards.filter(c => c.lv === 'full'), c => [c.era]),
143
+ place: countBy(S.cards, c => c.place), gen: countBy(S.cards, c => c.gen),
144
+ }
145
+ }))
146
+
147
+ router.post('/reload', wrap(async () => { await refresh(true); return { ok: true, cards: S.cards.length } }))
148
+
149
+ router.get('/cards', wrap(req => {
150
+ const list = sortCards(filterCards(req.query))
151
+ const size = Math.min(50, Math.max(1, Number(req.query.size) || 20))
152
+ const page = Math.max(1, Number(req.query.page) || 1)
153
+ return { total: list.length, page, size, items: list.slice((page - 1) * size, page * size).map(lite) }
154
+ }))
155
+
156
+ router.get('/card', wrap(req => {
157
+ const c = S.byUid.get(String(req.query.uid || ''))
158
+ if (!c) { const e = new Error('没有这张卡'); e.status = 404; throw e }
159
+ return { card: lite(c), source: source().get(c.uid) || null }
160
+ }))
161
+
162
+ // 人物原型:输入“爷爷”,返回该人物的事件类型、情绪、生死状态分布,以及所有具体互动
163
+ router.get('/role', wrap(req => {
164
+ const role = String(req.query.r || '')
165
+ if (!role) { const e = new Error('请指定人物'); e.status = 400; throw e }
166
+ const all = S.cards.filter(c => c._roles.includes(role))
167
+ const list = sortCards(filterCards({ ...req.query, role }))
168
+ const acts = []
169
+ for (const c of list) {
170
+ if (c.lv !== 'full') continue
171
+ const ids = new Set((c.ppl || []).filter(p => p.role === role).map(p => p.id))
172
+ const person = (c.ppl || []).find(p => p.role === role)
173
+ for (const t of c.ties || []) if (ids.has(t.p)) for (const a of t.acts || []) acts.push({ a, uid: c.uid, rel: t.rel, tone: t.tone, st: person?.st, pov: c.pov?.role, q: c.q, mot: c.mot?.[0] })
174
+ }
175
+ acts.sort((a, b) => (b.q || 0) - (a.q || 0))
176
+ const people = []
177
+ for (const c of list) for (const p of c.ppl || []) if (p.role === role && (p.trait || p.want)) people.push({ trait: p.trait, want: p.want, st: p.st, uid: c.uid })
178
+ const lines = []
179
+ for (const c of list) for (const l of c.lines || []) lines.push({ l, uid: c.uid, emo: c.emo?.[0], fit: c.fit })
180
+ const size = Math.min(50, Math.max(1, Number(req.query.size) || 12))
181
+ const page = Math.max(1, Number(req.query.page) || 1)
182
+ return {
183
+ role, total_all: all.length, total: list.length,
184
+ motifs: countBy(all, c => [...new Set([...(c.mot || []), ...(c.ev || []).map(e => e.m)])]).map(x => ({ ...x, t: motifName(x.k), grp: motifGroup(x.k) })),
185
+ emo: countBy(all, c => c.emo),
186
+ st: countBy(all, c => (c.ppl || []).filter(p => p.role === role).map(p => p.st)),
187
+ tone: countBy(all, c => (c.ties || []).filter(t => (c.ppl || []).some(p => p.id === t.p && p.role === role)).map(t => t.tone)),
188
+ acts: acts.slice(0, 80), people: people.slice(0, 30), lines: lines.slice(0, 30),
189
+ page, size, items: list.slice((page - 1) * size, page * size).map(lite),
190
+ }
191
+ }))
192
+
193
+ /* ---------------- 组稿:挑选互不矛盾的素材并串成提纲 ---------------- */
194
+ const ANCIENT = new Set(['古代', '架空'])
195
+ const MODERN_ORDER = ['更早年代', '80年代', '90年代', '2000年代', '2010年代', '当代']
196
+ const ALIVE = new Set(['在世', '病重'])
197
+ const DEATH_MOTIFS = new Set(['f_ill', 'f_entrust', 'f_relic', 'f_guilt'])
198
+
199
+ function check(c, setup) {
200
+ const why = [], warn = []
201
+ const heroEra = setup.hero?.era || ''
202
+ if (heroEra && c.era && c.era !== '不明') {
203
+ const a = ANCIENT.has(heroEra), b = ANCIENT.has(c.era)
204
+ if (a !== b) why.push(`年代不符:素材是「${c.era}」,你的设定是「${heroEra}」`)
205
+ else if (!a && c.era !== heroEra) {
206
+ const older = MODERN_ORDER.indexOf(c.era) < MODERN_ORDER.indexOf(heroEra)
207
+ if (older && ['童年', '少年'].includes(c.pov?.age)) warn.push(`素材发生在「${c.era}」,可写成主角童年回忆`)
208
+ else if (older) warn.push(`素材年代是「${c.era}」,需改成你的时代背景或写成往事`)
209
+ else why.push(`素材年代「${c.era}」晚于你的设定「${heroEra}」`)
210
+ }
211
+ }
212
+ for (const m of setup.cast || []) {
213
+ if (!m.st) continue
214
+ for (const p of c.ppl || []) {
215
+ if (p.role !== m.role) continue
216
+ if (m.st === '在世' && p.st === '已故') why.push(`素材里${m.role}已去世,与你的设定(在世)冲突`)
217
+ if (m.st === '已故' && ALIVE.has(p.st)) warn.push(`你的设定里${m.role}已去世,这条只能写成生前往事`)
218
+ }
219
+ }
220
+ const sex = setup.hero?.sex
221
+ if (sex && c.pov?.sex && c.pov.sex !== '不明' && c.pov.sex !== sex) warn.push(`素材主角是${c.pov.sex}性,需转换成${sex}主角视角`)
222
+ if (setup.hero?.age && c.pov?.age && c.pov.age !== '不明' && c.pov.age !== setup.hero.age) {
223
+ const order = ['童年', '少年', '青年', '中年', '老年']
224
+ if (order.indexOf(c.pov.age) > order.indexOf(setup.hero.age)) why.push(`素材主角处于${c.pov.age},晚于你的主角年龄(${setup.hero.age})`)
225
+ else warn.push(`素材发生在主角${c.pov.age}时,可作为前史`)
226
+ }
227
+ if (c.risk) warn.push('红线提醒:' + c.risk)
228
+ return { ok: !why.length, why, warn }
229
+ }
230
+ function deathRoles(c) {
231
+ const hasDeath = (c.mot || []).some(m => DEATH_MOTIFS.has(m)) || (c.ev || []).some(e => DEATH_MOTIFS.has(e.m))
232
+ return (c.ppl || []).filter(p => p.st === '已故' && hasDeath).map(p => p.role)
233
+ }
234
+ function conflictWith(c, chosen) {
235
+ const dr = deathRoles(c)
236
+ for (const o of chosen) {
237
+ const od = deathRoles(o)
238
+ const both = dr.filter(r => od.includes(r))
239
+ if (both.length) return `与已选素材冲突:${both.join('、')}的离世只能写一次`
240
+ const ae = ANCIENT.has(c.era), be = ANCIENT.has(o.era)
241
+ if (c.era !== '不明' && o.era !== '不明' && ae !== be) return '与已选素材年代体系冲突(古代/现代)'
242
+ }
243
+ return ''
244
+ }
245
+ function scoreCard(c, setup, ws) {
246
+ const castRoles = (setup.cast || []).map(m => m.role)
247
+ let s = (c.q || 0) * 1.3
248
+ for (const r of castRoles) if (c._roles.includes(r)) {
249
+ s += 6
250
+ const ids = new Set((c.ppl || []).filter(p => p.role === r).map(p => p.id))
251
+ if ((c.ties || []).some(t => ids.has(t.p) && (t.acts || []).length)) s += 3
252
+ }
253
+ const mm = new Set([...(c.mot || []), ...(c.ev || []).map(e => e.m)])
254
+ for (const m of setup.mot || []) if (mm.has(m)) s += 4
255
+ for (const e of setup.emo || []) if ((c.emo || []).includes(e)) s += 2
256
+ for (const p of setup.hero?.place || []) if ((c.place || []).includes(p)) s += 1
257
+ if (setup.hero?.era && c.era === setup.hero.era) s += 1
258
+ if (setup.gen && (c.gen || []).includes(setup.gen)) s += 1.5
259
+ let hits = 0
260
+ for (const w of ws) if (c._doc.includes(w)) hits++
261
+ s += Math.min(6, hits * 1.5)
262
+ return s
263
+ }
264
+ function rng(seed) { let x = (Number(seed) || 0) * 9301 + 49297; return () => { x = (x * 9301 + 49297) % 233280; return x / 233280 } }
265
+
266
+ router.post('/compose', wrap(req => {
267
+ const b = req.body || {}
268
+ const setup = {
269
+ idea: String(b.idea || '').slice(0, 400),
270
+ hero: { sex: b.hero?.sex || '', era: b.hero?.era || '', age: b.hero?.age || '', place: Array.isArray(b.hero?.place) ? b.hero.place : [], note: String(b.hero?.note || '').slice(0, 300) },
271
+ cast: (Array.isArray(b.cast) ? b.cast : []).filter(m => m && m.role).slice(0, 6).map(m => ({ role: String(m.role), st: m.st || '', note: String(m.note || '').slice(0, 120) })),
272
+ emo: Array.isArray(b.emo) ? b.emo : [], mot: Array.isArray(b.mot) ? b.mot : [], gen: b.gen || '',
273
+ }
274
+ if (!setup.cast.length && !setup.mot.length && !setup.idea) { const e = new Error('请至少选择一个出场人物、一个母题,或写一句设定'); e.status = 400; throw e }
275
+ const exclude = new Set(Array.isArray(b.exclude) ? b.exclude : [])
276
+ const pin = Array.isArray(b.pin) ? b.pin : []
277
+ const ws = terms(setup.idea).filter(w => w.length >= 2)
278
+ const rand = rng(b.seed)
279
+ const scored = []
280
+ const rejected = []
281
+ for (const c of S.cards) {
282
+ if (exclude.has(c.uid)) continue
283
+ const s = scoreCard(c, setup, ws)
284
+ if (s < 8 && !pin.includes(c.uid)) continue
285
+ const ck = check(c, setup)
286
+ if (!ck.ok) { rejected.push({ c, s, why: ck.why }); continue }
287
+ scored.push({ c, s: s - ck.warn.length * 1.2, warn: ck.warn })
288
+ }
289
+ scored.sort((a, b) => b.s - a.s)
290
+ const chosen = [], picks = {}, alts = {}
291
+ const take = (slot, list, n = 1) => {
292
+ const ok = []
293
+ for (const x of list) {
294
+ if (chosen.includes(x.c)) continue
295
+ const cf = conflictWith(x.c, chosen)
296
+ if (cf) { rejected.push({ c: x.c, s: x.s, why: [cf] }); continue }
297
+ ok.push(x)
298
+ if (ok.length >= 8) break
299
+ }
300
+ if (!ok.length) return []
301
+ const got = []
302
+ const pool = ok.slice(0, Math.min(4, ok.length))
303
+ for (let i = 0; i < n && pool.length; i++) {
304
+ const k = Number(b.seed) ? Math.floor(rand() * Math.min(3, pool.length)) : 0
305
+ const x = pool.splice(k, 1)[0]
306
+ if (conflictWith(x.c, chosen)) continue
307
+ chosen.push(x.c); got.push(x)
308
+ }
309
+ alts[slot] = ok.filter(x => !got.includes(x)).slice(0, 5).map(x => ({ ...lite(x.c), score: Math.round(x.s * 10) / 10, warn: x.warn }))
310
+ return got
311
+ }
312
+ const full = scored.filter(x => x.c.lv === 'full')
313
+ // 固定的素材优先放入
314
+ for (const uid of pin) { const x = scored.find(y => y.c.uid === uid); if (x && !conflictWith(x.c, chosen)) { chosen.push(x.c); (picks.pinned ||= []).push(x) } }
315
+ const castRoles = setup.cast.map(m => m.role)
316
+ const mainList = full.filter(x => (x.c.ev || []).length >= 3 && (x.c.q || 0) >= 3)
317
+ picks.main = take('main', mainList.length ? mainList : full)
318
+ picks.people = {}
319
+ for (const r of castRoles) {
320
+ const list = full.filter(x => (x.c.ppl || []).some(p => p.role === r) && (x.c.ties || []).some(t => (x.c.ppl || []).some(p => p.id === t.p && p.role === r)))
321
+ picks.people[r] = take('role:' + r, list, 2)
322
+ }
323
+ picks.twist = take('twist', full.filter(x => x.c.twist))
324
+ picks.emotion = take('emotion', scored.filter(x => (x.c.lines || []).length && (!setup.emo.length || setup.emo.some(e => (x.c.emo || []).includes(e)))), 2)
325
+ // 提纲
326
+ const pk = x => ({ ...lite(x.c), score: Math.round(x.s * 10) / 10, warn: x.warn })
327
+ const mainCard = picks.main[0]?.c
328
+ const allPicked = chosen
329
+ const hookFrom = allPicked.find(c => c.hook) || null
330
+ const roleActs = {}
331
+ for (const r of castRoles) {
332
+ const items = []
333
+ for (const c of allPicked) {
334
+ const ids = new Set((c.ppl || []).filter(p => p.role === r).map(p => p.id))
335
+ for (const t of c.ties || []) if (ids.has(t.p)) for (const a of t.acts || []) items.push({ a, uid: c.uid, tone: t.tone })
336
+ }
337
+ roleActs[r] = items.slice(0, 8)
338
+ }
339
+ const outline = [
340
+ { step: '开篇钩子', text: hookFrom?.hook || mainCard?.log || '', uid: hookFrom?.uid || mainCard?.uid || '' },
341
+ ...((mainCard?.ev || []).map((e, i) => ({ step: i === 0 ? '主线起因' : `主线推进 ${i}`, text: [e.e, e.why && `(因为${e.why})`, e.then && `→ ${e.then}`].filter(Boolean).join(''), uid: mainCard.uid, m: e.m, mt: motifName(e.m) }))),
342
+ ...castRoles.flatMap(r => (picks.people[r] || []).map(x => ({ step: `${r}线`, text: x.c.log + (roleActs[r].filter(a => a.uid === x.c.uid).length ? ';互动:' + roleActs[r].filter(a => a.uid === x.c.uid).map(a => a.a).join(';') : ''), uid: x.c.uid }))),
343
+ ...picks.twist.map(x => ({ step: '反转', text: x.c.twist, uid: x.c.uid })),
344
+ ...picks.emotion.map(x => ({ step: '情绪收尾', text: (x.c.arc ? `情绪:${x.c.arc}。` : '') + (x.c.lines || []).slice(0, 2).join(' / '), uid: x.c.uid })),
345
+ ].filter(s => s.text)
346
+ const constraints = {
347
+ facts: allPicked.flatMap(c => (c.facts || []).map(t => ({ t, uid: c.uid }))),
348
+ needs: allPicked.flatMap(c => (c.needs || []).map(t => ({ t, uid: c.uid }))),
349
+ open: allPicked.flatMap(c => (c.open || []).map(t => ({ t, uid: c.uid }))),
350
+ warn: [...new Set([...scored.filter(x => allPicked.includes(x.c)).flatMap(x => x.warn)])],
351
+ }
352
+ const seen = new Set()
353
+ const rej = rejected.sort((a, b) => b.s - a.s).filter(x => !seen.has(x.c.uid) && seen.add(x.c.uid)).slice(0, 10).map(x => ({ uid: x.c.uid, log: x.c.log || (x.c.lines || [])[0], why: x.why }))
354
+ return {
355
+ setup, candidates: scored.length,
356
+ picks: {
357
+ pinned: (picks.pinned || []).map(pk), main: picks.main.map(pk), twist: picks.twist.map(pk), emotion: picks.emotion.map(pk),
358
+ people: Object.fromEntries(Object.entries(picks.people).map(([r, xs]) => [r, xs.map(pk)])),
359
+ },
360
+ alts, outline, role_acts: roleActs, constraints, rejected: rej,
361
+ details: allPicked.flatMap(c => (c.det || []).map(t => ({ t, uid: c.uid }))).slice(0, 16),
362
+ lines: allPicked.flatMap(c => (c.lines || []).map(t => ({ t, uid: c.uid }))).slice(0, 12),
363
+ }
364
+ }))
365
+
366
+ return router
367
+ }
fanqie/mount.js CHANGED
@@ -21,6 +21,8 @@ module.exports = function mountFanqie(app, passwordOk, express) {
21
  }
22
  app.use('/fanqie/api', (req, res, next) => (passwordOk(req) ? next() : res.status(401).json({ error: 'password required' })))
23
  app.use('/fanqie/api/materials', materials)
 
 
24
  app.get('/fanqie/api/health', (_req, res) => res.json({ ok: true }))
25
 
26
  // 小说项目工作台:项目、作品圣经、大纲、章节、版本和检查结果全部保存到 R2。
 
21
  }
22
  app.use('/fanqie/api', (req, res, next) => (passwordOk(req) ? next() : res.status(401).json({ error: 'password required' })))
23
  app.use('/fanqie/api/materials', materials)
24
+ // 母题库 v2(第二次提炼,按人物/关系/事件/逻辑约束检索 + 组稿),数据直接读 R2 motif_v2/
25
+ try { app.use('/fanqie/api/motif2', require('./motif2.js')(express)) } catch (e) { console.error('motif2 mount failed:', e) }
26
  app.get('/fanqie/api/health', (_req, res) => res.json({ ok: true }))
27
 
28
  // 小说项目工作台:项目、作品圣经、大纲、章节、版本和检查结果全部保存到 R2。
public/assets/{index-B0JKZHmZ.css → index-CJ2d1DZw.css} RENAMED
The diff for this file is too large to render. See raw diff
 
public/assets/index-CmUi1EQO.js ADDED
The diff for this file is too large to render. See raw diff
 
public/assets/index-D2be1U5S.js DELETED
The diff for this file is too large to render. See raw diff
 
public/index.html CHANGED
@@ -8,8 +8,8 @@
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
- <script type="module" crossorigin src="/assets/index-D2be1U5S.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-B0JKZHmZ.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
 
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
+ <script type="module" crossorigin src="/assets/index-CmUi1EQO.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-CJ2d1DZw.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
ui-src/src/App.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import React, { useEffect, useState } from 'react'
2
- import { BookOpen, Library, Radio, Compass, Moon, Sun, Lock, Feather } from 'lucide-react'
3
  import { authRequired, checkPassword, getPassword, setPassword, setUnauthorizedHandler } from './api'
4
  import { cx, useRoute } from './lib'
5
  import { ConfirmHost, ToastHost, Spinner } from './ui'
@@ -8,6 +8,7 @@ import Book from './rooms/Book'
8
  import LibraryRoom from './rooms/Library'
9
  import Sources from './rooms/Sources'
10
  import Guide from './rooms/Guide'
 
11
 
12
  type Gate = 'checking' | 'locked' | 'open'
13
 
@@ -65,6 +66,7 @@ const ROOMS = [
65
  { id: 'guide', match: ['guide'], label: '手册', icon: Compass },
66
  { id: 'shelf', match: ['', 'shelf', 'book'], label: '书房', icon: BookOpen },
67
  { id: 'library', match: ['library'], label: '素材馆', icon: Library },
 
68
  { id: 'sources', match: ['sources'], label: '采集', icon: Radio },
69
  ]
70
 
@@ -80,12 +82,13 @@ function Shell({ onLock }: { onLock: () => void }) {
80
  const head = parts[0] || ''
81
  const room = ROOMS.find(r => r.match.includes(head)) || ROOMS.find(r => r.id === 'shelf')!
82
  useEffect(() => {
83
- const titles: Record<string, string> = { shelf: '书房', library: '素材馆', sources: '素材采集', guide: '写作手册' }
84
  if (room.id !== 'shelf' || head !== 'book') document.title = `${titles[room.id]} · 小说写作台`
85
  }, [room.id, head])
86
 
87
  let content: React.ReactNode
88
  if (head === 'book' && parts[1]) content = <Book key={parts[1]} projectId={parts[1]} sub={parts[2] || ''} />
 
89
  else if (head === 'library') content = <LibraryRoom tab={parts[1] || 'materials'} arg={parts[2] || ''} />
90
  else if (head === 'sources') content = <Sources channel={parts[1] || ''} tab={parts[2] || ''} />
91
  else if (head === 'guide') content = <Guide section={parts[1] || 'start'} focus={parts[2]} />
 
1
  import React, { useEffect, useState } from 'react'
2
+ import { BookOpen, Library, Radio, Compass, Moon, Sun, Lock, Feather, Layers } from 'lucide-react'
3
  import { authRequired, checkPassword, getPassword, setPassword, setUnauthorizedHandler } from './api'
4
  import { cx, useRoute } from './lib'
5
  import { ConfirmHost, ToastHost, Spinner } from './ui'
 
8
  import LibraryRoom from './rooms/Library'
9
  import Sources from './rooms/Sources'
10
  import Guide from './rooms/Guide'
11
+ import Motif2Room from './rooms/Motif2'
12
 
13
  type Gate = 'checking' | 'locked' | 'open'
14
 
 
66
  { id: 'guide', match: ['guide'], label: '手册', icon: Compass },
67
  { id: 'shelf', match: ['', 'shelf', 'book'], label: '书房', icon: BookOpen },
68
  { id: 'library', match: ['library'], label: '素材馆', icon: Library },
69
+ { id: 'motif2', match: ['motif2'], label: '母题库', icon: Layers },
70
  { id: 'sources', match: ['sources'], label: '采集', icon: Radio },
71
  ]
72
 
 
82
  const head = parts[0] || ''
83
  const room = ROOMS.find(r => r.match.includes(head)) || ROOMS.find(r => r.id === 'shelf')!
84
  useEffect(() => {
85
+ const titles: Record<string, string> = { shelf: '书房', library: '素材馆', motif2: '母题库', sources: '素材采集', guide: '写作手册' }
86
  if (room.id !== 'shelf' || head !== 'book') document.title = `${titles[room.id]} · 小说写作台`
87
  }, [room.id, head])
88
 
89
  let content: React.ReactNode
90
  if (head === 'book' && parts[1]) content = <Book key={parts[1]} projectId={parts[1]} sub={parts[2] || ''} />
91
+ else if (head === 'motif2') content = <Motif2Room tab={parts[1] || 'role'} arg={parts[2] || ''} />
92
  else if (head === 'library') content = <LibraryRoom tab={parts[1] || 'materials'} arg={parts[2] || ''} />
93
  else if (head === 'sources') content = <Sources channel={parts[1] || ''} tab={parts[2] || ''} />
94
  else if (head === 'guide') content = <Guide section={parts[1] || 'start'} focus={parts[2]} />
ui-src/src/rooms/Motif2.tsx ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from 'react'
2
+ import { Users, Search, Sparkles, Copy, RefreshCw, Pin, X, ShieldCheck, AlertTriangle, BookmarkPlus, Plus, Trash2, Quote, Layers } from 'lucide-react'
3
+ import { get, post, qs } from '../api'
4
+ import { copyText, cx, fmtNum, go, useAsync, useDebounced } from '../lib'
5
+ import { Drawer, Empty, ErrorNote, Loading, Pager, Stars, Tabs, Tag, useToast } from '../ui'
6
+ import { basketAdd } from './Library'
7
+
8
+ const A = '/fanqie/api/motif2'
9
+ const api = {
10
+ meta: () => get<any>(`${A}/meta`),
11
+ role: (p: Record<string, any>) => get<any>(`${A}/role${qs(p)}`),
12
+ cards: (p: Record<string, any>) => get<any>(`${A}/cards${qs(p)}`),
13
+ card: (uid: string) => get<any>(`${A}/card${qs({ uid })}`),
14
+ compose: (body: any) => post<any>(`${A}/compose`, body),
15
+ reload: () => post<any>(`${A}/reload`, {}),
16
+ }
17
+ type T2 = 'role' | 'search' | 'compose'
18
+
19
+ export default function Motif2Room({ tab, arg }: { tab: string; arg: string }) {
20
+ const t = (['role', 'search', 'compose'].includes(tab) ? tab : 'role') as T2
21
+ const meta = useAsync(() => api.meta(), [])
22
+ const [openUid, setOpenUid] = useState('')
23
+ const p = meta.data?.progress
24
+ return (
25
+ <div className="room library m2">
26
+ <header className="room-head">
27
+ <div>
28
+ <div className="eyebrow"><Layers size={14} />母题库 v2</div>
29
+ <h1 className="room-title serif">按人物、事件、情绪找素材,自动串成提纲</h1>
30
+ <p className="muted small-note">
31
+ 这是对已清洗素材的第二次提炼:每条素材都拆成人物、与主角的互动、事件链和逻辑约束。旧版母题库仍在「素材馆」里,可以对比使用。
32
+ {p && <> 当前已提炼 <b>{fmtNum(p.done_items)}</b> / {fmtNum(p.total_items)} 条({p.done_batches}/{p.total_batches} 批),可用卡片 {fmtNum(meta.data.cards)} 张。</>}
33
+ </p>
34
+ </div>
35
+ </header>
36
+ <Tabs<T2> value={t} onChange={v => go(`motif2/${v}`)} className="room-tabs" items={[
37
+ { id: 'role', label: '按人物查' }, { id: 'search', label: '检索' }, { id: 'compose', label: '组稿' },
38
+ ]} />
39
+ <div className="room-body">
40
+ {meta.loading && !meta.data && <Loading label="正在载入母题库…" />}
41
+ {meta.error && <ErrorNote error={meta.error} onRetry={meta.reload} />}
42
+ {meta.data && t === 'role' && <RoleTab meta={meta.data} role={decodeURIComponent(arg || '')} onOpen={setOpenUid} />}
43
+ {meta.data && t === 'search' && <SearchTab meta={meta.data} onOpen={setOpenUid} />}
44
+ {meta.data && t === 'compose' && <ComposeTab meta={meta.data} onOpen={setOpenUid} />}
45
+ </div>
46
+ <CardDrawer uid={openUid} meta={meta.data} onClose={() => setOpenUid('')} />
47
+ </div>
48
+ )
49
+ }
50
+
51
+ const motifT = (meta: any, id: string) => { for (const g of Object.values(meta?.taxonomy?.motifs || {}) as any[]) if (g[id]) return g[id]; return id }
52
+ const countOf = (list: any[], k: string) => list?.find((x: any) => x.k === k)?.n || 0
53
+
54
+ /* ================= 按人物查 ================= */
55
+ function RoleTab({ meta, role, onOpen }: { meta: any; role: string; onOpen: (u: string) => void }) {
56
+ const roles: Record<string, string[]> = meta.taxonomy?.roles || {}
57
+ if (!role) return (
58
+ <div className="m2-roles">
59
+ <p className="page-sub muted">选一个人物原型,看看素材库里关于这类人物的事件、他们和主角之间的互动、常见情绪,以及可以借用的台词。</p>
60
+ {Object.entries(roles).map(([grp, list]) => (
61
+ <section key={grp} className="motif-group">
62
+ <h3 className="m2-grp">{grp}</h3>
63
+ <div className="m2-role-grid">
64
+ {list.map(r => <button key={r} className="motif-tile" onClick={() => go(`motif2/role/${encodeURIComponent(r)}`)}><b>{r}</b><span>{fmtNum(countOf(meta.roles, r))} 条素材</span></button>)}
65
+ </div>
66
+ </section>
67
+ ))}
68
+ </div>
69
+ )
70
+ return <RoleDetail meta={meta} role={role} onOpen={onOpen} />
71
+ }
72
+
73
+ function RoleDetail({ meta, role, onOpen }: { meta: any; role: string; onOpen: (u: string) => void }) {
74
+ const [m, setM] = useState('')
75
+ const [emo, setEmo] = useState('')
76
+ const [st, setSt] = useState('')
77
+ const [page, setPage] = useState(1)
78
+ const [view, setView] = useState<'acts' | 'cards' | 'people' | 'lines'>('acts')
79
+ useEffect(() => setPage(1), [m, emo, st, role])
80
+ const r = useAsync(() => api.role({ r: role, m, emo, st, page, size: 12 }), [role, m, emo, st, page])
81
+ const d = r.data
82
+ return (
83
+ <div className="m2-role">
84
+ <button className="link-btn back" onClick={() => go('motif2/role')}>← 全部人物</button>
85
+ <h2 className="serif m2-role-title">{role}<span className="muted">共 {fmtNum(d?.total_all ?? 0)} 条素材{d && d.total !== d.total_all ? `,筛选后 ${fmtNum(d.total)} 条` : ''}</span></h2>
86
+ {d && <div className="m2-filters">
87
+ <FilterRow label="事件类型" items={d.motifs.slice(0, 24).map((x: any) => ({ k: x.k, t: x.t, n: x.n }))} value={m} onChange={setM} />
88
+ <FilterRow label="情绪" items={d.emo.map((x: any) => ({ k: x.k, t: x.k, n: x.n }))} value={emo} onChange={setEmo} />
89
+ <FilterRow label={`${role}的状态`} items={d.st.map((x: any) => ({ k: x.k, t: x.k, n: x.n }))} value={st} onChange={setSt} />
90
+ {d.tone.length > 0 && <div className="m2-fr"><span className="m2-fl">与主角的关系</span><span className="muted small-note">{d.tone.map((x: any) => `${x.k} ${x.n}`).join(' · ')}</span></div>}
91
+ </div>}
92
+ <Tabs value={view} onChange={setView as any} items={[
93
+ { id: 'acts', label: '与主角的互动', count: d?.acts?.length }, { id: 'cards', label: '素材卡', count: d?.total },
94
+ { id: 'people', label: '人物侧写', count: d?.people?.length }, { id: 'lines', label: '台词金句', count: d?.lines?.length },
95
+ ]} />
96
+ {r.loading && !d && <Loading />}
97
+ {r.error && <ErrorNote error={r.error} onRetry={r.reload} />}
98
+ {d && view === 'acts' && (d.acts.length ? <ul className="m2-acts">
99
+ {d.acts.map((a: any, i: number) => (
100
+ <li key={i} onClick={() => onOpen(a.uid)}>
101
+ <span className="m2-act">{a.a}</span>
102
+ <span className="m2-act-meta">{a.rel && <Tag>{a.rel}</Tag>}{a.tone && <Tag>{a.tone}</Tag>}{a.st && a.st !== '不明' && <Tag tone={a.st === '已故' ? 'warn' : undefined}>{a.st}</Tag>}{a.mot && <span className="muted">{motifT(meta, a.mot)}</span>}</span>
103
+ </li>))}
104
+ </ul> : <Empty title="暂无互动记录">换个筛选条件试试,或等更多批次提炼完成。</Empty>)}
105
+ {d && view === 'cards' && <>
106
+ <div className="m2-cards">{d.items.map((c: any) => <CardMini key={c.uid} c={c} meta={meta} onOpen={onOpen} focus={role} />)}</div>
107
+ <Pager page={page} total={d.total} size={d.size} onChange={setPage} />
108
+ </>}
109
+ {d && view === 'people' && <ul className="m2-acts">{d.people.map((p: any, i: number) => <li key={i} onClick={() => onOpen(p.uid)}><span className="m2-act">{p.trait}{p.want ? `;想要/害怕:${p.want}` : ''}</span><span className="m2-act-meta">{p.st && p.st !== '不明' && <Tag>{p.st}</Tag>}</span></li>)}</ul>}
110
+ {d && view === 'lines' && <ul className="m2-acts">{d.lines.map((l: any, i: number) => <li key={i} onClick={() => onOpen(l.uid)}><span className="m2-act serif">「{l.l}」</span><span className="m2-act-meta">{l.emo && <Tag>{l.emo}</Tag>}{l.fit && <span className="muted">{l.fit}</span>}</span></li>)}</ul>}
111
+ </div>
112
+ )
113
+ }
114
+
115
+ function FilterRow({ label, items, value, onChange }: { label: string; items: { k: string; t: string; n: number }[]; value: string; onChange: (v: string) => void }) {
116
+ if (!items.length) return null
117
+ return (
118
+ <div className="m2-fr"><span className="m2-fl">{label}</span>
119
+ <div className="chips-row tight">
120
+ <button className={cx('chip', !value && 'on')} onClick={() => onChange('')}>全部</button>
121
+ {items.map(x => <button key={x.k} className={cx('chip', value === x.k && 'on')} onClick={() => onChange(value === x.k ? '' : x.k)}>{x.t}<em>{x.n}</em></button>)}
122
+ </div>
123
+ </div>
124
+ )
125
+ }
126
+
127
+ /* ================= 卡片 ================= */
128
+ function CardMini({ c, meta, onOpen, focus, extra }: { c: any; meta: any; onOpen: (u: string) => void; focus?: string; extra?: React.ReactNode }) {
129
+ const people = (c.ppl || []).map((p: any) => p.role + (p.st && p.st !== '在世' && p.st !== '不明' ? `(${p.st})` : ''))
130
+ const ties = focus ? (c.ties || []).filter((t: any) => (c.ppl || []).some((p: any) => p.id === t.p && p.role === focus)) : []
131
+ return (
132
+ <div className="m2-card" onClick={() => onOpen(c.uid)}>
133
+ <div className="m2-card-head">
134
+ <Stars n={c.q || 0} />
135
+ {c.lv === 'lite' ? <Tag>金句</Tag> : <Tag tone="accent">{c.era || '不明'}</Tag>}
136
+ {(c.emo || []).map((e: string) => <Tag key={e}>{e}</Tag>)}
137
+ </div>
138
+ <div className="m2-log">{c.lv === 'lite' ? `「${(c.lines || [])[0] || ''}」` : c.log}</div>
139
+ {c.lv === 'lite' && c.fit && <div className="muted small-note">适用:{c.fit}</div>}
140
+ {people.length > 0 && <div className="muted small-note">人物:{people.join('、')}{c.pov?.role ? ` | 主角:${c.pov.role}` : ''}</div>}
141
+ {ties.map((t: any, i: number) => <div key={i} className="m2-tie">{(t.acts || []).map((a: string, j: number) => <span key={j}>· {a}</span>)}</div>)}
142
+ {(c.mot || []).length > 0 && <div className="m2-tags">{c.mot.map((m: string) => <span key={m} className="m2-mot">{motifT(meta, m)}</span>)}</div>}
143
+ {extra}
144
+ </div>
145
+ )
146
+ }
147
+
148
+ function CardDrawer({ uid, meta, onClose }: { uid: string; meta: any; onClose: () => void }) {
149
+ const toast = useToast()
150
+ const r = useAsync(() => uid ? api.card(uid) : Promise.resolve(null), [uid])
151
+ const [showSrc, setShowSrc] = useState(false)
152
+ useEffect(() => setShowSrc(false), [uid])
153
+ const c = r.data?.card
154
+ return (
155
+ <Drawer open={!!uid} onClose={onClose} title="素材卡" width={620}
156
+ footer={c && <div className="row gap">
157
+ <button className="btn ghost" onClick={async () => { await copyText(cardText(c, meta)); toast('已复制这张卡', 'ok') }}><Copy size={14} />复制给 AI</button>
158
+ <button className="btn primary" onClick={() => toast(basketAdd({ uid: c.uid, sum: c.log || (c.lines || [])[0], g: '', k: c.lv === 'lite' ? 'quote' : 'story', q: c.q, card: { uid: c.uid, logline: c.log, hook: c.hook, twist: c.twist, arc: c.arc, details: c.det, people: (c.ppl || []).map((p: any) => ({ role: p.role, trait: p.trait, want: p.want })) } }) ? '已放进素材篮' : '已经在素材篮里了', 'ok')}><BookmarkPlus size={14} />放进素材篮</button>
159
+ </div>}>
160
+ {r.loading && <Loading />}
161
+ {r.error && <ErrorNote error={r.error} />}
162
+ {c && <div className="m2-detail">
163
+ <div className="m2-card-head"><Stars n={c.q || 0} />{c.lv === 'full' && <><Tag tone="accent">{c.era}</Tag>{(c.place || []).map((p: string) => <Tag key={p}>{p}</Tag>)}</>}{(c.gen || []).map((g: string) => <Tag key={g}>{g}</Tag>)}{(c.emo || []).map((e: string) => <Tag key={e}>{e}</Tag>)}{(c.pay || []).map((e: string) => <Tag key={e} tone="ok">{e}</Tag>)}</div>
164
+ {c.lv === 'full' ? <>
165
+ <p className="m2-log big serif">{c.log}</p>
166
+ {c.hook && <div className="bd-hook"><Quote size={14} />{c.hook}</div>}
167
+ <Block title={`主角:${c.pov?.role || ''}(${c.pov?.sex || ''} · 事发时${c.pov?.age || ''})`}>
168
+ {(c.ppl || []).map((p: any) => {
169
+ const ties = (c.ties || []).filter((t: any) => t.p === p.id)
170
+ return <div key={p.id} className="m2-person">
171
+ <b>{p.role}</b> <Tag tone={p.st === '已故' ? 'warn' : undefined}>{p.st}</Tag> <span className="muted">{p.trait}{p.want ? `;${p.want}` : ''}</span>
172
+ {ties.map((t: any, i: number) => <div key={i} className="m2-tie">与主角:{t.rel}({t.tone}){(t.acts || []).map((a: string, j: number) => <span key={j}>· {a}</span>)}</div>)}
173
+ </div>
174
+ })}
175
+ </Block>
176
+ <Block title="事件链">
177
+ <ol className="m2-ev">{(c.ev || []).map((e: any, i: number) => <li key={i}><span className="m2-mot">{motifT(meta, e.m)}</span>{e.e}{e.why && <span className="muted">(因:{e.why})</span>}{e.then && <span className="muted"> → {e.then}</span>}</li>)}</ol>
178
+ {c.arc && <div className="muted small-note">情绪弧线:{c.arc}</div>}
179
+ {c.twist && <div className="rs-note">反转:{c.twist}</div>}
180
+ </Block>
181
+ {(c.lines?.length > 0 || c.det?.length > 0) && <Block title="可借用的台词与细节">
182
+ {(c.lines || []).map((l: string, i: number) => <div key={i} className="serif">「{l}」</div>)}
183
+ {(c.det || []).map((l: string, i: number) => <div key={'d' + i}>· {l}</div>)}
184
+ </Block>}
185
+ <Block title="逻辑约束(串联时必须遵守)">
186
+ {(c.facts || []).map((x: string, i: number) => <div key={i} className="m2-c fact"><ShieldCheck size={13} />事实:{x}</div>)}
187
+ {(c.needs || []).map((x: string, i: number) => <div key={i} className="m2-c need"><AlertTriangle size={13} />前提:{x}</div>)}
188
+ {(c.open || []).map((x: string, i: number) => <div key={i} className="m2-c open">· 可自定:{x}</div>)}
189
+ {c.risk && <div className="m2-c need"><AlertTriangle size={13} />红线:{c.risk}</div>}
190
+ </Block>
191
+ </> : <>
192
+ {(c.lines || []).map((l: string, i: number) => <p key={i} className="m2-log big serif">「{l}」</p>)}
193
+ <div className="muted">适用:{c.fit}</div>
194
+ {(c.roles || []).length > 0 && <div className="muted small-note">适合人物:{c.roles.join('、')}</div>}
195
+ </>}
196
+ {(c.mot || []).length > 0 && <div className="m2-tags">{c.mot.map((m: string) => <span key={m} className="m2-mot">{motifT(meta, m)}</span>)}</div>}
197
+ {r.data?.source && <div className="m2-src">
198
+ <button className="link-btn" onClick={() => setShowSrc(s => !s)}>{showSrc ? '收起清洗后原文' : '查看清洗后原文(仅供核对,不要交给 AI 照搬)'}</button>
199
+ {showSrc && <pre className="m2-src-text">{r.data.source.text}</pre>}
200
+ </div>}
201
+ </div>}
202
+ </Drawer>
203
+ )
204
+ }
205
+ const Block = ({ title, children }: { title: string; children: React.ReactNode }) => <div className="bd-block"><h4>{title}</h4>{children}</div>
206
+
207
+ function cardText(c: any, meta: any) {
208
+ if (c.lv === 'lite') return `【金句】${(c.lines || []).join(' / ')}(适用:${c.fit})`
209
+ const out = [`【素材】${c.log}`]
210
+ out.push(`主角:${c.pov?.role}(${c.pov?.sex},事发时${c.pov?.age})|年代:${c.era}|场景:${(c.place || []).join('、')}`)
211
+ for (const p of c.ppl || []) {
212
+ const ties = (c.ties || []).filter((t: any) => t.p === p.id)
213
+ out.push(`人物:${p.role}(${p.st})${p.trait};${p.want}` + ties.map((t: any) => `|与主角:${t.rel},${(t.acts || []).join(';')}`).join(''))
214
+ }
215
+ out.push('事件:' + (c.ev || []).map((e: any) => `${e.e}${e.then ? '→' + e.then : ''}(${motifT(meta, e.m)})`).join(' ⇒ '))
216
+ if (c.twist) out.push(`反转:${c.twist}`)
217
+ if (c.arc) out.push(`情绪:${c.arc}`)
218
+ if (c.det?.length) out.push(`细节:${c.det.join(';')}`)
219
+ if (c.facts?.length) out.push(`必须遵守的事实:${c.facts.join(';')}`)
220
+ if (c.needs?.length) out.push(`使用前提:${c.needs.join(';')}`)
221
+ return out.join('\n')
222
+ }
223
+
224
+ /* ================= 检索 ================= */
225
+ function SearchTab({ meta, onOpen }: { meta: any; onOpen: (u: string) => void }) {
226
+ const [w, setW] = useState('')
227
+ const [f, setF] = useState<Record<string, string>>({ role: '', m: '', emo: '', era: '', place: '', gen: '', lv: '' })
228
+ const [page, setPage] = useState(1)
229
+ const dw = useDebounced(w, 400)
230
+ useEffect(() => setPage(1), [dw, f])
231
+ const r = useAsync(() => api.cards({ ...f, w: dw, page, size: 16 }), [dw, f, page])
232
+ const set = (k: string, v: string) => setF(p => ({ ...p, [k]: v }))
233
+ const motifs = meta.taxonomy?.motifs || {}
234
+ return (
235
+ <div className="m2-search">
236
+ <div className="sheet m2-sheet">
237
+ <input className="input" value={w} onChange={e => setW(e.target.value)} placeholder="关键词,空格分隔,例如:爷爷 学费 偷偷" />
238
+ <div className="m2-selects">
239
+ <Sel label="人物" value={f.role} onChange={v => set('role', v)} groups={Object.entries(meta.taxonomy?.roles || {}).map(([g, l]: any) => [g, l.map((x: string) => [x, x])])} />
240
+ <Sel label="母题" value={f.m} onChange={v => set('m', v)} groups={Object.entries(motifs).map(([g, o]: any) => [g, Object.entries(o)])} />
241
+ <Sel label="情绪" value={f.emo} onChange={v => set('emo', v)} groups={[['', (meta.taxonomy?.emo || []).map((x: string) => [x, x])]]} />
242
+ <Sel label="年代" value={f.era} onChange={v => set('era', v)} groups={[['', (meta.taxonomy?.era || []).map((x: string) => [x, x])]]} />
243
+ <Sel label="场景" value={f.place} onChange={v => set('place', v)} groups={[['', (meta.taxonomy?.place || []).map((x: string) => [x, x])]]} />
244
+ <Sel label="番茄题材" value={f.gen} onChange={v => set('gen', v)} groups={[['', (meta.taxonomy?.gen || []).map((x: string) => [x, x])]]} />
245
+ <Sel label="类型" value={f.lv} onChange={v => set('lv', v)} groups={[['', [['full', '完整故事'], ['lite', '金句文案']]]]} />
246
+ </div>
247
+ </div>
248
+ {r.error && <ErrorNote error={r.error} />}
249
+ {r.data && <div className="muted small-note">找到 {fmtNum(r.data.total)} 条</div>}
250
+ {r.data && <div className="m2-cards">{r.data.items.map((c: any) => <CardMini key={c.uid} c={c} meta={meta} onOpen={onOpen} focus={f.role} />)}</div>}
251
+ {r.data && <Pager page={page} total={r.data.total} size={r.data.size} onChange={setPage} />}
252
+ </div>
253
+ )
254
+ }
255
+ function Sel({ label, value, onChange, groups }: { label: string; value: string; onChange: (v: string) => void; groups: [string, [string, string][]][] }) {
256
+ return (
257
+ <label className="m2-sel"><span>{label}</span>
258
+ <select className="input mini" value={value} onChange={e => onChange(e.target.value)}>
259
+ <option value="">全部</option>
260
+ {groups.map(([g, items]) => g ? <optgroup key={g} label={g}>{items.map(([k, t]) => <option key={k} value={k}>{t}</option>)}</optgroup> : items.map(([k, t]) => <option key={k} value={k}>{t}</option>))}
261
+ </select>
262
+ </label>
263
+ )
264
+ }
265
+
266
+ /* ================= 组稿 ================= */
267
+ type CastM = { role: string; st: string; note: string }
268
+ function ComposeTab({ meta, onOpen }: { meta: any; onOpen: (u: string) => void }) {
269
+ const toast = useToast()
270
+ const tx = meta.taxonomy || {}
271
+ const [idea, setIdea] = useState('')
272
+ const [hero, setHero] = useState({ sex: '', era: '当代', age: '', place: [] as string[], note: '' })
273
+ const [cast, setCast] = useState<CastM[]>([{ role: '爷爷', st: '', note: '' }])
274
+ const [emo, setEmo] = useState<string[]>([])
275
+ const [mot, setMot] = useState<string[]>([])
276
+ const [gen, setGen] = useState('')
277
+ const [seed, setSeed] = useState(0)
278
+ const [pin, setPin] = useState<string[]>([])
279
+ const [exclude, setExclude] = useState<string[]>([])
280
+ const [res, setRes] = useState<any>(null)
281
+ const [busy, setBusy] = useState(false)
282
+ const [err, setErr] = useState('')
283
+ const allRoles: string[] = Object.values(tx.roles || {}).flat() as string[]
284
+ const run = async (s = seed, extra: { pin?: string[]; exclude?: string[] } = {}) => {
285
+ setBusy(true); setErr('')
286
+ try {
287
+ const r = await api.compose({ idea, hero, cast: cast.filter(c => c.role), emo, mot, gen, seed: s, pin: extra.pin ?? pin, exclude: extra.exclude ?? exclude })
288
+ setRes(r); setSeed(s)
289
+ } catch (e: any) { setErr(e.message) } finally { setBusy(false) }
290
+ }
291
+ const toggle = (arr: string[], set: (v: string[]) => void, v: string, max = 4) => set(arr.includes(v) ? arr.filter(x => x !== v) : arr.length >= max ? arr : [...arr, v])
292
+ const pack = useMemo(() => res ? packText(res, meta) : '', [res, meta])
293
+ const drop = (uid: string) => { const ex = [...exclude, uid]; setExclude(ex); run(seed, { exclude: ex, pin: pin.filter(x => x !== uid) }) }
294
+ const keep = (uid: string) => { const p = pin.includes(uid) ? pin.filter(x => x !== uid) : [...pin, uid]; setPin(p); toast(pin.includes(uid) ? '已取消固定' : '已固定:换一组时会保留这条', 'ok') }
295
+ const slot = (title: string, items: any[], note?: string) => items?.length ? (
296
+ <div className="m2-slot"><h4>{title}{note && <span className="muted"> · {note}</span>}</h4>
297
+ {items.map((c: any) => <CardMini key={c.uid} c={c} meta={meta} onOpen={onOpen} extra={
298
+ <div className="m2-slot-act" onClick={e => e.stopPropagation()}>
299
+ {(c.warn || []).map((w: string, i: number) => <div key={i} className="m2-warn"><AlertTriangle size={12} />{w}</div>)}
300
+ <button className={cx('btn small ghost', pin.includes(c.uid) && 'on')} onClick={() => keep(c.uid)}><Pin size={12} />{pin.includes(c.uid) ? '已固定' : '固定'}</button>
301
+ <button className="btn small ghost" onClick={() => drop(c.uid)}><X size={12} />不要这条</button>
302
+ </div>} />)}
303
+ </div>) : null
304
+ return (
305
+ <div className="compose m2-compose">
306
+ <section className="sheet compose-input">
307
+ <h2 className="sheet-title serif">1. 你的主角和故事</h2>
308
+ <textarea className="textarea serif-input" rows={2} value={idea} onChange={e => setIdea(e.target.value)} placeholder="一句话设定或关键词(可选),例如:被爷爷带大的穷小子,爷爷临终前留下一个旧木箱" />
309
+ <div className="m2-selects">
310
+ <label className="m2-sel"><span>主角性别</span><select className="input mini" value={hero.sex} onChange={e => setHero({ ...hero, sex: e.target.value })}><option value="">不限</option><option>男</option><option>女</option></select></label>
311
+ <label className="m2-sel"><span>故事年代</span><select className="input mini" value={hero.era} onChange={e => setHero({ ...hero, era: e.target.value })}><option value="">不限</option>{(tx.era || []).filter((x: string) => x !== '不明').map((x: string) => <option key={x}>{x}</option>)}</select></label>
312
+ <label className="m2-sel"><span>主角现在的年龄段</span><select className="input mini" value={hero.age} onChange={e => setHero({ ...hero, age: e.target.value })}><option value="">不限</option>{(tx.age || []).filter((x: string) => x !== '不明').map((x: string) => <option key={x}>{x}</option>)}</select></label>
313
+ <label className="m2-sel"><span>番茄题材</span><select className="input mini" value={gen} onChange={e => setGen(e.target.value)}><option value="">不限</option>{(tx.gen || []).map((x: string) => <option key={x}>{x}</option>)}</select></label>
314
+ </div>
315
+ <div className="fgroup-label">主要场景</div>
316
+ <div className="chips-row tight">{(tx.place || []).filter((x: string) => x !== '不明').map((p: string) => <button key={p} className={cx('chip', hero.place.includes(p) && 'on')} onClick={() => setHero({ ...hero, place: hero.place.includes(p) ? hero.place.filter(x => x !== p) : [...hero.place, p] })}>{p}</button>)}</div>
317
+
318
+ <h2 className="sheet-title serif">2. 出场人物(和他们在你书里的状态)</h2>
319
+ <div className="m2-cast">
320
+ {cast.map((m, i) => (
321
+ <div key={i} className="m2-cast-row">
322
+ <select className="input mini" value={m.role} onChange={e => setCast(cast.map((x, j) => j === i ? { ...x, role: e.target.value } : x))}>
323
+ {Object.entries(tx.roles || {}).map(([g, l]: any) => <optgroup key={g} label={g}>{l.map((r: string) => <option key={r}>{r}</option>)}</optgroup>)}
324
+ </select>
325
+ <select className="input mini" value={m.st} onChange={e => setCast(cast.map((x, j) => j === i ? { ...x, st: e.target.value } : x))}>
326
+ <option value="">状态不限</option><option value="在世">在世(不能用他去世的素材)</option><option value="已故">已故(在世的素材写成往事)</option>
327
+ </select>
328
+ <button className="btn small ghost" onClick={() => setCast(cast.filter((_, j) => j !== i))}><Trash2 size={13} /></button>
329
+ </div>
330
+ ))}
331
+ {cast.length < 6 && <button className="btn small ghost" onClick={() => setCast([...cast, { role: allRoles.find(r => !cast.some(c => c.role === r)) || '父亲', st: '', note: '' }])}><Plus size={13} />加一个人物</button>}
332
+ </div>
333
+
334
+ <h2 className="sheet-title serif">3. 想要的情绪和情节(可选)</h2>
335
+ <div className="chips-row tight">{(tx.emo || []).map((e: string) => <button key={e} className={cx('chip', emo.includes(e) && 'on')} onClick={() => toggle(emo, setEmo, e, 3)}>{e}</button>)}</div>
336
+ <div className="motif-chips">
337
+ {Object.entries(tx.motifs || {}).map(([g, o]: any) => (
338
+ <div key={g} className="mchip-row"><span className="mchip-grp">{g}</span>{Object.entries(o).map(([k, t]: any) => <button key={k} className={cx('chip', mot.includes(k) && 'on')} onClick={() => toggle(mot, setMot, k)}>{t}</button>)}</div>
339
+ ))}
340
+ </div>
341
+ <div className="row gap">
342
+ <button className="btn primary" disabled={busy} onClick={() => { setPin([]); setExclude([]); run(0, { pin: [], exclude: [] }) }}><Sparkles size={15} />{busy ? '正在组稿…' : '自动组稿'}</button>
343
+ {res && <button className="btn ghost" disabled={busy} onClick={() => run(seed + 1)}><RefreshCw size={14} />换一组(保留已固定的)</button>}
344
+ </div>
345
+ </section>
346
+ {err && <ErrorNote error={err} />}
347
+ {!res && !busy && !err && <Empty icon={<Users size={22} />} title="先定人物,再配素材">选好主角设定和出场人物,系统会挑出彼此不矛盾的素材,串成「开篇 → 主线 → 人物线 → 反转 → 收尾」的提纲,并标出必须遵守的事实。</Empty>}
348
+ {res && <section className="compose-result">
349
+ <div className="muted small-note">候选素材 {fmtNum(res.candidates)} 条,已排除与设定或彼此冲突的素材。</div>
350
+ <div className="sheet m2-outline">
351
+ <h2 className="sheet-title serif">组稿提纲</h2>
352
+ <ol>{res.outline.map((s: any, i: number) => <li key={i}><b>{s.step}</b>{s.mt && <span className="m2-mot">{s.mt}</span>}<span>{s.text}</span><button className="link-btn" onClick={() => onOpen(s.uid)}>出处</button></li>)}</ol>
353
+ </div>
354
+ {(res.constraints.facts.length > 0 || res.constraints.needs.length > 0) && <div className="sheet">
355
+ <h2 className="sheet-title serif">逻辑约束</h2>
356
+ {res.constraints.facts.map((x: any, i: number) => <div key={i} className="m2-c fact"><ShieldCheck size={13} />{x.t}</div>)}
357
+ {res.constraints.needs.map((x: any, i: number) => <div key={'n' + i} className="m2-c need"><AlertTriangle size={13} />前提:{x.t}</div>)}
358
+ {res.constraints.warn.map((x: string, i: number) => <div key={'w' + i} className="m2-c need"><AlertTriangle size={13} />{x}</div>)}
359
+ </div>}
360
+ <div className="m2-slots">
361
+ {slot('主线素材', res.picks.main)}
362
+ {Object.entries(res.picks.people).map(([r, xs]: any) => <React.Fragment key={r}>{slot(`${r}线`, xs, `${r}与主角的互动`)}</React.Fragment>)}
363
+ {slot('反转', res.picks.twist)}
364
+ {slot('情绪与台词', res.picks.emotion)}
365
+ {slot('你固定的素材', res.picks.pinned)}
366
+ </div>
367
+ {res.rejected.length > 0 && <details className="sheet m2-rej"><summary>被排除的高分素材({res.rejected.length})及原因</summary>
368
+ {res.rejected.map((x: any) => <div key={x.uid} className="m2-rej-row" onClick={() => onOpen(x.uid)}><span>{x.log}</span><span className="m2-warn">{x.why.join(';')}</span></div>)}
369
+ </details>}
370
+ <div className="prompt-box">
371
+ <div className="prompt-head"><b>素材包(只含精简卡片和约束,可直接交给 AI)</b>
372
+ <button className="btn small primary push" onClick={async () => { await copyText(pack); toast('素材包已复制', 'ok') }}><Copy size={14} />复制</button>
373
+ </div>
374
+ <pre>{pack}</pre>
375
+ </div>
376
+ </section>}
377
+ </div>
378
+ )
379
+ }
380
+
381
+ function packText(res: any, meta: any) {
382
+ const s = res.setup
383
+ const out: string[] = ['你是熟悉番茄小说平台规则的网文作者。下面是从真实故事中提炼出的素材卡和逻辑约束。请只借鉴其中的事件结构、人物互动和情绪,用原创的人物、名字和语言来写,不要照搬句子。']
384
+ out.push(`\n【设定】主角${s.hero.sex ? ':' + s.hero.sex : ''}${s.hero.age ? ',现在' + s.hero.age : ''}|年代:${s.hero.era || '不限'}|场景:${(s.hero.place || []).join('、') || '不限'}${s.idea ? '\n想法:' + s.idea : ''}`)
385
+ if (s.cast.length) out.push('出场人物:' + s.cast.map((m: any) => `${m.role}${m.st ? `(${m.st})` : ''}`).join('、'))
386
+ out.push('\n【组稿提纲】')
387
+ res.outline.forEach((x: any, i: number) => out.push(`${i + 1}. ${x.step}:${x.text}`))
388
+ for (const [r, acts] of Object.entries(res.role_acts || {}) as any) if (acts.length) out.push(`\n【${r}与主角的互动素材】\n` + acts.map((a: any) => `- ${a.a}`).join('\n'))
389
+ if (res.lines.length) out.push('\n【可化用的台词】\n' + res.lines.map((x: any) => `- ${x.t}`).join('\n'))
390
+ if (res.details.length) out.push('\n【生活细节】\n' + res.details.map((x: any) => `- ${x.t}`).join('\n'))
391
+ out.push('\n【必须遵守的逻辑】')
392
+ for (const x of res.constraints.facts) out.push(`- ${x.t}`)
393
+ for (const x of res.constraints.needs) out.push(`- 前提:${x.t}`)
394
+ for (const x of res.constraints.warn) out.push(`- 注意:${x}`)
395
+ out.push('- 所有人物为成年人;不写色情、血腥、自杀方法、违法手法;不涉政,不写真实地名、品牌和人名。')
396
+ out.push('\n【任务】先写出人物小传和分章大纲(标出每章用到哪条素材),确认逻辑不冲突后,再写第一章。')
397
+ void meta
398
+ return out.join('\n')
399
+ }
ui-src/src/styles.css CHANGED
@@ -1079,3 +1079,57 @@ select.input { appearance: none; padding-right: 28px; background-image: linear-g
1079
  .rule { padding: 14px; }
1080
  }
1081
  @media print { .guide-toc, .ai-actions, .toolbar, .chips-row { display: none !important; } .rule { break-inside: avoid; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1079
  .rule { padding: 14px; }
1080
  }
1081
  @media print { .guide-toc, .ai-actions, .toolbar, .chips-row { display: none !important; } .rule { break-inside: avoid; } }
1082
+
1083
+ /* ---------- 母题库 v2 ---------- */
1084
+ .m2 .chips-row.tight { margin: 4px 0; gap: 5px; }
1085
+ .m2-grp { font-size: 13px; color: var(--ink-3); margin: 18px 0 8px; font-weight: 600; letter-spacing: .06em; }
1086
+ .m2-role-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: 8px; }
1087
+ .m2-role-grid .motif-tile { display: flex; flex-direction: column; gap: 2px; align-items: flex-start; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface); text-align: left; }
1088
+ .m2-role-grid .motif-tile:hover { border-color: var(--accent); }
1089
+ .m2-role-grid .motif-tile span { font-size: 12px; color: var(--ink-3); }
1090
+ .m2-role-title { font-size: 24px; display: flex; align-items: baseline; gap: 12px; margin-bottom: 10px; }
1091
+ .m2-role-title span { font-size: 13px; font-family: inherit; }
1092
+ .m2-filters { display: flex; flex-direction: column; gap: 6px; margin-bottom: 14px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); }
1093
+ .m2-fr { display: flex; gap: 10px; align-items: flex-start; }
1094
+ .m2-fl { flex: 0 0 92px; font-size: 12px; color: var(--ink-3); padding-top: 8px; }
1095
+ .m2-acts { list-style: none; padding: 0; margin: 12px 0; display: flex; flex-direction: column; gap: 6px; }
1096
+ .m2-acts li { display: flex; justify-content: space-between; gap: 12px; padding: 10px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-s); cursor: pointer; line-height: 1.7; }
1097
+ .m2-acts li:hover { border-color: var(--accent); }
1098
+ .m2-act-meta { display: flex; gap: 4px; align-items: center; flex-shrink: 0; font-size: 12px; flex-wrap: wrap; justify-content: flex-end; max-width: 40%; }
1099
+ .m2-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 10px; margin: 12px 0; }
1100
+ .m2-card { display: flex; flex-direction: column; gap: 6px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); cursor: pointer; }
1101
+ .m2-card:hover { border-color: var(--accent); box-shadow: var(--shadow-s); }
1102
+ .m2-card-head { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
1103
+ .m2-log { line-height: 1.75; font-size: 14px; }
1104
+ .m2-log.big { font-size: 16px; margin: 12px 0; }
1105
+ .m2-tie { font-size: 12.5px; color: var(--ink-2); display: flex; flex-direction: column; gap: 1px; padding-left: 8px; border-left: 2px solid var(--accent-soft); margin-top: 4px; }
1106
+ .m2-tags { display: flex; gap: 4px; flex-wrap: wrap; }
1107
+ .m2-mot { display: inline-block; font-size: 11.5px; padding: 1px 7px; border-radius: 10px; background: var(--accent-soft); color: var(--accent); margin-right: 6px; }
1108
+ .m2-person { padding: 6px 0; border-bottom: 1px dashed var(--line); }
1109
+ .m2-ev { padding-left: 20px; display: flex; flex-direction: column; gap: 6px; line-height: 1.7; }
1110
+ .m2-c { display: flex; gap: 6px; align-items: flex-start; font-size: 13px; line-height: 1.7; padding: 2px 0; }
1111
+ .m2-c svg { margin-top: 4px; flex-shrink: 0; }
1112
+ .m2-c.fact { color: var(--ok); }
1113
+ .m2-c.need { color: var(--warn); }
1114
+ .m2-c.open { color: var(--ink-3); }
1115
+ .m2-src { margin-top: 18px; }
1116
+ .m2-src-text { white-space: pre-wrap; font-family: inherit; font-size: 13px; line-height: 1.8; background: var(--bg); padding: 12px; border-radius: var(--r-s); margin-top: 8px; color: var(--ink-2); max-height: 50vh; overflow: auto; }
1117
+ .m2-sheet { margin-top: 12px; }
1118
+ .m2-selects { display: flex; flex-wrap: wrap; gap: 10px 14px; margin: 12px 0 6px; }
1119
+ .m2-sel { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--ink-3); }
1120
+ .m2-cast { display: flex; flex-direction: column; gap: 8px; margin-bottom: 8px; align-items: flex-start; }
1121
+ .m2-cast-row { display: flex; gap: 8px; align-items: center; }
1122
+ .m2-compose .sheet-title { margin-top: 18px; }
1123
+ .m2-compose .sheet-title:first-child { margin-top: 0; }
1124
+ .m2-outline ol { padding-left: 22px; display: flex; flex-direction: column; gap: 8px; line-height: 1.75; }
1125
+ .m2-outline li b { margin-right: 8px; }
1126
+ .m2-outline li .link-btn { margin-left: 8px; font-size: 12px; }
1127
+ .m2-slots { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; margin-top: 18px; }
1128
+ .m2-slot h4 { font-size: 14px; margin-bottom: 8px; }
1129
+ .m2-slot .m2-card { margin-bottom: 8px; }
1130
+ .m2-slot-act { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 4px; cursor: default; }
1131
+ .m2-slot-act .btn.on { border-color: var(--accent); color: var(--accent); }
1132
+ .m2-warn { display: flex; gap: 4px; align-items: center; width: 100%; font-size: 12px; color: var(--warn); }
1133
+ .m2-rej summary { cursor: pointer; font-weight: 500; }
1134
+ .m2-rej-row { display: flex; flex-direction: column; gap: 2px; padding: 8px 0; border-bottom: 1px dashed var(--line); cursor: pointer; font-size: 13px; }
1135
+ @media (max-width: 720px) { .m2-fr { flex-direction: column; gap: 2px; } .m2-fl { padding-top: 0; } .m2-acts li { flex-direction: column; } .m2-act-meta { max-width: none; justify-content: flex-start; } }