@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,119 @@
1
+ // 由赛后结果视图计算本 Agent 的确定性局部结果。纯函数,无 I/O。
2
+ export const OUTCOME_VERSION = 1;
3
+
4
+ const NORMAL_RESULTS = new Set(['GOOD_WIN', 'WOLF_WIN']);
5
+ const VOTE_TYPES = new Set(['DAY_VOTE_SUBMIT', 'DAY_REVOTE_SUBMIT']);
6
+
7
+ const campOf = (role) => (role === 'WOLF' ? 'WOLF' : 'GOOD');
8
+
9
+ /**
10
+ * @param {object} replay GET /replay?view=result 的 data
11
+ * @param {string|number} selfAgentId
12
+ * @param {object} record /records 中的摘要(gameId、result、endedAt)
13
+ * @returns {{incident?:string, outcome?:object}}
14
+ */
15
+ export function computeOutcome(replay, selfAgentId, record = {}) {
16
+ const self = String(selfAgentId);
17
+ const gameId = record.gameId ?? replay?.events?.[0]?.gameId;
18
+ const result = record.result ?? replay?.game?.result;
19
+ const events = [...(replay?.events ?? [])].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
20
+ const init = events.find((e) => e.eventType === 'INITIAL_STATE');
21
+ const players = init?.payload?.players;
22
+ // 先确认是否本人参赛:/records 会混入同房间他人的局
23
+ if (!Array.isArray(players) || players.length === 0) return { incident: 'PARTICIPATION_UNKNOWN' };
24
+ if (!players.some((p) => String(p.agentId) === self)) return { incident: 'SELF_NOT_SEATED' };
25
+ if (!NORMAL_RESULTS.has(result)) return { incident: `RESULT_${result ?? 'UNKNOWN'}` };
26
+ const bySeat = new Map(players.map((p) => [Number(p.seat), { ...p, camp: campOf(p.role) }]));
27
+ if ([...bySeat.values()].some((p) => !p.role)) return { incident: 'ROLE_UNKNOWN' };
28
+ const me = [...bySeat.values()].find((p) => String(p.agentId) === self);
29
+
30
+ const alive = new Set(bySeat.keys());
31
+ const wolvesAmong = (seats) => seats.filter((s) => bySeat.get(s).camp === 'WOLF').length;
32
+ const votes = [];
33
+ const shots = []; // 女巫毒、猎人枪:只在本 Agent 是该角色时记
34
+ let death = null;
35
+
36
+ for (const e of events) {
37
+ const p = e.payload ?? {};
38
+ if (e.eventType === 'ELIMINATION' && p.seat != null) {
39
+ const seat = Number(p.seat);
40
+ const cause = p.cause;
41
+ if (seat === me.seat && !death) death = { cause, phase: e.phase ?? null };
42
+ if (cause === 'POISON' && me.role === 'WITCH') shots.push(shotOutcome('WITCH_POISON', seat, alive));
43
+ if (cause === 'HUNTER_SHOT' && me.role === 'HUNTER') shots.push(shotOutcome('HUNTER_SHOT', seat, alive));
44
+ alive.delete(seat);
45
+ continue;
46
+ }
47
+ if (VOTE_TYPES.has(e.eventType) && String(e.actorAgentId) === self) {
48
+ const others = [...alive].filter((s) => s !== me.seat);
49
+ const target = p.targetSeat == null ? null : Number(p.targetSeat);
50
+ const v = { type: e.eventType === 'DAY_REVOTE_SUBMIT' ? 'REVOTE' : 'VOTE', round: p.round ?? null, targetSeat: target };
51
+ if (target == null || !bySeat.has(target)) {
52
+ v.abstain = true;
53
+ } else if (others.length) {
54
+ const wolves = wolvesAmong(others);
55
+ if (me.camp === 'GOOD') {
56
+ v.hitWolf = bySeat.get(target).camp === 'WOLF';
57
+ v.random = round3(wolves / others.length);
58
+ } else {
59
+ v.onGood = bySeat.get(target).camp === 'GOOD';
60
+ v.random = round3(1 - wolves / others.length);
61
+ }
62
+ }
63
+ votes.push(v);
64
+ }
65
+ }
66
+
67
+ function shotOutcome(kind, seat, aliveNow) {
68
+ const others = [...aliveNow].filter((s) => s !== me.seat);
69
+ return {
70
+ kind,
71
+ targetSeat: seat,
72
+ hitWolf: bySeat.get(seat)?.camp === 'WOLF',
73
+ random: others.length ? round3(wolvesAmong(others) / others.length) : null,
74
+ };
75
+ }
76
+
77
+ const won = (result === 'GOOD_WIN') === (me.camp === 'GOOD');
78
+ const outcome = {
79
+ v: OUTCOME_VERSION,
80
+ gameId,
81
+ endedAt: record.endedAt ?? null,
82
+ seat: me.seat,
83
+ role: me.role,
84
+ camp: me.camp,
85
+ result,
86
+ won,
87
+ votes,
88
+ shots,
89
+ death,
90
+ };
91
+ outcome.surprise = surpriseFlags(outcome, events, bySeat);
92
+ return { outcome };
93
+ }
94
+
95
+ /** 意外局标记:供第二层决定是否需要模型复盘。只用确定性事实。 */
96
+ function surpriseFlags(o, events, bySeat) {
97
+ const flags = [];
98
+ if (o.camp === 'WOLF' && o.death?.cause === 'VOTED_OUT') flags.push('WOLF_VOTED_OUT');
99
+ if (o.camp === 'GOOD' && o.death?.cause === 'VOTED_OUT') flags.push('GOOD_VOTED_OUT');
100
+ // 好人投票未中,但同轮多数好人投中了狼
101
+ if (o.camp === 'GOOD') {
102
+ for (const v of o.votes.filter((x) => x.hitWolf === false && x.type === 'VOTE')) {
103
+ const sameRound = events.filter(
104
+ (e) => e.eventType === 'DAY_VOTE_SUBMIT' && e.payload?.round === v.round &&
105
+ bySeat.get(Number(e.payload?.voterSeat))?.camp === 'GOOD' && e.payload?.targetSeat != null,
106
+ );
107
+ const hits = sameRound.filter((e) => bySeat.get(Number(e.payload.targetSeat))?.camp === 'WOLF').length;
108
+ if (sameRound.length >= 2 && hits * 2 > sameRound.length) {
109
+ flags.push('GOOD_VOTE_MISSED_MAJORITY');
110
+ break;
111
+ }
112
+ }
113
+ }
114
+ if (o.shots.some((s) => s.kind === 'WITCH_POISON' && !s.hitWolf)) flags.push('POISON_ON_GOOD');
115
+ if (o.shots.some((s) => s.kind === 'HUNTER_SHOT' && !s.hitWolf)) flags.push('SHOT_ON_GOOD');
116
+ return flags;
117
+ }
118
+
119
+ const round3 = (x) => Math.round(x * 1000) / 1000;
@@ -0,0 +1,70 @@
1
+ // 平台层检验:把多个 Agent 对同一条种子经验的标注合并起来检验。纯函数,无 I/O。
2
+ //
3
+ // 单个 Agent 一周只打几十局,一条经验很难攒够 MIN_WINDOWS 个照做窗口;种子经验 ID 全平台一致,可以合并。
4
+ // - 同一个窗口可能被多个 Agent 标注(预言家首日决策窗口同局 8 个 Agent 都会分到),按窗口去重:
5
+ // 多数票决定 followed,票数持平的窗口不计入(标注有分歧,说明触发条件本身含糊)。
6
+ // - 去重后的窗口和单 Agent 计分口径一致:只计照做的,每局最多 PER_GAME 个,z = (O−E)/√V。
7
+ // - verified:≥MIN_WINDOWS 个窗口、来自 ≥MIN_GAMES 局、z ≥ Z;rejected:≥MIN_WINDOWS 个窗口且 z ≤ −Z。
8
+ // 结论写进 seeds.json 的 platform 字段随 skill 下发,Agent 本地据此把种子当作 ready(见 lessons.statusOf)。
9
+ import { MIN_WINDOWS, MIN_GAMES, Z, PER_GAME, NA_MIN_LABELS, NA_MAX_RATE, zOf, liftOf } from './lessons.mjs';
10
+
11
+ /**
12
+ * @param {Array<object>} states 各 Agent 的 lessons.json
13
+ * @param {string[]} seedIds 要检验的种子 ID
14
+ * @returns {{ [id]: { status, n, games, good, expected, z, lift, agents, labeled, agreement, tied } }}
15
+ */
16
+ export function poolSeeds(states, seedIds) {
17
+ const out = {};
18
+ for (const id of seedIds) {
19
+ const byWindow = new Map();
20
+ const agents = new Set();
21
+ for (const st of states) {
22
+ const l = st?.lessons?.[id];
23
+ if (!l) continue;
24
+ for (const e of l.evidence ?? []) {
25
+ // 只取 APPLY 标注(带基线 p 的),NEW 的来源证据不算
26
+ if (!('p' in e) || e.p == null || !e.outcome) continue;
27
+ agents.add(String(st.agentId));
28
+ const w = byWindow.get(e.windowId) ?? { gameId: String(e.gameId), outcome: e.outcome, p: e.p, votes: [] };
29
+ w.votes.push(e.followed);
30
+ byWindow.set(e.windowId, w);
31
+ }
32
+ }
33
+ let multi = 0, agreed = 0, tied = 0, na = 0, applicable = 0;
34
+ const s = { n: 0, good: 0, expected: 0, variance: 0, perGame: {} };
35
+ // 按局、窗口 ID 排序,保证 PER_GAME 截断结果稳定
36
+ const windows = [...byWindow.entries()].sort(([a, x], [b, y]) => Number(x.gameId) - Number(y.gameId) || a.localeCompare(b));
37
+ for (const [, w] of windows) {
38
+ if (w.votes.length > 1) {
39
+ multi += 1;
40
+ if (w.votes.every((v) => v === w.votes[0])) agreed += 1;
41
+ }
42
+ const counts = new Map();
43
+ for (const v of w.votes) counts.set(v, (counts.get(v) ?? 0) + 1);
44
+ const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1]);
45
+ if (ranked.length > 1 && ranked[0][1] === ranked[1][1]) { tied += 1; continue; }
46
+ if (ranked[0][0] === 'na') { na += 1; continue; }
47
+ applicable += 1;
48
+ if (ranked[0][0] !== true || (s.perGame[w.gameId] ?? 0) >= PER_GAME) continue;
49
+ s.perGame[w.gameId] = (s.perGame[w.gameId] ?? 0) + 1;
50
+ s.n += 1;
51
+ s.good += w.outcome === 'good' ? 1 : 0;
52
+ s.expected += w.p;
53
+ s.variance += w.p * (1 - w.p);
54
+ }
55
+ const z = zOf(s);
56
+ const games = Object.keys(s.perGame).length;
57
+ const labels = na + applicable;
58
+ const naRate = labels ? na / labels : 0;
59
+ const status = s.n >= MIN_WINDOWS && games >= MIN_GAMES && z >= Z && labels >= NA_MIN_LABELS && naRate <= NA_MAX_RATE ? 'verified'
60
+ : s.n >= MIN_WINDOWS && z <= -Z ? 'rejected' : 'testing';
61
+ out[id] = {
62
+ status, n: s.n, games, good: s.good, expected: round(s.expected), z: round(z), lift: liftOf(s),
63
+ applicable, na, naRate: round(naRate),
64
+ agents: agents.size, labeled: byWindow.size, agreement: multi ? round(agreed / multi) : null, tied,
65
+ };
66
+ }
67
+ return out;
68
+ }
69
+
70
+ const round = (x) => Math.round(x * 100) / 100;
@@ -0,0 +1,155 @@
1
+ // P2 投影:把 ready 的经验写进 runtime 自动加载的说明文件。纯函数,无 I/O。
2
+ //
3
+ // arena 的对局 prompt 只认 system context 中“唯一、marker 成对且结构完整的 WEREWOLF_RUNTIME v1 受管区块”,
4
+ // 并要求不要引用 prompt 之外的其他信息(WerewolfPromptRenderer.appendSkillHint)。所以投影不能另起区块,
5
+ // 只能写进 WEREWOLF_RUNTIME 的 `### active lessons` 小节:
6
+ // - 已有区块(werewolf-play 安装的):只替换 active lessons 小节,profile 与执行契约原样保留;
7
+ // - 没有区块(其他 runtime 的新用户):按 werewolf-play runtime v1 的结构新建一个完整区块。
8
+ import { createHash } from 'node:crypto';
9
+ import { zOf } from './lessons.mjs';
10
+
11
+ export const START = '<!-- WEREWOLF_RUNTIME_START -->';
12
+ export const END = '<!-- WEREWOLF_RUNTIME_END -->';
13
+ export const PER_ROLE = 3;
14
+ export const MAX_CHARS = 3000; // 只限 lessons 小节;旧插件对整个区块的上限是 8000
15
+ // 只允许写这些 runtime 自动加载的文件,防止误写任意文件
16
+ export const ALLOWED_TARGETS = ['AGENTS.md', 'CLAUDE.md'];
17
+
18
+ const ROLE_CN = { WOLF: '狼人', VILLAGER: '平民', SEER: '预言家', WITCH: '女巫', HUNTER: '猎人', ANY: '任何身份' };
19
+ const ORDER = ['ANY', 'WOLF', 'VILLAGER', 'SEER', 'WITCH', 'HUNTER'];
20
+ const LESSONS_HEADING = /^### active lessons[ \t]*$/m;
21
+
22
+ /** 选出要投影的经验:ready,按角色分组、每组按分数取前 PER_ROLE 条 */
23
+ export function selectProjected(lessonsState) {
24
+ const ready = Object.values(lessonsState.lessons).filter((l) => l.status === 'ready');
25
+ const picked = [];
26
+ for (const role of ORDER) {
27
+ picked.push(...ready.filter((l) => l.role === role).sort((a, b) => zOf(b.stats ?? {}) - zOf(a.stats ?? {}) || a.id.localeCompare(b.id)).slice(0, PER_ROLE));
28
+ }
29
+ return picked;
30
+ }
31
+
32
+ // 标签字段与 werewolf-play 的 lesson 格式对齐(status/risk/phase/role/players),runtime 才会采用
33
+ const PHASE = { DAY_VOTE: 'DAY_VOTE_TURN', DAY_SPEECH: 'DAY_SPEAK_TURN', SEER_CLAIM: 'DAY_SPEAK_TURN' };
34
+ const ROLE_CODE = { WOLF: 'WEREWOLF' };
35
+ const entry = (l) => [
36
+ `**标签**:id=${l.id} | status=active | risk=strategy | source=werewolf-evolution | phase=${PHASE[l.decisionType] ?? l.decisionType} | role=${ROLE_CODE[l.role] ?? l.role} | players=8 | score=${l.score} |`,
37
+ `**情况**:${l.trigger}`,
38
+ `**做法**:${l.rule}`,
39
+ `**不适用**:${l.boundary}`,
40
+ ].join('\n');
41
+
42
+ /** 生成 active lessons 小节正文;没有经验时为 none;超长时从低分开始丢弃 */
43
+ export function renderLessonsBody(lessons) {
44
+ let list = [...lessons];
45
+ for (;;) {
46
+ const text = list.length ? list.map(entry).join('\n\n') : 'none';
47
+ if (text.length <= MAX_CHARS || !list.length) return { text, lessons: list };
48
+ const lowest = [...list].sort((a, b) => a.score - b.score)[0];
49
+ list = list.filter((l) => l !== lowest);
50
+ }
51
+ }
52
+
53
+ /** 定位唯一的 RUNTIME 区块;没有返回 null;标记异常抛错 */
54
+ function locate(content) {
55
+ const starts = content.split(START).length - 1;
56
+ const ends = content.split(END).length - 1;
57
+ if (!starts && !ends) return null;
58
+ const s = content.indexOf(START);
59
+ const e = content.indexOf(END);
60
+ if (starts !== 1 || ends !== 1 || e < s) throw new Error('WEREWOLF_RUNTIME 区块标记重复或不完整,请手工检查后再投影');
61
+ const block = content.slice(s, e + END.length);
62
+ const m = LESSONS_HEADING.exec(block);
63
+ if (!m) throw new Error('WEREWOLF_RUNTIME 区块缺少 “### active lessons” 小节,请手工检查后再投影');
64
+ return { s, e, bodyStart: s + m.index + m[0].length, bodyEnd: e };
65
+ }
66
+
67
+ // 旧插件会在小节里放 `<!-- profile_review_required: … -->` 之类的状态标记,替换正文时要原样保留
68
+ const MARKER_LINE = /^<!--.*-->$/;
69
+ function splitBody(raw) {
70
+ const lines = raw.trim().split('\n');
71
+ return { text: lines.filter((l) => !MARKER_LINE.test(l.trim())).join('\n').trim(), markers: lines.filter((l) => MARKER_LINE.test(l.trim())) };
72
+ }
73
+
74
+ /** 读出 active lessons 小节正文(去首尾空白、不含状态标记);没有区块返回 null */
75
+ export function extractLessonsBody(content) {
76
+ const loc = locate(content);
77
+ return loc ? splitBody(content.slice(loc.bodyStart, loc.bodyEnd)).text : null;
78
+ }
79
+
80
+ // 执行契约里关于 lesson 权限的那一条。旧版(werewolf-play 0.1.x 安装)只允许改善表达,
81
+ // 2026-10-20 起允许策略类 lesson(投票、发言立场、身份起跳时机),但仍受规则、合法动作和硬信息约束。
82
+ export const LEGACY_CONTRACT_RULE = [
83
+ '- lessons 只能改善既定动作后的表达或执行,不得改变 actionType、actionData、目标、投票、',
84
+ ' 用药、开枪、查验、身份起跳或狼队战术。',
85
+ ];
86
+ export const CONTRACT_RULE = [
87
+ '- 适用的 lessons 可以影响投票目标、发言立场和身份起跳时机等策略选择,但只能在当前 prompt',
88
+ ' 给出的合法动作与目标中选择;与查验结果、私有信息等硬信息冲突时以硬信息为准。',
89
+ ];
90
+ export function canonicalRuntime(lessonsBody) {
91
+ return [
92
+ START,
93
+ '## werewolf-play runtime v1',
94
+ '',
95
+ 'runtime_version: 1',
96
+ 'active_profile: smart',
97
+ '',
98
+ '### GAME_EVENT execution contract',
99
+ '',
100
+ '- 本区块仅在 GAME_EVENT 生效,且已由 OpenClaw 自动注入;GAME_EVENT 不调用工具、不读取',
101
+ ' memory、skill 或 profile 文件。',
102
+ '- 游戏规则与 channel JSON schema > active profile > applicable lessons > 当前局势偏好。',
103
+ '- active/probation lessons 合计最多采用 3 条;只有 trigger、boundary、phase、role 和 players',
104
+ ' 都匹配当前 prompt 时才适用。',
105
+ ...CONTRACT_RULE,
106
+ '- profile、lessons 和内部推理不得出现在 JSON 对象外。',
107
+ '',
108
+ '### active profile playbook',
109
+ '',
110
+ '无额外风格指令。按角色基础策略玩。',
111
+ '',
112
+ '### active lessons',
113
+ '',
114
+ lessonsBody,
115
+ END,
116
+ ].join('\n');
117
+ }
118
+
119
+ /**
120
+ * 写入 lessons 小节。
121
+ * @param {string} content 文件内容
122
+ * @param {string|null} body 小节正文;null 表示撤销投影(恢复为 none,或删除由 evo 新建的区块)
123
+ * @param {{removeIfCreated?: boolean}} opts
124
+ * @returns {{content: string, created: boolean}}
125
+ */
126
+ export function upsertRuntimeLessons(content, body, { removeIfCreated = false, restoreContract = false } = {}) {
127
+ const loc = locate(content);
128
+ if (!loc) {
129
+ if (body == null) return { content, created: false };
130
+ return { content: `${content.replace(/\n*$/, '')}${content.trim() ? '\n\n' : ''}${canonicalRuntime(body)}\n`, created: true };
131
+ }
132
+ if (body == null && removeIfCreated) {
133
+ const before = content.slice(0, loc.s).replace(/\n*$/, '');
134
+ const after = content.slice(loc.e + END.length).replace(/^\n*/, '');
135
+ return { content: before && after ? `${before}\n\n${after}` : `${before}${after}${before || after ? '\n' : ''}`, created: false };
136
+ }
137
+ const { markers } = splitBody(content.slice(loc.bodyStart, loc.bodyEnd));
138
+ const next = `\n\n${[body ?? 'none', ...markers].join('\n')}\n`;
139
+ let out = content.slice(0, loc.bodyStart) + next + content.slice(loc.bodyEnd);
140
+ // 投影时把旧契约换成新契约;撤销投影且契约是 evo 换的,换回旧契约
141
+ const [from, to] = body != null ? [LEGACY_CONTRACT_RULE, CONTRACT_RULE] : restoreContract ? [CONTRACT_RULE, LEGACY_CONTRACT_RULE] : [null, null];
142
+ let contractChanged = false;
143
+ if (from) {
144
+ // 只替换与已知文本逐字一致的那一条,别的改动(用户或插件自定义的契约)不碰
145
+ const block = out.slice(loc.s, loc.bodyStart);
146
+ const at = block.indexOf(from.join('\n'));
147
+ if (at >= 0) {
148
+ out = out.slice(0, loc.s) + block.slice(0, at) + to.join('\n') + block.slice(at + from.join('\n').length) + out.slice(loc.bodyStart);
149
+ contractChanged = true;
150
+ }
151
+ }
152
+ return { content: out, created: false, contractChanged };
153
+ }
154
+
155
+ export const hashText = (t) => createHash('sha256').update(t).digest('hex').slice(0, 16);
@@ -0,0 +1,139 @@
1
+ // 投影的文件读写与自检。
2
+ import { readFileSync, writeFileSync, renameSync, existsSync, readdirSync } from 'node:fs';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
+ import { loadJson, saveJson } from './store.mjs';
5
+ import { emptyLessons, migrateLessons, checkWithdraw } from './lessons.mjs';
6
+ import { ALLOWED_TARGETS, selectProjected, renderLessonsBody, upsertRuntimeLessons, extractLessonsBody, hashText } from './projection.mjs';
7
+
8
+ const DEFAULT_CONFIG = { projection: { enabled: false, target: null } };
9
+
10
+ export const loadConfig = (dir) => ({ ...DEFAULT_CONFIG, ...(loadJson(dir, 'config.json') ?? {}) });
11
+
12
+ /**
13
+ * 校验投影目标:只允许 AGENTS.md / CLAUDE.md,文件必须已存在,
14
+ * 且目标所在目录不能被多个 Agent 共用(共用会把不同 Agent 的经验混在一起)。
15
+ */
16
+ export function checkTarget(target, agentId) {
17
+ const abs = resolve(target);
18
+ if (!ALLOWED_TARGETS.includes(basename(abs))) return `投影目标只能是 ${ALLOWED_TARGETS.join(' / ')}:${abs}`;
19
+ if (!existsSync(abs)) return `投影目标不存在:${abs}(请指定 runtime 自动加载的那份说明文件)`;
20
+ const ctxRoot = join(dirname(abs), '.clawtopia');
21
+ if (existsSync(ctxRoot)) {
22
+ const agents = readdirSync(ctxRoot).filter((n) => /^agent-\d+$/.test(n));
23
+ const others = agents.filter((n) => n !== `agent-${agentId}`);
24
+ if (others.length) return `目录 ${dirname(abs)} 被多个 Agent 共用(${agents.join(', ')}),请改用本 Agent 自己 workspace 下的说明文件`;
25
+ }
26
+ return null;
27
+ }
28
+
29
+ function writeAtomic(file, text) {
30
+ const tmp = `${file}.evo-tmp-${process.pid}`;
31
+ writeFileSync(tmp, text);
32
+ renameSync(tmp, file);
33
+ }
34
+
35
+ export const GUARD_GAMES = 10;
36
+ export const GUARD_BEFORE = 20;
37
+ export const GUARD_TIMEOUT_RISE = 0.1;
38
+
39
+ /** 投影从哪一局开始生效:启用时记下;更早版本启用的按第一次投影的时间从 ledger 推算 */
40
+ function projectionSince(cfg, ledger, prev) {
41
+ if (cfg.sinceGameId) return Number(cfg.sinceGameId);
42
+ const at = prev?.history?.[0]?.at;
43
+ if (!at) return 0;
44
+ const after = Object.values(ledger?.games ?? {}).filter((o) => o.endedAt && Date.parse(o.endedAt) > Date.parse(at)).map((o) => Number(o.gameId));
45
+ return after.length ? Math.min(...after) : Number.MAX_SAFE_INTEGER;
46
+ }
47
+
48
+ /**
49
+ * 整体保险:投影后至少 GUARD_GAMES 局,出现超时/熔断的局占比比投影前 GUARD_BEFORE 局高出 GUARD_TIMEOUT_RISE 时,
50
+ * 说明投影内容可能干扰了模型(太长、格式),整体关闭投影。返回原因或 null。
51
+ */
52
+ export function projectionGuard(ledger, since) {
53
+ const games = Object.values(ledger?.games ?? {}).filter((o) => o.timeouts != null).sort((a, b) => a.gameId - b.gameId);
54
+ const after = games.filter((o) => Number(o.gameId) >= since);
55
+ const before = games.filter((o) => Number(o.gameId) < since).slice(-GUARD_BEFORE);
56
+ if (after.length < GUARD_GAMES || before.length < GUARD_GAMES) return null;
57
+ const rate = (list) => list.filter((o) => o.timeouts > 0).length / list.length;
58
+ const [a, b] = [rate(after), rate(before)];
59
+ return a - b >= GUARD_TIMEOUT_RISE ? `投影后 ${after.length} 局里有超时/熔断的局占 ${Math.round(a * 100)}%,投影前 ${before.length} 局只有 ${Math.round(b * 100)}%` : null;
60
+ }
61
+
62
+ /** 按当前经验重建 active lessons 小节并写入目标;先做自动撤下和整体保险。未启用时不做任何事 */
63
+ export function runProjection(dir, agentId, now) {
64
+ const cfg = loadConfig(dir).projection;
65
+ if (!cfg.enabled) return { enabled: false };
66
+ const bad = checkTarget(cfg.target, agentId);
67
+ if (bad) throw new Error(bad);
68
+ const state = migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(agentId), now);
69
+ const ledger = loadJson(dir, 'ledger.json');
70
+ const since = projectionSince(cfg, ledger, loadJson(dir, 'projection.json'));
71
+ const guard = projectionGuard(ledger, since);
72
+ if (guard) return { ...disableProjection(dir, now), disabledBy: guard };
73
+ const withdrawn = checkWithdraw(state, (loadJson(dir, 'projection.json')?.current?.lessons ?? []).map((l) => l.id), since, now);
74
+ if (withdrawn.length) saveJson(dir, 'lessons.json', state);
75
+ const { text, lessons } = renderLessonsBody(selectProjected(state));
76
+ const before = readFileSync(cfg.target, 'utf8');
77
+ const { content: after, created, contractChanged } = upsertRuntimeLessons(before, text);
78
+ if (after !== before) writeAtomic(cfg.target, after);
79
+ const prev = loadJson(dir, 'projection.json') ?? { current: null, history: [] };
80
+ const record = {
81
+ at: now, target: cfg.target, hash: hashText(text), lessons: lessons.map((l) => ({ id: l.id, score: l.score })),
82
+ // 区块是 evo 新建的,关闭投影时整块删除;否则只把 lessons 恢复为 none
83
+ createdBlock: created || Boolean(prev.current?.createdBlock && prev.current.target === cfg.target),
84
+ // 契约是 evo 从旧版换成新版的,关闭投影时换回去
85
+ contractChanged: Boolean(contractChanged || (prev.current?.contractChanged && prev.current.target === cfg.target)),
86
+ };
87
+ const changed = prev.current?.hash !== record.hash;
88
+ saveJson(dir, 'projection.json', { current: record, history: changed ? [...prev.history, record].slice(-50) : prev.history });
89
+ return { enabled: true, target: cfg.target, lessons: record.lessons, changed, createdBlock: record.createdBlock, withdrawn };
90
+ }
91
+
92
+ export function enableProjection(dir, agentId, target, now) {
93
+ const abs = resolve(target.replace(/^~(?=\/|$)/, process.env.HOME ?? '~'));
94
+ const bad = checkTarget(abs, agentId);
95
+ if (bad) throw new Error(bad);
96
+ const games = Object.keys(loadJson(dir, 'ledger.json')?.games ?? {}).map(Number);
97
+ const sinceGameId = (games.length ? Math.max(...games) : 0) + 1;
98
+ saveJson(dir, 'config.json', { ...loadConfig(dir), projection: { enabled: true, target: abs, sinceGameId } });
99
+ return runProjection(dir, agentId, now);
100
+ }
101
+
102
+ /** 关闭投影:lessons 小节恢复为 none;若区块由 evo 新建则整块删除 */
103
+ export function disableProjection(dir, now) {
104
+ const cfg = loadConfig(dir);
105
+ const target = cfg.projection.target;
106
+ const prev = loadJson(dir, 'projection.json');
107
+ let removed = false;
108
+ if (target && existsSync(target)) {
109
+ const before = readFileSync(target, 'utf8');
110
+ const { content: after } = upsertRuntimeLessons(before, null, { removeIfCreated: Boolean(prev?.current?.createdBlock), restoreContract: Boolean(prev?.current?.contractChanged) });
111
+ if (after !== before) { writeAtomic(target, after); removed = true; }
112
+ }
113
+ saveJson(dir, 'config.json', { ...cfg, projection: { enabled: false, target } });
114
+ if (prev?.current) saveJson(dir, 'projection.json', { current: null, history: [...prev.history, { at: now, target, disabled: true }].slice(-50) });
115
+ return { enabled: false, target, removed };
116
+ }
117
+
118
+ /** 投影自检:返回 [{name, level: ok|warn|error, msg}] */
119
+ export function checkProjection(dir, agentId) {
120
+ const out = [];
121
+ const cfg = loadConfig(dir).projection;
122
+ if (!cfg.enabled) {
123
+ out.push({ name: 'projection', level: 'ok', msg: '投影未启用(P1:只积累经验)' });
124
+ return out;
125
+ }
126
+ const bad = checkTarget(cfg.target, agentId);
127
+ if (bad) return [{ name: 'projection.target', level: 'error', msg: bad }];
128
+ const body = extractLessonsBody(readFileSync(cfg.target, 'utf8'));
129
+ const cur = loadJson(dir, 'projection.json')?.current;
130
+ if (body == null) out.push({ name: 'projection.block', level: 'error', msg: `${cfg.target} 中没有 WEREWOLF_RUNTIME 区块,运行 project 重建` });
131
+ else if (!cur || hashText(body) !== cur.hash) out.push({ name: 'projection.block', level: 'error', msg: 'active lessons 与记录不一致(可能被手工或其他插件改动),运行 project 重建' });
132
+ else {
133
+ const expect = hashText(renderLessonsBody(selectProjected(migrateLessons(loadJson(dir, 'lessons.json') ?? emptyLessons(agentId)))).text);
134
+ out.push(expect === cur.hash
135
+ ? { name: 'projection.block', level: 'ok', msg: `已投影 ${cur.lessons.length} 条:${cur.lessons.map((l) => l.id).join(', ') || '(无 ready 经验,显示 none)'}` }
136
+ : { name: 'projection.block', level: 'warn', msg: '经验已更新但区块尚未重建,运行 project' });
137
+ }
138
+ return out;
139
+ }
@@ -0,0 +1,42 @@
1
+ // 复盘前检查本 Agent 是否已经坐进某个房间(等待开局或对局中)。
2
+ //
3
+ // 坐在房间里时,随时可能收到开局能力检测(只许回 OK、时间敏感)或对局行动,
4
+ // 这时做模型复盘会和对局抢同一个模型,可能导致超时被托管。
5
+ // 平台只在对局结束时写 game_record,所以不能靠 /records 判断“进行中”(2026-10-19 实测
6
+ // 近 30 天 154 局没有一条 ended_at 为空),只能看房间里的玩家列表。
7
+ const MAX_PAGES = 5;
8
+
9
+ /**
10
+ * @param {object} p
11
+ * @param {object} p.api createApi() 结果(rooms、room)
12
+ * @param {string} p.agentId
13
+ * @param {Iterable<string|number>} [p.extraRoomIds] 额外检查的房间(如最近对局所在房间,覆盖不公开列出的房间)
14
+ * @returns {Promise<{seated: boolean, roomId?: string, status?: string, checked: number}>}
15
+ */
16
+ export async function findSeat({ api, agentId, extraRoomIds = [] }) {
17
+ const self = String(agentId);
18
+ const candidates = new Set([...extraRoomIds].map(String));
19
+ let cursor = null;
20
+ for (let i = 0; i < MAX_PAGES; i += 1) {
21
+ const data = await api.rooms(cursor);
22
+ for (const r of data?.rooms ?? []) {
23
+ if (Number(r.currentPlayers) > 0) candidates.add(String(r.roomId));
24
+ }
25
+ if (!data?.hasMore || !data.nextCursor) break;
26
+ cursor = data.nextCursor;
27
+ }
28
+ let checked = 0;
29
+ for (const id of candidates) {
30
+ let room;
31
+ try {
32
+ room = await api.room(id);
33
+ } catch {
34
+ continue; // 房间已解散等:跳过该房间,不影响其他房间
35
+ }
36
+ checked += 1;
37
+ if ((room?.players ?? []).some((p) => String(p.agentId) === self)) {
38
+ return { seated: true, roomId: id, status: room.status, checked };
39
+ }
40
+ }
41
+ return { seated: false, checked };
42
+ }
@@ -0,0 +1,82 @@
1
+ // 本地状态:<dir>/werewolf-evolution/ledger.json。原子写入 + 简单写锁 + 保留最近备份。
2
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, openSync, closeSync, unlinkSync, statSync, readdirSync, copyFileSync } from 'node:fs';
3
+ import { join, dirname, basename } from 'node:path';
4
+
5
+ export const SCHEMA_VERSION = 1;
6
+ const LOCK_STALE_MS = 5 * 60 * 1000;
7
+ const KEEP_BACKUPS = 5;
8
+
9
+ export function stateDir(dir) {
10
+ return join(dir, 'werewolf-evolution');
11
+ }
12
+
13
+ export function emptyLedger(agentId, now) {
14
+ return { schemaVersion: SCHEMA_VERSION, agentId: String(agentId), createdAt: now, lastSyncAt: null, floorGameId: null, games: {}, incidents: {}, notMine: [] };
15
+ }
16
+
17
+ export function loadLedger(dir, agentId, now) {
18
+ const ledger = loadJson(dir, 'ledger.json');
19
+ if (!ledger) return emptyLedger(agentId, now);
20
+ if (ledger.schemaVersion !== SCHEMA_VERSION) throw new Error(`ledger schemaVersion=${ledger.schemaVersion},本版本只支持 ${SCHEMA_VERSION}`);
21
+ if (String(ledger.agentId) !== String(agentId)) throw new Error(`ledger 属于 Agent ${ledger.agentId},与当前 ${agentId} 不一致`);
22
+ return ledger;
23
+ }
24
+
25
+ export function saveLedger(dir, ledger) {
26
+ saveJson(dir, 'ledger.json', ledger);
27
+ }
28
+
29
+ /** 读 <stateDir>/<name>;不存在返回 null */
30
+ export function loadJson(dir, name) {
31
+ try {
32
+ return JSON.parse(readFileSync(join(stateDir(dir), name), 'utf8'));
33
+ } catch (e) {
34
+ if (e.code === 'ENOENT') return null;
35
+ throw e;
36
+ }
37
+ }
38
+
39
+ /** 原子写 <stateDir>/<name>,并在 backups/ 保留最近 5 个旧版本 */
40
+ export function saveJson(dir, name, obj) {
41
+ const sdir = stateDir(dir);
42
+ const file = join(sdir, name);
43
+ mkdirSync(dirname(file), { recursive: true });
44
+ const tmp = `${file}.tmp-${process.pid}`;
45
+ writeFileSync(tmp, JSON.stringify(obj, null, 1) + '\n');
46
+ const base = basename(name, '.json');
47
+ try {
48
+ statSync(file);
49
+ const bdir = join(sdir, 'backups');
50
+ mkdirSync(bdir, { recursive: true });
51
+ copyFileSync(file, join(bdir, `${base}-${Date.now()}.json`));
52
+ const old = readdirSync(bdir).filter((f) => f.startsWith(`${base}-`)).sort();
53
+ for (const f of old.slice(0, Math.max(0, old.length - KEEP_BACKUPS))) unlinkSync(join(bdir, f));
54
+ } catch (e) {
55
+ if (e.code !== 'ENOENT') throw e;
56
+ }
57
+ renameSync(tmp, file);
58
+ }
59
+
60
+ /** 独占写锁;超过 5 分钟的锁视为残留并接管。 */
61
+ export async function withLock(dir, fn) {
62
+ const sdir = stateDir(dir);
63
+ mkdirSync(sdir, { recursive: true });
64
+ const lock = join(sdir, '.lock');
65
+ let fd;
66
+ try {
67
+ fd = openSync(lock, 'wx');
68
+ } catch (e) {
69
+ if (e.code !== 'EEXIST') throw e;
70
+ const age = Date.now() - statSync(lock).mtimeMs;
71
+ if (age < LOCK_STALE_MS) throw new Error('另一个 evo 进程正在运行(.lock),本次跳过');
72
+ unlinkSync(lock);
73
+ fd = openSync(lock, 'wx');
74
+ }
75
+ writeFileSync(fd, String(process.pid));
76
+ closeSync(fd);
77
+ try {
78
+ return await fn();
79
+ } finally {
80
+ try { unlinkSync(lock); } catch { /* 已被清理 */ }
81
+ }
82
+ }