@myclaw163/clawclaw-cli 0.7.14 → 0.7.16

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.
Files changed (45) hide show
  1. package/docs/runtime/strategy-runtime.md +1 -1
  2. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +4 -4
  3. package/package.json +1 -1
  4. package/skills/clawclaw/SKILL.md +2 -2
  5. package/skills/clawclaw/references/COMMANDS.md +1 -1
  6. package/skills/clawclaw/references/STRATEGIES.md +4 -4
  7. package/src/lib/game-client.ts +2 -0
  8. package/src/lib/strategy-export.test.ts +13 -0
  9. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +1 -0
  10. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1 -0
  11. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +1 -1
  12. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +203 -0
  13. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +209 -5
  14. package/src/sdk/index.ts +2 -2
  15. package/src/sdk/strategy-plugin/index.test.ts +10 -4
  16. package/src/sdk/strategy-plugin/index.ts +13 -2
  17. package/src/strategies/avoid-players.ts +4 -5
  18. package/src/strategies/find-player.ts +5 -6
  19. package/src/strategies/game-utils.test.ts +22 -0
  20. package/src/strategies/game-utils.ts +12 -39
  21. package/src/strategies/goals/avoid-players-top.test.ts +2 -2
  22. package/src/strategies/goals/avoid-players-top.ts +1 -1
  23. package/src/strategies/goals/crab-octopus-reflexes.ts +10 -10
  24. package/src/strategies/goals/find-player-top.ts +7 -8
  25. package/src/strategies/goals/kill-lone-top.test.ts +27 -2
  26. package/src/strategies/goals/kill-lone-top.ts +16 -12
  27. package/src/strategies/goals/kill-target-goal.ts +3 -3
  28. package/src/strategies/goals/kill-target-top.test.ts +66 -0
  29. package/src/strategies/goals/kill-target-top.ts +4 -6
  30. package/src/strategies/goals/normal-shrimp-top.test.ts +2 -2
  31. package/src/strategies/goals/normal-shrimp-top.ts +3 -3
  32. package/src/strategies/goals/paradise-fish-top.test.ts +3 -3
  33. package/src/strategies/goals/paradise-fish-top.ts +2 -2
  34. package/src/strategies/goals/social-task-top.ts +3 -3
  35. package/src/strategies/goals/task-kill-report-top.ts +2 -2
  36. package/src/strategies/goals/warrior-shrimp-top.test.ts +3 -3
  37. package/src/strategies/goals/warrior-shrimp-top.ts +11 -7
  38. package/src/strategies/kill-lone.ts +7 -12
  39. package/src/strategies/kill-target.ts +5 -6
  40. package/src/strategies/paradise-fish.ts +8 -8
  41. package/src/strategies/player-targets.ts +0 -8
  42. package/src/strategies/shrimp-memory.ts +13 -13
  43. package/src/strategies/social-task.ts +4 -4
  44. package/src/strategies/task-kill-report.ts +5 -5
  45. package/src/strategies/warrior-memory.ts +7 -12
@@ -45,6 +45,18 @@ export const CLAWCLAW_STRATEGY_PLUGIN_ID = 'clawclaw.strategy';
45
45
  export const CLAWCLAW_STRATEGY_STATE_TOPIC = 'strategy.status';
46
46
  export const CLAWCLAW_STRATEGY_EVENT_TYPES = ['strategy_alert', 'robot_speak_rule'] as const;
47
47
 
48
+ const STRATEGY_REPORT_LOCALE = 'zh-CN';
49
+ const STRATEGY_REPORT_RETRY_MS = 1_000;
50
+
51
+ interface StrategyReportTarget extends ClawclawResolvedResourceMetadata {
52
+ readonly fingerprint: string;
53
+ }
54
+
55
+ interface StrategyReportAttempt {
56
+ readonly lifecycleGeneration: number;
57
+ readonly fingerprint: string;
58
+ }
59
+
48
60
  export interface ClawclawStrategySelection extends StrategySource {
49
61
  readonly parameters?: Readonly<Record<string, unknown>>;
50
62
  readonly controls?: readonly StrategyControlSpec[];
@@ -184,18 +196,27 @@ function validStrategyControlValue(spec: StrategyControlSpec, value: unknown): b
184
196
  if (spec.type === 'number') return typeof value === 'number' && Number.isFinite(value);
185
197
  if (spec.type === 'string') return typeof value === 'string';
186
198
  if (spec.type === 'enum') return typeof value === 'string' && !!spec.values?.includes(value);
199
+ if (spec.type === 'player_seats') {
200
+ return Array.isArray(value) && value.every((entry) => (
201
+ Number.isInteger(entry) && entry >= 1 && entry <= 10
202
+ ));
203
+ }
187
204
  return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
188
205
  }
189
206
 
190
- function validateParallelControls(
207
+ function validateControlValues(
191
208
  selection: ClawclawStrategySelection,
192
209
  values: Readonly<Record<string, unknown>>,
210
+ requireDeclared: boolean,
193
211
  ): void {
194
212
  const controls = new Map((selection.controls ?? []).map((control) => [control.id, control]));
195
- if (controls.size === 0) throw new Error('strategy_controls_not_supported');
213
+ if (requireDeclared && controls.size === 0) throw new Error('strategy_controls_not_supported');
196
214
  for (const [key, value] of Object.entries(values)) {
197
215
  const spec = controls.get(key);
198
- if (!spec) throw new Error(`unsupported_strategy_control:${key}`);
216
+ if (!spec) {
217
+ if (requireDeclared) throw new Error(`unsupported_strategy_control:${key}`);
218
+ continue;
219
+ }
199
220
  if (!validStrategyControlValue(spec, value)) {
200
221
  throw new Error(`invalid_strategy_control:${key}`);
201
222
  }
@@ -211,6 +232,25 @@ function diagnosticErrorCode(error: unknown, fallback: string): string {
211
232
  return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
212
233
  }
213
234
 
235
+ function isSuccessfulStrategyReportResponse(value: unknown): boolean {
236
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
237
+ const result = value as Record<string, unknown>;
238
+ if (
239
+ result.status !== 'success'
240
+ || result.source !== 'backend'
241
+ || result.actionOutcome !== 'confirmed'
242
+ ) return false;
243
+ const response = result.value;
244
+ if (!response || typeof response !== 'object' || Array.isArray(response)) return false;
245
+ const root = response as Record<string, unknown>;
246
+ const data = root.data;
247
+ return root.success === true
248
+ && !!data
249
+ && typeof data === 'object'
250
+ && !Array.isArray(data)
251
+ && (data as Record<string, unknown>).ok === true;
252
+ }
253
+
214
254
  function strategyActionControllerId(strategyId: string, generation: number): string {
215
255
  return `${strategyId}@activation-${generation}`;
216
256
  }
@@ -408,6 +448,13 @@ implements RuntimeEpochPlugin<Record<string, any>> {
408
448
  private selectedGeneration = 0;
409
449
  private parameterGeneration = 0;
410
450
  private readonly committedActionDedupeKeys = new Map<string, number>();
451
+ private strategyReportTarget?: StrategyReportTarget;
452
+ private strategyReportAcknowledgedFingerprint?: string;
453
+ private strategyReportInFlight?: StrategyReportAttempt;
454
+ private strategyReportTimer?: ReturnType<typeof setTimeout>;
455
+ private strategyReportContext?: RuntimeEpochPluginContext<Record<string, any>>;
456
+ private strategyReportEligible = false;
457
+ private strategyReportLifecycleGeneration = 0;
411
458
 
412
459
  constructor(options: ClawclawStrategyPluginOptions = {}) {
413
460
  this.after = [...(options.after ?? [])];
@@ -449,9 +496,9 @@ implements RuntimeEpochPlugin<Record<string, any>> {
449
496
  if (!target) throw new Error('no_active_strategy');
450
497
  const revision = ++this.controlRevision;
451
498
  const cloned = structuredClone(values);
499
+ validateControlValues(target, cloned, target.execution === 'parallel_compute');
452
500
  let preAppliedValues: Readonly<Record<string, unknown>> | undefined;
453
501
  if (target.execution === 'parallel_compute') {
454
- validateParallelControls(target, cloned);
455
502
  preAppliedValues = structuredClone({
456
503
  ...(target.parameters ?? {}),
457
504
  ...cloned,
@@ -494,6 +541,160 @@ implements RuntimeEpochPlugin<Record<string, any>> {
494
541
  }, locale);
495
542
  }
496
543
 
544
+ private refreshStrategyReportRuntime(
545
+ input: RuntimeEpochPluginInput<Record<string, any>>,
546
+ context: RuntimeEpochPluginContext<Record<string, any>>,
547
+ ): void {
548
+ const wasEligible = this.strategyReportEligible;
549
+ const state = input.epoch.state;
550
+ this.strategyReportContext = context;
551
+ this.strategyReportEligible = isClawclawRuntimeState(state)
552
+ && state.connection === 'connected'
553
+ && freshWanderingEpoch(input);
554
+
555
+ const descriptor = this.activeResourceDescriptor(STRATEGY_REPORT_LOCALE);
556
+ const nextTarget = descriptor
557
+ ? {
558
+ ...descriptor,
559
+ fingerprint: JSON.stringify([descriptor.id, descriptor.name, descriptor.description]),
560
+ }
561
+ : undefined;
562
+ const targetChanged = nextTarget?.fingerprint !== this.strategyReportTarget?.fingerprint;
563
+ if (targetChanged) {
564
+ this.strategyReportTarget = nextTarget;
565
+ this.clearStrategyReportTimer();
566
+ }
567
+
568
+ const target = this.strategyReportTarget;
569
+ if (!target || this.strategyReportAcknowledgedFingerprint === target.fingerprint) {
570
+ this.clearStrategyReportTimer();
571
+ return;
572
+ }
573
+ if (targetChanged || (!wasEligible && this.strategyReportEligible)) {
574
+ this.scheduleStrategyReport(0, true);
575
+ }
576
+ }
577
+
578
+ private clearStrategyReportTimer(): void {
579
+ if (!this.strategyReportTimer) return;
580
+ clearTimeout(this.strategyReportTimer);
581
+ this.strategyReportTimer = undefined;
582
+ }
583
+
584
+ private scheduleStrategyReport(delayMs: number, replace = false): void {
585
+ const target = this.strategyReportTarget;
586
+ if (
587
+ !target
588
+ || this.strategyReportAcknowledgedFingerprint === target.fingerprint
589
+ || this.strategyReportInFlight
590
+ ) return;
591
+ if (this.strategyReportTimer) {
592
+ if (!replace) return;
593
+ this.clearStrategyReportTimer();
594
+ }
595
+ const lifecycleGeneration = this.strategyReportLifecycleGeneration;
596
+ this.strategyReportTimer = setTimeout(() => {
597
+ this.strategyReportTimer = undefined;
598
+ if (lifecycleGeneration !== this.strategyReportLifecycleGeneration) return;
599
+ this.startStrategyReportAttempt();
600
+ }, delayMs);
601
+ this.strategyReportTimer.unref?.();
602
+ }
603
+
604
+ /** Starts one host-owned report without extending the ordered Strategy commit. */
605
+ private startStrategyReportAttempt(): void {
606
+ const target = this.strategyReportTarget;
607
+ const context = this.strategyReportContext;
608
+ if (
609
+ !target
610
+ || this.strategyReportAcknowledgedFingerprint === target.fingerprint
611
+ || this.strategyReportInFlight
612
+ ) return;
613
+ if (!this.strategyReportEligible || !context || context.signal.aborted) {
614
+ this.scheduleStrategyReport(STRATEGY_REPORT_RETRY_MS);
615
+ return;
616
+ }
617
+
618
+ const attempt: StrategyReportAttempt = {
619
+ lifecycleGeneration: this.strategyReportLifecycleGeneration,
620
+ fingerprint: target.fingerprint,
621
+ };
622
+ this.strategyReportInFlight = attempt;
623
+ context.diagnostic('strategy.report.started', {
624
+ strategy_id: target.id,
625
+ }, 'debug');
626
+
627
+ let pending: Promise<unknown>;
628
+ try {
629
+ pending = context.capabilities.performAction(
630
+ CLAWCLAW_ACTION_CAPABILITY,
631
+ {
632
+ route: 'game',
633
+ action: {
634
+ action: 'strategy',
635
+ name: target.name,
636
+ description: target.description,
637
+ },
638
+ },
639
+ );
640
+ } catch (error) {
641
+ this.finishStrategyReportAttempt(attempt, false, error);
642
+ return;
643
+ }
644
+ void pending.then(
645
+ (result) => this.finishStrategyReportAttempt(
646
+ attempt,
647
+ isSuccessfulStrategyReportResponse(result),
648
+ result,
649
+ ),
650
+ (error) => this.finishStrategyReportAttempt(attempt, false, error),
651
+ );
652
+ }
653
+
654
+ private finishStrategyReportAttempt(
655
+ attempt: StrategyReportAttempt,
656
+ successful: boolean,
657
+ result: unknown,
658
+ ): void {
659
+ if (
660
+ attempt.lifecycleGeneration !== this.strategyReportLifecycleGeneration
661
+ || this.strategyReportInFlight?.fingerprint !== attempt.fingerprint
662
+ ) return;
663
+ this.strategyReportInFlight = undefined;
664
+ const target = this.strategyReportTarget;
665
+ if (successful && target?.fingerprint === attempt.fingerprint) {
666
+ this.strategyReportAcknowledgedFingerprint = attempt.fingerprint;
667
+ this.clearStrategyReportTimer();
668
+ this.strategyReportContext?.diagnostic('strategy.report.completed', {
669
+ strategy_id: target.id,
670
+ }, 'info');
671
+ return;
672
+ }
673
+
674
+ if (target?.fingerprint === attempt.fingerprint) {
675
+ this.strategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
676
+ strategy_id: target.id,
677
+ retry_ms: STRATEGY_REPORT_RETRY_MS,
678
+ error_code: diagnosticErrorCode(result, 'STRATEGY_REPORT_RESPONSE_INVALID'),
679
+ }, 'warn');
680
+ this.scheduleStrategyReport(STRATEGY_REPORT_RETRY_MS);
681
+ return;
682
+ }
683
+ if (target && this.strategyReportAcknowledgedFingerprint !== target.fingerprint) {
684
+ this.scheduleStrategyReport(0);
685
+ }
686
+ }
687
+
688
+ private resetStrategyReporting(): void {
689
+ this.strategyReportLifecycleGeneration += 1;
690
+ this.clearStrategyReportTimer();
691
+ this.strategyReportTarget = undefined;
692
+ this.strategyReportAcknowledgedFingerprint = undefined;
693
+ this.strategyReportInFlight = undefined;
694
+ this.strategyReportContext = undefined;
695
+ this.strategyReportEligible = false;
696
+ }
697
+
497
698
  async update(
498
699
  input: RuntimeEpochPluginInput<Record<string, any>>,
499
700
  context: RuntimeEpochPluginContext<Record<string, any>>,
@@ -643,6 +844,7 @@ implements RuntimeEpochPlugin<Record<string, any>> {
643
844
  context: RuntimeEpochPluginContext<Record<string, any>>,
644
845
  ): Promise<RuntimeEpochPluginResult> {
645
846
  const proposal = strategyProposal(computation.proposal);
847
+ this.refreshStrategyReportRuntime(input, context);
646
848
  const previousInvokedEpochSeq = this.lastInvokedEpochSeq;
647
849
  this.lastInvokedEpochSeq = input.epoch.epochSeq;
648
850
  if (previousInvokedEpochSeq !== null && input.epoch.epochSeq > previousInvokedEpochSeq + 1) {
@@ -670,6 +872,7 @@ implements RuntimeEpochPlugin<Record<string, any>> {
670
872
  return { outcome: 'noop', reason: 'strategy_computation_superseded' };
671
873
  }
672
874
  await this.applyPendingSelection(context);
875
+ this.refreshStrategyReportRuntime(input, context);
673
876
  if (!this.selected || this.selectedGeneration !== proposal.generation) {
674
877
  return { outcome: 'noop', reason: 'strategy_computation_superseded' };
675
878
  }
@@ -788,6 +991,7 @@ implements RuntimeEpochPlugin<Record<string, any>> {
788
991
  }
789
992
 
790
993
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
994
+ this.resetStrategyReporting();
791
995
  const executor = this.executor;
792
996
  this.executor = undefined;
793
997
  const parallelExecutor = this.parallelExecutor;
@@ -951,7 +1155,7 @@ implements RuntimeEpochPlugin<Record<string, any>> {
951
1155
  }
952
1156
  if (selected.execution === 'parallel_compute') {
953
1157
  try {
954
- validateParallelControls(selected, control.values);
1158
+ validateControlValues(selected, control.values, true);
955
1159
  const result = this.parallelExecutor?.applyControl
956
1160
  ? await this.parallelExecutor.applyControl({
957
1161
  epochId: input.epoch.epochSeq,
package/src/sdk/index.ts CHANGED
@@ -67,8 +67,8 @@ export type { SpeechModuleConfig, SpeechEvalResult } from '../strategies/speech-
67
67
  // Greeting utilities (for exported strategies that use greeting phrases)
68
68
  export { parseGreetingArgs, GreetingTracker, MAX_GREETING_PHRASES, GREETING_TEXT_MAX_LENGTH, GREETING_COOLDOWN_MS } from '../strategies/greeting.js';
69
69
 
70
- // Player targeting utilities (for exported strategies)
71
- export { parseTargetArgs, stripRoleIds } from '../strategies/player-targets.js';
70
+ // Player role-label utilities (for exported strategies)
71
+ export { stripRoleIds } from '../strategies/player-targets.js';
72
72
 
73
73
  // Goal system (for exported strategies that use the goal framework)
74
74
  export { GoalRootStrategy } from '../strategies/goals/goal-root-strategy.js';
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import {
3
3
  ClawclawGoalStrategy,
4
4
  ClawclawStrategy,
5
+ clawclawStrategySeatList,
5
6
  type ClawclawStrategyAction,
6
7
  type ClawclawStrategyGameState,
7
8
  STRATEGY_PLUGIN_API_VERSION,
@@ -41,6 +42,11 @@ class TestStrategy extends ClawclawStrategy {
41
42
  }
42
43
 
43
44
  describe('Strategy Plugin SDK', () => {
45
+ it('reads player_seats controls as numeric seat arrays only', () => {
46
+ expect(clawclawStrategySeatList({ targets: [6, '6', '木桩机器虾', 0, 11] }, 'targets'))
47
+ .toEqual([6]);
48
+ });
49
+
44
50
  it('defines one class with manifest and update as the authoring contract', () => {
45
51
  expect(TestStrategy.apiVersion).toBe(STRATEGY_PLUGIN_API_VERSION);
46
52
  expect(TestStrategy.manifest.id).toBe('test-strategy');
@@ -103,7 +109,7 @@ describe('Strategy Plugin SDK', () => {
103
109
  description: 'Exercises the npm Goal migration boundary.',
104
110
  controls: [{
105
111
  id: 'targets',
106
- type: 'player_refs',
112
+ type: 'player_seats',
107
113
  description: 'Fixture arguments.',
108
114
  default: [],
109
115
  }],
@@ -203,7 +209,7 @@ describe('Strategy Plugin SDK', () => {
203
209
  parameters: {},
204
210
  });
205
211
 
206
- const instance = new FixtureGoalStrategy({ targets: ['first'] });
212
+ const instance = new FixtureGoalStrategy({ targets: [2] });
207
213
  await instance.update(makeFrame(1), api);
208
214
  await instance.update(makeFrame(2), api);
209
215
 
@@ -250,11 +256,11 @@ describe('Strategy Plugin SDK', () => {
250
256
  epochId: 3,
251
257
  scope: { sessionId: 'session', segmentId: 'game' },
252
258
  revision: 7,
253
- values: { targets: ['changed'] },
259
+ values: { targets: [3] },
254
260
  })).toMatchObject({
255
261
  accepted: true,
256
262
  appliedRevision: 7,
257
- effectiveValues: { targets: ['changed'] },
263
+ effectiveValues: { targets: [3] },
258
264
  });
259
265
  expect(createCount).toBe(2);
260
266
  expect(mapLoadCount).toBe(2);
@@ -62,7 +62,7 @@ export interface StrategyFrame<TState = Record<string, unknown>> {
62
62
 
63
63
  export interface StrategyControlSpec {
64
64
  readonly id: string;
65
- readonly type: 'string' | 'boolean' | 'number' | 'enum' | 'player_refs' | 'string_list';
65
+ readonly type: 'string' | 'boolean' | 'number' | 'enum' | 'player_seats' | 'string_list';
66
66
  readonly description: string;
67
67
  readonly values?: readonly string[];
68
68
  readonly default?: unknown;
@@ -417,6 +417,18 @@ export function clawclawStrategyStringList(
417
417
  : [];
418
418
  }
419
419
 
420
+ export function clawclawStrategySeatList(
421
+ parameters: Readonly<Record<string, unknown>>,
422
+ controlId: string,
423
+ ): number[] {
424
+ const value = parameters[controlId];
425
+ return Array.isArray(value)
426
+ ? value.filter((entry): entry is number => (
427
+ Number.isInteger(entry) && entry >= 1 && entry <= 10
428
+ ))
429
+ : [];
430
+ }
431
+
420
432
  export function clawclawStrategyString(
421
433
  parameters: Readonly<Record<string, unknown>>,
422
434
  controlId: string,
@@ -1312,7 +1324,6 @@ export interface StrategyInstance<
1312
1324
  // authoring API does not export GameClient, transport, SQLite, or Runtime
1313
1325
  // internals. Strategy source is still trusted same-process code, not sandboxed.
1314
1326
  export { parseGreetingArgs } from '../../strategies/greeting.js';
1315
- export { parseTargetArgs } from '../../strategies/player-targets.js';
1316
1327
  export { SpeechModule, getSpeechConfigForRole } from '../../strategies/speech-module.js';
1317
1328
  export { GoalRootStrategy } from '../../strategies/goals/goal-root-strategy.js';
1318
1329
  export { TaskOnlyTop } from '../../strategies/goals/task-only-top.js';
@@ -1,10 +1,9 @@
1
1
  import {
2
2
  ClawclawGoalStrategy,
3
- clawclawStrategyStringList,
3
+ clawclawStrategySeatList,
4
4
  } from '../sdk/strategy-plugin/index.js';
5
5
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
6
6
  import { AvoidPlayersTop } from './goals/avoid-players-top.js';
7
- import { parseTargetArgs } from './player-targets.js';
8
7
 
9
8
  export default class AvoidPlayersStrategy extends ClawclawGoalStrategy {
10
9
  static readonly manifest = {
@@ -14,8 +13,8 @@ export default class AvoidPlayersStrategy extends ClawclawGoalStrategy {
14
13
  execution: 'parallel_analyze',
15
14
  controls: [{
16
15
  id: 'targets',
17
- type: 'player_refs',
18
- description: '需要回避的座位号或玩家名列表。',
16
+ type: 'player_seats',
17
+ description: '需要回避的玩家座位号列表。',
19
18
  default: [],
20
19
  }],
21
20
  } as const;
@@ -24,7 +23,7 @@ export default class AvoidPlayersStrategy extends ClawclawGoalStrategy {
24
23
  super(parameters, {
25
24
  id: 'avoid-players',
26
25
  create: (values) => {
27
- const targets = parseTargetArgs(clawclawStrategyStringList(values, 'targets'));
26
+ const targets = clawclawStrategySeatList(values, 'targets');
28
27
  return new GoalRootStrategy('avoid-players', () => new AvoidPlayersTop(targets), {
29
28
  resetOnMeetingResume: false,
30
29
  });
@@ -1,10 +1,9 @@
1
1
  import {
2
2
  ClawclawGoalStrategy,
3
- clawclawStrategyStringList,
3
+ clawclawStrategySeatList,
4
4
  } from '../sdk/strategy-plugin/index.js';
5
5
  import { GoalRootStrategy } from './goals/goal-root-strategy.js';
6
6
  import { FindPlayerTop } from './goals/find-player-top.js';
7
- import { parseTargetArgs } from './player-targets.js';
8
7
 
9
8
  export default class FindPlayerStrategy extends ClawclawGoalStrategy {
10
9
  static readonly manifest = {
@@ -14,8 +13,8 @@ export default class FindPlayerStrategy extends ClawclawGoalStrategy {
14
13
  execution: 'parallel_analyze',
15
14
  controls: [{
16
15
  id: 'targets',
17
- type: 'player_refs',
18
- description: '要寻找并跟踪的单个玩家。',
16
+ type: 'player_seats',
17
+ description: '要寻找并跟踪的单个玩家座位号。',
19
18
  }],
20
19
  } as const;
21
20
 
@@ -23,12 +22,12 @@ export default class FindPlayerStrategy extends ClawclawGoalStrategy {
23
22
  super(parameters, {
24
23
  id: 'find-player',
25
24
  validateParameters: (values) => (
26
- parseTargetArgs(clawclawStrategyStringList(values, 'targets')).length === 1
25
+ clawclawStrategySeatList(values, 'targets').length === 1
27
26
  ? undefined
28
27
  : '盯人策略必须配置且只能配置一个目标玩家。'
29
28
  ),
30
29
  create: (values) => {
31
- const targets = parseTargetArgs(clawclawStrategyStringList(values, 'targets'));
30
+ const targets = clawclawStrategySeatList(values, 'targets');
32
31
  return new GoalRootStrategy('find-player', () => new FindPlayerTop(targets[0]), {
33
32
  resetOnMeetingResume: false,
34
33
  });
@@ -6,6 +6,8 @@ import {
6
6
  emergencyRushDecision,
7
7
  firstAvailableTask,
8
8
  killYieldsToEmergencyRepair,
9
+ matchesTarget,
10
+ nearestVisibleTarget,
9
11
  nearestSafeTask,
10
12
  PatrolState,
11
13
  safePatrolStep,
@@ -66,6 +68,26 @@ function context(overrides: Partial<StrategyContext> = {}): StrategyContext {
66
68
  };
67
69
  }
68
70
 
71
+ describe('seat-only player targets', () => {
72
+ it('selects only the configured seat when multiple players share one name', () => {
73
+ const ctx = context({
74
+ playerNamesBySeat: {
75
+ '2': '木桩机器虾',
76
+ '6': '木桩机器虾',
77
+ },
78
+ });
79
+ const sameNamePlayers = [
80
+ { name: '木桩机器虾', seat: 2, room: '居住区', x: 10, y: 0, distance: 10 },
81
+ { name: '木桩机器虾', seat: 6, room: '居住区', x: 20, y: 0, distance: 20 },
82
+ ];
83
+ const current = state({ players: sameNamePlayers });
84
+
85
+ expect(matchesTarget(6, sameNamePlayers[0], ctx)).toBe(false);
86
+ expect(matchesTarget(6, sameNamePlayers[1], ctx)).toBe(true);
87
+ expect(nearestVisibleTarget(current, ctx, [6])?.seat).toBe(6);
88
+ });
89
+ });
90
+
69
91
  describe('CorpseMemory', () => {
70
92
  it('uses the last visible position immediately after a confirmed kill', () => {
71
93
  const memory = new CorpseMemory();
@@ -758,42 +758,17 @@ export function nonTeammatesVisible(state: GameState, ctx: StrategyContext): Pla
758
758
  : players;
759
759
  }
760
760
 
761
- /**
762
- * Resolve a target string (seat number or player name) to a seat number.
763
- * Names are resolved through `ctx.playerNamesBySeat` (seat → name). Returns
764
- * null when the target cannot be resolved to a seat (unknown name, empty input).
765
- */
766
- export function targetSeat(target: string, ctx: StrategyContext): number | null {
767
- const trimmed = target.trim();
768
- if (!trimmed) return null;
769
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
770
- const folded = trimmed.toLowerCase();
771
- for (const [seat, name] of Object.entries(ctx.playerNamesBySeat)) {
772
- if (name && name.toLowerCase() === folded) return Number(seat);
773
- }
774
- return null;
775
- }
776
-
777
761
  export function matchesTarget(
778
- target: string,
762
+ targetSeat: number,
779
763
  player: { name?: string; seat?: number },
780
- ctx: StrategyContext,
764
+ _ctx: StrategyContext,
781
765
  ): boolean {
782
- const trimmed = target.trim();
783
- const seat = targetSeat(trimmed, ctx);
784
- if (seat != null && player.seat != null && player.seat === seat) return true;
785
- if (seat != null) {
786
- // 座位号参数对无名/缺 seat 的条目(如只有名字的尸体):经 seat→name 反查命中。
787
- const nameFromSeat = ctx.playerNamesBySeat[String(seat)];
788
- if (nameFromSeat && player.name && player.name.toLowerCase() === nameFromSeat.toLowerCase()) return true;
789
- }
790
- const normalized = trimmed.toLowerCase();
791
- return player.name != null && player.name.toLowerCase() === normalized;
766
+ return Number.isInteger(targetSeat) && player.seat === targetSeat;
792
767
  }
793
768
 
794
769
  export function matchesAnyTarget(
795
770
  player: { name?: string; seat?: number },
796
- targets: string[],
771
+ targets: number[],
797
772
  ctx: StrategyContext,
798
773
  ): boolean {
799
774
  return targets.some(target => matchesTarget(target, player, ctx));
@@ -801,26 +776,24 @@ export function matchesAnyTarget(
801
776
 
802
777
  export function isTargetAlive(
803
778
  state: GameState,
804
- target: string,
779
+ targetSeat: number,
805
780
  ctx: StrategyContext,
806
781
  ): boolean {
807
- if (isRecentlyKilledTarget(target, ctx)) return false;
808
- const player = state.all_players?.find(p => matchesTarget(target, p, ctx));
782
+ if (isRecentlyKilledTarget(targetSeat, ctx)) return false;
783
+ const player = state.all_players?.find(p => matchesTarget(targetSeat, p, ctx));
809
784
  return player ? player.is_alive !== false : true;
810
785
  }
811
786
 
812
- export function isRecentlyKilledTarget(target: string, ctx: StrategyContext): boolean {
813
- const seat = targetSeat(target, ctx);
814
- if (seat == null) return false;
815
- const until = ctx.recentlyKilledTargets?.get(String(seat));
787
+ export function isRecentlyKilledTarget(targetSeat: number, ctx: StrategyContext): boolean {
788
+ const until = ctx.recentlyKilledTargets?.get(String(targetSeat));
816
789
  if (until == null) return false;
817
790
  if (until > Date.now()) return true;
818
- ctx.recentlyKilledTargets?.delete(String(seat));
791
+ ctx.recentlyKilledTargets?.delete(String(targetSeat));
819
792
  return false;
820
793
  }
821
794
 
822
795
  export function visibleLivePlayers(state: GameState, ctx: StrategyContext): PlayerInfo[] {
823
- return state.players.filter(p => isTargetAlive(state, p.name, ctx));
796
+ return state.players.filter(p => p.seat == null || isTargetAlive(state, p.seat, ctx));
824
797
  }
825
798
 
826
799
  export function nearestPlayerByDistance(state: GameState, players: PlayerInfo[]): PlayerInfo | null {
@@ -832,7 +805,7 @@ export function nearestPlayerByDistance(state: GameState, players: PlayerInfo[])
832
805
  export function nearestVisibleTarget(
833
806
  state: GameState,
834
807
  ctx: StrategyContext,
835
- targets: string[],
808
+ targets: number[],
836
809
  ): PlayerInfo | null {
837
810
  return nearestPlayerByDistance(
838
811
  state,
@@ -65,7 +65,7 @@ describe('AvoidPlayersTop', () => {
65
65
  });
66
66
 
67
67
  it('patrols without stop_on_player when the configured avoid target is dead', () => {
68
- const top = new AvoidPlayersTop(['dead-target']);
68
+ const top = new AvoidPlayersTop([2]);
69
69
  const ctx = context();
70
70
  const current = state({
71
71
  players: [{ name: 'roadie', x: 200, y: 0, room: 'start' }],
@@ -83,7 +83,7 @@ describe('AvoidPlayersTop', () => {
83
83
  });
84
84
 
85
85
  it('uses targets as the complete active avoid list', () => {
86
- const top = new AvoidPlayersTop(['danger']);
86
+ const top = new AvoidPlayersTop([2]);
87
87
  const current = state({
88
88
  players: [{ name: 'danger', seat: 2, x: 200, y: 0, room: 'start' }],
89
89
  all_players: [{ name: 'danger', seat: 2, role: 'unknown', is_alive: true }],
@@ -13,7 +13,7 @@ export class AvoidPlayersTop extends Goal {
13
13
  private moveMode: 'patrol' | 'flee' | null = null;
14
14
  private lastAvoidNoticeKey = '';
15
15
 
16
- constructor(private readonly targets: string[]) {
16
+ constructor(private readonly targets: number[]) {
17
17
  super();
18
18
  }
19
19
 
@@ -10,7 +10,6 @@ import {
10
10
  reportCorpseDecision,
11
11
  playerStrategyIntent,
12
12
  strategyDecision,
13
- targetSeat,
14
13
  } from '../game-utils.js';
15
14
  import type { BehaviorDecision, StrategyContext } from '../types.js';
16
15
 
@@ -43,9 +42,10 @@ export function corpseReportWithNonTeammate(state: GameState, ctx: StrategyConte
43
42
  if (report.action.type === 'report') {
44
43
  // 实时给 Agent 一条「为什么是我报的尸」简报:报尸=召集会议,是高风险自证动作。
45
44
  // 若尸体很可能是自己刚才下的那一刀,必须显式提醒,免得 Agent 之后发言露馅。
46
- const corpseName = nearestReportableCorpse(state)?.name ?? '';
45
+ const corpse = nearestReportableCorpse(state);
46
+ const corpseName = corpse?.name ?? '';
47
47
  ctx.agentAlerts.push(
48
- isRecentOwnKill(ctx, corpseName)
48
+ isRecentOwnKill(ctx, corpse)
49
49
  ? `我刚下手的目标${corpseName ? `(${corpseName})` : ''}尸体被${witnessNames}撞见,我抢先报尸召集会议、把自己装成发现者并把嫌疑引向在场者。接下来发言/投票要顺着「我是主动报告的人」走,绝不能承认是自己动的手。`
50
50
  : `尸体旁有${witnessNames}在场,我抢先报尸召集会议、伪装成主动报告的好人。发言时按「主动报告的发现者」立场走。`,
51
51
  );
@@ -91,16 +91,16 @@ export function immediateLoneKillDecision(
91
91
  * 这具尸体是不是「自己刚才下的那一刀」。先按尸体座位号精确匹配 recentlyKilledTargets(刚杀过且未过期),
92
92
  * 座位对不上但近期确实杀过人时,冒出的尸体大概率也是自己造成的,按 true 处理(宁可多提醒一次)。
93
93
  */
94
- function isRecentOwnKill(ctx: StrategyContext, corpseName: string): boolean {
94
+ function isRecentOwnKill(
95
+ ctx: StrategyContext,
96
+ corpse: { seat?: number } | null,
97
+ ): boolean {
95
98
  const map = ctx.recentlyKilledTargets;
96
99
  if (!map || map.size === 0) return false;
97
100
  const now = Date.now();
98
- if (corpseName) {
99
- const seat = targetSeat(corpseName, ctx);
100
- if (seat != null) {
101
- const until = map.get(String(seat));
102
- if (until != null && until > now) return true;
103
- }
101
+ if (corpse?.seat != null) {
102
+ const until = map.get(String(corpse.seat));
103
+ if (until != null && until > now) return true;
104
104
  }
105
105
  for (const until of map.values()) {
106
106
  if (until > now) return true;