feiyu-brain 1.5.1 → 1.6.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/smoke.mjs ADDED
@@ -0,0 +1,41 @@
1
+ // 集成冒烟:完全按 bridge.js 的调用方式跑一遍。
2
+ // node smoke.mjs
3
+ // 验证:插件能被桥接 import、wakeLine 能生成、不抛异常、长度可控。
4
+
5
+ import * as brain from './index.js';
6
+
7
+ const ID = 'smoke';
8
+
9
+ // 第一次(会现场出生,等同桥接首启)
10
+ const first = brain.wakeLine(ID, { who: '扶摇', words: ['嘴硬', '推荐'] });
11
+ console.log('── 第一次唤醒注入 ──');
12
+ console.log(first);
13
+ console.log(`\n长度:${first.length} 字符`);
14
+
15
+ // 模拟桥接连续几条消息
16
+ for (const [who, text] of [
17
+ ['扶摇', '你真是又嘴硬又爱怼人'],
18
+ ['访秋辞', '给我推荐点东西呗'],
19
+ ['许璐', '这鱼今天怎么这么收敛'],
20
+ ]) {
21
+ brain.observe(ID, { text, who, what: text, via: 'chat' });
22
+ }
23
+
24
+ const snap = brain.snapshot(ID);
25
+ console.log('\n── 快照 ──');
26
+ console.log(JSON.stringify({
27
+ styleName: snap.styleName,
28
+ style: snap.style,
29
+ briefChars: snap.briefChars,
30
+ flow: snap.flow,
31
+ weights: { count: snap.weights.count, identity: snap.weights.identity },
32
+ memory: snap.memory,
33
+ observations: snap.observations,
34
+ invariants: snap.invariants,
35
+ }, null, 2));
36
+
37
+ if (snap.invariants.length) {
38
+ console.error('\n✘ 不变量违规');
39
+ process.exit(1);
40
+ }
41
+ console.log('\n✔ 冒烟通过');
package/store.js CHANGED
@@ -172,9 +172,20 @@ export function writeJsonAtomic(file, data) {
172
172
  fs.renameSync(tmp, file);
173
173
  }
174
174
 
175
+ const AUDIT_MAX_BYTES = 2 * 1024 * 1024;
176
+
175
177
  export function appendAudit(id, entry) {
176
178
  ensureDir(brainDir(id));
177
- fs.appendFileSync(auditFile(id), `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8');
179
+ const file = auditFile(id);
180
+ // 轮转:审计只追加,长期跑会无限长(审查报告 B3)
181
+ try {
182
+ if (fs.existsSync(file) && fs.statSync(file).size > AUDIT_MAX_BYTES) {
183
+ const old = `${file}.1`;
184
+ try { if (fs.existsSync(old)) fs.unlinkSync(old); } catch { /* 忽略 */ }
185
+ fs.renameSync(file, old);
186
+ }
187
+ } catch { /* 转不过去就继续追加 */ }
188
+ fs.appendFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8');
178
189
  }
179
190
 
180
191
  export function readAudit(id, limit = 20) {
@@ -0,0 +1,132 @@
1
+ // 适配器契约测试:两种接入方式都必须成立。
2
+ // node test-adapters.mjs
3
+
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ import { createBridgeAdapter } from './adapters/qq-bridge.js';
10
+ import { createUniversalHost } from './adapters/universal.js';
11
+ import { TencentOfficialAdapter } from './adapters/tencent-official.js';
12
+ import { normalizeEvent } from './core/event.js';
13
+
14
+ let pass = 0;
15
+ const fails = [];
16
+ function t(name, fn) {
17
+ try { fn(); pass += 1; console.log(` ✔ ${name}`); }
18
+ catch (e) { fails.push({ name, msg: e.message }); console.log(` ✘ ${name}\n ${e.message}`); }
19
+ }
20
+
21
+ console.log('\n── 通用事件协议 ──');
22
+ t('任何平台的字段都能归一化成同一种事件', () => {
23
+ const a = normalizeEvent({ sender: 'A', text: 'hi', chatId: 'group:1' }, 'x');
24
+ const b = normalizeEvent({ userName: 'A', content: 'hi', channelId: 'group:1' }, 'y');
25
+ assert.equal(a.sender, b.sender);
26
+ assert.equal(a.text, b.text);
27
+ assert.equal(a.chatId, b.chatId);
28
+ });
29
+
30
+ t('自己的消息不算经历', () => {
31
+ const ev = normalizeEvent({ sender: '我', text: 'x', isSelf: true });
32
+ assert.equal(ev.isSelf, true);
33
+ });
34
+
35
+ console.log('\n── 老用户:桥接适配器 ──');
36
+ const fakeBrainApi = {
37
+ observe: (id, ev) => ({ ok: true, id, who: ev.sender }),
38
+ wakeLine: (id, ev) => `【此刻的她】测试鱼(who=${ev?.sender ?? '-'})`,
39
+ };
40
+
41
+ t('桥接状态 → 注入段', () => {
42
+ const ad = createBridgeAdapter({ log: () => {}, id: 'default' });
43
+ const st = { unread: [{ seq: 3, sender: '扶摇', plain: '你嘴真硬' }], recentMessages: [] };
44
+ const line = ad.buildBrainLine('group:1', st, fakeBrainApi);
45
+ assert.match(line, /【此刻的她】/);
46
+ assert.ok(line.endsWith('\n\n'));
47
+ });
48
+
49
+ t('同一条消息不重复"经历"', () => {
50
+ let count = 0;
51
+ const api = { observe: () => { count += 1; }, wakeLine: () => 'x' };
52
+ const ad = createBridgeAdapter({ log: () => {} });
53
+ const st = { unread: [{ seq: 7, sender: 'A', plain: 'a' }], recentMessages: [] };
54
+ ad.buildBrainLine('k', st, api);
55
+ ad.buildBrainLine('k', st, api);
56
+ assert.equal(count, 1, `观察了 ${count} 次`);
57
+ });
58
+
59
+ t('桥接崩溃不会连带崩溃', () => {
60
+ const broken = { observe: () => { throw new Error('boom'); }, wakeLine: () => { throw new Error('boom'); } };
61
+ const ad = createBridgeAdapter({ log: () => {} });
62
+ const st = { unread: [{ seq: 9, sender: 'A', plain: 'a' }], recentMessages: [] };
63
+ assert.equal(ad.buildBrainLine('k2', st, broken), '');
64
+ });
65
+
66
+ console.log('\n── 新用户:腾讯官方适配器 ──');
67
+ t('缺 appId/secret 立刻报错(不静默失败)', () => {
68
+ assert.throws(() => new TencentOfficialAdapter({}), /appId/);
69
+ });
70
+
71
+ t('群 @ 消息映射正确', () => {
72
+ const bot = new TencentOfficialAdapter({ appId: '1', clientSecret: 's', log: () => {} });
73
+ const ev = bot.toBrainEvent('GROUP_AT_MESSAGE_CREATE', {
74
+ id: 'msg1', content: ' 你好 ', group_openid: 'G1', author: { member_openid: 'M1' }, timestamp: 1700000000000,
75
+ });
76
+ assert.equal(ev.chatKind, 'group');
77
+ assert.equal(ev.chatId, 'group:G1');
78
+ assert.equal(ev.text, '你好');
79
+ assert.equal(ev.isAtMe, true);
80
+ });
81
+
82
+ t('私聊消息映射正确', () => {
83
+ const bot = new TencentOfficialAdapter({ appId: '1', clientSecret: 's', log: () => {} });
84
+ const ev = bot.toBrainEvent('C2C_MESSAGE_CREATE', {
85
+ id: 'msg2', content: '在吗', author: { user_openid: 'U1' },
86
+ });
87
+ assert.equal(ev.chatKind, 'private');
88
+ assert.equal(ev.chatId, 'private:U1');
89
+ assert.equal(ev.text, '在吗');
90
+ });
91
+
92
+ t('未支持的事件返回 null(不瞎猜)', () => {
93
+ const bot = new TencentOfficialAdapter({ appId: '1', clientSecret: 's', log: () => {} });
94
+ assert.equal(bot.toBrainEvent('AT_MESSAGE_CREATE', {}), null);
95
+ });
96
+
97
+ console.log('\n── 任意平台:通用宿主 ──');
98
+ t('handle 返回注入段 + 事件', () => {
99
+ const calls = [];
100
+ const brain = {
101
+ wake: (ev) => { calls.push(ev); return { text: `【此刻的她】x` }; },
102
+ };
103
+ const host = createUniversalHost({ brain, buildSystemPrompt: (seg) => `SYS\n${seg}` });
104
+ const r = host.handle({ sender: 'A', text: 'hi', chatId: 'group:1' });
105
+ assert.match(r.system, /^SYS/);
106
+ assert.equal(calls.length, 1);
107
+ });
108
+
109
+ console.log('\n── 打包边界 ──');
110
+ t('package.json 可发布(不私藏依赖、声明 exports)', () => {
111
+ const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
112
+ assert.ok(pkg.name);
113
+ assert.equal(pkg.private, undefined);
114
+ assert.ok(pkg.exports['.']);
115
+ assert.ok(pkg.files.includes('adapters/'));
116
+ });
117
+
118
+ t('adapters 目录里有三种接法', () => {
119
+ const dir = new URL('./adapters/', import.meta.url);
120
+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.js'));
121
+ for (const need of ['index.js', 'qq-bridge.js', 'tencent-official.js', 'universal.js']) {
122
+ assert.ok(files.includes(need), `缺 ${need}`);
123
+ }
124
+ });
125
+
126
+ console.log(`\n${'─'.repeat(40)}`);
127
+ console.log(`通过 ${pass} 项,失败 ${fails.length} 项`);
128
+ if (fails.length) {
129
+ for (const f of fails) console.log(` ✘ ${f.name}: ${f.msg}`);
130
+ process.exit(1);
131
+ }
132
+ console.log('全部通过 ✔');