File size: 19,591 Bytes
50e9802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Build and verify the director LoRA corpus against the LIVE browser protocol.
//
// The radio-script SFT set (kaggle/director_probe.py MODE=collect) teaches six
// lines of "开场:... / 叙述:...". The browser never asks for that. It asks for
// [memory] + [plan] + [continue]/[pause] + 0-3 spoken lines, and it parses the
// answer with director.js. Training on the radio format would teach the model
// to emit labels that cleanSpoken() then strips or throws away.
//
// So prompts come from the real Director class, and targets are accepted only
// if the real Director.parse() says they are clean. Same ruler on both sides.
//
// Usage (run locally, then push the outputs into the HF bundle):
//   node kaggle/director_lora_data.mjs prompts --n 4000 --out kaggle/out/director_prompts.jsonl
//   node kaggle/director_lora_data.mjs verify \
//        --prompts kaggle/out/director_prompts.jsonl \
//        --raw kaggle/out/director_raw.jsonl \
//        --out kaggle/out/director_sft.jsonl
//
// `raw` is one JSON object per line: {"id": "...", "raw": "<model output>"}.
// The generator of `raw` (base self-sampling or a larger teacher) lives on
// Kaggle; this script only decides what is good enough to train on.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { Director } from '../director.js';
import { STORIES, CHAT } from './director_lora_corpus.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const GENRES = JSON.parse(fs.readFileSync(path.join(ROOT, 'config/genres.json'), 'utf8')).genres;

const TOPICS = [
  '雨夜的末班公交', '一家很老的唱片店', '海边的灯塔', '凌晨的便利店',
  '搬家时翻出的旧照片', '楼下那棵一直没有开花的树', '深夜的收音机',
  '一场没有下完的雨', '旧公寓的电梯', '凌晨四点的菜市场', '山顶的观景台',
  '一个人的火锅店', '医院走廊的灯', '江边的长椅', '落了灰的钢琴',
  '雨天的出租车', '深夜的洗衣房', '开在二楼的旧书店', '废弃的火车站',
  '冬天的第一个霜降', '阳台上的那盆绿萝', '深夜的加油站', '清晨的面包房',
  '海边的小旅馆', '老街的修表摊', '天台上的风', '没有寄出的信',
  '一只总在窗边的猫', '雨停之后的马路', '深夜的游泳池', '断电的夜晚',
  '巷子尽头的路灯', '夏天最后一场雨', '老式闹钟的指针', '凌晨的公交站',
  '一条很长的隧道', '停电的电梯间', '小城的电影院', '合上的日记本',
  '厨房里烧开的水', '旧毛衣的口袋', '修好的那盏台灯', '雪停后的清晨',
];

const QUESTIONS = [
  '外面还在下雨吗', '你为什么总放这首歌', '现在几点了',
  '能说说海边吗', '你有没有想念过谁', '这封信后来寄出去了吗',
  '灯怎么忽然暗了', '你是谁', '今天有点累', '睡不着',
  '陪我说会儿话', '那个人后来回来了吗', '窗台上那盆花开了吗',
  '你还记得那家旧书店吗', '外面的车声怎么停了', '这首歌叫什么名字',
  '雨会下到天亮吗', '刚才那句话是什么意思', '你也听过钟声吗',
];

// These flip Director state in app.js (NEW_STORY_RE / CONTINUE_STORY_RE /
// STOP_RE / RESUME_RE), so a plain chat prompt would be off-distribution.
const STATE_FLIP = /讲(?:个|一个|一段)?故事|说(?:个|一个|一段)?故事|睡前故事|换个故事|新故事|继续讲|接着讲|不要停|晚安|别说了|回到剧本|继续读|接着读|停一下/;
const PLAIN_QUESTIONS = QUESTIONS.filter((q) => !STATE_FLIP.test(q));

const STORY_OPENERS = [
  '讲个故事吧', '说个故事', '来段睡前故事', '换个故事', '讲一个关于旧车站的故事',
];

const PLAN_SETS = [
  ['她在末班车站等一个不会来的人', '雨把时刻表泡得看不清', '一个卖花的老太太收摊',
   '她替老太太拎起铁桶', '末班车终于亮着灯拐过街角'],
  ['灯塔守夜人发现灯芯裂了', '他翻出三十年前的修理手册', '海面漂来一只空木箱',
   '箱子里是一叠没寄出的信', '天亮前灯重新亮起来'],
  ['旧书店在清仓', '男孩买到一本写满批注的书', '批注和他在同一页停住',
   '他按书里的地址找过去', '门牌还在,人已经搬走很久'],
  ['停电那晚整栋楼都醒了', '有人把蜡烛放在楼梯口', '邻居们第一次互相报名字',
   '电来的那一刻谁都没动', '蜡烛一直留到烧完'],
  ['修表摊的老匠人收了最后一个徒弟', '徒弟想换掉所有旧零件', '老匠人让他先听声音',
   '第一只被修好的表走慢了两分钟', '他们决定不调回来'],
];

const DOC_SNIPPET = '书页片段:《城与年》第七章\n'
  + '雨季过去的第三天,河滩上留下许多细小的贝壳。她沿着水线慢慢走,'
  + '鞋跟陷进湿沙里,每一步都发出很轻的声响。远处的摆渡人把船拴好,'
  + '抬头看了一眼云,又低下头去。';

const SPOKEN_HISTORY = [
  '灯亮起来的时候,站台只剩她一个。',
  '她把伞收好,听见远处有车进站。',
  '雨顺着棚檐滴下来,一滴一滴落在铁轨上。',
  '卖花的老太太把最后一把白菊抱进怀里。',
  '他翻过那页,纸角上还留着一小块水渍。',
  '走廊尽头的窗没关严,风把窗帘推得轻轻晃。',
];

function rng(seed) {
  let s = seed >>> 0;
  return () => {
    s = (s * 1664525 + 1013904223) >>> 0;
    return s / 4294967296;
  };
}

function pick(r, arr) { return arr[Math.floor(r() * arr.length) % arr.length]; }

function newDirector(genre) {
  const d = new Director({ genres: GENRES });
  d.setGenre(genre);
  return d;
}

function seedHistory(d, r, n = 3) {
  for (let i = 0; i < n; i++) {
    d.history.push({ role: i % 2 ? 'assistant' : 'user',
                     text: pick(r, i % 2 ? SPOKEN_HISTORY : PLAIN_QUESTIONS) });
  }
  d.memory = pick(r, [
    '她在末班车站等人,雨还没停。',
    '灯塔的灯芯裂了,守夜人正在翻旧手册。',
    '旧书店清仓,男孩买到一本写满批注的书。',
  ]);
}

function startStory(d, r, beat) {
  d.beginStory();
  d.program.plan = pick(r, PLAN_SETS);
  d.program.planAsked = true;
  d.program.beat = beat;
  d.memory = `故事进行到第 ${beat + 1} 拍:${d.program.plan[Math.min(beat, 4)]}`;
  seedHistory(d, r, 2 + Math.floor(r() * 3));
}

function storyFirst(d, r) {
  d.beginStory();
  return { userText: pick(r, STORY_OPENERS), autonomous: false };
}

// One build() per scenario. Each mutates a fresh Director into the state the
// app would be in, then returns the exact arguments Director.next() passes to
// messages().
const SCENES = [
  { name: 'chat_idle', genre: 'sleep', weight: 14, max: 280,
    build: (d, r) => { if (r() < 0.5) seedHistory(d, r); return { autonomous: true }; } },
  { name: 'chat_question', genre: 'sleep', weight: 14, max: 280,
    build: (d, r) => { if (r() < 0.6) seedHistory(d, r, 2);
      return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false }; } },
  { name: 'chat_followup', genre: 'sleep', weight: 8, max: 280,
    build: (d, r) => { seedHistory(d, r, 5); return { autonomous: true }; } },
  { name: 'chat_strict', genre: 'sleep', weight: 6, max: 240,
    build: (d, r) => { seedHistory(d, r, 2);
      return { autonomous: true, strict: true }; } },
  { name: 'story_plan', genre: 'story', weight: 10, max: 440,
    build: storyFirst },
  { name: 'story_beat', genre: 'story', weight: 16, max: 340,
    build: (d, r) => { startStory(d, r, 1 + Math.floor(r() * 20));
      return { autonomous: true }; } },
  { name: 'story_continue', genre: 'story', weight: 8, max: 340,
    build: (d, r) => { startStory(d, r, 2 + Math.floor(r() * 12));
      return { userText: '继续讲', autonomous: false }; } },
  { name: 'story_barge', genre: 'story', weight: 5, max: 340,
    build: (d, r) => { startStory(d, r, 3 + Math.floor(r() * 10));
      return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false }; } },
  { name: 'story_strict', genre: 'story', weight: 4, max: 240,
    build: (d, r) => { startStory(d, r, 4 + Math.floor(r() * 8));
      return { autonomous: true, strict: true }; } },
  { name: 'document_idle', genre: 'sleep', weight: 5, max: 280,
    build: (d, r) => { seedHistory(d, r, 2);
      return { autonomous: true, extraContext: DOC_SNIPPET }; } },
  { name: 'document_question', genre: 'sleep', weight: 5, max: 280,
    build: (d, r) => { seedHistory(d, r, 2);
      return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false,
               extraContext: DOC_SNIPPET }; } },
  { name: 'document_resume', genre: 'sleep', weight: 5, max: 280,
    build: (d, r) => { seedHistory(d, r, 3);
      return { userText: '回到剧本', autonomous: false,
               extraContext: `你在朗读《城与年》。\n${DOC_SNIPPET}` }; } },
];

function arg(name, fallback) {
  const i = process.argv.indexOf(`--${name}`);
  return i > 0 ? process.argv[i + 1] : fallback;
}

function readJsonl(file) {
  return fs.readFileSync(file, 'utf8').split('\n')
    .filter((l) => l.trim()).map((l) => JSON.parse(l));
}

function writeJsonl(file, rows) {
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, rows.map((r) => JSON.stringify(r, null, 0)).join('\n') + '\n');
}

function prompts() {
  const n = Number(arg('n', 4000));
  const seed = Number(arg('seed', 20261106));
  const out = arg('out', path.join(HERE, 'out', 'director_prompts.jsonl'));
  const r = rng(seed);
  const total = SCENES.reduce((s, x) => s + x.weight, 0);
  const rows = [];
  const counts = {};
  for (let i = 0; i < n; i++) {
    let t = r() * total, s = SCENES[0];
    for (const cand of SCENES) { t -= cand.weight; if (t <= 0) { s = cand; break; } }
    const d = newDirector(s.genre);
    const opts = s.build(d, r);
    const messages = d.messages(opts);
    counts[s.name] = (counts[s.name] || 0) + 1;
    rows.push({
      id: `d${String(i).padStart(5, '0')}`,
      kind: s.name,
      genre: s.genre,
      beat: d.program.beat,
      plan_wanted: d.wantsPlan(),
      max_new_tokens: s.max,
      messages,
    });
  }
  writeJsonl(out, rows);
  console.log(`wrote ${rows.length} prompts -> ${out}`);
  console.log(counts);
}

// Strict on purpose. cleanSpoken() in the app repairs dirty output at playback
// time; a training target must NOT need that repair, or the model learns to
// rely on it and the dirty-format rate goes up instead of down.
const DIRTY = /```|\|.*\||^\s*[-*#>]|你[::]|用户[::]|旁白[::]|叙述者[::]|作为\s*AI|<\|[^|>]*\|>|([^)]*)|\([^)]*\)|(?:用户|对话|会话|节目)(?:已|结束)/m;

function judge(prompt, raw) {
  const d = newDirector(prompt.genre);
  // llm.worker.js decodes with skip_special_tokens:false, Kaggle samplers do
  // not. Drop chat markers at the edges; the trainer appends EOS itself.
  const text = String(raw || '').replace(/<\|[^|>]*\|>/g, ' ').trim();
  const p = d.parse(text, d.maxChars());
  const bad = [];
  const strict = prompt.kind.endsWith('_strict');
  if (!text) bad.push('empty');
  if (!p.lines.length) bad.push('no_lines');
  if (p.lines.length > 3) bad.push('too_many_lines');
  if (p.pause) bad.push('early_pause');
  if (!strict && !p.memory) bad.push('no_memory');
  else if (p.memory && !d.goodMemory(p.memory)) bad.push('meta_memory');
  if (!strict && !p.explicitContinue) bad.push('no_control');
  if (strict && /\[(?:memory|continue|pause|plan)\]/i.test(text)) bad.push('strict_has_tags');
  if (prompt.plan_wanted && p.plan.length < 5) bad.push('missing_plan');
  if (DIRTY.test(text)) bad.push('dirty');
  if (/[\u4e00-\u9fff]/.test(text) === false) bad.push('not_chinese');
  if (/[A-Za-z0-9]/.test(p.lines.join(''))) bad.push('latin_or_digit');
  const keys = p.lines.map((s) => s.replace(/[\s,,。!?!?、;;…::]/g, ''));
  if (new Set(keys).size !== keys.length) bad.push('repeated_line');
  for (const line of p.lines) {
    if (line.length > d.maxChars() + 2) bad.push('long_line');
  }
  return { bad, parsed: p, text };
}

function verify() {
  const promptsFile = arg('prompts', path.join(HERE, 'out', 'director_prompts.jsonl'));
  const rawFile = arg('raw', path.join(HERE, 'out', 'director_raw.jsonl'));
  const out = arg('out', path.join(HERE, 'out', 'director_sft.jsonl'));
  const allPrompts = readJsonl(promptsFile);
  const byId = new Map(allPrompts.map((p) => [p.id, p]));
  const raws = readJsonl(rawFile);
  const kept = [];
  const seenResponse = new Set();
  const reasons = {};
  const dedup = process.argv.includes('--dedup');
  let missing = 0, dupes = 0;
  for (const row of raws) {
    const prompt = byId.get(row.id);
    if (!prompt) { missing++; continue; }
    const { bad, text } = judge(prompt, row.raw);
    if (bad.length) {
      for (const b of bad) reasons[b] = (reasons[b] || 0) + 1;
      continue;
    }
    if (dedup && seenResponse.has(text)) { dupes++; continue; }
    seenResponse.add(text);
    kept.push({ id: row.id, kind: prompt.kind, genre: prompt.genre,
                messages: prompt.messages,
                response: text });
  }
  let final = kept;
  const target = Number(arg('target', 0));
  if (target > 0) {
    const kindCount = {};
    for (const p of allPrompts) kindCount[p.kind] = (kindCount[p.kind] || 0) + 1;
    const groups = {};
    for (const row of kept) (groups[row.kind] ||= []).push(row);
    final = [];
    for (const [kind, rows] of Object.entries(groups)) {
      const quota = Math.max(1, Math.round(target * (kindCount[kind] || 0) / allPrompts.length));
      final.push(...rows.slice(0, quota));
    }
    const sr = rng(Number(arg('seed', 20261107)));
    for (let i = final.length - 1; i > 0; i--) {
      const j = Math.floor(sr() * (i + 1));
      [final[i], final[j]] = [final[j], final[i]];
    }
  }
  writeJsonl(out, final);
  const finalKinds = {};
  for (const row of final) finalKinds[row.kind] = (finalKinds[row.kind] || 0) + 1;
  console.log(`kept ${final.length} (from ${raws.length} raw, ${kept.length} clean, ${dupes} dupes dropped, ${missing} missing id)`);
  console.log('by kind', finalKinds);
  if (Object.keys(reasons).length) console.log('rejects', reasons);
}

function findStory(sys) {
  const m = sys.match(/计划:\n1\.\s*([^\n]+)/);
  if (!m) return null;
  return STORIES.find((s) => s.plan[0] === m[1].trim()) || null;
}

function pickVar(r, arr, k) { return arr[(Math.floor(r() * arr.length) + k) % arr.length]; }

// Free recombination at sentence level. Each sentence keeps the memory of the
// group it came from, so the [memory] line still matches the beat. For the
// question pool only group-opening sentences may lead the answer.
function pairsOf(pool, headed) {
  return {
    all: pool.flatMap((x) => x.lines.map((line, i) => ({
      line, memory: x.memory, head: headed && i === 0,
    }))),
    heads: pool.map((x) => ({ line: x.lines[0], memory: x.memory, head: true })),
  };
}

const CHAT_PAIRS = {
  idle: pairsOf(CHAT.idle, false),
  question: pairsOf(CHAT.question, true),
  document: pairsOf(CHAT.document, false),
  strict: pairsOf([...CHAT.idle, ...CHAT.question, ...CHAT.document,
                   ...CHAT.strict.map((lines) => ({ memory: '', lines }))], false),
};

function composeFree(r, pairSet, variant) {
  const pool = pairSet.heads.length ? pairSet.heads : pairSet.all;
  const i = Math.floor(r() * pool.length) + variant * 5;
  const a = pool[i % pool.length];
  const j = Math.floor(r() * pairSet.all.length) + variant * 11;
  const c = pairSet.all[j % pairSet.all.length];
  const lines = (variant % 5 === 4) ? [a.line]
    : [...new Set([a.line, c.line])];
  // Keep [memory] off the spoken line. Otherwise the model learns to write the
  // state twice: once as a tag, once aloud as the first sentence.
  const memPool = [...new Set(pairSet.all.map((x) => x.memory).filter(Boolean))];
  let memory = a.memory;
  for (let t = 0; t < 5 && memPool.length > 1; t++) {
    const cand = memPool[(Math.floor(r() * memPool.length) + t) % memPool.length];
    if (cand !== a.memory) { memory = cand; break; }
  }
  return { memory, lines };
}

function envelope(memory, lines) {
  return `[memory] ${memory}\n[continue]\n${lines.join('\n')}`;
}

// Rebuild a beat from a three-beat window. Sentences stay in narrative order,
// but which ones land in this answer changes, so 2k rows do not collapse into
// a couple hundred memorised strings.
function storyWindow(s, idx) {
  const out = [];
  for (let j = idx - 1; j <= idx + 1; j++) {
    out.push(s.beats[(j + s.beats.length) % s.beats.length]);
  }
  return out;
}

function composeWindow(r, items, variant) {
  const pool = items.flatMap((x) => x.lines);
  const count = 2 + (variant % 2);
  const start = (Math.floor(r() * 3) + variant * 2) % (pool.length - count + 1);
  const memory = items[(variant + 1) % items.length].memory;
  return envelope(memory, pool.slice(start, start + count));
}

function responseFor(p, r, variant) {
  const sys = p.messages[0].content;
  if (p.kind.endsWith('_strict')) {
    const c = composeFree(r, CHAT_PAIRS.strict, variant);
    return c.lines.join('\n');
  }
  if (p.kind === 'story_plan') {
    const s = pickVar(r, STORIES, variant);
    const o = pickVar(r, s.openings, variant);
    const pool = [...o.lines, ...storyWindow(s, variant % 3).flatMap((x) => x.lines)];
    const start = (Math.floor(r() * 4) + variant) % (pool.length - 1);
    const spoken = pool.slice(start, start + 2);
    return `[memory] ${o.memory}\n${s.plan.map((x) => `[plan] ${x}`).join('\n')}\n`
      + `[continue]\n${spoken.join('\n')}`;
  }
  if (p.kind.startsWith('story_')) {
    const s = findStory(sys) || pickVar(r, STORIES, variant);
    const m = sys.match(/第 (\d+) 拍/);
    const beat = m ? Number(m[1]) : 2;
    const idx = (Math.max(1, beat) - 1 + variant) % s.beats.length;
    return composeWindow(r, storyWindow(s, idx), variant);
  }
  const pairSet = p.kind.startsWith('document_') ? CHAT_PAIRS.document
    : p.kind === 'chat_question' ? CHAT_PAIRS.question : CHAT_PAIRS.idle;
  const c = composeFree(r, pairSet, variant);
  return envelope(c.memory, c.lines);
}

function assemble() {
  const promptsFile = arg('prompts', path.join(HERE, 'out', 'director_prompts.jsonl'));
  const out = arg('out', path.join(HERE, 'out', 'director_raw.jsonl'));
  const seed = Number(arg('seed', 20261107));
  const rows = readJsonl(promptsFile);
  const r = rng(seed);
  const seen = new Set();
  const raws = [];
  const rejects = {};
  let accepted = 0;
  for (const p of rows) {
    let raw = '';
    for (let k = 0; k < 10; k++) {
      raw = responseFor(p, r, k);
      if (!seen.has(raw)) break;
    }
    seen.add(raw);
    const { bad } = judge(p, raw);
    if (bad.length) for (const x of bad) rejects[x] = (rejects[x] || 0) + 1;
    else accepted++;
    raws.push({ id: p.id, raw });
  }
  writeJsonl(out, raws);
  console.log(`assembled ${raws.length} responses -> ${out}`);
  console.log(`unique ${seen.size} (${(seen.size / raws.length * 100).toFixed(1)}%)`);
  console.log(`verify preview: ${accepted}/${raws.length} (${(accepted / raws.length * 100).toFixed(1)}%) would pass`);
  if (Object.keys(rejects).length) console.log('rejects', rejects);
}

const cmd = process.argv[2];
if (cmd === 'prompts') prompts();
else if (cmd === 'assemble') assemble();
else if (cmd === 'verify') verify();
else {
  console.log('usage: director_lora_data.mjs prompts|assemble|verify [--n --seed --out --prompts --raw]');
  process.exit(1);
}