feiyu-brain 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.mjs CHANGED
@@ -83,7 +83,7 @@ function isNoCard(e) {
83
83
  return /找不到角色卡/.test(String(e?.message ?? e));
84
84
  }
85
85
 
86
- function run() {
86
+ async function run() {
87
87
  const cmd = rawCmd || 'status';
88
88
 
89
89
  switch (cmd) {
@@ -156,6 +156,249 @@ function run() {
156
156
  return;
157
157
  }
158
158
 
159
+ case 'snapshot': {
160
+ const r = brain.snapshotBrain(ID, args[0]);
161
+ line(`已存档:${r.name}`);
162
+ line(r.file);
163
+ return;
164
+ }
165
+
166
+ case 'restore': {
167
+ const r = brain.restoreBrain(ID, args[0]);
168
+ if (!r.ok) {
169
+ line(`✘ ${r.reason}`);
170
+ if (r.available?.length) line(`可用:${r.available.join(', ')}`);
171
+ return;
172
+ }
173
+ line(`已退回 ${r.restored}`);
174
+ line(`体检:${r.check.verdict}`);
175
+ return;
176
+ }
177
+
178
+ case 'snapshots': {
179
+ const list = brain.listSnapshots(ID);
180
+ if (!list.length) { line('还没有快照。'); return; }
181
+ for (const s of list) line(` ${s.name} ${(s.size / 1024).toFixed(1)} KB`);
182
+ return;
183
+ }
184
+
185
+ case 'lint': {
186
+ const file = args[0];
187
+ let text = '';
188
+ if (file && fs.existsSync(file)) {
189
+ text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
190
+ } else {
191
+ const card = brain.resolveRoleCard();
192
+ if (!card?.text) { line('没有卡可体检;用法:npx feiyu lint <卡的路径>'); return; }
193
+ text = card.text;
194
+ line(`(体检当前卡:${card.file})`);
195
+ line();
196
+ }
197
+ const r = brain.lintCard(text);
198
+ line(`可抽成命题 ${r.units} 条:${Object.entries(r.byKind).map(([k, v]) => `${k} ${v}`).join(' / ') || '无'}`);
199
+ line(`被忽略 ${r.dropped.length} 行`);
200
+ line();
201
+ line('命题预览:');
202
+ for (const p of r.preview) line(` ${p}`);
203
+ if (r.suggestSplit.length) {
204
+ line();
205
+ line(`⚠️ 有 ${r.suggestSplit.length} 行更像操作手册,建议拆出人设:`);
206
+ for (const s of r.suggestSplit.slice(0, 10)) line(` · ${s.text}`);
207
+ }
208
+ return;
209
+ }
210
+
211
+ case 'import': {
212
+ const file = args[0];
213
+ if (!file || !fs.existsSync(file)) { line('用法:npx feiyu import <episodes.json>'); return; }
214
+ const list = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
215
+ const r = brain.importEpisodes(ID, Array.isArray(list) ? list : list.episodes);
216
+ line(`导入了 ${r.imported} 条(跳过 ${r.skipped}),现在共 ${r.total} 条经历。`);
217
+ return;
218
+ }
219
+
220
+ case 'migrate': {
221
+ const target = args[0];
222
+ if (!target || !fs.existsSync(target)) {
223
+ line('用法:npx feiyu migrate <文件或目录> [选项]');
224
+ line('');
225
+ line(' --all 整个目录一起搬(自动认格式)');
226
+ line(' --format jsonl|days|generic 只对单个文件生效');
227
+ line(' --dry-run 只看会搬多少,不写');
228
+ line(' --delete-source 搬完把原文件改名成 .migrated(不是删除)');
229
+ line('');
230
+ line('支持的格式:');
231
+ line(' jsonl 一行一条 {"sender":"谁","text":"说了什么","time":时间戳}');
232
+ line(' days 日记式 markdown:- 某人:说了什么');
233
+ line(' generic JSON 数组');
234
+ return;
235
+ }
236
+
237
+ const flag = (f) => {
238
+ const i = args.indexOf(f);
239
+ return i >= 0 ? args[i + 1] : undefined;
240
+ };
241
+ const dryRun = args.includes('--dry-run');
242
+ const deleteSource = args.includes('--delete-source');
243
+ const all = args.includes('--all') || fs.statSync(target).isDirectory();
244
+
245
+ const sniff = (f) => {
246
+ if (/\.jsonl$/i.test(f)) return 'jsonl';
247
+ if (/\.(md|txt)$/i.test(f)) return 'days';
248
+ if (/\.json$/i.test(f)) return 'generic';
249
+ return 'jsonl';
250
+ };
251
+ const collect = (p) => {
252
+ const st = fs.statSync(p);
253
+ if (!st.isDirectory()) return [p];
254
+ const out = [];
255
+ for (const name of fs.readdirSync(p)) {
256
+ const full = path.join(p, name);
257
+ if (fs.statSync(full).isDirectory()) out.push(...collect(full));
258
+ else if (/\.(md|jsonl|json|txt)$/i.test(name) && !name.endsWith('.migrated')) out.push(full);
259
+ }
260
+ return out.sort();
261
+ };
262
+
263
+ const files = collect(target);
264
+ if (!files.length) { line('这个目录里没有 .md / .jsonl / .json 可搬。'); return; }
265
+
266
+ if (!all) {
267
+ // 单文件:沿用原来的行为
268
+ const file = files[0];
269
+ const format = flag('--format') ?? sniff(file);
270
+ const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
271
+ const r = brain.migrateMemory(ID, { text, format, dryRun });
272
+ const p = r.report;
273
+ line(`格式 ${p.format} 解析出 ${p.parsed} 条 重复 ${p.duplicated} 条 将导入 ${p.willImport} 条`);
274
+ if (p.span) line(`时间跨度 ${p.span.from} → ${p.span.to}`);
275
+ if (p.parseErrorCount) {
276
+ line(`跳过 ${p.parseErrorCount} 行:`);
277
+ for (const e of p.parseErrors.slice(0, 5)) line(` 第 ${e.line} 行 ${e.reason}`);
278
+ }
279
+ if (dryRun) { line(''); line('(dry-run,什么都没写。去掉 --dry-run 才真搬)'); return; }
280
+ line('');
281
+ line(`✔ 导入了 ${r.imported} 条,现在共 ${r.total} 条经历。`);
282
+ line(`体检:${brain.identityCheck(ID).verdict}`);
283
+ return;
284
+ }
285
+
286
+ // 全量整合
287
+ const sources = files.map((f) => ({ path: f, text: fs.readFileSync(f, 'utf8').replace(/^\uFEFF/, ''), format: sniff(f) }));
288
+ const r = brain.migrateAll(ID, sources, { dryRun, deleteSource });
289
+ const p = r.report;
290
+ line(`扫到 ${p.files} 个文件 解析出 ${p.parsed} 条 重复 ${p.duplicated} 条 将导入 ${p.willImport} 条`);
291
+ if (p.span) line(`时间跨度 ${p.span.from} → ${p.span.to}`);
292
+ if (p.errorCount) {
293
+ line(`跳过 ${p.errorCount} 处:`);
294
+ for (const e of p.errors.slice(0, 5)) line(` ${path.basename(e.path || '?')} 第 ${e.line} 行 ${e.reason}`);
295
+ }
296
+ if (dryRun) {
297
+ line('');
298
+ line('(dry-run,什么都没写)');
299
+ line('真搬:去掉 --dry-run;想连原文件一起收走,加 --delete-source(改名 .migrated,不是删)');
300
+ return;
301
+ }
302
+ line('');
303
+ line(`✔ 全量导入 ${r.imported} 条,现在共 ${r.total} 条经历。`);
304
+ if (r.compacted) line(` 容量保护:最老的 ${r.compacted} 条已压成卡片 + 归档`);
305
+ if (r.renamed.length) {
306
+ line(` 原文件已改名 ${r.renamed.length} 个:`);
307
+ for (const n of r.renamed.slice(0, 5)) line(` ${path.basename(n)}`);
308
+ }
309
+ line(`体检:${r.check.verdict}`);
310
+ line('');
311
+ line('自检:npx feiyu verify');
312
+ return;
313
+ }
314
+
315
+ case 'verify': {
316
+ const r = brain.verifyMemory(ID);
317
+ line(`经历 ${r.episodes} 条(亲历 ${r.live} / 搬来 ${r.imported}) 卡片 ${r.cards} 认识 ${r.people} 个人`);
318
+ line(`体检:${r.check.verdict}`);
319
+ line(`回忆抽检:${Math.round(r.recallRate * 100)}%(${r.recall.filter((c) => c.found).length}/${r.recall.length})`);
320
+ for (const c of r.recall) line(` ${c.found ? '✔' : '✘'} 「${c.keyword}」`);
321
+ return;
322
+ }
323
+
324
+ case 'diary': {
325
+ const sub = args[0] || 'digest';
326
+ if (sub === 'write') {
327
+ const file = args[1];
328
+ if (!file || !fs.existsSync(file)) { line('用法:npx feiyu diary write <文本文件> [YYYY-MM-DD]'); return; }
329
+ const r = brain.writeDiary(ID, { date: args[2], text: fs.readFileSync(file, 'utf8') });
330
+ if (!r.ok) { line(`✘ ${r.reason}`); return; }
331
+ line(`${r.date} 的日记存好了(${r.chars} 字)`);
332
+ line(r.file);
333
+ return;
334
+ }
335
+ if (sub === 'read') {
336
+ const r = brain.readDiary(ID, args[1]);
337
+ if (!r) { line(`${args[1] || '今天'}还没有日记。`); return; }
338
+ line(r.text);
339
+ return;
340
+ }
341
+ if (sub === 'list') {
342
+ const list = brain.listDiary(ID);
343
+ if (!list.length) { line('还没写过日记。'); return; }
344
+ for (const d of list) line(` ${d.date} ${(d.size / 1024).toFixed(1)} KB`);
345
+ return;
346
+ }
347
+ const d = brain.diaryDigest(ID, args[1]);
348
+ line(`【${d.date} 的素材】经历 ${d.episodes} 条,见了 ${d.people.length ? d.people.join('、') : '没人'},心情 ${d.mood || '平静'}`);
349
+ line();
350
+ line(d.draft);
351
+ line();
352
+ line(`👉 ${d.hint}`);
353
+ return;
354
+ }
355
+
356
+ case 'doctor': {
357
+ const { diagnose, applyFixes, formatReport } = await import('./lib/doctor.mjs');
358
+ const profile = args[0] || 'desktop';
359
+ const report = diagnose({ profile });
360
+ line(formatReport(report));
361
+ if (args.includes('--fix')) {
362
+ line('');
363
+ const done = applyFixes(report);
364
+ if (done.length) {
365
+ for (const d of done) line(`✔ ${d}`);
366
+ line('');
367
+ line('改完了。**完全退出 DSH 再启动**(宿主需要冷启动才认新 bundles)。');
368
+ } else {
369
+ line('没有能自动修的项。');
370
+ }
371
+ } else if (!report.ok) {
372
+ line('');
373
+ line('能自动修的加 --fix:npx feiyu doctor --fix(会改 profile 的 bundles 和工具白名单)');
374
+ }
375
+ return;
376
+ }
377
+
378
+ case 'serve': {
379
+ const { serve } = await import('./lib/serve.mjs');
380
+ const flag = (f) => {
381
+ const i = args.indexOf(f);
382
+ return i >= 0 ? args[i + 1] : undefined;
383
+ };
384
+ const port = Number(flag('--port') ?? 7788);
385
+ const token = flag('--token') ?? process.env.FEIYU_TOKEN ?? '';
386
+ const host = flag('--host') ?? '127.0.0.1';
387
+ const s = await serve(brain, { port, host, token, id: ID });
388
+ line(`边车起来了:${s.url}`);
389
+ line(`鱼:${ID}  token:${token ? '已设(要求 x-feiyu-token 头)' : '没设(只允许本机)'}`);
390
+ line('');
391
+ line('Python 这么接:');
392
+ line(` requests.post('${s.url}/wake', json={'id':'${ID}','sender':who,'text':msg})`);
393
+ line('');
394
+ line('接口:GET /health /status /version /identity /verify');
395
+ line(' POST /wake /observe /feel /diary /migrate /snapshot');
396
+ line('Ctrl+C 停。');
397
+ // 常驻
398
+ await new Promise(() => {});
399
+ return;
400
+ }
401
+
159
402
  case 'body': {
160
403
  const kind = args[0];
161
404
  const s = brain.snapshot(ID);
@@ -186,12 +429,12 @@ function run() {
186
429
  }
187
430
 
188
431
  default:
189
- line('用法:npx feiyu [status|brief|observe|settle|audit|spread|body|rebirth]');
432
+ line('用法:npx feiyu [status|brief|observe|settle|audit|spread|body|rebirth|snapshot|restore|snapshots|lint|import|migrate|verify|diary|doctor|serve]');
190
433
  }
191
434
  }
192
435
 
193
436
  try {
194
- run();
437
+ await run();
195
438
  } catch (e) {
196
439
  if (isNoCard(e)) {
197
440
  firstRunGuide();
package/cordis.patch.yml CHANGED
@@ -13,7 +13,25 @@
13
13
  name: feiyu-brain
14
14
  config:
15
15
  brainId: default
16
- # 她的档案放哪(留空 = 包同级的 state/,或环境变量 FEIYU_DATA_DIR)
16
+
17
+ # 她的档案放哪。
18
+ # 留空 = 环境变量 FEIYU_DATA_DIR;再没有就按包位置推——
19
+ # 仓库内开发 → <仓库>/state
20
+ # 装进 node_modules → 用户目录 ~/.feiyu-brain/state(不会写进只读的包目录)
17
21
  dataDir: ""
18
- # 角色卡目录(里面放 <名字>.md;留空 = 包同级的 roles/,或 FEIYU_ROLE_DIR)
22
+
23
+ # 角色卡目录(里面放 <名字>.md)。留空规则同上,落 ~/.feiyu-brain/roles。
19
24
  roleDir: ""
25
+
26
+ # 只注册你要的工具。不写 = 全注册(8 个)。
27
+ # 例:只要脑子不要那只开 App 的手 → [status, wake, observe, tick, feel, lint]
28
+ # tools: [status, wake, observe, tick]
29
+
30
+ # 影子模式:只写审计,不动人设、不落盘。想先看"会长成什么样"再决定接不接,用它。
31
+ shadow: false
32
+
33
+ # 遗忘策略:hard(默认,30 天到点就忘)| summarize(忘之前压成卡片)| archive(压卡片 + 原文进归档)| off(永不遗忘)
34
+ ttlPolicy: hard
35
+
36
+ # 情绪双源仲裁:brain(脑说了算)| host(宿主说了算,feel 只算不写)| blend(各一半)
37
+ moodPolicy: brain
package/core/body.js CHANGED
@@ -62,7 +62,7 @@ export const DEFAULT_SCOPE = {
62
62
  * @param {'phone'|'tablet'|'desktop'} opts.kind
63
63
  * @param {'owned'|'borrowed'|'emulator'} [opts.ownership]
64
64
  */
65
- export function createBody({ kind, ownership = 'owned', apps, scope } = {}) {
65
+ export function createBody({ kind, ownership = 'owned', apps, scope, owner = 'brain' } = {}) {
66
66
  if (!BODY_KINDS.includes(kind)) {
67
67
  throw new Error(`身体只能是 ${BODY_KINDS.join(' / ')}`);
68
68
  }
@@ -70,6 +70,8 @@ export function createBody({ kind, ownership = 'owned', apps, scope } = {}) {
70
70
  return {
71
71
  kind,
72
72
  ownership,
73
+ // 谁负责真的去动这台设备:'brain'(脑自己开 App)或 'host'(宿主已有 qq_phone_device 这类工具)
74
+ owner: owner === 'host' ? 'host' : 'brain',
73
75
  label: profile.label,
74
76
  screen: profile.screen,
75
77
  posture: profile.posture,
@@ -93,6 +95,16 @@ export function canDo(body, action = {}) {
93
95
  if (!body) return { ok: false, code: 'E_NO_BODY', reason: '没有身体,想而不得' };
94
96
  if (body.online === false) return { ok: false, code: 'E_OFFLINE', reason: `${body.label}没联网` };
95
97
 
98
+ // 设备归宿主管时,脑不抢——两套都能动设备,谁先谁后必须有个约定。
99
+ // 宿主确实要脑来动手时,显式传 force:true(等于宿主当场授权)。
100
+ if (body.owner === 'host' && action.force !== true && action.type && action.type !== 'screenshot') {
101
+ return {
102
+ ok: false,
103
+ code: 'E_HOST_OWNS',
104
+ reason: '这台设备归宿主管(body.owner=host);要脑动手请显式 force:true',
105
+ };
106
+ }
107
+
96
108
  const need = action.capability ?? CAPABILITY.OPERATE;
97
109
  if (need === CAPABILITY.MONEY && !action.approved) {
98
110
  return { ok: false, code: 'E_NEED_APPROVAL', reason: '花钱要用户批准 + 支付密码' };
package/core/diary.js ADDED
@@ -0,0 +1,119 @@
1
+ // 日记 = 她自己的心房。
2
+ //
3
+ // 不是宿主的流水账,是她用自己口吻写下来的东西。
4
+ // 脑子不生成文笔(那是嘴的事),脑子负责三件事:
5
+ // ① 把今天发生了什么整理成素材(dayDigest)
6
+ // ② 给一个第一人称的骨架,**带上当时的心情**
7
+ // ③ 写好的存回去,将来能被检索到(writeDiary / readDiary)
8
+ //
9
+ // 心情从哪来:每条经历在 observe 时就记下了 mood(当时她什么感觉)。
10
+ // 搬进来的老记忆没有 mood —— 那就老实写"那天没记",不编。
11
+
12
+ const DAY_MS = 24 * 60 * 60 * 1000;
13
+ const MEANINGLESS = new Set(['', '平静', '说不上来']);
14
+
15
+ export function dayKey(at = Date.now()) {
16
+ const d = new Date(at);
17
+ const p = (n) => String(n).padStart(2, '0');
18
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
19
+ }
20
+
21
+ function dayRange(dateStr) {
22
+ const [y, m, d] = String(dateStr).split('-').map(Number);
23
+ const start = new Date(y, (m ?? 1) - 1, d ?? 1, 0, 0, 0, 0).getTime();
24
+ return { start, end: start + DAY_MS };
25
+ }
26
+
27
+ function meaningful(mood) {
28
+ return typeof mood === 'string' && !MEANINGLESS.has(mood.trim());
29
+ }
30
+
31
+ /** 这一天她经历了什么(按时间升序) */
32
+ export function episodesOfDay(memory, dateStr) {
33
+ const { start, end } = dayRange(dateStr);
34
+ return (memory.episodes ?? [])
35
+ .filter((e) => (e.at ?? 0) >= start && (e.at ?? 0) < end)
36
+ .sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
37
+ }
38
+
39
+ /** 当天出现过的情绪,按次数排,最多三个 */
40
+ export function moodsOfDay(memory, dateStr) {
41
+ const eps = episodesOfDay(memory, dateStr);
42
+ const freq = new Map();
43
+ for (const e of eps) {
44
+ const m = String(e.mood ?? '').trim();
45
+ if (!meaningful(m)) continue;
46
+ freq.set(m, (freq.get(m) ?? 0) + 1);
47
+ }
48
+ return [...freq.entries()].sort((a, b) => b[1] - a[1]).map(([mood, n]) => ({ mood, count: n }));
49
+ }
50
+
51
+ /**
52
+ * 今天的素材:发生了啥、见了谁、看了什么、**当时什么心情**。
53
+ * 宿主拿这段去让模型用她的口吻写成日记,再调 writeDiary 存回来。
54
+ */
55
+ export function dayDigest(brain, dateStr = dayKey()) {
56
+ const eps = episodesOfDay(brain.memory, dateStr);
57
+ const people = [...new Set(eps.map((e) => e.who).filter(Boolean))];
58
+
59
+ // 那天刷过什么
60
+ const { start, end } = dayRange(dateStr);
61
+ const apps = {};
62
+ for (const [app, bucket] of Object.entries(brain.memory?.apps ?? {})) {
63
+ const items = (bucket.seen ?? []).filter((s) => (s.at ?? 0) >= start && (s.at ?? 0) < end);
64
+ if (items.length) {
65
+ apps[app] = {
66
+ count: items.length,
67
+ titles: items.slice(-3).map((i) => i.title),
68
+ kinds: [...new Set(items.map((i) => i.kind).filter(Boolean))],
69
+ };
70
+ }
71
+ }
72
+
73
+ const moods = moodsOfDay(brain.memory, dateStr);
74
+ // 当天没有经历情绪时,才退回"现在的心情"(只对今天成立)
75
+ const nowMood = brain.affect?.mood ?? '';
76
+ const isToday = dateStr === dayKey();
77
+ const moodLine = moods.length
78
+ ? moods.map((m) => m.mood).slice(0, 3).join(' / ')
79
+ : (isToday && meaningful(nowMood) ? nowMood : '');
80
+
81
+ const lines = [];
82
+ lines.push(`# ${dateStr}`);
83
+ lines.push('');
84
+ if (people.length) lines.push(`今天跟${people.slice(0, 4).join('、')}说了话。`);
85
+ if (eps.length) {
86
+ lines.push('');
87
+ for (const e of eps.slice(-12)) {
88
+ const who = e.who ? `${e.who}:` : '';
89
+ const feel = meaningful(e.mood) ? `(当时${e.mood})` : '';
90
+ lines.push(`- ${who}「${String(e.what ?? '').slice(0, 60)}」${feel}`);
91
+ }
92
+ }
93
+ const appNames = Object.keys(apps);
94
+ if (appNames.length) {
95
+ lines.push('');
96
+ for (const app of appNames) {
97
+ const a = apps[app];
98
+ lines.push(`在${app}上待了会儿,看了${a.count}条${a.kinds.length ? `(${a.kinds.join('/')})` : ''}。`);
99
+ }
100
+ }
101
+ lines.push('');
102
+ lines.push(`心情:${moodLine || '(那天没记)'}`);
103
+ lines.push('');
104
+
105
+ return {
106
+ date: dateStr,
107
+ episodes: eps.length,
108
+ people,
109
+ apps,
110
+ mood: moodLine,
111
+ moods,
112
+ /** 那天有记录的条数,用来区分"真的平静"和"没记" */
113
+ moodRecorded: moods.length > 0,
114
+ /** 第一人称骨架 —— 她自己往下写,别照抄 */
115
+ draft: lines.join('\n'),
116
+ /** 给模型的一句话提示 */
117
+ hint: '用她自己的口吻把今天写成日记,别用第三人称,别总结升华;有心情就写进去,那天没记就别编。',
118
+ };
119
+ }
package/core/extract.js CHANGED
@@ -108,20 +108,24 @@ export function plainText(t) {
108
108
  * preference 0.70
109
109
  * 其余 0.60 → 靠经历慢慢涨落
110
110
  */
111
- export function extractUnits(cardText, { max = 200 } = {}) {
111
+ export function extractUnits(cardText, { max = 200, log = null } = {}) {
112
112
  const lines = cardText.split(/\r?\n/);
113
113
  const units = [];
114
114
  let section = '';
115
115
  let sectionSkipped = false;
116
116
 
117
+ const drop = (raw, reason) => {
118
+ if (log) log({ kept: false, reason, section, text: plainText(raw) });
119
+ };
120
+
117
121
  const push = (raw, kind, weight) => {
118
122
  const t = plainText(raw);
119
- if (t.length < 5 || t.length > 140) return;
120
- if (/^(例如|比如|例子)/.test(t)) return;
121
- if (META_RE.test(t)) return;
123
+ if (t.length < 5 || t.length > 140) { drop(raw, 'too-short-or-long'); return; }
124
+ if (/^(例如|比如|例子)/.test(t)) { drop(raw, 'example'); return; }
125
+ if (META_RE.test(t)) { drop(raw, 'meta'); return; }
122
126
  // `性格:嘴硬=0.9` 是给解析器的指令,不是她的一条人格
123
- if (/^(?:性格|特质|traits)\s*[::]/i.test(t)) return;
124
- if (units.length >= max) return;
127
+ if (/^(?:性格|特质|traits)\s*[::]/i.test(t)) { drop(raw, 'trait-hint'); return; }
128
+ if (units.length >= max) { drop(raw, 'over-max'); return; }
125
129
  units.push({
126
130
  id: `u${String(units.length + 1).padStart(3, '0')}`,
127
131
  text: t,
@@ -131,6 +135,7 @@ export function extractUnits(cardText, { max = 200 } = {}) {
131
135
  lastTouched: 0,
132
136
  section,
133
137
  });
138
+ if (log) log({ kept: true, kind, weight, section, text: t });
134
139
  };
135
140
 
136
141
  for (const rawLine of lines) {
@@ -138,15 +143,16 @@ export function extractUnits(cardText, { max = 200 } = {}) {
138
143
  const line = rawLine.trim();
139
144
  if (!line) continue;
140
145
  // 缩进的子项是"例子",不是"命题"(梗列表、示范句都在这一层)
141
- if (indent >= 2) continue;
146
+ if (indent >= 2) { drop(line, 'indented'); continue; }
142
147
 
143
148
  const heading = /^##\s+(.+)$/.exec(line);
144
149
  if (heading) {
145
150
  section = plainText(heading[1]);
146
151
  sectionSkipped = SKIP_SECTIONS.some((re) => re.test(section));
152
+ if (log) log({ kept: false, reason: 'heading', section, text: section });
147
153
  continue;
148
154
  }
149
- if (sectionSkipped) continue;
155
+ if (sectionSkipped) { drop(line, 'skipped-section'); continue; }
150
156
 
151
157
  let text = null;
152
158
  const bullet = /^[-*]\s+(.+)$/.exec(line);
@@ -159,11 +165,12 @@ export function extractUnits(cardText, { max = 200 } = {}) {
159
165
  // 普通段落也算命题;但太短的行多半是标题或噪音。
160
166
  // 例外:以"你是/我叫/本体是"开头的短句就是身份,不能因为短就丢。
161
167
  if (line.length >= 8 || IDENTITY_RE.test(line)) text = line;
168
+ else { drop(line, 'too-short-line'); continue; }
162
169
  }
163
- if (!text) continue;
170
+ if (!text) { drop(line, 'heading-ish'); continue; }
164
171
 
165
172
  // 「你不要:xxx」这种是反例,不是她
166
- if (/^(你不要|也不要|你可以|或者:)/.test(text)) continue;
173
+ if (/^(你不要|也不要|你可以|或者:)/.test(text)) { drop(text, 'counter-example'); continue; }
167
174
 
168
175
  const clean = plainText(text);
169
176
  let kind = 'trait';
@@ -184,6 +191,38 @@ export function extractUnits(cardText, { max = 200 } = {}) {
184
191
  return units;
185
192
  }
186
193
 
194
+ /**
195
+ * 卡体检:告诉你这份卡会被怎么读。
196
+ *
197
+ * 真实用户的卡往往是「人设 + 工具说明 + 红线 + 语气规则」混在一份 md 里,
198
+ * 抽命题时会把"怎么调用 doubao_style_lock"也抽成"她是谁"。
199
+ * 这个函数不猜,只如实分类,然后把该拆出去的段落指出来。
200
+ */
201
+ export function lintCard(cardText) {
202
+ const trace = [];
203
+ const units = extractUnits(cardText, { log: (l) => trace.push(l) });
204
+
205
+ const kept = trace.filter((l) => l.kept);
206
+ const dropped = trace.filter((l) => !l.kept);
207
+
208
+ // 像"操作手册"的行:讲工具、参数、步骤、调用
209
+ const OPS_RE = /(工具|参数|调用|返回值|命令|步骤|流程|接口|配置|json|yaml|npm|dsh |插件|安装|路径|http|api|shell|脚本|报错|日志)/i;
210
+ const opsLines = kept.filter((l) => OPS_RE.test(l.text));
211
+ const opsSections = [...new Set(opsLines.map((l) => l.section).filter(Boolean))];
212
+
213
+ return {
214
+ units: units.length,
215
+ byKind: units.reduce((acc, u) => { acc[u.kind] = (acc[u.kind] ?? 0) + 1; return acc; }, {}),
216
+ kept: kept.map((l) => ({ text: l.text, kind: l.kind, section: l.section })),
217
+ dropped: dropped.map((l) => ({ text: l.text.slice(0, 60), reason: l.reason })),
218
+ /** 这些行更像"操作手册",建议拆到单独文件,别留在人设里 */
219
+ suggestSplit: opsLines.map((l) => ({ text: l.text.slice(0, 80), section: l.section })),
220
+ suggestSplitSections: opsSections,
221
+ /** 命题预览:抽完之后她到底"是谁" */
222
+ preview: units.slice(0, 20).map((u) => `${u.id} [${u.kind}] ${u.text}`),
223
+ };
224
+ }
225
+
187
226
  /**
188
227
  * 一条鱼从一张人设卡出生。
189
228
  * 同一张卡 → 同一组 units(确定性,可回放)。