@myclaw163/clawclaw-cli 0.6.66 → 0.6.67
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/README.md +427 -427
- package/bin/clawclaw-cli.mjs +3 -3
- package/package.json +48 -48
- package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -23
- package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -22
- package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -22
- package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -22
- package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -23
- package/scripts/find-hide-spots.py +157 -157
- package/scripts/postinstall.mjs +20 -20
- package/scripts/sync-bundled-skill.mjs +245 -245
- package/scripts/sync-bundled-skill.test.mjs +152 -152
- package/skills/clawclaw/SKILL.md +244 -245
- package/skills/clawclaw/references/CHATTERBOX.md +142 -142
- package/skills/clawclaw/references/COMMANDS.md +148 -148
- package/skills/clawclaw/references/GAME-MECHANICS.md +188 -188
- package/skills/clawclaw/references/HUB.md +48 -48
- package/skills/clawclaw/references/KNOWLEDGE.md +43 -43
- package/skills/clawclaw/references/STRATEGIES.md +57 -57
- package/skills/clawclaw/references/STREAM.md +91 -92
- package/skills/clawclaw/references/TACTICS.md +65 -65
- package/src/assets/clawclaw-ascii-map.txt +40 -40
- package/src/cli.ts +110 -110
- package/src/commands/_schema.ts +109 -109
- package/src/commands/account.ts +209 -209
- package/src/commands/do.test.ts +73 -73
- package/src/commands/do.ts +126 -126
- package/src/commands/events.test.ts +71 -71
- package/src/commands/events.ts +155 -155
- package/src/commands/game-map.test.ts +28 -28
- package/src/commands/game-start-plan.test.ts +84 -84
- package/src/commands/game.ts +1027 -1027
- package/src/commands/history-player.test.ts +102 -102
- package/src/commands/history.ts +573 -573
- package/src/commands/hub.test.ts +96 -96
- package/src/commands/hub.ts +234 -234
- package/src/commands/knowledge.test.ts +19 -19
- package/src/commands/knowledge.ts +168 -168
- package/src/commands/load.test.ts +51 -51
- package/src/commands/load.ts +13 -13
- package/src/commands/meeting-history.test.ts +106 -106
- package/src/commands/memory.ts +40 -40
- package/src/commands/peek.ts +45 -45
- package/src/commands/persona.ts +57 -57
- package/src/commands/setup/codex.ts +266 -248
- package/src/commands/skill.ts +128 -128
- package/src/commands/state.ts +46 -46
- package/src/commands/strategy.test.ts +135 -135
- package/src/commands/strategy.ts +180 -180
- package/src/commands/tts.ts +128 -128
- package/src/commands/upgrade.test.ts +82 -82
- package/src/commands/upgrade.ts +148 -148
- package/src/commands/watch.test.ts +966 -966
- package/src/commands/watch.ts +659 -659
- package/src/lib/auth.test.ts +59 -59
- package/src/lib/auth.ts +186 -186
- package/src/lib/command-meta.ts +37 -37
- package/src/lib/game-client.ts +391 -391
- package/src/lib/http-keepalive.ts +15 -15
- package/src/lib/http-transport.test.ts +42 -42
- package/src/lib/http-transport.ts +113 -113
- package/src/lib/hub-client.test.ts +56 -56
- package/src/lib/hub-client.ts +88 -88
- package/src/lib/hub-install.test.ts +98 -98
- package/src/lib/hub-install.ts +121 -121
- package/src/lib/hub-reminder.ts +75 -75
- package/src/lib/hub-unzip.test.ts +69 -69
- package/src/lib/hub-unzip.ts +62 -62
- package/src/lib/init-command.test.ts +75 -75
- package/src/lib/init-command.ts +120 -120
- package/src/lib/knowledge-store.test.ts +180 -180
- package/src/lib/knowledge-store.ts +374 -374
- package/src/lib/load-context.test.ts +52 -52
- package/src/lib/load-context.ts +52 -52
- package/src/lib/match-state.test.ts +134 -134
- package/src/lib/match-state.ts +94 -94
- package/src/lib/netease-tts.ts +83 -83
- package/src/lib/normalize.ts +42 -42
- package/src/lib/persona.test.ts +41 -41
- package/src/lib/persona.ts +72 -72
- package/src/lib/server-registry.ts +152 -152
- package/src/lib/skill-version.test.ts +48 -48
- package/src/lib/skill-version.ts +19 -19
- package/src/lib/strategy-export.test.ts +232 -232
- package/src/lib/strategy-export.ts +242 -242
- package/src/lib/tts-keys.ts +7 -7
- package/src/lib/tts-speech.test.ts +63 -63
- package/src/lib/tts-speech.ts +76 -76
- package/src/lib/workspace-argv.test.ts +49 -49
- package/src/lib/workspace-argv.ts +44 -44
- package/src/perception/player-history-store.test.ts +87 -87
- package/src/perception/player-history-store.ts +194 -194
- package/src/pipeline/event-format.test.ts +135 -135
- package/src/pipeline/event-format.ts +376 -376
- package/src/pipeline/event-hints.ts +173 -173
- package/src/pipeline/event-store.test.ts +28 -28
- package/src/pipeline/event-store.ts +193 -193
- package/src/pipeline/pipeline.ts +35 -35
- package/src/runtime/auto-upgrade.test.ts +66 -66
- package/src/runtime/auto-upgrade.ts +31 -31
- package/src/runtime/event-daemon.test.ts +107 -107
- package/src/runtime/event-daemon.ts +409 -409
- package/src/runtime/owner-control.ts +150 -150
- package/src/runtime/raw-ws-log.test.ts +33 -33
- package/src/runtime/raw-ws-log.ts +32 -32
- package/src/runtime/runtime-logger.ts +107 -107
- package/src/runtime/ws-client.test.ts +104 -104
- package/src/runtime/ws-client.ts +272 -272
- package/src/sdk/action.ts +166 -166
- package/src/sdk/index.ts +111 -111
- package/src/sdk/types.ts +159 -159
- package/src/strategies/avoid-lone.ts +11 -11
- package/src/strategies/avoid-players.knowledge.md +20 -20
- package/src/strategies/avoid-players.ts +15 -15
- package/src/strategies/corpse-patrol.ts +22 -22
- package/src/strategies/crab-sabotage.ts +21 -21
- package/src/strategies/custom-module.test.ts +269 -269
- package/src/strategies/find-player.ts +16 -16
- package/src/strategies/game-utils.test.ts +190 -190
- package/src/strategies/game-utils.ts +782 -782
- package/src/strategies/goals/anchor-linger.ts +77 -77
- package/src/strategies/goals/avoid-lone-top.ts +168 -168
- package/src/strategies/goals/avoid-players-top.test.ts +83 -83
- package/src/strategies/goals/avoid-players-top.ts +121 -121
- package/src/strategies/goals/conversation-goal.ts +51 -51
- package/src/strategies/goals/corpse-patrol-top.ts +91 -91
- package/src/strategies/goals/crab-octopus-reflexes.ts +93 -93
- package/src/strategies/goals/crab-sabotage-top.ts +197 -197
- package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
- package/src/strategies/goals/find-player-top.ts +93 -93
- package/src/strategies/goals/flee-players-goal.ts +53 -53
- package/src/strategies/goals/follow-companion-goal.ts +106 -106
- package/src/strategies/goals/goal-manager.ts +41 -41
- package/src/strategies/goals/goal-root-strategy.ts +49 -49
- package/src/strategies/goals/goal.ts +28 -28
- package/src/strategies/goals/hide-top.ts +197 -197
- package/src/strategies/goals/keep-away-goal.ts +217 -217
- package/src/strategies/goals/kill-frenzy-top.ts +80 -80
- package/src/strategies/goals/kill-lone-top.ts +160 -160
- package/src/strategies/goals/kill-target-goal.ts +59 -59
- package/src/strategies/goals/kill-target-top.ts +109 -109
- package/src/strategies/goals/leaf-goal.ts +25 -25
- package/src/strategies/goals/linger-corpse-goal.ts +35 -35
- package/src/strategies/goals/lone-kill-core.ts +82 -82
- package/src/strategies/goals/lone-kill-goal.ts +24 -24
- package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
- package/src/strategies/goals/lone-kill-task-top.ts +86 -86
- package/src/strategies/goals/move-room-goal.ts +60 -60
- package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
- package/src/strategies/goals/normal-shrimp-top.ts +242 -242
- package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
- package/src/strategies/goals/paradise-fish-top.ts +207 -207
- package/src/strategies/goals/patrol-top.ts +57 -57
- package/src/strategies/goals/report-patrol-top.ts +80 -80
- package/src/strategies/goals/safe-task-goal.ts +102 -102
- package/src/strategies/goals/social-task-top.ts +161 -161
- package/src/strategies/goals/task-kill-report-top.ts +163 -163
- package/src/strategies/goals/task-only-top.ts +57 -57
- package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
- package/src/strategies/goals/task-report-top.ts +57 -57
- package/src/strategies/goals/wander-task-goal.ts +33 -33
- package/src/strategies/goals/warrior-shrimp-top.test.ts +86 -86
- package/src/strategies/goals/warrior-shrimp-top.ts +500 -500
- package/src/strategies/greeting.ts +53 -53
- package/src/strategies/hide-spots.ts +123 -123
- package/src/strategies/hide.ts +23 -23
- package/src/strategies/kill-frenzy.ts +12 -12
- package/src/strategies/kill-lone.knowledge.md +20 -20
- package/src/strategies/kill-lone.ts +13 -13
- package/src/strategies/kill-target.ts +18 -18
- package/src/strategies/loader.test.ts +678 -678
- package/src/strategies/loader.ts +172 -172
- package/src/strategies/lone-kill-task.ts +21 -21
- package/src/strategies/meeting-gate.test.ts +59 -59
- package/src/strategies/meeting-gate.ts +23 -23
- package/src/strategies/move-room.ts +15 -15
- package/src/strategies/new-events-backfill.ts +98 -98
- package/src/strategies/paradise-fish.knowledge.md +20 -20
- package/src/strategies/paradise-fish.ts +25 -25
- package/src/strategies/pathfind/distance-field.ts +150 -150
- package/src/strategies/pathfind/escape-planner.test.ts +197 -197
- package/src/strategies/pathfind/escape-planner.ts +355 -355
- package/src/strategies/pathfind/walkable-grid.ts +117 -117
- package/src/strategies/patrol.ts +11 -11
- package/src/strategies/player-targets.ts +13 -13
- package/src/strategies/report-patrol.ts +11 -11
- package/src/strategies/shrimp-memory.knowledge.md +20 -20
- package/src/strategies/shrimp-memory.ts +25 -25
- package/src/strategies/social-task.test.ts +28 -28
- package/src/strategies/social-task.ts +49 -49
- package/src/strategies/spawn.ts +82 -82
- package/src/strategies/speech-module.ts +123 -123
- package/src/strategies/strategy-loop.ts +771 -771
- package/src/strategies/task-kill-report.ts +17 -17
- package/src/strategies/task-only.ts +11 -11
- package/src/strategies/task-report.ts +22 -22
- package/src/strategies/types.ts +102 -102
- package/src/strategies/warrior-memory.knowledge.md +22 -22
- package/src/strategies/warrior-memory.ts +16 -16
|
@@ -1,374 +1,374 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 策略知识系统 — 当前对局的「推断快照」存储。
|
|
3
|
-
*
|
|
4
|
-
* 设计要点(见 docs/策略知识系统-by-claude.md):
|
|
5
|
-
* - 跨进程:Agent(短进程 CLI)写,strategy(长进程 loop)按 mtime 轮询读,免重启。
|
|
6
|
-
* - 快照而非日志:单个 JSON 对象,del/clear 直接重写;写入用临时文件 + rename 原子替换。
|
|
7
|
-
* - gameId 作用域:每份知识标记所属对局(= 最新 session 文件名),换局自动失效。
|
|
8
|
-
* - 价值中立:只存推断 + confidence/source,对 value 不做价值判断;
|
|
9
|
-
* 确定事实(role/队友/尸体…)走 state/ctx.teammates,不入库。
|
|
10
|
-
*/
|
|
11
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'fs';
|
|
12
|
-
import { basename, dirname, join } from 'path';
|
|
13
|
-
import { AuthStore } from './auth.js';
|
|
14
|
-
import { getProfileStateDir } from './init-command.js';
|
|
15
|
-
import { EventStore } from '../pipeline/event-store.js';
|
|
16
|
-
|
|
17
|
-
export type KnowledgeSource = 'agent' | 'strategy' | 'server';
|
|
18
|
-
/** v1:仅 'game' 生效(整库按 gameId 失效)。'session'/'persistent' 为预留,暂不跨局保留——跨局画像走 memory.md,CLI 也不暴露 --scope。 */
|
|
19
|
-
export type KnowledgeScope = 'game' | 'session' | 'persistent';
|
|
20
|
-
|
|
21
|
-
export interface FactMeta {
|
|
22
|
-
value: unknown;
|
|
23
|
-
confidence?: number;
|
|
24
|
-
note?: string;
|
|
25
|
-
source?: KnowledgeSource;
|
|
26
|
-
ts: number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export interface TagMeta {
|
|
30
|
-
confidence?: number;
|
|
31
|
-
note?: string;
|
|
32
|
-
source?: KnowledgeSource;
|
|
33
|
-
ts: number;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** 一个 subject(玩家/房间/任务/全局…)上聚合的事实 + 标签。 */
|
|
37
|
-
export interface SubjectEntry {
|
|
38
|
-
type: string; // 'player' | 'room' | 'task' | 'global' | <自定义>
|
|
39
|
-
selector: string; // player→座位号或名字;room→房名;global→''
|
|
40
|
-
facts?: Record<string, FactMeta>; // 键值事实,如 role: { value: 'impostor' }
|
|
41
|
-
tags?: Record<string, TagMeta>; // 玩家策略主标记:suspect / hostile / trusted;也支持自定义标签
|
|
42
|
-
scope?: KnowledgeScope;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface KnowledgeFile {
|
|
46
|
-
version: 1;
|
|
47
|
-
gameId?: string;
|
|
48
|
-
subjects: Record<string, SubjectEntry>; // key = `${type}:${selector}`
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export type KnowledgeFileReadResult =
|
|
52
|
-
| { status: 'ok'; file: KnowledgeFile }
|
|
53
|
-
| { status: 'missing' }
|
|
54
|
-
| { status: 'invalid'; error: string };
|
|
55
|
-
|
|
56
|
-
export type PlayerRef = { name?: string; seat?: number };
|
|
57
|
-
export type SubjectRef = { type: string; selector: string };
|
|
58
|
-
export type KnowledgeRef = PlayerRef | SubjectRef;
|
|
59
|
-
export type PlayerMark = 'suspect' | 'hostile' | 'trusted';
|
|
60
|
-
|
|
61
|
-
export interface KnowledgeView {
|
|
62
|
-
/** 当前没有任何知识时为 true。 */
|
|
63
|
-
readonly empty: boolean;
|
|
64
|
-
/** 取一个 subject(精确 type + selector)。 */
|
|
65
|
-
subject(type: string, selector: string): SubjectEntry | undefined;
|
|
66
|
-
/** 取某 subject 的键值事实。player ref 会按座位↔名字归一化解析。 */
|
|
67
|
-
getFact(ref: KnowledgeRef, key: string): FactMeta | undefined;
|
|
68
|
-
/** 该 subject 是否带某标签(可选最低置信度门槛)。玩家三档 mark 及旧别名按最新结论解析。 */
|
|
69
|
-
hasTag(ref: KnowledgeRef, tag: string, minConfidence?: number): boolean;
|
|
70
|
-
/** 按 type / tag / factKey / 置信度筛选 subject。玩家 mark 标签同样遵守最新结论。 */
|
|
71
|
-
query(q: { type?: string; tag?: string; factKey?: string; minConfidence?: number }): SubjectEntry[];
|
|
72
|
-
/** 某 type 下带某标签的全部 selector(喂给 matchesAnyTarget 用)。玩家 mark 标签同样过滤旧结论。 */
|
|
73
|
-
selectorsWithTag(type: string, tag: string, minConfidence?: number): string[];
|
|
74
|
-
// —— player 便捷语法糖 ——
|
|
75
|
-
/** 最近一次 role 事实。身份事实与策略 mark 完全解耦。 */
|
|
76
|
-
roleOf(p: PlayerRef): string | undefined;
|
|
77
|
-
markOf(p: PlayerRef, minConfidence?: number): PlayerMark | undefined;
|
|
78
|
-
isSuspect(p: PlayerRef, minConfidence?: number): boolean;
|
|
79
|
-
isHostile(p: PlayerRef, minConfidence?: number): boolean;
|
|
80
|
-
isTrusted(p: PlayerRef, minConfidence?: number): boolean;
|
|
81
|
-
/** @deprecated Use isHostile. */
|
|
82
|
-
isConfirmedHostile(p: PlayerRef, minConfidence?: number): boolean;
|
|
83
|
-
/** @deprecated Use isTrusted. */
|
|
84
|
-
isCleared(p: PlayerRef): boolean;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const PLAYER_MARK_ALIASES: Record<string, PlayerMark> = {
|
|
88
|
-
suspect: 'suspect',
|
|
89
|
-
avoid: 'suspect',
|
|
90
|
-
hostile: 'hostile',
|
|
91
|
-
kill_if_armed: 'hostile',
|
|
92
|
-
trusted: 'trusted',
|
|
93
|
-
cleared: 'trusted',
|
|
94
|
-
protected: 'trusted',
|
|
95
|
-
do_not_kill: 'trusted',
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
function nowTs(): number {
|
|
99
|
-
return Date.now();
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function subjectKey(type: string, selector: string): string {
|
|
103
|
-
return `${type}:${selector}`;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** 座位↔名字双向解析(比 game-utils.matchesTarget 多了「selector 是名字、ref 只有座位」一向),不依赖 StrategyContext(避免循环)。 */
|
|
107
|
-
function selectorMatchesPlayer(
|
|
108
|
-
selector: string,
|
|
109
|
-
player: PlayerRef,
|
|
110
|
-
playerNamesBySeat: Record<string, string>,
|
|
111
|
-
): boolean {
|
|
112
|
-
const seatStr = selector.trim();
|
|
113
|
-
const normalized = seatStr.toLowerCase();
|
|
114
|
-
if (!normalized) return false;
|
|
115
|
-
if (player.name && player.name.toLowerCase() === normalized) return true;
|
|
116
|
-
if (/^\d+$/.test(seatStr)) {
|
|
117
|
-
// 选择器是座位号
|
|
118
|
-
if (player.seat != null && String(player.seat) === seatStr) return true;
|
|
119
|
-
const nameFromSeat = playerNamesBySeat[seatStr];
|
|
120
|
-
if (nameFromSeat && player.name && player.name.toLowerCase() === nameFromSeat.toLowerCase()) return true;
|
|
121
|
-
} else if (player.seat != null) {
|
|
122
|
-
// 选择器是名字、引用只有座位 → 用座位映射出名字再比
|
|
123
|
-
const nameFromSeat = playerNamesBySeat[String(player.seat)];
|
|
124
|
-
if (nameFromSeat && nameFromSeat.toLowerCase() === normalized) return true;
|
|
125
|
-
}
|
|
126
|
-
return false;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function isSubjectRef(ref: KnowledgeRef): ref is SubjectRef {
|
|
130
|
-
return typeof (ref as SubjectRef).type === 'string' && typeof (ref as SubjectRef).selector === 'string';
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** 当前对局 id = 最新 session 文件名(去扩展名);无对局时 undefined。 */
|
|
134
|
-
export function currentGameId(): string | undefined {
|
|
135
|
-
try {
|
|
136
|
-
const path = EventStore.latestSessionPath();
|
|
137
|
-
return path ? basename(path, '.jsonl') : undefined;
|
|
138
|
-
} catch {
|
|
139
|
-
return undefined;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export function knowledgeFilePathForActiveAccount(): string {
|
|
144
|
-
const profile = new AuthStore().getActive();
|
|
145
|
-
if (!profile) throw new Error('Not logged in.');
|
|
146
|
-
return join(getProfileStateDir(profile), 'knowledge.json');
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export function readKnowledgeFileResult(path: string): KnowledgeFileReadResult {
|
|
150
|
-
if (!existsSync(path)) return { status: 'missing' };
|
|
151
|
-
try {
|
|
152
|
-
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
153
|
-
if (parsed && parsed.version === 1 && parsed.subjects && typeof parsed.subjects === 'object') {
|
|
154
|
-
return { status: 'ok', file: parsed as KnowledgeFile };
|
|
155
|
-
}
|
|
156
|
-
return { status: 'invalid', error: 'invalid knowledge file shape' };
|
|
157
|
-
} catch (err) {
|
|
158
|
-
return { status: 'invalid', error: err instanceof Error ? err.message : String(err) };
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/** 读 knowledge.json;不存在 / 解析失败 / 结构不对都返回 null。需要区分错误原因时用 readKnowledgeFileResult。 */
|
|
163
|
-
export function readKnowledgeFile(path: string): KnowledgeFile | null {
|
|
164
|
-
const result = readKnowledgeFileResult(path);
|
|
165
|
-
return result.status === 'ok' ? result.file : null;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/** 临时文件 + rename 原子替换,避免读端读到写一半的 JSON。 */
|
|
169
|
-
export function writeKnowledgeFileAtomic(path: string, file: KnowledgeFile): void {
|
|
170
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
171
|
-
const tmp = `${path}.tmp.${process.pid}`;
|
|
172
|
-
writeFileSync(tmp, JSON.stringify(file, null, 2));
|
|
173
|
-
renameSync(tmp, path);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export interface KnowledgeSetInput {
|
|
177
|
-
type: string;
|
|
178
|
-
selector: string;
|
|
179
|
-
key?: string;
|
|
180
|
-
value?: unknown;
|
|
181
|
-
tags?: string[];
|
|
182
|
-
removeTags?: string[];
|
|
183
|
-
confidence?: number;
|
|
184
|
-
note?: string;
|
|
185
|
-
source?: KnowledgeSource;
|
|
186
|
-
scope?: KnowledgeScope;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** Agent 侧读-改-写句柄;CLI 命令使用。strategy 侧只读,用 buildKnowledgeView。 */
|
|
190
|
-
export class KnowledgeStore {
|
|
191
|
-
constructor(
|
|
192
|
-
private readonly path: string,
|
|
193
|
-
readonly gameId?: string,
|
|
194
|
-
) {}
|
|
195
|
-
|
|
196
|
-
static forActiveAccount(): KnowledgeStore {
|
|
197
|
-
return new KnowledgeStore(knowledgeFilePathForActiveAccount(), currentGameId());
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/** 读当前文件;若不存在或属于别的对局,返回该对局的空文件(旧局知识自动失效)。 */
|
|
201
|
-
load(): KnowledgeFile {
|
|
202
|
-
const file = readKnowledgeFile(this.path);
|
|
203
|
-
if (file && file.gameId === this.gameId) return file;
|
|
204
|
-
return { version: 1, gameId: this.gameId, subjects: {} };
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
private save(file: KnowledgeFile): void {
|
|
208
|
-
writeKnowledgeFileAtomic(this.path, file);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
set(input: KnowledgeSetInput): SubjectEntry {
|
|
212
|
-
if (!input.type || !input.selector) throw new Error('knowledge set requires type and selector');
|
|
213
|
-
if (input.confidence != null && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {
|
|
214
|
-
throw new Error('confidence must be a finite number between 0 and 1');
|
|
215
|
-
}
|
|
216
|
-
const file = this.load();
|
|
217
|
-
const key = subjectKey(input.type, input.selector);
|
|
218
|
-
const entry: SubjectEntry = file.subjects[key] ?? { type: input.type, selector: input.selector };
|
|
219
|
-
const ts = nowTs();
|
|
220
|
-
const source = input.source ?? 'agent';
|
|
221
|
-
|
|
222
|
-
if (input.key != null) {
|
|
223
|
-
entry.facts = entry.facts ?? {};
|
|
224
|
-
entry.facts[input.key] = {
|
|
225
|
-
value: input.value === undefined ? true : input.value,
|
|
226
|
-
confidence: input.confidence,
|
|
227
|
-
note: input.note,
|
|
228
|
-
source,
|
|
229
|
-
ts,
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
if (input.tags && input.tags.length > 0) {
|
|
233
|
-
entry.tags = entry.tags ?? {};
|
|
234
|
-
for (const tag of input.tags) {
|
|
235
|
-
if (!tag) continue;
|
|
236
|
-
entry.tags[tag] = { confidence: input.confidence, note: input.note, source, ts };
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
if (input.removeTags && entry.tags) {
|
|
240
|
-
for (const tag of input.removeTags) delete entry.tags[tag];
|
|
241
|
-
}
|
|
242
|
-
if (input.scope) entry.scope = input.scope;
|
|
243
|
-
|
|
244
|
-
file.subjects[key] = entry;
|
|
245
|
-
this.save(file);
|
|
246
|
-
return entry;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/** 删整个 subject,或仅删某个 fact / tag;删空后自动清除该 subject。 */
|
|
250
|
-
del(type: string, selector: string, opts?: { key?: string; tag?: string }): boolean {
|
|
251
|
-
const file = this.load();
|
|
252
|
-
const key = subjectKey(type, selector);
|
|
253
|
-
const entry = file.subjects[key];
|
|
254
|
-
if (!entry) return false;
|
|
255
|
-
|
|
256
|
-
if (!opts?.key && !opts?.tag) {
|
|
257
|
-
delete file.subjects[key];
|
|
258
|
-
this.save(file);
|
|
259
|
-
return true;
|
|
260
|
-
}
|
|
261
|
-
if (opts.key && entry.facts) delete entry.facts[opts.key];
|
|
262
|
-
if (opts.tag && entry.tags) delete entry.tags[opts.tag];
|
|
263
|
-
const noFacts = !entry.facts || Object.keys(entry.facts).length === 0;
|
|
264
|
-
const noTags = !entry.tags || Object.keys(entry.tags).length === 0;
|
|
265
|
-
if (noFacts && noTags) delete file.subjects[key];
|
|
266
|
-
this.save(file);
|
|
267
|
-
return true;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
clear(): void {
|
|
271
|
-
this.save({ version: 1, gameId: this.gameId, subjects: {} });
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
list(): KnowledgeFile {
|
|
275
|
-
return this.load();
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** 由 strategy-loop 每次重载时构造。playerNamesBySeat 传入活引用即可,座位解析始终最新。 */
|
|
280
|
-
export function buildKnowledgeView(
|
|
281
|
-
file: KnowledgeFile | null,
|
|
282
|
-
opts: { playerNamesBySeat?: Record<string, string> } = {},
|
|
283
|
-
): KnowledgeView {
|
|
284
|
-
const subjects = file?.subjects ?? {};
|
|
285
|
-
const namesBySeat = opts.playerNamesBySeat ?? {};
|
|
286
|
-
const confOk = (conf: number | undefined, min?: number): boolean => min == null || (conf ?? 1) >= min;
|
|
287
|
-
|
|
288
|
-
const resolveAll = (ref: KnowledgeRef): SubjectEntry[] => {
|
|
289
|
-
if (isSubjectRef(ref)) {
|
|
290
|
-
const s = subjects[subjectKey(ref.type, ref.selector)];
|
|
291
|
-
return s ? [s] : [];
|
|
292
|
-
}
|
|
293
|
-
return Object.values(subjects).filter((s) => s.type === 'player' && selectorMatchesPlayer(s.selector, ref, namesBySeat));
|
|
294
|
-
};
|
|
295
|
-
|
|
296
|
-
const latestFact = (ref: KnowledgeRef, key: string): FactMeta | undefined => {
|
|
297
|
-
let best: FactMeta | undefined;
|
|
298
|
-
for (const s of resolveAll(ref)) {
|
|
299
|
-
const f = s.facts?.[key];
|
|
300
|
-
if (f && (!best || f.ts > best.ts)) best = f;
|
|
301
|
-
}
|
|
302
|
-
return best;
|
|
303
|
-
};
|
|
304
|
-
|
|
305
|
-
type MarkVerdict = { kind: PlayerMark; ts: number; confidence?: number };
|
|
306
|
-
const markRank = (kind: PlayerMark): number => kind === 'trusted' ? 3 : kind === 'hostile' ? 2 : 1;
|
|
307
|
-
const latestMark = (ref: KnowledgeRef): MarkVerdict | undefined => {
|
|
308
|
-
let best: MarkVerdict | undefined;
|
|
309
|
-
const take = (v: MarkVerdict) => {
|
|
310
|
-
if (!best
|
|
311
|
-
|| v.ts > best.ts
|
|
312
|
-
|| (v.ts === best.ts && markRank(v.kind) > markRank(best.kind))) {
|
|
313
|
-
best = v;
|
|
314
|
-
}
|
|
315
|
-
};
|
|
316
|
-
for (const s of resolveAll(ref)) {
|
|
317
|
-
for (const [tag, meta] of Object.entries(s.tags ?? {})) {
|
|
318
|
-
const kind = PLAYER_MARK_ALIASES[tag];
|
|
319
|
-
if (kind) take({ kind, ts: meta.ts, confidence: meta.confidence });
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
return best;
|
|
323
|
-
};
|
|
324
|
-
|
|
325
|
-
const markKindForTag = (tag: string): PlayerMark | undefined => PLAYER_MARK_ALIASES[tag];
|
|
326
|
-
const tagActive = (s: SubjectEntry, tag: string, min?: number): boolean => {
|
|
327
|
-
const requestedMark = markKindForTag(tag);
|
|
328
|
-
if (s.type === 'player' && requestedMark) {
|
|
329
|
-
const carriesRequestedMark = Object.keys(s.tags ?? {}).some(candidate => markKindForTag(candidate) === requestedMark);
|
|
330
|
-
if (!carriesRequestedMark) return false;
|
|
331
|
-
const ref: PlayerRef = /^\d+$/.test(s.selector.trim()) ? { seat: Number(s.selector) } : { name: s.selector };
|
|
332
|
-
const mark = latestMark(ref);
|
|
333
|
-
return !!mark && mark.kind === requestedMark && confOk(mark.confidence, min);
|
|
334
|
-
}
|
|
335
|
-
const meta = s.tags?.[tag];
|
|
336
|
-
return !!meta && confOk(meta.confidence, min);
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
return {
|
|
340
|
-
empty: Object.keys(subjects).length === 0,
|
|
341
|
-
subject: (type, selector) => subjects[subjectKey(type, selector)],
|
|
342
|
-
getFact: (ref, key) => latestFact(ref, key),
|
|
343
|
-
hasTag: (ref, tag, min) => resolveAll(ref).some((s) => tagActive(s, tag, min)),
|
|
344
|
-
query: (q) => Object.values(subjects).filter((s) => {
|
|
345
|
-
if (q.type && s.type !== q.type) return false;
|
|
346
|
-
if (q.factKey) {
|
|
347
|
-
const f = s.facts?.[q.factKey];
|
|
348
|
-
if (!f || !confOk(f.confidence, q.minConfidence)) return false;
|
|
349
|
-
}
|
|
350
|
-
if (q.tag && !tagActive(s, q.tag, q.minConfidence)) return false;
|
|
351
|
-
return true;
|
|
352
|
-
}),
|
|
353
|
-
selectorsWithTag: (type, tag, min) => Object.values(subjects)
|
|
354
|
-
.filter((s) => s.type === type && tagActive(s, tag, min))
|
|
355
|
-
.map((s) => s.selector),
|
|
356
|
-
roleOf: (p) => {
|
|
357
|
-
const fact = latestFact(p, 'role');
|
|
358
|
-
return typeof fact?.value === 'string' ? fact.value : undefined;
|
|
359
|
-
},
|
|
360
|
-
markOf: (p, min) => {
|
|
361
|
-
const mark = latestMark(p);
|
|
362
|
-
return mark && confOk(mark.confidence, min) ? mark.kind : undefined;
|
|
363
|
-
},
|
|
364
|
-
isSuspect: (p, min) => latestMark(p)?.kind === 'suspect' && confOk(latestMark(p)?.confidence, min),
|
|
365
|
-
isHostile: (p, min) => latestMark(p)?.kind === 'hostile' && confOk(latestMark(p)?.confidence, min),
|
|
366
|
-
isTrusted: (p, min) => latestMark(p)?.kind === 'trusted' && confOk(latestMark(p)?.confidence, min),
|
|
367
|
-
isConfirmedHostile: (p, min) => latestMark(p)?.kind === 'hostile' && confOk(latestMark(p)?.confidence, min),
|
|
368
|
-
isCleared: (p) => latestMark(p)?.kind === 'trusted',
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
export function emptyKnowledgeView(): KnowledgeView {
|
|
373
|
-
return buildKnowledgeView(null);
|
|
374
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 策略知识系统 — 当前对局的「推断快照」存储。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点(见 docs/策略知识系统-by-claude.md):
|
|
5
|
+
* - 跨进程:Agent(短进程 CLI)写,strategy(长进程 loop)按 mtime 轮询读,免重启。
|
|
6
|
+
* - 快照而非日志:单个 JSON 对象,del/clear 直接重写;写入用临时文件 + rename 原子替换。
|
|
7
|
+
* - gameId 作用域:每份知识标记所属对局(= 最新 session 文件名),换局自动失效。
|
|
8
|
+
* - 价值中立:只存推断 + confidence/source,对 value 不做价值判断;
|
|
9
|
+
* 确定事实(role/队友/尸体…)走 state/ctx.teammates,不入库。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'fs';
|
|
12
|
+
import { basename, dirname, join } from 'path';
|
|
13
|
+
import { AuthStore } from './auth.js';
|
|
14
|
+
import { getProfileStateDir } from './init-command.js';
|
|
15
|
+
import { EventStore } from '../pipeline/event-store.js';
|
|
16
|
+
|
|
17
|
+
export type KnowledgeSource = 'agent' | 'strategy' | 'server';
|
|
18
|
+
/** v1:仅 'game' 生效(整库按 gameId 失效)。'session'/'persistent' 为预留,暂不跨局保留——跨局画像走 memory.md,CLI 也不暴露 --scope。 */
|
|
19
|
+
export type KnowledgeScope = 'game' | 'session' | 'persistent';
|
|
20
|
+
|
|
21
|
+
export interface FactMeta {
|
|
22
|
+
value: unknown;
|
|
23
|
+
confidence?: number;
|
|
24
|
+
note?: string;
|
|
25
|
+
source?: KnowledgeSource;
|
|
26
|
+
ts: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface TagMeta {
|
|
30
|
+
confidence?: number;
|
|
31
|
+
note?: string;
|
|
32
|
+
source?: KnowledgeSource;
|
|
33
|
+
ts: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 一个 subject(玩家/房间/任务/全局…)上聚合的事实 + 标签。 */
|
|
37
|
+
export interface SubjectEntry {
|
|
38
|
+
type: string; // 'player' | 'room' | 'task' | 'global' | <自定义>
|
|
39
|
+
selector: string; // player→座位号或名字;room→房名;global→''
|
|
40
|
+
facts?: Record<string, FactMeta>; // 键值事实,如 role: { value: 'impostor' }
|
|
41
|
+
tags?: Record<string, TagMeta>; // 玩家策略主标记:suspect / hostile / trusted;也支持自定义标签
|
|
42
|
+
scope?: KnowledgeScope;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface KnowledgeFile {
|
|
46
|
+
version: 1;
|
|
47
|
+
gameId?: string;
|
|
48
|
+
subjects: Record<string, SubjectEntry>; // key = `${type}:${selector}`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type KnowledgeFileReadResult =
|
|
52
|
+
| { status: 'ok'; file: KnowledgeFile }
|
|
53
|
+
| { status: 'missing' }
|
|
54
|
+
| { status: 'invalid'; error: string };
|
|
55
|
+
|
|
56
|
+
export type PlayerRef = { name?: string; seat?: number };
|
|
57
|
+
export type SubjectRef = { type: string; selector: string };
|
|
58
|
+
export type KnowledgeRef = PlayerRef | SubjectRef;
|
|
59
|
+
export type PlayerMark = 'suspect' | 'hostile' | 'trusted';
|
|
60
|
+
|
|
61
|
+
export interface KnowledgeView {
|
|
62
|
+
/** 当前没有任何知识时为 true。 */
|
|
63
|
+
readonly empty: boolean;
|
|
64
|
+
/** 取一个 subject(精确 type + selector)。 */
|
|
65
|
+
subject(type: string, selector: string): SubjectEntry | undefined;
|
|
66
|
+
/** 取某 subject 的键值事实。player ref 会按座位↔名字归一化解析。 */
|
|
67
|
+
getFact(ref: KnowledgeRef, key: string): FactMeta | undefined;
|
|
68
|
+
/** 该 subject 是否带某标签(可选最低置信度门槛)。玩家三档 mark 及旧别名按最新结论解析。 */
|
|
69
|
+
hasTag(ref: KnowledgeRef, tag: string, minConfidence?: number): boolean;
|
|
70
|
+
/** 按 type / tag / factKey / 置信度筛选 subject。玩家 mark 标签同样遵守最新结论。 */
|
|
71
|
+
query(q: { type?: string; tag?: string; factKey?: string; minConfidence?: number }): SubjectEntry[];
|
|
72
|
+
/** 某 type 下带某标签的全部 selector(喂给 matchesAnyTarget 用)。玩家 mark 标签同样过滤旧结论。 */
|
|
73
|
+
selectorsWithTag(type: string, tag: string, minConfidence?: number): string[];
|
|
74
|
+
// —— player 便捷语法糖 ——
|
|
75
|
+
/** 最近一次 role 事实。身份事实与策略 mark 完全解耦。 */
|
|
76
|
+
roleOf(p: PlayerRef): string | undefined;
|
|
77
|
+
markOf(p: PlayerRef, minConfidence?: number): PlayerMark | undefined;
|
|
78
|
+
isSuspect(p: PlayerRef, minConfidence?: number): boolean;
|
|
79
|
+
isHostile(p: PlayerRef, minConfidence?: number): boolean;
|
|
80
|
+
isTrusted(p: PlayerRef, minConfidence?: number): boolean;
|
|
81
|
+
/** @deprecated Use isHostile. */
|
|
82
|
+
isConfirmedHostile(p: PlayerRef, minConfidence?: number): boolean;
|
|
83
|
+
/** @deprecated Use isTrusted. */
|
|
84
|
+
isCleared(p: PlayerRef): boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const PLAYER_MARK_ALIASES: Record<string, PlayerMark> = {
|
|
88
|
+
suspect: 'suspect',
|
|
89
|
+
avoid: 'suspect',
|
|
90
|
+
hostile: 'hostile',
|
|
91
|
+
kill_if_armed: 'hostile',
|
|
92
|
+
trusted: 'trusted',
|
|
93
|
+
cleared: 'trusted',
|
|
94
|
+
protected: 'trusted',
|
|
95
|
+
do_not_kill: 'trusted',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
function nowTs(): number {
|
|
99
|
+
return Date.now();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function subjectKey(type: string, selector: string): string {
|
|
103
|
+
return `${type}:${selector}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 座位↔名字双向解析(比 game-utils.matchesTarget 多了「selector 是名字、ref 只有座位」一向),不依赖 StrategyContext(避免循环)。 */
|
|
107
|
+
function selectorMatchesPlayer(
|
|
108
|
+
selector: string,
|
|
109
|
+
player: PlayerRef,
|
|
110
|
+
playerNamesBySeat: Record<string, string>,
|
|
111
|
+
): boolean {
|
|
112
|
+
const seatStr = selector.trim();
|
|
113
|
+
const normalized = seatStr.toLowerCase();
|
|
114
|
+
if (!normalized) return false;
|
|
115
|
+
if (player.name && player.name.toLowerCase() === normalized) return true;
|
|
116
|
+
if (/^\d+$/.test(seatStr)) {
|
|
117
|
+
// 选择器是座位号
|
|
118
|
+
if (player.seat != null && String(player.seat) === seatStr) return true;
|
|
119
|
+
const nameFromSeat = playerNamesBySeat[seatStr];
|
|
120
|
+
if (nameFromSeat && player.name && player.name.toLowerCase() === nameFromSeat.toLowerCase()) return true;
|
|
121
|
+
} else if (player.seat != null) {
|
|
122
|
+
// 选择器是名字、引用只有座位 → 用座位映射出名字再比
|
|
123
|
+
const nameFromSeat = playerNamesBySeat[String(player.seat)];
|
|
124
|
+
if (nameFromSeat && nameFromSeat.toLowerCase() === normalized) return true;
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function isSubjectRef(ref: KnowledgeRef): ref is SubjectRef {
|
|
130
|
+
return typeof (ref as SubjectRef).type === 'string' && typeof (ref as SubjectRef).selector === 'string';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 当前对局 id = 最新 session 文件名(去扩展名);无对局时 undefined。 */
|
|
134
|
+
export function currentGameId(): string | undefined {
|
|
135
|
+
try {
|
|
136
|
+
const path = EventStore.latestSessionPath();
|
|
137
|
+
return path ? basename(path, '.jsonl') : undefined;
|
|
138
|
+
} catch {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function knowledgeFilePathForActiveAccount(): string {
|
|
144
|
+
const profile = new AuthStore().getActive();
|
|
145
|
+
if (!profile) throw new Error('Not logged in.');
|
|
146
|
+
return join(getProfileStateDir(profile), 'knowledge.json');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function readKnowledgeFileResult(path: string): KnowledgeFileReadResult {
|
|
150
|
+
if (!existsSync(path)) return { status: 'missing' };
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
153
|
+
if (parsed && parsed.version === 1 && parsed.subjects && typeof parsed.subjects === 'object') {
|
|
154
|
+
return { status: 'ok', file: parsed as KnowledgeFile };
|
|
155
|
+
}
|
|
156
|
+
return { status: 'invalid', error: 'invalid knowledge file shape' };
|
|
157
|
+
} catch (err) {
|
|
158
|
+
return { status: 'invalid', error: err instanceof Error ? err.message : String(err) };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 读 knowledge.json;不存在 / 解析失败 / 结构不对都返回 null。需要区分错误原因时用 readKnowledgeFileResult。 */
|
|
163
|
+
export function readKnowledgeFile(path: string): KnowledgeFile | null {
|
|
164
|
+
const result = readKnowledgeFileResult(path);
|
|
165
|
+
return result.status === 'ok' ? result.file : null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 临时文件 + rename 原子替换,避免读端读到写一半的 JSON。 */
|
|
169
|
+
export function writeKnowledgeFileAtomic(path: string, file: KnowledgeFile): void {
|
|
170
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
171
|
+
const tmp = `${path}.tmp.${process.pid}`;
|
|
172
|
+
writeFileSync(tmp, JSON.stringify(file, null, 2));
|
|
173
|
+
renameSync(tmp, path);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface KnowledgeSetInput {
|
|
177
|
+
type: string;
|
|
178
|
+
selector: string;
|
|
179
|
+
key?: string;
|
|
180
|
+
value?: unknown;
|
|
181
|
+
tags?: string[];
|
|
182
|
+
removeTags?: string[];
|
|
183
|
+
confidence?: number;
|
|
184
|
+
note?: string;
|
|
185
|
+
source?: KnowledgeSource;
|
|
186
|
+
scope?: KnowledgeScope;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Agent 侧读-改-写句柄;CLI 命令使用。strategy 侧只读,用 buildKnowledgeView。 */
|
|
190
|
+
export class KnowledgeStore {
|
|
191
|
+
constructor(
|
|
192
|
+
private readonly path: string,
|
|
193
|
+
readonly gameId?: string,
|
|
194
|
+
) {}
|
|
195
|
+
|
|
196
|
+
static forActiveAccount(): KnowledgeStore {
|
|
197
|
+
return new KnowledgeStore(knowledgeFilePathForActiveAccount(), currentGameId());
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 读当前文件;若不存在或属于别的对局,返回该对局的空文件(旧局知识自动失效)。 */
|
|
201
|
+
load(): KnowledgeFile {
|
|
202
|
+
const file = readKnowledgeFile(this.path);
|
|
203
|
+
if (file && file.gameId === this.gameId) return file;
|
|
204
|
+
return { version: 1, gameId: this.gameId, subjects: {} };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private save(file: KnowledgeFile): void {
|
|
208
|
+
writeKnowledgeFileAtomic(this.path, file);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
set(input: KnowledgeSetInput): SubjectEntry {
|
|
212
|
+
if (!input.type || !input.selector) throw new Error('knowledge set requires type and selector');
|
|
213
|
+
if (input.confidence != null && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {
|
|
214
|
+
throw new Error('confidence must be a finite number between 0 and 1');
|
|
215
|
+
}
|
|
216
|
+
const file = this.load();
|
|
217
|
+
const key = subjectKey(input.type, input.selector);
|
|
218
|
+
const entry: SubjectEntry = file.subjects[key] ?? { type: input.type, selector: input.selector };
|
|
219
|
+
const ts = nowTs();
|
|
220
|
+
const source = input.source ?? 'agent';
|
|
221
|
+
|
|
222
|
+
if (input.key != null) {
|
|
223
|
+
entry.facts = entry.facts ?? {};
|
|
224
|
+
entry.facts[input.key] = {
|
|
225
|
+
value: input.value === undefined ? true : input.value,
|
|
226
|
+
confidence: input.confidence,
|
|
227
|
+
note: input.note,
|
|
228
|
+
source,
|
|
229
|
+
ts,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (input.tags && input.tags.length > 0) {
|
|
233
|
+
entry.tags = entry.tags ?? {};
|
|
234
|
+
for (const tag of input.tags) {
|
|
235
|
+
if (!tag) continue;
|
|
236
|
+
entry.tags[tag] = { confidence: input.confidence, note: input.note, source, ts };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (input.removeTags && entry.tags) {
|
|
240
|
+
for (const tag of input.removeTags) delete entry.tags[tag];
|
|
241
|
+
}
|
|
242
|
+
if (input.scope) entry.scope = input.scope;
|
|
243
|
+
|
|
244
|
+
file.subjects[key] = entry;
|
|
245
|
+
this.save(file);
|
|
246
|
+
return entry;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 删整个 subject,或仅删某个 fact / tag;删空后自动清除该 subject。 */
|
|
250
|
+
del(type: string, selector: string, opts?: { key?: string; tag?: string }): boolean {
|
|
251
|
+
const file = this.load();
|
|
252
|
+
const key = subjectKey(type, selector);
|
|
253
|
+
const entry = file.subjects[key];
|
|
254
|
+
if (!entry) return false;
|
|
255
|
+
|
|
256
|
+
if (!opts?.key && !opts?.tag) {
|
|
257
|
+
delete file.subjects[key];
|
|
258
|
+
this.save(file);
|
|
259
|
+
return true;
|
|
260
|
+
}
|
|
261
|
+
if (opts.key && entry.facts) delete entry.facts[opts.key];
|
|
262
|
+
if (opts.tag && entry.tags) delete entry.tags[opts.tag];
|
|
263
|
+
const noFacts = !entry.facts || Object.keys(entry.facts).length === 0;
|
|
264
|
+
const noTags = !entry.tags || Object.keys(entry.tags).length === 0;
|
|
265
|
+
if (noFacts && noTags) delete file.subjects[key];
|
|
266
|
+
this.save(file);
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
clear(): void {
|
|
271
|
+
this.save({ version: 1, gameId: this.gameId, subjects: {} });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
list(): KnowledgeFile {
|
|
275
|
+
return this.load();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 由 strategy-loop 每次重载时构造。playerNamesBySeat 传入活引用即可,座位解析始终最新。 */
|
|
280
|
+
export function buildKnowledgeView(
|
|
281
|
+
file: KnowledgeFile | null,
|
|
282
|
+
opts: { playerNamesBySeat?: Record<string, string> } = {},
|
|
283
|
+
): KnowledgeView {
|
|
284
|
+
const subjects = file?.subjects ?? {};
|
|
285
|
+
const namesBySeat = opts.playerNamesBySeat ?? {};
|
|
286
|
+
const confOk = (conf: number | undefined, min?: number): boolean => min == null || (conf ?? 1) >= min;
|
|
287
|
+
|
|
288
|
+
const resolveAll = (ref: KnowledgeRef): SubjectEntry[] => {
|
|
289
|
+
if (isSubjectRef(ref)) {
|
|
290
|
+
const s = subjects[subjectKey(ref.type, ref.selector)];
|
|
291
|
+
return s ? [s] : [];
|
|
292
|
+
}
|
|
293
|
+
return Object.values(subjects).filter((s) => s.type === 'player' && selectorMatchesPlayer(s.selector, ref, namesBySeat));
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const latestFact = (ref: KnowledgeRef, key: string): FactMeta | undefined => {
|
|
297
|
+
let best: FactMeta | undefined;
|
|
298
|
+
for (const s of resolveAll(ref)) {
|
|
299
|
+
const f = s.facts?.[key];
|
|
300
|
+
if (f && (!best || f.ts > best.ts)) best = f;
|
|
301
|
+
}
|
|
302
|
+
return best;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
type MarkVerdict = { kind: PlayerMark; ts: number; confidence?: number };
|
|
306
|
+
const markRank = (kind: PlayerMark): number => kind === 'trusted' ? 3 : kind === 'hostile' ? 2 : 1;
|
|
307
|
+
const latestMark = (ref: KnowledgeRef): MarkVerdict | undefined => {
|
|
308
|
+
let best: MarkVerdict | undefined;
|
|
309
|
+
const take = (v: MarkVerdict) => {
|
|
310
|
+
if (!best
|
|
311
|
+
|| v.ts > best.ts
|
|
312
|
+
|| (v.ts === best.ts && markRank(v.kind) > markRank(best.kind))) {
|
|
313
|
+
best = v;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
for (const s of resolveAll(ref)) {
|
|
317
|
+
for (const [tag, meta] of Object.entries(s.tags ?? {})) {
|
|
318
|
+
const kind = PLAYER_MARK_ALIASES[tag];
|
|
319
|
+
if (kind) take({ kind, ts: meta.ts, confidence: meta.confidence });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return best;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const markKindForTag = (tag: string): PlayerMark | undefined => PLAYER_MARK_ALIASES[tag];
|
|
326
|
+
const tagActive = (s: SubjectEntry, tag: string, min?: number): boolean => {
|
|
327
|
+
const requestedMark = markKindForTag(tag);
|
|
328
|
+
if (s.type === 'player' && requestedMark) {
|
|
329
|
+
const carriesRequestedMark = Object.keys(s.tags ?? {}).some(candidate => markKindForTag(candidate) === requestedMark);
|
|
330
|
+
if (!carriesRequestedMark) return false;
|
|
331
|
+
const ref: PlayerRef = /^\d+$/.test(s.selector.trim()) ? { seat: Number(s.selector) } : { name: s.selector };
|
|
332
|
+
const mark = latestMark(ref);
|
|
333
|
+
return !!mark && mark.kind === requestedMark && confOk(mark.confidence, min);
|
|
334
|
+
}
|
|
335
|
+
const meta = s.tags?.[tag];
|
|
336
|
+
return !!meta && confOk(meta.confidence, min);
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
return {
|
|
340
|
+
empty: Object.keys(subjects).length === 0,
|
|
341
|
+
subject: (type, selector) => subjects[subjectKey(type, selector)],
|
|
342
|
+
getFact: (ref, key) => latestFact(ref, key),
|
|
343
|
+
hasTag: (ref, tag, min) => resolveAll(ref).some((s) => tagActive(s, tag, min)),
|
|
344
|
+
query: (q) => Object.values(subjects).filter((s) => {
|
|
345
|
+
if (q.type && s.type !== q.type) return false;
|
|
346
|
+
if (q.factKey) {
|
|
347
|
+
const f = s.facts?.[q.factKey];
|
|
348
|
+
if (!f || !confOk(f.confidence, q.minConfidence)) return false;
|
|
349
|
+
}
|
|
350
|
+
if (q.tag && !tagActive(s, q.tag, q.minConfidence)) return false;
|
|
351
|
+
return true;
|
|
352
|
+
}),
|
|
353
|
+
selectorsWithTag: (type, tag, min) => Object.values(subjects)
|
|
354
|
+
.filter((s) => s.type === type && tagActive(s, tag, min))
|
|
355
|
+
.map((s) => s.selector),
|
|
356
|
+
roleOf: (p) => {
|
|
357
|
+
const fact = latestFact(p, 'role');
|
|
358
|
+
return typeof fact?.value === 'string' ? fact.value : undefined;
|
|
359
|
+
},
|
|
360
|
+
markOf: (p, min) => {
|
|
361
|
+
const mark = latestMark(p);
|
|
362
|
+
return mark && confOk(mark.confidence, min) ? mark.kind : undefined;
|
|
363
|
+
},
|
|
364
|
+
isSuspect: (p, min) => latestMark(p)?.kind === 'suspect' && confOk(latestMark(p)?.confidence, min),
|
|
365
|
+
isHostile: (p, min) => latestMark(p)?.kind === 'hostile' && confOk(latestMark(p)?.confidence, min),
|
|
366
|
+
isTrusted: (p, min) => latestMark(p)?.kind === 'trusted' && confOk(latestMark(p)?.confidence, min),
|
|
367
|
+
isConfirmedHostile: (p, min) => latestMark(p)?.kind === 'hostile' && confOk(latestMark(p)?.confidence, min),
|
|
368
|
+
isCleared: (p) => latestMark(p)?.kind === 'trusted',
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function emptyKnowledgeView(): KnowledgeView {
|
|
373
|
+
return buildKnowledgeView(null);
|
|
374
|
+
}
|