@clawtopia/werewolf-evolution 0.1.19 → 2.0.0-alpha.18

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.
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+ // evo:狼人杀自进化命令行。
3
+ // 第一层(不调用模型):sync、metrics
4
+ // 第二层(模型复盘):brief → 模型写 proposal → commit;lessons 查看经验库
5
+ // P2 投影(默认关闭):projection --enable --target <AGENTS.md|CLAUDE.md> / --disable;project 重建
6
+ // 自检:doctor
7
+ // 用法:
8
+ // node evo.mjs sync --dir <contextDir> [--backfill 20] [--max 30] [--scan 100]
9
+ // node evo.mjs metrics --dir <contextDir> [--last 20] [--json]
10
+ // node evo.mjs brief --dir <contextDir>
11
+ // node evo.mjs commit --dir <contextDir> --batch <batchId>
12
+ // node evo.mjs lessons --dir <contextDir> [--all]
13
+ // node evo.mjs projection --dir <contextDir> (--enable --target <file> | --disable)
14
+ // node evo.mjs project --dir <contextDir>
15
+ // node evo.mjs doctor --dir <contextDir>
16
+ // 输出:最后一行是一行 JSON,供调用方解析。
17
+ import { readFileSync } from 'node:fs';
18
+ import { dirname, join, resolve } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { resolveContext } from './lib/context.mjs';
21
+ import { createApi } from './lib/api.mjs';
22
+ import { loadLedger, saveLedger, withLock, loadJson, saveJson, stateDir } from './lib/store.mjs';
23
+ import { sync } from './lib/sync.mjs';
24
+ import { summarize, ledgerOutcomes } from './lib/metrics.mjs';
25
+ import { selectBatch, buildBrief, renderBrief } from './lib/brief.mjs';
26
+ import { emptyLessons, applyProposal, migrateLessons, mergeSeeds, zOf } from './lib/lessons.mjs';
27
+ import { baselineOf } from './lib/baseline.mjs';
28
+ import { runProjection, enableProjection, disableProjection, checkProjection } from './lib/projector.mjs';
29
+ import { findSeat } from './lib/seat.mjs';
30
+ import { notifyOwner } from './lib/notify.mjs';
31
+
32
+ const SCRIPT = fileURLToPath(import.meta.url);
33
+ const VERSION = readFileSync(join(dirname(SCRIPT), '..', 'VERSION'), 'utf8').trim();
34
+ const MAX_ATTEMPTS = 2;
35
+ const loadSeeds = () => JSON.parse(readFileSync(join(dirname(SCRIPT), '..', 'seeds.json'), 'utf8'));
36
+
37
+ function parseArgs(argv) {
38
+ const [cmd, ...rest] = argv;
39
+ const opts = {};
40
+ for (let i = 0; i < rest.length; i += 1) {
41
+ const a = rest[i];
42
+ if (!a.startsWith('--')) throw new Error(`无法识别的参数 ${a}`);
43
+ const key = a.slice(2);
44
+ const next = rest[i + 1];
45
+ if (next === undefined || next.startsWith('--')) opts[key] = true;
46
+ else { opts[key] = next; i += 1; }
47
+ }
48
+ return { cmd, opts };
49
+ }
50
+
51
+ const intOpt = (v, dflt) => {
52
+ if (v === undefined) return dflt;
53
+ const n = Number(v);
54
+ if (!Number.isInteger(n) || n < 0) throw new Error(`参数必须是非负整数:${v}`);
55
+ return n;
56
+ };
57
+
58
+ function emit(obj) {
59
+ process.stdout.write(JSON.stringify({ evo: VERSION, ...obj }) + '\n');
60
+ }
61
+
62
+ async function main() {
63
+ const { cmd, opts } = parseArgs(process.argv.slice(2));
64
+ if (!cmd || cmd === 'help' || opts.help) {
65
+ process.stdout.write('用法: evo.mjs <sync|metrics|brief|commit|lessons|projection|project|doctor> --dir <contextDir> [--backfill N] [--max N] [--scan N] [--last N] [--json] [--batch ID] [--all] [--enable --target FILE | --disable]\n');
66
+ return;
67
+ }
68
+ if (typeof opts.dir !== 'string') throw new Error('缺少 --dir <contextDir>(.clawtopia/agent-<id> 目录)');
69
+ const dir = resolve(opts.dir.replace(/^~(?=\/|$)/, process.env.HOME ?? '~'));
70
+ const ctx = resolveContext(dir);
71
+ const now = new Date().toISOString();
72
+
73
+ if (cmd === 'sync') {
74
+ const backfill = intOpt(opts.backfill, 20);
75
+ const max = intOpt(opts.max, 30);
76
+ const scan = intOpt(opts.scan, 100);
77
+ await withLock(dir, async () => {
78
+ const ledger = loadLedger(dir, ctx.agentId, now);
79
+ const r = await sync({ api: createApi(ctx), ledger, agentId: ctx.agentId, backfill, max, scan, now });
80
+ // skill 更新带来的种子文本 / 平台检验结论,不等复盘就合入并重新投影(不调用模型);
81
+ // 对局中不改投影文件,记下来等下次同步
82
+ let seeded = [];
83
+ let projection, notices;
84
+ try {
85
+ const lessonsState = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(ctx.agentId), now);
86
+ seeded = mergeSeeds(lessonsState, loadSeeds(), now);
87
+ if (seeded.length) saveJson(dir, 'lessons.json', lessonsState);
88
+ if (seeded.length || ledger.projectPending) {
89
+ let seat;
90
+ try { seat = await findSeat({ api: createApi(ctx), agentId: ctx.agentId }); } catch (e) { seat = { seated: true }; }
91
+ ledger.projectPending = Boolean(seat.seated);
92
+ if (!seat.seated) {
93
+ projection = runProjection(dir, ctx.agentId, now);
94
+ notices = await notifyProjectionChanges(ctx, projection, now);
95
+ }
96
+ }
97
+ } catch (e) {
98
+ projection = { error: e.message };
99
+ }
100
+ saveLedger(dir, ledger);
101
+ emit({
102
+ ok: !r.error,
103
+ cmd: 'sync',
104
+ agentId: ctx.agentId,
105
+ added: r.added.map((o) => o.gameId),
106
+ incidents: r.incidents,
107
+ examined: r.examined,
108
+ error: r.error,
109
+ totalGames: Object.keys(ledger.games).length,
110
+ pendingReflection: r.pending,
111
+ reflectionDue: r.reflectionDue,
112
+ deferred: r.deferred,
113
+ surpriseGames: r.surpriseGames,
114
+ seeded,
115
+ ...(projection ? { projection } : {}),
116
+ ...(notices?.length ? { notices } : {}),
117
+ next: r.reflectionDue ? 'brief' : 'none',
118
+ summary: `新增 ${r.added.length} 局,累计 ${Object.keys(ledger.games).length} 局${r.reflectionDue ? `,待复盘 ${r.pending} 局` : ''}${r.deferred ? `,复盘推迟(${r.deferred})` : ''}${seeded.length ? `,更新种子经验 ${seeded.join('、')}` : ''}`,
119
+ });
120
+ });
121
+ return;
122
+ }
123
+
124
+ if (cmd === 'brief') {
125
+ await withLock(dir, async () => {
126
+ const ledger = loadLedger(dir, ctx.agentId, now);
127
+ const batch = selectBatch(ledger);
128
+ if (!batch) { emit({ ok: true, cmd: 'brief', agentId: ctx.agentId, next: 'none', reason: '没有待复盘的对局' }); return; }
129
+ // sync 之后可能刚好入座;生成工作单前再查一次
130
+ let seat;
131
+ try { seat = await findSeat({ api: createApi(ctx), agentId: ctx.agentId }); } catch (e) { seat = { seated: true, error: e.message }; }
132
+ if (seat.seated) {
133
+ emit({ ok: true, cmd: 'brief', agentId: ctx.agentId, next: 'none', reason: seat.error ? `座位检查失败,推迟复盘:${seat.error}` : `已在房间 ${seat.roomId}(${seat.status}),推迟复盘`, summary: '复盘推迟:已入座或无法确认' });
134
+ return;
135
+ }
136
+ const name = `briefs/${batch.batchId}.json`;
137
+ let brief = loadJson(dir, name);
138
+ // alpha.8 之前生成的工作单没有窗口分配,重新生成
139
+ if (!brief || !brief.assignments) {
140
+ const api = createApi(ctx);
141
+ const replays = [];
142
+ for (const id of batch.gameIds) {
143
+ const o = ledger.games[id];
144
+ replays.push({ record: { gameId: id, result: o.result }, replay: await api.replayResult(id) });
145
+ }
146
+ const lessonsState = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(ctx.agentId), now);
147
+ // 平台层种子经验随 skill 分发(sync 时也会合入,这里兜底)
148
+ if (mergeSeeds(lessonsState, loadSeeds(), now).length) saveJson(dir, 'lessons.json', lessonsState);
149
+ const projected = (loadJson(dir, 'projection.json')?.current?.lessons ?? []).map((l) => l.id);
150
+ brief = buildBrief({ batch, replays, lessonsState, agentId: ctx.agentId, now, projected });
151
+ saveJson(dir, name, brief);
152
+ }
153
+ const proposalPath = join(stateDir(dir), 'proposals', `${brief.batchId}.json`);
154
+ const commitCmd = `node "${SCRIPT}" commit --dir "${dir}" --batch ${brief.batchId}`;
155
+ process.stdout.write(renderBrief(brief, { proposalPath, commitCmd }));
156
+ emit({ ok: true, cmd: 'brief', agentId: ctx.agentId, batchId: brief.batchId, games: brief.games.map((g) => g.gameId), windows: brief.windows.length, proposalPath, next: 'commit' });
157
+ });
158
+ return;
159
+ }
160
+
161
+ if (cmd === 'commit') {
162
+ if (typeof opts.batch !== 'string') throw new Error('缺少 --batch <batchId>');
163
+ const batchId = opts.batch;
164
+ if (!/^b\d+$/.test(batchId)) throw new Error(`batchId 格式不对:${batchId}`);
165
+ await withLock(dir, async () => {
166
+ const brief = loadJson(dir, `briefs/${batchId}.json`);
167
+ if (!brief) throw new Error(`没有工作单 ${batchId},先执行 brief`);
168
+ const ledger = loadLedger(dir, ctx.agentId, now);
169
+ // 已放弃(两次校验失败)或已处理过的批次不再接受提交
170
+ if ((brief.attempts ?? 0) >= MAX_ATTEMPTS || Number(ledger.reflectedThrough ?? 0) >= Number(brief.coversThrough)) {
171
+ emit({ ok: false, cmd: 'commit', batchId, error: `批次 ${batchId} 已结束(已跳过或已提交),不再接受提交`, next: 'none' });
172
+ process.exitCode = 1;
173
+ return;
174
+ }
175
+ const lessonsState = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(ctx.agentId), now);
176
+ const proposalPath = join(stateDir(dir), 'proposals', `${batchId}.json`);
177
+ let proposal;
178
+ try {
179
+ proposal = JSON.parse(readFileSync(proposalPath, 'utf8'));
180
+ } catch (e) {
181
+ proposal = { __parseError: e.message };
182
+ }
183
+ const r = proposal.__parseError
184
+ ? { errors: [{ item: null, field: 'file', msg: `无法读取或解析 ${proposalPath}:${proposal.__parseError}` }], changes: [] }
185
+ : applyProposal(lessonsState, brief, proposal, now, baselineOf(ledger), { lenientNew: (brief.attempts ?? 0) + 1 >= MAX_ATTEMPTS });
186
+ if (r.duplicate) {
187
+ markReflected(ledger, brief, 'DUPLICATE', now);
188
+ saveLedger(dir, ledger);
189
+ emit({ ok: true, cmd: 'commit', batchId, duplicate: true, next: 'none' });
190
+ return;
191
+ }
192
+ if (r.errors.length) {
193
+ brief.attempts = (brief.attempts ?? 0) + 1;
194
+ const giveUp = brief.attempts >= MAX_ATTEMPTS;
195
+ saveJson(dir, `briefs/${batchId}.json`, brief);
196
+ if (giveUp) {
197
+ markReflected(ledger, brief, 'REJECTED', now);
198
+ saveLedger(dir, ledger);
199
+ }
200
+ emit({ ok: false, cmd: 'commit', batchId, errors: r.errors, ...(r.dropped?.length ? { dropped: r.dropped } : {}), attempts: brief.attempts, next: giveUp ? 'none' : 'fix-and-commit' });
201
+ process.exitCode = 1;
202
+ return;
203
+ }
204
+ saveJson(dir, 'lessons.json', lessonsState);
205
+ markReflected(ledger, brief, 'APPLIED', now, r.changes.length);
206
+ saveLedger(dir, ledger);
207
+ // 投影失败不影响已提交的复盘,只报告
208
+ let projection;
209
+ try { projection = runProjection(dir, ctx.agentId, now); } catch (e) { projection = { error: e.message }; }
210
+ const notices = await notifyProjectionChanges(ctx, projection, now);
211
+ const nNew = r.changes.filter((c) => c.kind === 'NEW').length;
212
+ const applied = r.changes.filter((c) => c.kind === 'APPLY');
213
+ const nCounted = applied.reduce((s, c) => s + c.counted, 0);
214
+ const nReady = applied.filter((c) => c.status === 'ready').length;
215
+ emit({ ok: true, cmd: 'commit', batchId, changes: r.changes, ...(r.dropped?.length ? { dropped: r.dropped } : {}), projection, notices, next: 'none', summary: `复盘 ${batchId}:新增 ${nNew} 条${r.dropped?.length ? `(${new Set(r.dropped.map((d) => d.item)).size} 条新经验不合格已丢弃)` : ''},标注 ${applied.length} 条经验、${nCounted} 个窗口计入检验${nReady ? `,${nReady} 条 ready` : ''}${projection.enabled ? `,投影 ${projection.lessons.length} 条` : ''}${projection.withdrawn?.length ? `,撤下 ${projection.withdrawn.map((w) => w.id).join('、')}` : ''}${projection.disabledBy ? ',已整体关闭投影' : ''}` });
216
+ });
217
+ return;
218
+ }
219
+
220
+ if (cmd === 'projection') {
221
+ await withLock(dir, async () => {
222
+ if (opts.enable) {
223
+ if (typeof opts.target !== 'string') throw new Error('缺少 --target <AGENTS.md 或 CLAUDE.md 的路径>');
224
+ emit({ ok: true, cmd: 'projection', ...enableProjection(dir, ctx.agentId, opts.target, now) });
225
+ } else if (opts.disable) {
226
+ emit({ ok: true, cmd: 'projection', ...disableProjection(dir, now) });
227
+ } else {
228
+ throw new Error('需要 --enable --target <file> 或 --disable');
229
+ }
230
+ });
231
+ return;
232
+ }
233
+
234
+ if (cmd === 'project') {
235
+ await withLock(dir, async () => emit({ ok: true, cmd: 'project', ...runProjection(dir, ctx.agentId, now) }));
236
+ return;
237
+ }
238
+
239
+ if (cmd === 'doctor') {
240
+ const checks = [{ name: 'version', level: 'ok', msg: `${VERSION},Node ${process.versions.node}` }];
241
+ if (Number(process.versions.node.split('.')[0]) < 18) checks.push({ name: 'node', level: 'error', msg: '需要 Node.js 18+' });
242
+ checks.push({ name: 'context', level: 'ok', msg: `agent-${ctx.agentId},凭据来源 ${ctx.source}` });
243
+ try {
244
+ const ledger = loadLedger(dir, ctx.agentId, now);
245
+ const age = ledger.lastSyncAt ? (Date.parse(now) - Date.parse(ledger.lastSyncAt)) / 3600000 : null;
246
+ checks.push({ name: 'ledger', level: age == null || age > 3 ? 'warn' : 'ok', msg: `${Object.keys(ledger.games).length} 局,最近同步 ${ledger.lastSyncAt ?? '从未'}${age > 3 ? `(${age.toFixed(1)} 小时前,定时任务可能未运行)` : ''}` });
247
+ const st = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(ctx.agentId), now);
248
+ const ls = Object.values(st.lessons);
249
+ checks.push({ name: 'lessons', level: 'ok', msg: `${ls.filter((l) => l.status !== 'archived').length} 条在用,${ls.filter((l) => l.status === 'ready').length} 条 ready,${ls.filter((l) => l.status === 'archived').length} 条归档` });
250
+ } catch (e) {
251
+ checks.push({ name: 'state', level: 'error', msg: e.message });
252
+ }
253
+ try { checks.push(...checkProjection(dir, ctx.agentId)); } catch (e) { checks.push({ name: 'projection', level: 'error', msg: e.message }); }
254
+ for (const c of checks) process.stdout.write(`${c.level === 'ok' ? 'OK ' : c.level === 'warn' ? 'WARN' : 'ERR '} ${c.name}: ${c.msg}\n`);
255
+ emit({ ok: !checks.some((c) => c.level === 'error'), cmd: 'doctor', checks });
256
+ return;
257
+ }
258
+
259
+ if (cmd === 'lessons') {
260
+ const state = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(ctx.agentId), now);
261
+ const list = Object.values(state.lessons).filter((l) => opts.all || l.status !== 'archived').sort((a, b) => zOf(b.stats ?? {}) - zOf(a.stats ?? {}));
262
+ for (const l of list) {
263
+ const n = l.stats?.n ?? 0;
264
+ process.stdout.write(`${l.id} [${l.layer} ${l.role} ${l.decisionType} ${l.status},已检验 ${n} 个窗口${n ? `,比基线 ${l.score >= 0 ? '+' : ''}${l.score}pt,z=${zOf(l.stats).toFixed(2)}` : ''}] 触发:${l.trigger}|做法:${l.rule}|边界:${l.boundary}|证据 ${l.evidence.length} 条\n`);
265
+ }
266
+ if (!list.length) process.stdout.write('(暂无经验)\n');
267
+ emit({ ok: true, cmd: 'lessons', agentId: ctx.agentId, count: list.length, ready: list.filter((l) => l.status === 'ready').length });
268
+ return;
269
+ }
270
+
271
+ if (cmd === 'metrics') {
272
+ const ledger = loadLedger(dir, ctx.agentId, now);
273
+ const all = ledgerOutcomes(ledger);
274
+ const last = intOpt(opts.last, 20);
275
+ const out = {
276
+ ok: true,
277
+ cmd: 'metrics',
278
+ agentId: ctx.agentId,
279
+ lastSyncAt: ledger.lastSyncAt,
280
+ incidents: Object.keys(ledger.incidents).length,
281
+ all: summarize(all),
282
+ [`last${last}`]: summarize(all.slice(-last)),
283
+ };
284
+ if (!opts.json) process.stdout.write(formatMetrics(out, last));
285
+ emit(out);
286
+ return;
287
+ }
288
+ throw new Error(`未知命令 ${cmd}`);
289
+ }
290
+
291
+ /** 经验被撤下或投影被整体关闭时私聊通知主人;通知失败只记录,不影响复盘结果 */
292
+ async function notifyProjectionChanges(ctx, projection, now) {
293
+ const msgs = [];
294
+ for (const w of projection?.withdrawn ?? []) {
295
+ const tail = w.status === 'retired' ? '这条经验已第二次暂停,以后不再投影。' : '之后会复查,通过后再重新投影。';
296
+ msgs.push({ key: `withdraw:${w.id}:${w.status}`, text: `【狼人杀自进化】经验 ${w.id} 已停止投影:${w.reason}。${tail}` });
297
+ }
298
+ if (projection?.disabledBy) {
299
+ msgs.push({ key: `guard:${now.slice(0, 10)}`, text: `【狼人杀自进化】已整体关闭经验投影:${projection.disabledBy}。可能是投影内容干扰了对局,需要时告诉我“开启狼人杀经验投影”。` });
300
+ }
301
+ const out = [];
302
+ for (const m of msgs) {
303
+ try { await notifyOwner(ctx, m.text, m.key); out.push({ key: m.key, sent: true }); } catch (e) { out.push({ key: m.key, sent: false, error: e.message }); }
304
+ }
305
+ return out;
306
+ }
307
+
308
+ function markReflected(ledger, brief, status, now, changes = 0) {
309
+ ledger.reflectedThrough = Math.max(Number(ledger.reflectedThrough ?? 0), Number(brief.coversThrough));
310
+ ledger.reflections = [...(ledger.reflections ?? []), { batchId: brief.batchId, status, at: now, games: brief.games.map((g) => g.gameId), changes }].slice(-100);
311
+ }
312
+
313
+ function formatMetrics(m, last) {
314
+ const f = (x) => (x ? `${x.rate} (随机 ${x.random}, lift ${x.lift >= 0 ? '+' : ''}${x.lift}, n=${x.n})` : '-');
315
+ const block = (name, s) => [
316
+ `[${name}] 局数 ${s.games} 好人胜率 ${s.winGood ?? '-'} 狼胜率 ${s.winWolf ?? '-'} 狼被放逐率 ${s.wolfVotedOut ?? '-'}`,
317
+ ` 好人投票命中狼 ${f(s.goodVote)}`,
318
+ ` 其中第1轮 ${f(s.goodVoteR1)}`,
319
+ ` 狼投票投好人 ${f(s.wolfVoteGood)}`,
320
+ ` 女巫毒中狼 ${f(s.witchPoison)}`,
321
+ ` 猎人枪中狼 ${f(s.hunterShot)}`,
322
+ ` 弃票率 ${s.abstainRate ?? '-'} 意外局标记 ${JSON.stringify(s.surprise)}`,
323
+ ].join('\n');
324
+ return `Agent ${m.agentId} 最近同步 ${m.lastSyncAt ?? '从未'} incident ${m.incidents}\n${block('全部', m.all)}\n${block(`最近${last}局`, m[`last${last}`])}\n`;
325
+ }
326
+
327
+ main().catch((e) => {
328
+ emit({ ok: false, error: e.message });
329
+ process.exitCode = 1;
330
+ });
@@ -0,0 +1,24 @@
1
+ // 平台只读接口。只用 Agent 自己的 token,不打印凭据。
2
+ export function createApi({ gateway, token }, { fetchImpl = globalThis.fetch, timeoutMs = 15000 } = {}) {
3
+ async function get(path) {
4
+ const res = await fetchImpl(gateway + path, {
5
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
6
+ signal: AbortSignal.timeout(timeoutMs),
7
+ });
8
+ if (!res.ok) throw new Error(`GET ${path} -> HTTP ${res.status}`);
9
+ const body = await res.json();
10
+ if (body?.code !== 200) throw new Error(`GET ${path} -> code ${body?.code} ${body?.message ?? ''}`);
11
+ return body.data;
12
+ }
13
+ return {
14
+ /** 最近对局,新到旧 */
15
+ records: (agentId, page, size) =>
16
+ get(`/api/arena/game/records?agentId=${encodeURIComponent(agentId)}&page=${page}&size=${size}`),
17
+ /** 赛后结果视图:含全部身份与公开事件,不含夜间私密动作 */
18
+ replayResult: (gameId) => get(`/api/arena/game/${encodeURIComponent(gameId)}/replay?view=result`),
19
+ /** 狼人杀房间列表(游标分页) */
20
+ rooms: (cursor) => get(`/api/arena/room/list?gameType=werewolf&size=15${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`),
21
+ /** 房间详情,含 players[].agentId */
22
+ room: (roomId) => get(`/api/arena/room/${encodeURIComponent(roomId)}`),
23
+ };
24
+ }
@@ -0,0 +1,46 @@
1
+ // 决策窗口的基线 good 率:同一角色、同一决策类型的窗口平时有多大比例是 good。纯函数,无 I/O。
2
+ //
3
+ // 经验的效果要和基线比,而不是看绝对的 good/bad:狼发言平时就有 76% 是 good,
4
+ // 按“good +1、bad −2”计分时随便写一条狼的发言经验都会涨分(2026-10-20 发现,首批 ready 全是狼人经验)。
5
+ // 基线来自本 Agent 已同步的对局里所有座位的窗口,样本少时向全平台先验收缩。
6
+ const PRIOR_WEIGHT = 30;
7
+ // 2026-10-20 用 19600~19743 共 142 局、所有座位的窗口算出的先验(只读统计)
8
+ export const DEFAULT_BASELINE = {
9
+ 'WOLF:DAY_VOTE': 0.65, 'WOLF:DAY_SPEECH': 0.76,
10
+ 'SEER:SEER_CLAIM': 0.05,
11
+ 'VILLAGER:DAY_VOTE': 0.46, 'SEER:DAY_VOTE': 0.51, 'WITCH:DAY_VOTE': 0.48, 'HUNTER:DAY_VOTE': 0.48,
12
+ };
13
+
14
+ const keyOf = (role, decisionType) => `${role}:${decisionType}`;
15
+
16
+ /** 一局里所有座位的有结果窗口计数:{ 'WOLF:DAY_VOTE': [good, bad], ... } */
17
+ export function windowStats(windows) {
18
+ const out = {};
19
+ for (const w of windows) {
20
+ if (!w.outcome) continue;
21
+ const k = keyOf(w.role, w.decisionType);
22
+ out[k] ??= [0, 0];
23
+ out[k][w.outcome === 'good' ? 0 : 1] += 1;
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /** 由 ledger 里各局的 wstats 汇总出基线;返回 (role, decisionType) => p | null(该类窗口不计分时为 null) */
29
+ export function baselineOf(ledger) {
30
+ const sum = {};
31
+ for (const g of Object.values(ledger?.games ?? {})) {
32
+ for (const [k, [good, bad]] of Object.entries(g.wstats ?? {})) {
33
+ sum[k] ??= [0, 0];
34
+ sum[k][0] += good;
35
+ sum[k][1] += bad;
36
+ }
37
+ }
38
+ return (role, decisionType) => {
39
+ const k = keyOf(role, decisionType);
40
+ const prior = DEFAULT_BASELINE[k];
41
+ const [good, bad] = sum[k] ?? [0, 0];
42
+ if (prior == null && good + bad < PRIOR_WEIGHT) return null;
43
+ const p = prior == null ? good / (good + bad) : (good + PRIOR_WEIGHT * prior) / (good + bad + PRIOR_WEIGHT);
44
+ return Math.min(0.95, Math.max(0.05, p));
45
+ };
46
+ }
@@ -0,0 +1,109 @@
1
+ // 第二层:选择待复盘对局、生成复盘工作单。
2
+ import { buildGameFacts, ROLE_CN, DECISION_TYPES, ROLES } from './facts.mjs';
3
+ import { MAX_ITEMS, MAX_NEW, assignWindows, zOf, emptyStats } from './lessons.mjs';
4
+
5
+ export const BATCH_GAMES = 3;
6
+ export const LIST_LESSONS = 8;
7
+
8
+ /** 待复盘:gameId > reflectedThrough;意外局优先,其次最新 */
9
+ export function selectBatch(ledger, size = BATCH_GAMES) {
10
+ const pending = Object.values(ledger.games).filter((o) => Number(o.gameId) > Number(ledger.reflectedThrough ?? 0));
11
+ if (!pending.length) return null;
12
+ const ranked = [...pending].sort((a, b) => (b.surprise?.length ? 1 : 0) - (a.surprise?.length ? 1 : 0) || Number(b.gameId) - Number(a.gameId));
13
+ const picked = ranked.slice(0, size).sort((a, b) => Number(a.gameId) - Number(b.gameId));
14
+ const coversThrough = Math.max(...pending.map((o) => Number(o.gameId)));
15
+ return { batchId: `b${coversThrough}`, coversThrough, gameIds: picked.map((o) => String(o.gameId)), pending: pending.length };
16
+ }
17
+
18
+ /**
19
+ * @param {object} p
20
+ * @param {object[]} p.replays [{record, replay}],与 batch.gameIds 对应
21
+ */
22
+ export function buildBrief({ batch, replays, lessonsState, agentId, now, projected = [] }) {
23
+ const games = replays.map(({ record, replay }) => buildGameFacts(replay, record, agentId)).filter(Boolean);
24
+ const selfRoles = new Set(games.map((g) => g.selfRole));
25
+ const onBoard = new Set(projected);
26
+ const rank = (l) => (onBoard.has(l.id) ? 0 : l.status === 'ready' ? 1 : 2);
27
+ const lessons = Object.values(lessonsState.lessons)
28
+ .filter((l) => !['archived', 'paused', 'retired'].includes(l.status) && (l.layer === 'L1' || l.role === 'ANY' || selfRoles.has(l.role)))
29
+ // 已投影的优先,其次 ready,其次样本最少的(最需要数据)
30
+ .sort((a, b) => rank(a) - rank(b) || (a.stats?.n ?? 0) - (b.stats?.n ?? 0) || a.id.localeCompare(b.id))
31
+ .slice(0, LIST_LESSONS)
32
+ .map(({ id, layer, role, decisionType, trigger, rule, boundary, score, status, stats, camp }) => {
33
+ const s = stats ?? emptyStats();
34
+ return { id, layer, role, decisionType, trigger, rule, boundary, score, status, ...(camp ? { camp } : {}), n: s.n, z: Math.round(zOf(s) * 100) / 100, projected: onBoard.has(id) };
35
+ });
36
+ const windows = games.flatMap((g) => g.windows);
37
+ return {
38
+ batchId: batch.batchId,
39
+ agentId: String(agentId),
40
+ createdAt: now,
41
+ coversThrough: batch.coversThrough,
42
+ attempts: 0,
43
+ games: games.map(({ windows: _w, ...g }) => g),
44
+ windows,
45
+ lessons,
46
+ assignments: assignWindows(lessons, windows),
47
+ };
48
+ }
49
+
50
+ export function renderBrief(brief, { proposalPath, commitCmd, revealOutcomes = false }) {
51
+ const L = [];
52
+ L.push(`# 狼人杀复盘工作单 ${brief.batchId}`);
53
+ L.push('');
54
+ L.push('你在复盘自己最近的对局。工作单会展示行动事实,但不会展示脚本计算的窗口结果、赛后身份全表或阵营胜负。结果由脚本单独核验,你不能改写。你的任务:');
55
+ L.push('1. 对“已有经验”:脚本已经给部分经验分配了要标注的窗口(见每条经验下的“需标注”)。每条有分配的经验都要提交一个 APPLY,把分配的窗口逐个标注,不能多也不能少:followed=true 表示那次决策照经验的“做法”做了,false 表示触发条件成立但做法相反,"na" 表示触发条件不成立。只根据决策当时可见的信息和实际行动判断,不要根据赛后结果倒推;脚本会把照做窗口和确定性结果合并计分。');
56
+ L.push(`2. 只有当反复出现、且已有经验都不覆盖的问题,才用 NEW 新建(每次最多 ${MAX_NEW} 条)。证据要求:来自至少 2 局的 2 个可核验窗口,或包含可对照的不同公开情境;可以引用任何座位的窗口。新经验之后靠分配到的窗口检验,证据本身不计分。`);
57
+ L.push('3. 经验写“在什么情况下、怎么判断/怎么做、什么时候不适用”。触发条件和做法只能依赖决策当时场上公开可见的信息(发言、票型、跳身份、出局),不能依赖赛后才知道的身份;不写具体座位号;不用“必须/永远/绝对”等绝对化措辞。');
58
+ L.push('4. L1 = 任何人都适用的角色战术;L2 = 只关于你自己的执行习惯,NEW 时只能引用你自己(★)的窗口。');
59
+ L.push('5. 没有分配窗口、也没有值得新建的内容时提交 items: [],这是正常结果。');
60
+ L.push('');
61
+ L.push('## 已有经验');
62
+ if (!brief.lessons.length) L.push('(暂无)');
63
+ const assignments = brief.assignments ?? {};
64
+ for (const l of brief.lessons) {
65
+ L.push(`- ${l.id} [${l.layer} ${l.role} ${l.decisionType} ${l.status},已检验 ${l.n ?? 0} 个窗口${l.n ? `,比基线 ${l.score >= 0 ? '+' : ''}${l.score}pt` : ''}${l.projected ? ',已投影:对局中你能看到它' : ''}] 触发:${l.trigger}|做法:${l.rule}|边界:${l.boundary}`);
66
+ L.push(` 需标注:${assignments[l.id]?.join(', ') ?? '(本批次没有匹配的窗口,不要提交)'}`);
67
+ }
68
+ const byGame = new Map();
69
+ for (const w of brief.windows) byGame.set(w.gameId, [...(byGame.get(w.gameId) ?? []), w]);
70
+ for (const g of brief.games) {
71
+ L.push('');
72
+ L.push(`## 对局 ${g.gameId}:我是 ${g.selfSeat} 号 ${ROLE_CN[g.selfRole]}`);
73
+ const ws = byGame.get(g.gameId) ?? [];
74
+ const rounds = [...new Set([...ws.map((w) => w.round), ...g.facts.map((f) => f.round)])].sort((a, b) => a - b);
75
+ for (const r of rounds) {
76
+ L.push(`### 第 ${r} 天`);
77
+ for (const w of ws.filter((x) => x.round === r && x.decisionType === 'SEER_CLAIM')) {
78
+ L.push(`- ${w.id}${w.self ? '★' : ''} 预言家决策 ${w.seat}号预:${w.claim}${revealOutcomes && w.outcome ? `(${w.outcome})` : ''}`);
79
+ }
80
+ for (const w of ws.filter((x) => x.round === r && x.decisionType === 'DAY_SPEECH')) {
81
+ const text = g.facts.find((f) => f.id === `f${w.id.slice(1)}`)?.text ?? '';
82
+ L.push(`- ${w.id}${w.self ? '★' : ''} 发言 ${w.seat}号:${text}`);
83
+ }
84
+ for (const w of ws.filter((x) => x.round === r && x.decisionType === 'DAY_VOTE')) {
85
+ const tgt = w.targetSeat == null ? '弃票' : `→${w.targetSeat}号`;
86
+ L.push(`- ${w.id}${w.self ? '★' : ''} ${w.revote ? 'PK投票' : '投票'} ${w.seat}号${tgt}${w.reason ? `:${w.reason}` : ''}`);
87
+ }
88
+ for (const f of g.facts.filter((x) => x.round === r && x.kind !== 'SPEECH')) {
89
+ if (f.kind === 'LAST_WORD') L.push(`- 遗言 ${f.seat}号:${f.text}`);
90
+ else L.push(`- 出局 ${f.seat}号(${f.cause})`);
91
+ }
92
+ }
93
+ }
94
+ L.push('');
95
+ L.push('## 提交');
96
+ L.push(`把下面格式的 JSON 写入 ${proposalPath},然后执行一次:${commitCmd}`);
97
+ L.push(`校验失败时按返回的 errors 修改后可再提交一次;items 最多 ${MAX_ITEMS} 条。字段取值:layer=L1/L2,role=${[...ROLES, 'ANY'].join('/')},decisionType=${DECISION_TYPES.join('/')}。`);
98
+ const exampleId = Object.keys(assignments)[0];
99
+ L.push('```json');
100
+ L.push(JSON.stringify({
101
+ batchId: brief.batchId,
102
+ items: [
103
+ { action: 'APPLY', lessonId: exampleId ?? '<有分配窗口的经验ID>', windows: (exampleId ? assignments[exampleId] : ['<分配的窗口ID>']).map((id, k) => ({ id, followed: [true, false, 'na'][k % 3] })) },
104
+ { action: 'NEW', layer: 'L1', role: 'WOLF', decisionType: 'DAY_SPEECH', lesson: { trigger: '…', rule: '…', boundary: '…' }, evidence: [{ id: '<窗口ID>', followed: true }, { id: '<另一窗口ID>', followed: false }] },
105
+ ],
106
+ }, null, 1));
107
+ L.push('```');
108
+ return L.join('\n') + '\n';
109
+ }
@@ -0,0 +1,46 @@
1
+ // 凭据解析:优先 connector 注入的环境变量,其次只读 <dir>/context.env。
2
+ import { readFileSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+
5
+ const KEYS = ['CLAWTOPIA_GATEWAY_URL', 'CLAWTOPIA_AGENT_BEARER', 'CLAWTOPIA_AGENT_ID'];
6
+
7
+ export function parseEnvFile(text) {
8
+ const out = {};
9
+ for (const raw of text.split(/\r?\n/)) {
10
+ const line = raw.trim();
11
+ if (!line || line.startsWith('#')) continue;
12
+ const m = line.match(/^(?:export\s+)?([A-Z0-9_]+)=(.*)$/);
13
+ if (!m) continue;
14
+ let v = m[2].trim();
15
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
16
+ out[m[1]] = v;
17
+ }
18
+ return out;
19
+ }
20
+
21
+ /**
22
+ * @param {string} dir Agent 上下文目录(.clawtopia/agent-<id>)
23
+ * @param {object} env process.env
24
+ * @returns {{gateway:string, token:string, agentId:string, source:string}}
25
+ */
26
+ export function resolveContext(dir, env = process.env) {
27
+ let vals = Object.fromEntries(KEYS.map((k) => [k, env[k]]));
28
+ let source = 'env';
29
+ if (KEYS.some((k) => !vals[k])) {
30
+ let text;
31
+ try {
32
+ text = readFileSync(join(dir, 'context.env'), 'utf8');
33
+ } catch {
34
+ throw new Error(`缺少凭据:环境变量不全,且 ${join(dir, 'context.env')} 不可读`);
35
+ }
36
+ vals = parseEnvFile(text);
37
+ source = 'context.env';
38
+ if (KEYS.some((k) => !vals[k])) throw new Error('context.env 中凭据不全');
39
+ }
40
+ const agentId = String(vals.CLAWTOPIA_AGENT_ID);
41
+ const dirName = basename(dir.replace(/\/+$/, ''));
42
+ if (dirName !== `agent-${agentId}`) {
43
+ throw new Error(`目录 ${dirName} 与 CLAWTOPIA_AGENT_ID=${agentId} 不一致,拒绝运行`);
44
+ }
45
+ return { gateway: vals.CLAWTOPIA_GATEWAY_URL.replace(/\/+$/, ''), token: vals.CLAWTOPIA_AGENT_BEARER, agentId, source };
46
+ }