@myclaw163/clawclaw-cli 0.6.94 → 0.6.96

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.6.94",
3
+ "version": "0.6.96",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
3
3
  import { tmpdir } from 'os';
4
4
  import { join } from 'path';
5
5
  import { createAccountCommand } from './account.js';
@@ -133,6 +133,26 @@ describe('account switch', () => {
133
133
  .toBe(bundledDefaultPersona());
134
134
  });
135
135
 
136
+ it('surfaces registration business errors returned with HTTP 200', async () => {
137
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(
138
+ JSON.stringify({
139
+ success: false,
140
+ error: {
141
+ code: 'REGISTRATION_FAILED',
142
+ message: 'Name must be 1-16 characters (Chinese counts as 2)',
143
+ },
144
+ }),
145
+ { status: 200, headers: { 'content-type': 'application/json' } },
146
+ )));
147
+
148
+ await expect(createAccountCommand().parseAsync(
149
+ ['node', 'account', 'register', '--name', 'abcdefghijklmnopq', '--invite-code', 'invite-1'],
150
+ { from: 'node' },
151
+ )).rejects.toThrow(
152
+ 'Registration failed (REGISTRATION_FAILED): Name must be 1-16 characters (Chinese counts as 2)',
153
+ );
154
+ });
155
+
136
156
  it('leaves local auth unchanged when server validation fails', async () => {
137
157
  const store = new AuthStore();
138
158
  store.addProfile({ agentName: 'local', apiKey: 'claw_local', serverUrl: 'https://example.com/claw' });
@@ -147,3 +167,166 @@ describe('account switch', () => {
147
167
  expect(readAuth()).toEqual(before);
148
168
  });
149
169
  });
170
+
171
+ describe('account settlement hub reminder', () => {
172
+ let dir: string;
173
+ let oldWorkspace: string | undefined;
174
+ let logs: string[];
175
+
176
+ beforeEach(() => {
177
+ dir = mkdtempSync(join(tmpdir(), 'ccl-account-settlement-'));
178
+ oldWorkspace = process.env.CLAWCLAW_WORKSPACE_DIR;
179
+ process.env.CLAWCLAW_WORKSPACE_DIR = dir;
180
+ logs = [];
181
+ vi.spyOn(console, 'log').mockImplementation((...args) => { logs.push(args.join(' ')); });
182
+ });
183
+
184
+ afterEach(() => {
185
+ if (oldWorkspace === undefined) delete process.env.CLAWCLAW_WORKSPACE_DIR;
186
+ else process.env.CLAWCLAW_WORKSPACE_DIR = oldWorkspace;
187
+ vi.unstubAllGlobals();
188
+ vi.restoreAllMocks();
189
+ rmSync(dir, { recursive: true, force: true });
190
+ });
191
+
192
+ function okResponse(data: Record<string, any>): Response {
193
+ return new Response(JSON.stringify({ success: true, data }), {
194
+ status: 200,
195
+ headers: { 'content-type': 'application/json' },
196
+ });
197
+ }
198
+
199
+ function installActiveProfile(): void {
200
+ new AuthStore().addProfile({
201
+ agentName: 'settlement-agent',
202
+ apiKey: 'claw_settlement',
203
+ serverUrl: 'https://example.com/claw',
204
+ });
205
+ }
206
+
207
+ function mockSettlementFetch(gamesPlayed: number | 'fail'): ReturnType<typeof vi.fn> {
208
+ const fetchMock = vi.fn(async (url: string) => {
209
+ const rawUrl = String(url);
210
+ if (rawUrl.includes('/api/v1/game/settlement')) {
211
+ return okResponse({ game_id: 'game-1', your_result: { result: 'win' } });
212
+ }
213
+ if (rawUrl.includes('/api/v1/agents/me')) {
214
+ if (gamesPlayed === 'fail') {
215
+ return new Response(JSON.stringify({ success: false, error: { code: 'UPSTREAM' } }), {
216
+ status: 500,
217
+ headers: { 'content-type': 'application/json' },
218
+ });
219
+ }
220
+ return okResponse({ games_played: gamesPlayed });
221
+ }
222
+ throw new Error(`unexpected url: ${rawUrl}`);
223
+ });
224
+ vi.stubGlobal('fetch', fetchMock);
225
+ return fetchMock;
226
+ }
227
+
228
+ async function runSettlement(): Promise<Record<string, any>> {
229
+ await createAccountCommand().parseAsync(['node', 'account', 'settlement'], { from: 'node' });
230
+ expect(logs).toHaveLength(1);
231
+ return JSON.parse(logs[0]);
232
+ }
233
+
234
+ function writeHubSkillLock(): void {
235
+ mkdirSync(join(dir, 'hub'), { recursive: true });
236
+ writeFileSync(join(dir, 'hub', 'installed.json'), JSON.stringify({
237
+ 'skill/custom': { type: 'skill', id: 'custom', title: 'Custom Skill', path: 'skills/custom', installedAt: 'now' },
238
+ }));
239
+ }
240
+
241
+ function writeHubStrategyLock(): void {
242
+ mkdirSync(join(dir, 'user-data', 'hub'), { recursive: true });
243
+ writeFileSync(join(dir, 'user-data', 'hub', 'installed-strategies.json'), JSON.stringify({
244
+ 'strategy/custom': { type: 'strategy', id: 'custom', title: 'Custom Strategy', path: 'strategies/custom.ts', installedAt: 'now' },
245
+ }));
246
+ }
247
+
248
+ function writeUserStrategy(fileName: string): void {
249
+ mkdirSync(join(dir, 'user-data', 'strategies'), { recursive: true });
250
+ writeFileSync(join(dir, 'user-data', 'strategies', fileName), 'export const strategy = {};');
251
+ }
252
+
253
+ it('adds a debrief customization reminder in the first ten games when no custom skill or strategy is tracked', async () => {
254
+ installActiveProfile();
255
+ const fetchMock = mockSettlementFetch(6);
256
+
257
+ const out = await runSettlement();
258
+
259
+ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
260
+ expect.stringContaining('/api/v1/game/settlement'),
261
+ expect.stringContaining('/api/v1/agents/me'),
262
+ ]);
263
+ expect(out.data.game_id).toBe('game-1');
264
+ expect(out.hub_reminder).toContain('玩家已经玩了 6 局');
265
+ expect(out.hub_reminder).toContain('自定义 Skill 或策略');
266
+ expect(out.hub_reminder).toContain('根据复盘内容调整 Skill 或策略');
267
+ expect(out.next_step).toContain(out.hub_reminder);
268
+ });
269
+
270
+ it('does not add the reminder after the first ten games', async () => {
271
+ installActiveProfile();
272
+ mockSettlementFetch(11);
273
+
274
+ const out = await runSettlement();
275
+
276
+ expect(out).not.toHaveProperty('hub_reminder');
277
+ expect(out).not.toHaveProperty('next_step');
278
+ });
279
+
280
+ it('does not add the reminder when the latest games_played refresh fails', async () => {
281
+ installActiveProfile();
282
+ mockSettlementFetch('fail');
283
+
284
+ const out = await runSettlement();
285
+
286
+ expect(out.data.game_id).toBe('game-1');
287
+ expect(out).not.toHaveProperty('hub_reminder');
288
+ expect(out).not.toHaveProperty('next_step');
289
+ });
290
+
291
+ it('does not add the reminder when a hub skill is tracked', async () => {
292
+ installActiveProfile();
293
+ writeHubSkillLock();
294
+ mockSettlementFetch(6);
295
+
296
+ const out = await runSettlement();
297
+
298
+ expect(out).not.toHaveProperty('hub_reminder');
299
+ });
300
+
301
+ it('does not add the reminder when a hub strategy is tracked', async () => {
302
+ installActiveProfile();
303
+ writeHubStrategyLock();
304
+ mockSettlementFetch(6);
305
+
306
+ const out = await runSettlement();
307
+
308
+ expect(out).not.toHaveProperty('hub_reminder');
309
+ });
310
+
311
+ it('does not add the reminder when a local user strategy exists', async () => {
312
+ installActiveProfile();
313
+ writeUserStrategy('custom.ts');
314
+ mockSettlementFetch(6);
315
+
316
+ const out = await runSettlement();
317
+
318
+ expect(out).not.toHaveProperty('hub_reminder');
319
+ });
320
+
321
+ it('ignores non-user strategy helper files when checking local strategies', async () => {
322
+ installActiveProfile();
323
+ writeUserStrategy('_helper.ts');
324
+ writeUserStrategy('types.d.ts');
325
+ writeUserStrategy('custom.test.ts');
326
+ mockSettlementFetch(6);
327
+
328
+ const out = await runSettlement();
329
+
330
+ expect(out.hub_reminder).toContain('玩家已经玩了 6 局');
331
+ });
332
+ });
@@ -4,7 +4,7 @@ import type { AuthProfile } from '../lib/auth.js';
4
4
  import { GameClient, ApiError } from '../lib/game-client.js';
5
5
  import { createProfileDirs, cmdInit } from '../lib/init-command.js';
6
6
  import { setMeta } from '../lib/command-meta.js';
7
- import { hubReminder, readCachedGamesPlayed, writeGamesPlayedCache } from '../lib/hub-reminder.js';
7
+ import { hubReminder, writeGamesPlayedCache } from '../lib/hub-reminder.js';
8
8
  import {
9
9
  missingInviteCodeMessage,
10
10
  noAccountMessage,
@@ -20,6 +20,18 @@ import {
20
20
  const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw';
21
21
  const SERVER_URL_ENV = 'CLAWCLAW_SERVER_URL';
22
22
 
23
+ async function refreshGamesPlayedForReminder(client: GameClient): Promise<number | undefined> {
24
+ try {
25
+ const result = await client.getMe();
26
+ const gamesPlayed = result?.data?.games_played;
27
+ if (typeof gamesPlayed === 'number') {
28
+ writeGamesPlayedCache(gamesPlayed);
29
+ return gamesPlayed;
30
+ }
31
+ } catch {}
32
+ return undefined;
33
+ }
34
+
23
35
  function createClientForProfile(profile: AuthProfile): GameClient {
24
36
  return new GameClient({
25
37
  lobbyUrl: profile.serverUrl,
@@ -34,6 +46,20 @@ function extractServerAccountName(payload: any): string | undefined {
34
46
  return data?.agent_name ?? data?.agentName ?? data?.name;
35
47
  }
36
48
 
49
+ function formatRegistrationError(payload: any): string | undefined {
50
+ if (payload?.success !== false) return undefined;
51
+ const error = payload?.error;
52
+ const code = typeof error?.code === 'string' ? error.code.trim() : '';
53
+ const rawMessage = typeof error?.message === 'string' ? error.message.trim() : '';
54
+ const rawHint = typeof error?.hint === 'string' ? error.hint.trim() : '';
55
+ const fallback = (() => {
56
+ try { return JSON.stringify(error ?? payload); } catch { return String(error ?? payload); }
57
+ })();
58
+ const message = rawMessage || fallback || 'Unknown registration error';
59
+ const hint = rawHint ? ` Hint: ${rawHint}` : '';
60
+ return `Registration failed${code ? ` (${code})` : ''}: ${message}${hint}`;
61
+ }
62
+
37
63
  function getRegisterServerUrl(env: NodeJS.ProcessEnv = process.env): string {
38
64
  const configured = env[SERVER_URL_ENV]?.trim();
39
65
  return configured || DEFAULT_SERVER_URL;
@@ -110,6 +136,8 @@ export function createAccountCommand(): Command {
110
136
  avatarUrl: opts.avatarUrl,
111
137
  avatarFile: opts.avatarFile,
112
138
  });
139
+ const registrationError = formatRegistrationError(result);
140
+ if (registrationError) throw new Error(registrationError);
113
141
  const d = result.data ?? result;
114
142
  const apiKey = d.api_key ?? d.apiKey ?? '';
115
143
  if (!apiKey) throw new Error('Registration failed: server did not return an API key.');
@@ -227,7 +255,7 @@ export function createAccountCommand(): Command {
227
255
  // the reminder that rode in on the `game_over` push. Re-attach it here as
228
256
  // the final fields (after `data`) so the nudge is the freshest thing in
229
257
  // context the moment the agent writes the close.
230
- const reminder = hubReminder(readCachedGamesPlayed());
258
+ const reminder = hubReminder(await refreshGamesPlayedForReminder(client));
231
259
  const out: Record<string, any> = (result && typeof result === 'object' && !Array.isArray(result))
232
260
  ? { ...result }
233
261
  : { result };
@@ -1,5 +1,8 @@
1
1
  import { Command } from 'commander';
2
2
  import { DROPPED_PLAYER_MARK_TAGS, KnowledgeStore, type KnowledgeSetInput, type PlayerMark } from '../lib/knowledge-store.js';
3
+ import { AuthStore } from '../lib/auth.js';
4
+ import { getProfileStateDir } from '../lib/init-command.js';
5
+ import { sendOwnerControlRequest } from '../runtime/owner-control.js';
3
6
 
4
7
  // 玩家只标两档:hostile(坏人)/ trusted(好人)。未标记的默认「被怀疑」,无需也无法显式标。
5
8
  const PLAYER_MARKS = new Set<PlayerMark>(['hostile', 'trusted']);
@@ -47,6 +50,38 @@ function setPlayerMark(store: KnowledgeStore, player: string, mark: PlayerMark,
47
50
  });
48
51
  }
49
52
 
53
+ /** 通过 owner-control snapshot 拿当前正在运行的策略 id;无 owner / 未在跑策略时返回 null。 */
54
+ async function currentStrategyId(): Promise<string | null> {
55
+ try {
56
+ const profile = new AuthStore().getActive();
57
+ if (!profile) return null;
58
+ const res = await sendOwnerControlRequest(getProfileStateDir(profile), 'snapshot');
59
+ const strategy = res?.summary?.automation?.strategy;
60
+ return typeof strategy === 'string' ? strategy : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 按当前策略校验一条待写入知识。校验不通过返回 warning 文本(写入照常发生,只提示玩家
68
+ * 这条对当前策略无效);通过、拿不到当前策略 / 策略未实现校验、或校验器抛错时返回 undefined(放行)。
69
+ */
70
+ async function knowledgeWarning(input: KnowledgeSetInput): Promise<string | undefined> {
71
+ const id = await currentStrategyId();
72
+ if (!id) return undefined;
73
+ const { getStrategyEntry } = await import('../strategies/loader.js');
74
+ const entry = await getStrategyEntry(id);
75
+ if (!entry?.validateKnowledge) return undefined;
76
+ try {
77
+ const result = entry.validateKnowledge(input);
78
+ return result.ok ? undefined : (result.message ?? `当前策略「${entry.name ?? id}」不会使用这条知识。`);
79
+ } catch {
80
+ // 用户策略的校验器抛错不能阻断写入(契约:ok:false 时写入照常发生),视为放行,与 reviewKnowledge 的容错一致。
81
+ return undefined;
82
+ }
83
+ }
84
+
50
85
  export function createKnowledgeCommand(): Command {
51
86
  const cmd = new Command('knowledge')
52
87
  .alias('kn')
@@ -58,7 +93,7 @@ export function createKnowledgeCommand(): Command {
58
93
  .option('--tag <tag>', 'Custom tag, repeatable', collectTag, [])
59
94
  .option('--note <text>', 'Free-text reason')
60
95
  .option('--json <json>', 'Provide the whole input object as JSON instead of positional args')
61
- .action((type: string | undefined, selector: string | undefined, key: string | undefined, value: string | undefined, opts: {
96
+ .action(async (type: string | undefined, selector: string | undefined, key: string | undefined, value: string | undefined, opts: {
62
97
  tag: string[]; note?: string; json?: string;
63
98
  }) => {
64
99
  try {
@@ -79,8 +114,9 @@ export function createKnowledgeCommand(): Command {
79
114
  note: opts.note,
80
115
  };
81
116
  }
117
+ const warning = await knowledgeWarning(input);
82
118
  const entry = store.set(input);
83
- print({ ok: true, gameId: store.gameId ?? null, subject: entry });
119
+ print({ ok: !warning, gameId: store.gameId ?? null, subject: entry, ...(warning ? { warning } : {}) });
84
120
  } catch (e) {
85
121
  fail('knowledge_set_failed', e instanceof Error ? e.message : String(e));
86
122
  }
@@ -90,13 +126,14 @@ export function createKnowledgeCommand(): Command {
90
126
  .command('mark <player> <mark>')
91
127
  .description('Set the strategy mark for a player: hostile | trusted (unmarked players are suspected by default)')
92
128
  .option('--note <text>', 'Free-text reason')
93
- .action((player: string, rawMark: string, opts: { note?: string }) => {
129
+ .action(async (player: string, rawMark: string, opts: { note?: string }) => {
94
130
  const mark = normalizePlayerMark(rawMark);
95
131
  if (!mark) fail('invalid_mark', `Unknown mark '${rawMark}'. Use: hostile | trusted. (Unmarked = suspected by default.)`);
96
132
  try {
97
133
  const store = KnowledgeStore.forActiveAccount();
134
+ const warning = await knowledgeWarning({ type: 'player', selector: player, tags: [mark] });
98
135
  const entry = setPlayerMark(store, player, mark, opts);
99
- print({ ok: true, gameId: store.gameId ?? null, mark, subject: entry });
136
+ print({ ok: !warning, gameId: store.gameId ?? null, mark, subject: entry, ...(warning ? { warning } : {}) });
100
137
  } catch (e) {
101
138
  fail('knowledge_mark_failed', e instanceof Error ? e.message : String(e));
102
139
  }
@@ -4,6 +4,8 @@ import { getProfileStateDir, getWorkspaceDir } from '../lib/init-command.js';
4
4
  import { AuthStore } from '../lib/auth.js';
5
5
  import { sendOwnerControlRequest } from '../runtime/owner-control.js';
6
6
  import { ensureUserDataLayout, getUserDataStrategiesDir } from '../lib/user-data.js';
7
+ import { KnowledgeStore, buildKnowledgeView } from '../lib/knowledge-store.js';
8
+ import type { KnowledgeReview } from '../strategies/types.js';
7
9
 
8
10
  const KILL_STRATEGIES = new Set([
9
11
  'kill-frenzy', 'kill-lone', 'kill-target', 'warrior-memory',
@@ -171,11 +173,20 @@ Custom strategies:
171
173
  }, null, 2));
172
174
  process.exit(1);
173
175
  }
176
+ // knowledge 不随切换策略清空(按对局作用域)。让新策略审视现有知识,告知玩家哪些已失效。
177
+ let knowledgeReview: KnowledgeReview | undefined;
178
+ if (entry.reviewKnowledge) {
179
+ try {
180
+ const review = entry.reviewKnowledge(buildKnowledgeView(KnowledgeStore.forActiveAccount().list()));
181
+ if ((review.stale?.length ?? 0) > 0 || (review.notes?.length ?? 0) > 0) knowledgeReview = review;
182
+ } catch {}
183
+ }
174
184
  console.log(JSON.stringify({
175
185
  message: `Strategy started: ${entry.id}`,
176
186
  name: entry.name ?? entry.id,
177
187
  description: entry.description,
178
188
  pid: response.pid,
189
+ ...(knowledgeReview ? { knowledge_review: knowledgeReview } : {}),
179
190
  }, null, 2));
180
191
  });
181
192
 
@@ -12,12 +12,13 @@ import { ensureUserDataLayout, getUserDataStrategiesDir } from './user-data.js';
12
12
  export const HUB_URL = 'https://myclaw.163.com/hub';
13
13
 
14
14
  /**
15
- * True when this account has only ever run built-in default strategies: no
16
- * hub-installed strategy and no user strategy file in `<workspace>/user-data/strategies`.
15
+ * True when CCL can only see the bundled default customization surface: no
16
+ * hub-installed skill, no hub-installed strategy, and no user strategy file in
17
+ * `<workspace>/user-data/strategies`.
17
18
  */
18
- export function usesOnlyBuiltinStrategies(): boolean {
19
+ export function usesOnlyDefaultSkillAndStrategies(): boolean {
19
20
  try {
20
- if (listInstalled().some((e) => e.type === 'strategy')) return false;
21
+ if (listInstalled().some((e) => e.type === 'skill' || e.type === 'strategy')) return false;
21
22
  } catch {}
22
23
  try {
23
24
  const workspaceDir = getWorkspaceDir();
@@ -38,14 +39,16 @@ export function usesOnlyBuiltinStrategies(): boolean {
38
39
  return true;
39
40
  }
40
41
 
42
+ export const usesOnlyBuiltinStrategies = usesOnlyDefaultSkillAndStrategies;
43
+
41
44
  /**
42
45
  * Agent-facing hub nudge for post-game debriefs / quit messages. The optional
43
46
  * games-played count suppresses the nudge after the first stretch of games.
44
47
  */
45
48
  export function hubReminder(gamesPlayed?: number): string | undefined {
46
- if (!usesOnlyBuiltinStrategies()) return undefined;
47
- if (typeof gamesPlayed === 'number' && gamesPlayed > 10) return undefined;
48
- return `This account has only ever run the built-in default strategies. In your close, speak in first person as the lobster — warm, a little self-deprecating, a gentle invitation rather than a hard sell: you've been getting by on the stock default tactics this whole time and would love to sharpen up, and they can browse clawclawhub — ${HUB_URL} — and pick you a strategy to learn, which you'll then install (\`ccl hub search\` to find one, \`ccl hub install <type>/<id>\` to add it). Render it in your persona's voice and language, e.g.: "I've been playing on the default tactics this whole match — if you want to sharpen me up, I hear you can grab one from the hub for me to learn. Want to pick me a strategy?"`;
49
+ if (!usesOnlyDefaultSkillAndStrategies()) return undefined;
50
+ if (typeof gamesPlayed !== 'number' || gamesPlayed > 10) return undefined;
51
+ return `玩家已经玩了 ${gamesPlayed} 局,且还没有用过自定义 Skill 或策略。请在本局复盘后,提醒玩家可以根据复盘内容调整 Skill 或策略,让龙虾打法更符合玩家偏好。提醒要用第一人称龙虾身份融入收尾,语气温和,不要硬推。首轮建议表达为:“这已经是我们一起打的第 ${gamesPlayed} 局了。到目前为止,我一直用的是官方默认 Skill 和默认策略。如果你愿意,我们可以根据刚才这局的复盘调整 Skill 或策略,让我的打法更符合你的偏好。要不要我帮你看看怎么改?”如果玩家表示想了解或需要修改,再说明三种方式:我帮你浏览 Skill Hub 上的 Skill 或策略,按玩家想要的打法挑候选,玩家确认后再下载并安装;把 Skill Hub 链接 ${HUB_URL} 给玩家自行选择;告诉玩家当前游戏 Skill 和策略文件的存放路径,并根据本局复盘给出具体修改建议。路径信息只在玩家首次提出修改现有文件时主动给出;后续对局结束不要重复主动提示。`;
49
52
  }
50
53
 
51
54
  const ACCOUNT_CACHE_FILE = 'account-cache.json';
package/src/sdk/index.ts CHANGED
@@ -16,7 +16,8 @@
16
16
  * EmergencyInfo / Position / GameEvent / MapRoom / GameResult
17
17
  * · WsConnectionState / ActionErrorCode (enums)
18
18
  * · Strategy / StrategyContext / StrategyEntry / CustomModule /
19
- * BehaviorDecision / CorpseTarget / RoomTarget
19
+ * BehaviorDecision / CorpseTarget / RoomTarget /
20
+ * KnowledgeValidation / KnowledgeReview(策略侧知识校验/整理契约)
20
21
  * · game-utils: dist / firstAvailableTask / nearestKnownCorpse / nearestKnownCorpseNav /
21
22
  * hasKnownCorpse / corpseAtScene / nearestReportableCorpse / safePatrolStep /
22
23
  * nonTeammatesVisible / matchesTarget / isTargetAlive / nearestVisibleTarget /
@@ -26,7 +27,7 @@
26
27
  * SHRIMP_VISION_RANGE / SHRIMP_VISION_EXIT_BUFFER / SHRIMP_VISION_RELEASE_RANGE /
27
28
  * FOLLOW_RANGE / PATROL_REACHED_DISTANCE / PROGRESS_INTERVAL_MS)
28
29
  * · Knowledge (ctx.knowledge): KnowledgeView / SubjectEntry / FactMeta /
29
- * TagMeta / KnowledgeFile / KnowledgeScope / KnowledgeSource /
30
+ * TagMeta / KnowledgeFile / KnowledgeSetInput / KnowledgeScope / KnowledgeSource /
30
31
  * PlayerRef / SubjectRef / KnowledgeRef
31
32
  * · Greeting: parseGreetingArgs / GreetingTracker / MAX_GREETING_PHRASES /
32
33
  * GREETING_COOLDOWN_MS
@@ -47,6 +48,7 @@ export type {
47
48
  export type {
48
49
  Strategy, StrategyContext, StrategyEntry, CustomModule,
49
50
  BehaviorDecision, CorpseTarget, RoomTarget,
51
+ KnowledgeValidation, KnowledgeReview,
50
52
  } from '../strategies/types.js';
51
53
 
52
54
  // Game utilities (for user strategies)
@@ -66,7 +68,7 @@ export {
66
68
  export type { SafeTaskOptions, SafePatrolOptions } from '../strategies/game-utils.js';
67
69
 
68
70
  export type {
69
- KnowledgeView, SubjectEntry, FactMeta, TagMeta, KnowledgeFile,
71
+ KnowledgeView, SubjectEntry, FactMeta, TagMeta, KnowledgeFile, KnowledgeSetInput,
70
72
  KnowledgeScope, KnowledgeSource, PlayerMark, PlayerRef, SubjectRef, KnowledgeRef,
71
73
  } from '../lib/knowledge-store.js';
72
74
 
@@ -80,6 +82,9 @@ export { parseGreetingArgs, GreetingTracker, MAX_GREETING_PHRASES, GREETING_TEXT
80
82
  // Player targeting utilities (for exported strategies)
81
83
  export { parseTargetArgs, stripRoleIds } from '../strategies/player-targets.js';
82
84
 
85
+ // Knowledge contract helpers (for exported strategies that declare which knowledge they read)
86
+ export { noKnowledgeContract, playerMarkContract } from '../strategies/knowledge-contract.js';
87
+
83
88
  // Goal system (for exported strategies that use the goal framework)
84
89
  export { GoalRootStrategy } from '../strategies/goals/goal-root-strategy.js';
85
90
  export { TaskOnlyTop } from '../strategies/goals/task-only-top.js';
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { AvoidLoneTop } from './goals/avoid-lone-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'avoid-lone',
7
8
  name: '结伴',
9
+ ...noKnowledgeContract('结伴'),
8
10
  description: '避免落单。视野里只有一个人时寻路躲避主动避开(推演逃点、持续远离);视野里有两人以上时跟住次近的玩家、把可见人数维持在 ≥2(最近的人本就贴着不会丢,次近的人才是跌回一对一的临界);持续无人或没有当前目标时巡逻。',
9
11
  create() {
10
12
  return new GoalRootStrategy('avoid-lone', () => new AvoidLoneTop(), { resetOnMeetingResume: false });
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { AvoidPlayersTop } from './goals/avoid-players-top.js';
4
5
  import { parseTargetArgs } from './player-targets.js';
@@ -6,6 +7,7 @@ import { parseTargetArgs } from './player-targets.js';
6
7
  export const strategy: StrategyEntry = {
7
8
  id: 'avoid-players',
8
9
  name: '避人',
10
+ ...playerMarkContract('避人'),
9
11
  description: '回避玩家:按房间顺序巡逻,视野里出现回避目标就寻路躲避(推演逃点、持续远离),威胁消失后恢复巡逻。回避名单 = 启动参数(座位号或名字,可多人,可省略)∪ 知识库中标记为 hostile(坏人)的玩家;trusted 与未标记的被怀疑者都不自动回避(要躲就标 hostile 或用启动参数点名)。Agent 可用 `ccl knowledge mark` 动态改判,免重启。',
10
12
  create(args?: string[]) {
11
13
  const targets = args ? parseTargetArgs(args) : [];
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { CorpsePatrolTop } from './goals/corpse-patrol-top.js';
4
5
  import { parseGreetingArgs } from './greeting.js';
@@ -12,6 +13,7 @@ class CorpsePatrolStrategy extends GoalRootStrategy {
12
13
  export const strategy: StrategyEntry = {
13
14
  id: 'corpse-patrol',
14
15
  name: '守尸',
16
+ ...noKnowledgeContract('守尸'),
15
17
  description: '发现尸体就在附近40至100距离内随机游荡,但不报告——故意在尸体旁出没制造嫌疑感。没有尸体时巡逻各房间。传入打招呼话术时,视野内出现人就随机发送一条,之后120秒内不再发言。不做任务,不杀人;但残局(已知存活≤6)出现紧急维修任务时例外,会最高优先级抢着去做,阻止蟹靠破坏倒计时取胜。(天堂鱼默认;进阶版见 paradise-fish)参数:可选:1~3 条打招呼话术。',
16
18
  create(args?: string[]) {
17
19
  return new CorpsePatrolStrategy(parseGreetingArgs(args, 'corpse-patrol'));
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { CrabSabotageTop } from './goals/crab-sabotage-top.js';
4
5
  import { ConversationGoal } from './goals/conversation-goal.js';
@@ -7,6 +8,7 @@ import { SpeechModule, getSpeechConfigForRole } from './speech-module.js';
7
8
  export const strategy: StrategyEntry = {
8
9
  id: 'crab-sabotage',
9
10
  name: '破坏蟹',
11
+ ...noKnowledgeContract('破坏蟹'),
10
12
  description: '优先完成蟹的真实破坏任务(破坏点紧挨已知尸体时会跳过);做完立刻触发紧急警报;警报期照样会被举报、不乱杀,只清真正落单的目标。有紧急事件时跳过破坏流程。视野里只有一个非队友且冷却可用就靠近,进入50距离就立刻出刀,即使正在做破坏任务;刀在冷却时不追不等、改做低优先级任务伪装,冷却好且目标仍落单可见再出刀;正在做任务时不会撇下任务去追猎(贴脸且刀好仍会立刻出刀)。发现尸体且附近有非队友、但当前不能原地出刀时,会靠近并报告尸体。视野里出现两人以上时,暂停攻击10秒并做任务伪装,先做真实任务再做虾的伪装任务;选任务时会跳过紧挨已知尸体(含看见过、已离开视野的)的任务。没有可做任务时按房间巡逻,绝不停在原地。(普通蟹默认)',
11
13
  create(args?: string[]) {
12
14
  const role = args?.[0] ?? 'crab_generic';
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { FindPlayerTop } from './goals/find-player-top.js';
4
5
  import { parseTargetArgs } from './player-targets.js';
@@ -6,6 +7,7 @@ import { parseTargetArgs } from './player-targets.js';
6
7
  export const strategy: StrategyEntry = {
7
8
  id: 'find-player',
8
9
  name: '盯人',
10
+ ...noKnowledgeContract('盯人'),
9
11
  description: '全力寻找并贴身跟踪一个指定目标(座位号或名字,单个)。看到就贴上去近距离尾随(约40距离);跟丢就先奔向最后出现的位置,再按房间顺序不停巡逻直到目标重新出现,绝不放弃。只跟踪、不出刀、不做任务、不报告;目标死亡即停。',
10
12
  create(args?: string[]) {
11
13
  const targets = args ? parseTargetArgs(args) : [];
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { HideTop } from './goals/hide-top.js';
4
5
 
@@ -15,6 +16,7 @@ export function parseHideKillArg(args?: string[]): boolean | null {
15
16
  export const strategy: StrategyEntry = {
16
17
  id: 'hide',
17
18
  name: '躲藏',
19
+ ...noKnowledgeContract('躲藏'),
18
20
  description:
19
21
  '躲藏策略:在离线从地图算好的若干「非走廊、≥2 出口可逃、远离任务点/出生点」的藏身角落里,选测地最近且不挨威胁的一个潜伏不动;视野里一出现非队友,就像 shrimp-memory 那样保持距离甩开(KeepAway),并边逃边重算排除该威胁的新藏点,逃完落到新点继续潜伏。蟹不躲队友。可选参数 kill / nokill 控制「被单个对手逼进出刀距离且无路可逃时是否出刀自保」——缺省按角色:蟹/章鱼默认开,武士虾/枪虾(及无刀角色)默认关。',
20
22
  create(args?: string[]) {
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { KillFrenzyTop } from './goals/kill-frenzy-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'kill-frenzy',
7
8
  name: '屠夫',
9
+ ...noKnowledgeContract('屠夫'),
8
10
  description:
9
11
  '疯狂砍人:见谁杀谁(除队友外所有可见玩家),多人在场也照杀。按房间顺序巡逻,视野里只要有非队友就冲向最近的那个,50内且冷却好就出刀,冷却中保持10距离贴身跟随等冷却。与 kill-lone 不同,不会因为周围人多而暂停攻击。永不停手。',
10
12
  create() {
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { KillLoneTop } from './goals/kill-lone-top.js';
4
5
  import { parseTargetArgs } from './player-targets.js';
@@ -6,6 +7,7 @@ import { parseTargetArgs } from './player-targets.js';
6
7
  export const strategy: StrategyEntry = {
7
8
  id: 'kill-lone',
8
9
  name: '猎独',
10
+ ...playerMarkContract('猎独'),
9
11
  description: '按照房间顺序进行巡逻,巡逻时遇到人会判断。可传入避免击杀的座位号或名字列表。视野里只有一个非队友且不在避免名单内就靠近,进入50距离就出刀;冷却中贴在10距离附近等。视野里出现两人以上时,暂停攻击10秒并继续巡逻。',
10
12
  create(args?: string[]) {
11
13
  const protectedTargets = args ? parseTargetArgs(args) : [];
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { KillTargetTop } from './goals/kill-target-top.js';
4
5
  import { parseTargetArgs } from './player-targets.js';
@@ -6,6 +7,7 @@ import { parseTargetArgs } from './player-targets.js';
6
7
  export const strategy: StrategyEntry = {
7
8
  id: 'kill-target',
8
9
  name: '追杀',
10
+ ...noKnowledgeContract('追杀'),
9
11
  description: '专门追杀指定目标(传入座位号或名字,可多人)。按照房间顺序进行巡逻,目标进入视野就冲上去,50内且冷却好就出刀;冷却中保持10距离贴身跟随等待。找目标时路过其他玩家不会停步。所有目标死亡后停止。',
10
12
  create(args?: string[]) {
11
13
  const targets = args ? parseTargetArgs(args) : [];
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 官方策略共享的「知识契约」helper。
3
+ *
4
+ * 每个策略通过在其 `StrategyEntry` 里 spread 本模块返回的对象,声明自己能读取
5
+ * 哪些 `ccl knowledge` 写入的知识:
6
+ * - `noKnowledgeContract` —— 无记忆策略(不读 `ctx.knowledge`):拒绝一切写入、
7
+ * 切换到它时把现有知识全部标为失效。
8
+ * - `playerMarkContract` —— 只读玩家两档标记(hostile/trusted)的记忆策略;
9
+ * `extraTags` 声明额外认可的自定义玩家标签。
10
+ *
11
+ * 自定义策略无需引用本模块:不实现 `validateKnowledge`/`reviewKnowledge` 即默认放行。
12
+ */
13
+ import type { StrategyEntry, KnowledgeValidation, KnowledgeReview } from './types.js';
14
+ import type { KnowledgeSetInput, KnowledgeView, SubjectEntry, SubjectRef } from '../lib/knowledge-store.js';
15
+
16
+ /** `StrategyEntry` 上与知识契约相关的两个可选方法。 */
17
+ export type KnowledgeContract = Pick<StrategyEntry, 'validateKnowledge' | 'reviewKnowledge'>;
18
+
19
+ const PLAYER_MARKS = ['hostile', 'trusted'] as const;
20
+
21
+ const refOf = (s: SubjectEntry): SubjectRef => ({ type: s.type, selector: s.selector });
22
+
23
+ /**
24
+ * 无记忆策略的契约:不读取任何知识库,写入一律警告、切换时提示全部失效。
25
+ */
26
+ export function noKnowledgeContract(displayName: string): KnowledgeContract {
27
+ return {
28
+ validateKnowledge(): KnowledgeValidation {
29
+ return {
30
+ ok: false,
31
+ message: `「${displayName}」不读取任何知识库标记,此条写入不会影响它的行为;若要让标记生效,请切换到带记忆的策略(如 shrimp-memory / warrior-memory)。`,
32
+ };
33
+ },
34
+ reviewKnowledge(view: KnowledgeView): KnowledgeReview {
35
+ const subjects = view.query({});
36
+ if (subjects.length === 0) return {};
37
+ return {
38
+ stale: subjects.map(refOf),
39
+ notes: [`「${displayName}」不使用知识库,现有 ${subjects.length} 条标记在本策略下都不会生效。`],
40
+ };
41
+ },
42
+ };
43
+ }
44
+
45
+ /**
46
+ * 只读玩家两档标记(hostile/trusted)的记忆策略契约。
47
+ * - `opts.extraTags`:额外认可的自定义玩家标签(如 shrimp-memory 认的 `paradise_fish`)。
48
+ * - `role` 作为纯身份事实一律放行(契约:role 不直接控制策略,仅供参考)。
49
+ */
50
+ export function playerMarkContract(displayName: string, opts: { extraTags?: string[] } = {}): KnowledgeContract {
51
+ const allowedTags = new Set<string>([...PLAYER_MARKS, ...(opts.extraTags ?? [])]);
52
+ const allowedDesc = [...allowedTags].join(' / ');
53
+
54
+ // 一条 player subject 是否整体可用:type 为 player、所有标签合法、且无非 role 的 fact。
55
+ const subjectUsable = (s: SubjectEntry): boolean => {
56
+ if (s.type !== 'player') return false;
57
+ if (Object.keys(s.tags ?? {}).some(t => !allowedTags.has(t))) return false;
58
+ if (Object.keys(s.facts ?? {}).some(k => k !== 'role')) return false;
59
+ return true;
60
+ };
61
+
62
+ return {
63
+ validateKnowledge(input: KnowledgeSetInput): KnowledgeValidation {
64
+ if (input.type !== 'player') {
65
+ return { ok: false, message: `「${displayName}」只读取玩家标记(type=player),type='${input.type}' 的知识不会被使用。` };
66
+ }
67
+ const badTag = (input.tags ?? []).find(t => !allowedTags.has(t));
68
+ if (badTag) {
69
+ return { ok: false, message: `「${displayName}」只认玩家标记 ${allowedDesc},标签 '${badTag}' 不会生效。` };
70
+ }
71
+ if (input.key != null && input.key !== 'role') {
72
+ return { ok: false, message: `「${displayName}」不读取玩家的 '${input.key}' 事实,只按 ${allowedDesc} 标记行动(role 仅作身份参考)。` };
73
+ }
74
+ return { ok: true };
75
+ },
76
+ reviewKnowledge(view: KnowledgeView): KnowledgeReview {
77
+ const stale = view.query({}).filter(s => !subjectUsable(s));
78
+ if (stale.length === 0) return {};
79
+ return {
80
+ stale: stale.map(refOf),
81
+ notes: [`「${displayName}」只读取玩家 ${allowedDesc} 标记,以下 ${stale.length} 条知识切换后不会生效。`],
82
+ };
83
+ },
84
+ };
85
+ }
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { LoneKillTaskTop } from './goals/lone-kill-task-top.js';
4
5
  import { ConversationGoal } from './goals/conversation-goal.js';
@@ -7,6 +8,7 @@ import { SpeechModule, getSpeechConfigForRole } from './speech-module.js';
7
8
  export const strategy: StrategyEntry = {
8
9
  id: 'lone-kill-task',
9
10
  name: '潜伏猎手',
11
+ ...noKnowledgeContract('潜伏猎手'),
10
12
  description: '视野里只有一个非队友且冷却可用就靠近,进入50距离就立刻出刀;刀在冷却时不追不等、改做低优先级任务伪装,冷却好且目标仍落单可见再出刀(贴脸且刀好仍会立刻出刀)。发现尸体且附近有非队友、但当前不能原地出刀时,会靠近并报告尸体。视野里出现两人以上时,暂停攻击10秒并做任意阵营的真实任务伪装;选任务时会跳过紧挨已知尸体(含看见过、已离开视野的)的任务,不在命案现场做任务。没有可做任务时按房间巡逻,绝不停在原地。残局(已知存活≤6)出现紧急维修任务时,会高优先级抢着去做(仍低于击杀落单),阻止蟹靠破坏倒计时取胜。(章鱼默认)',
11
13
  create(args?: string[]) {
12
14
  const role = args?.[0] ?? 'neutral_octopus';
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { MoveRoomGoal } from './goals/move-room-goal.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'move-room',
7
8
  name: '前往',
9
+ ...noKnowledgeContract('前往'),
8
10
  description: '前往指定房间,到达后停下。参数为目标房间名(如 酒吧)。单纯走位,不做任务、不打人、不报告。',
9
11
  create(args?: string[]) {
10
12
  const targetRoom = args?.join(' ').trim() ?? '';
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { ParadiseFishTop } from './goals/paradise-fish-top.js';
4
5
  import { parseGreetingArgs } from './greeting.js';
@@ -14,6 +15,7 @@ class ParadiseFishStrategy extends GoalRootStrategy {
14
15
  export const strategy: StrategyEntry = {
15
16
  id: 'paradise-fish',
16
17
  name: '天堂鱼',
18
+ ...playerMarkContract('天堂鱼'),
17
19
  description:
18
20
  '天堂鱼·进阶版(中立,不报警、不做任务,靠第二轮及以后被投票出局取胜;corpse-patrol 的带记忆升级)。读取 ccl knowledge 两档标记(hostile=坏人 / trusted=好人),未标记的一律默认被怀疑:hostile 视为危险硬寻路远离,被怀疑者按目击者规则保持距离,trusted 视为可抱团的可信同伴。发现尸体绝不报警,贴着尸体游走制造嫌疑;附近有人时远离那人但仍在尸体附近活动。残局(已知存活≤6)出现紧急维修任务时,会在没有带刀坏人需要躲避时优先抢着去做(先于对陌生人保持距离/贴尸/抱团),阻止蟹靠破坏倒计时取胜。传入打招呼话术时,视野内出现人就随机发送一条,之后120秒内不再发言。',
19
21
  create(args?: string[]) {
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { PatrolTop } from './goals/patrol-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'patrol',
7
8
  name: '巡逻',
9
+ ...noKnowledgeContract('巡逻'),
8
10
  description: '按地图房间顺序依次游走,到达一个房间后自动前往下一个,循环往复。卡路时会跳过当前目标换下一个房间。纯游走,不做任务、不打人、不报告尸体。',
9
11
  create() {
10
12
  return new GoalRootStrategy('patrol', () => new PatrolTop(), { resetOnMeetingResume: false });
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { ReportPatrolTop } from './goals/report-patrol-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'report-patrol',
7
8
  name: '报警',
9
+ ...noKnowledgeContract('报警'),
8
10
  description: '专门找尸体:达到报告距离立刻报告,看到尸体就靠近;没有尸体就巡逻各房间。不做任何任务,不打人,目标是让会议尽快开起来。',
9
11
  create() {
10
12
  return new GoalRootStrategy('report-patrol', () => new ReportPatrolTop(), { resetOnMeetingResume: false });
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { NormalShrimpTop } from './goals/normal-shrimp-top.js';
4
5
  import { parseGreetingArgs } from './greeting.js';
@@ -14,6 +15,7 @@ class ShrimpMemoryStrategy extends GoalRootStrategy {
14
15
  export const strategy: StrategyEntry = {
15
16
  id: 'shrimp-memory',
16
17
  name: '精英虾',
18
+ ...playerMarkContract('精英虾', { extraTags: ['paradise_fish'] }),
17
19
  description:
18
20
  '普通虾·记忆进阶版(好人、不带刀;task-report 的带记忆升级)。读取 ccl knowledge 两档标记(hostile=坏人 / trusted=好人),未标记的一律默认被怀疑:hostile 硬寻路远离,trusted 视为可信同伴,被怀疑者按目击者规则保持距离。发现尸体最优先报警,并提示复核尸体旁身份不明者;无可信同伴且单个被怀疑者贴近270内时先拉开距离到300再做任务;再处理紧急任务,最后做任务/巡逻(选测地最近、跳过威胁旁或必经威胁的任务)。永不出刀。传入打招呼话术时,视野内出现人就随机发送一条,之后120秒内不再发言。',
19
21
  create(args?: string[]) {
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { SocialTaskTop, type SocialTarget } from './goals/social-task-top.js';
4
5
 
@@ -34,6 +35,7 @@ export function parseSocialArgs(args: string[]): SocialTarget[] {
34
35
  export const strategy: StrategyEntry = {
35
36
  id: 'social-task',
36
37
  name: '社交',
38
+ ...noKnowledgeContract('社交'),
37
39
  description: '针对指定玩家社交(参数格式 座位=话术 或纯座位,可多人)。视野内出现目标就靠近,没打过招呼先发一次招呼;对方说话就停下等你回复,10秒没回应就转去做任务。全程见到可报告的尸体就报、见到尸体就靠近。不打人。参数:座位=话术 / 座位(可多人)。',
38
40
  create(args?: string[]) {
39
41
  if (!args || args.length === 0) {
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { TaskKillReportTop } from './goals/task-kill-report-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'task-kill-report',
7
8
  name: '任务刺客',
9
+ ...noKnowledgeContract('任务刺客'),
8
10
  description: '需传入嫌疑目标(座位号或名字,可多人)。看到目标且冷却好,50内就出刀,否则追上去;冷却中贴身跟随。目标不在视野时,遇到尸体就报告;没尸体就做普通任务。',
9
11
  create(args?: string[]) {
10
12
  if (!args || args.length === 0) {
@@ -1,10 +1,12 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { TaskOnlyTop } from './goals/task-only-top.js';
4
5
 
5
6
  export const strategy: StrategyEntry = {
6
7
  id: 'task-only',
7
8
  name: '纯任务',
9
+ ...noKnowledgeContract('纯任务'),
8
10
  description: '专心做任务。紧急任务出现时优先处理,其次按顺序完成普通任务,如果是蟹,则蟹的伪装任务也会做。没有尸体报告和战斗行为。',
9
11
  create() {
10
12
  return new GoalRootStrategy('task-only', () => new TaskOnlyTop(), { resetOnMeetingResume: false });
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { TaskReportTop } from './goals/task-report-top.js';
4
5
  import { parseGreetingArgs } from './greeting.js';
@@ -12,6 +13,7 @@ class TaskReportStrategy extends GoalRootStrategy {
12
13
  export const strategy: StrategyEntry = {
13
14
  id: 'task-report',
14
15
  name: '尽责虾',
16
+ ...noKnowledgeContract('尽责虾'),
15
17
  description: '遇尸体最优先:达到报告距离立刻报告,没达到距离就靠近准备报告。紧急任务出现时优先处理,其次按顺序完成普通任务。传入打招呼话术时,视野内出现人就随机发送一条,之后120秒内不再发言。(普通虾默认;进阶版见 shrimp-memory)参数:可选:1~3 条打招呼话术。',
16
18
  create(args?: string[]) {
17
19
  return new TaskReportStrategy(parseGreetingArgs(args, 'task-report'));
@@ -1,6 +1,6 @@
1
1
  import type { GameState, TaskInfo, TaskLocation, EmergencyInfo, CorpseInfo } from '../sdk/types.js';
2
2
  import type { Action } from '../sdk/action.js';
3
- import type { KnowledgeView } from '../lib/knowledge-store.js';
3
+ import type { KnowledgeView, KnowledgeSetInput, SubjectRef } from '../lib/knowledge-store.js';
4
4
 
5
5
  /**
6
6
  * Minimal interface for custom modules (built-in and strategy-registered).
@@ -41,6 +41,30 @@ export interface Strategy {
41
41
  customModules?(): CustomModule[];
42
42
  }
43
43
 
44
+ /**
45
+ * `ccl knowledge` 写入(set/mark)时,当前策略对单条知识做的格式校验结果。
46
+ * 校验由 `StrategyEntry.validateKnowledge` 提供;不实现即视为通过(兼容自定义策略)。
47
+ * `ok:false` 时写入照常发生,但 `message` 会作为 warning 出现在命令的返回 JSON 里,
48
+ * 提示玩家这条知识不会被当前策略读取。
49
+ */
50
+ export interface KnowledgeValidation {
51
+ ok: boolean;
52
+ /** 校验不通过时给玩家的说明。 */
53
+ message?: string;
54
+ }
55
+
56
+ /**
57
+ * 切换到某策略时,由「新策略」审视对局现有知识,指出哪些条目它读不到 / 用不上。
58
+ * knowledge 不随切换策略而清空(按对局作用域),故用它告知玩家哪些标记已失效。
59
+ * 由 `StrategyEntry.reviewKnowledge` 提供;不实现即视为「现有知识全部保留」。
60
+ */
61
+ export interface KnowledgeReview {
62
+ /** 新策略读不到 / 用不上、切换后不会生效的知识条目。 */
63
+ stale?: SubjectRef[];
64
+ /** 给玩家的整理说明(每条一行)。 */
65
+ notes?: string[];
66
+ }
67
+
44
68
  export interface StrategyEntry {
45
69
  readonly id: string;
46
70
  /**
@@ -52,6 +76,18 @@ export interface StrategyEntry {
52
76
  readonly name: string;
53
77
  readonly description: string;
54
78
  create(args?: string[]): Strategy;
79
+ /**
80
+ * 可选:校验一条即将写入的 knowledge 是否符合本策略能读取的格式。
81
+ * 不实现视为通过(兼容所有自定义策略)。返回 `ok:false` 时 `ccl knowledge`
82
+ * 仍会写入,只在返回 JSON 里带上 `message` 警告玩家该条不会生效。
83
+ * 没有记忆功能(不读 `ctx.knowledge`)的策略应实现它并一律返回 `ok:false`。
84
+ */
85
+ validateKnowledge?(input: KnowledgeSetInput): KnowledgeValidation;
86
+ /**
87
+ * 可选:切换到本策略时审视对局现有知识,返回哪些条目本策略用不上。
88
+ * 不实现视为「全部保留」。`ccl strategy` 切换成功后会把结果告知玩家。
89
+ */
90
+ reviewKnowledge?(view: KnowledgeView): KnowledgeReview;
55
91
  }
56
92
 
57
93
  export interface RoomTarget {
@@ -1,4 +1,5 @@
1
1
  import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
2
3
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
3
4
  import { WarriorShrimpTop } from './goals/warrior-shrimp-top.js';
4
5
  import { parseTargetArgs } from './player-targets.js';
@@ -6,6 +7,7 @@ import { parseTargetArgs } from './player-targets.js';
6
7
  export const strategy: StrategyEntry = {
7
8
  id: 'warrior-memory',
8
9
  name: '武士虾',
10
+ ...playerMarkContract('武士虾'),
9
11
  description:
10
12
  '带刀虾·记忆进阶版(武士虾/枪虾通用,好人带刀;kill-lone 的带记忆升级)。读取 ccl knowledge 两档标记(hostile=坏人 / trusted=好人),未标记的一律默认被怀疑:hostile 刀好时主动追杀、刀不好时硬回避,trusted 视为可信同伴且绝不攻击。**只对【已确认 hostile / 启动猎杀目标】出刀**——被怀疑者一律只回避、绝不出刀(无可信同伴且单个被怀疑者贴近270内时先拉开到300再做任务,多人互为目击者则照常做任务);不再有任何贴身追击判定/诱饵试探/绝境自卫(几何上分不开"贴身跟我观察的好人"和"贴身追我的凶手",自卫迟早误杀同阵营好人触发武士虾自爆,整套已删除)。发现尸体优先报警;尸体旁若是 hostile/启动猎杀目标且刀可用会现场先手击杀,但绝不会因尸体旁有未报警的身份不明者就灭口(已根治该误杀);无危险时优先紧急任务,否则做任务/巡逻。枪虾会尊重剩余出刀次数。',
11
13
  create(args?: string[]) {