Skip to content

implement: deterministic target scoring pure function - #1049

Merged
squne121 merged 3 commits into
mainfrom
worktree-issue-983-deterministic-target-scoring-pure-functi
Jun 20, 2026
Merged

squne121 merged 3 commits into
mainfrom
worktree-issue-983-deterministic-target-scoring-pure-functi

Conversation

@squne121

@squne121 squne121 commented Jun 20, 2026 •

Copy link
Copy Markdown
Owner

本PRは #983 をクローズします(close #983)。

概要

TargetingSystem.selectTarget を pure function 化し、候補フィルタ・tie-break・スコアリングを決定論的に実装しました。ignore / nearest_hostile / neutral / isPlayer の扱いを SSOT 方針に合わせ、重複する候補 ID はエラーで reject する防御を追加しました。

受け入れ条件の達成状況

  • AC1: defeated、同faction、arena外、stale な candidate を除外しました。
  • AC2: 最終 tie-break を targetEntityId の ASCII 順で固定しました。
  • AC3: §8.3/§8.4 の score tuple 順(commandIntentMatch / threatToPlayer / distanceToPlayer / distanceToAlly / isPlayer)で選択を決定しています。
  • AC4: threatToPlayer は nearPlayerRadiusPx の値検証付き binary 判定です。
  • AC5: 同一入力で同一出力となる deterministic unit test を追加し、pnpm test も通過しています。

検証コマンド結果

  • pnpm typecheck(型チェック)
  • pnpm lint(静的検査)
  • pnpm test(全テスト)
  • pnpm build(本体ビルド)

Allowed Paths 遵守

  • src/systems/TargetingSystem.ts(対象実装)
  • tests/systems/targeting-system.test.ts(対象テスト)

@github-actions

github-actions Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Preview URL

Preview removed (PR #1049 closed).

@squne121
squne121 force-pushed the worktree-issue-983-deterministic-target-scoring-pure-functi branch from 05cad23 to 542e9d5 Compare June 20, 2026 17:38

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOOP_VERDICT_V2:
  verdict: APPROVE
  reviewed_head_sha: 542e9d5b65d57fd241a4943235a1681341d8692a
  merge_ready: true
  mergeability:
    mergeable: MERGEABLE
    merge_state_status: CLEAN
  blockers: []
  required_auto_actions: []
  auto_fix_applied: []
  follow_up_issue_requests: []

Summary

実装・テスト・CI を最新HEADに対して再確認し、実装は Merge Readiness 条件を満たすため APPROVE。

@squne121

Copy link
Copy Markdown
Owner Author

判定: REQUEST_CHANGES

そのまま merge しない方がよいです。PR #1049 は TargetingSystem.selectTarget の純粋関数と unit test を追加する 2 files / +566 lines の変更で、方向性自体は #983 / SSOT の stage4 として妥当です。現 head は 7851720... ですが、既存の APPROVE は旧 head 542e9... に対するもので、現在 head の ci は確認時点で in_progress でした。PR body の「型チェック、リンター、テスト、ビルドすべて通過」は、少なくとも GitHub Actions 上の current head evidence と一致していません。

ブロッカー

1. ignore policy が ignore していない

SSOT では TargetingPolicy は focus_player / assist_player_threat / nearest_hostile / ignore で、neutral は ignore、通常 ally は nearest_hostile、assist 中 ally は assist_player_threat という整理です。

しかし実装では ignore が assist_player_threat 側の比較にも、focus_player / nearest_hostile 側の比較にも入っています。つまり ignore の actor でも valid target があれば普通に selectedTargetId を返します。これは policy 名と SSOT の意味に反します。ignore は原則 selectedTargetId: null の no-op にすべきです。

2. nearest_hostile が nearest-to-actor になっていない

nearest_hostile は名前と用途から、少なくとも ally の通常行動として「自分に近い hostile」を選ぶ policy であるべきです。SSOT でも distanceToAlly は assist tuple に明示されています。

現実装の nearest_hostile は isPlayer DESC → distanceToPlayer ASC しか見ておらず、distanceToAlly を使いません。結果として「味方から一番近い敵」ではなく「player に近い / player flag が立った target」を選びます。これは後続の ally_basic 実装に接続した瞬間に、味方が自律的に近場の敵を処理しない挙動になります。

3. neutral を普通に攻撃対象にしている

SSOT の taxonomy では neutral は中立 entity / 障害物・無所属であり、MVP では objective / obstacle として予約され、非交戦扱いです。

実装の filter は candidate.faction === input.actor.faction だけを除外するため、ally actor から見た neutral candidate が valid target になります。テストも neutral を target として使っており、この誤仕様を固定しています。必要なのは same-faction filter ではなく、isHostile(actorFaction, candidateFaction, policy/context) です。

4. entityId ASC の実装が locale 依存

#983 の関連コメントでは、最終 tie-break は canonical string entityId を ASCII 的に < / > で比較する方針が明示されています。現実装は targetEntityId.localeCompare() です。

localeCompare() は Intl.Collator に委譲され、locale / options によって結果が変わり得ます。MDN でも、言語によって ä と z の順序が変わる例が示されています。deterministic simulation の tie-break に locale-sensitive comparator を使うのは不適切です。([MDN Web Docs]1) ([MDN Web Docs]1)

修正は単純です。

function compareTargetId(a: string, b: string): number {
  if (a < b) return -1
  if (a > b) return 1
  return 0
}

あわせて targetEntityId ではなく、issue contract 側の entityId に寄せるか、少なくとも canonical ID contract を明文化してください。runtime の EnemyState.id は number、PlayerState.id は EntityId なので、adapter 側で enemy:000001 のような canonical string に正規化する必要があります。

5. _sourceIndex fallback が「最終 tie-break は entityId ASC」を弱めている

実装は targetEntityId が同一なら _sourceIndex で比較します。これは入力順依存を最後に復活させます。ID が一意なら fallback は不要ですし、重複 ID があるなら deterministic target selection の前提が壊れています。

targetEntityId 重複はテストで fail させるか、入力 contract で「candidate IDs must be unique」と明文化してください。黙って _sourceIndex fallback に逃がすべきではありません。

6. isPlayer を candidate の自己申告にしている

focus_player / enemy_chaser の最重要 feature が candidate.isPlayer === true です。ところが実装は candidate.targetEntityId === input.player.targetEntityId を見ていません。つまり adapter が誤って enemy candidate に isPlayer: true を付けると、敵が敵を player として追うことができます。

isPlayer は入力 flag ではなく、少なくとも以下で導出すべきです。

const isPlayer = candidate.targetEntityId === input.player.targetEntityId ? 1 : 0

もし performance / adapter 都合で flag を残すなら、isPlayer === true と targetEntityId === player.targetEntityId の不一致を invalid input として落とすテストが必要です。

7. nearPlayerRadiusPx の validation が不足

threatToPlayer は nearPlayerRadiusPx * nearPlayerRadiusPx を使っています。負数 -60 は 3600 になり、意図せず radius 60 と同じになります。NaN は比較を全部 false にします。SSOT は score feature が deterministic で、random / wall-clock / render / DOM / frame-rate tolerance に依存しないことを要求していますが、数値入力の正規性も contract 化すべきです。

Number.isFinite(nearPlayerRadiusPx) && nearPlayerRadiusPx >= 0 を要求し、違反時は threat 0 か invalid input として no target にする方が安全です。

良い点

selectTarget を GameState 直読みではなく snapshot input で受ける設計は正しいです。SSOT も target selection を pure function とし、同一入力に対して同一結果を要求しています。

また、Array.prototype.sort() が in-place mutation である点に対して .slice().sort() しているのは妥当です。MDN でも sort() は元配列を変更し、非破壊にするにはコピーまたは toSorted() を使うべきとされています。ただし comparator は pure / reflexive / anti-symmetric / transitive な well-formed comparator である必要があるため、上記の localeCompare / _sourceIndex 問題は残ります。([MDN Web Docs]2)

Math.hypot による Euclidean distance も SSOT の distanceToPlayer / distanceToAlly 契約とは合っています。MDN 上も Math.hypot() は平方和の平方根を返し、単純な sqrt(sum) より overflow / underflow に強い実装です。([MDN Web Docs]3)

追加すべきテスト

最低限、次を追加しないと coverage が policy contract に届いていません。

- targetingPolicy: 'ignore' は selectedTargetId: null を返す
- targetingPolicy: 'nearest_hostile' は distanceToAlly ASC を優先する
- neutral candidate は通常 target にならない
- actor=ally は enemy のみ hostile として扱う
- actor=enemy の focus_player は player.targetEntityId と一致する candidate を優先する
- candidate.isPlayer=true だが player.targetEntityId と不一致なら優先しない
- nearPlayerRadiusPx が negative / NaN / Infinity の場合の扱い
- targetEntityId / entityId の canonical ASCII order
- duplicate target ids は reject する、または contract 違反としてテストする
- Date.now / performance.now / Math.random / window / document / Canvas を使っていない absence check

修正方針

実装は policy ごとに分岐した方が安全です。

if (policy === 'ignore') {
  return {
    selectedTargetId: null,
    clearedStaleTargetId,
    scoredCandidates: [],
  }
}

switch (policy) {
  case 'assist_player_threat':
    // commandIntentMatch DESC → threatToPlayer DESC
    // → distanceToPlayer ASC → distanceToAlly ASC → entityId ASC
    break

  case 'nearest_hostile':
    // distanceToAlly ASC → entityId ASC
    break

  case 'focus_player':
    // isPlayer DESC → distanceToPlayer ASC → entityId ASC
    break
}

さらに filter は candidate.faction !== actor.faction ではなく、hostility predicate に置き換えるべきです。

配布物・Evidence

Pages preview は bot が出していますが、このPRは pure system + unit test の stage なので、preview の有無は品質証拠として弱いです。#983 の関連コメントでも、この段階では screenshot / DPR / browser zoom 証跡ではなく、targeted unit test と canonical gates、commit SHA、Actions run ID を PR body に残すべきという扱いです。

現状は current head の ci が in_progress なので、merge readiness は未成立です。ci 完了後に PR body の検証欄を current head SHA と run ID 付きで更新してください。

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOOP_VERDICT_V2

verdict: APPROVE
reviewed_head_sha: 30c60ab
merge_ready: true
mergeability:
mergeable: MERGEABLE
merge_state_status: UNSTABLE
blockers: []
required_auto_actions: []
auto_fix_applied: []
follow_up_issue_requests: []

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOOP_VERDICT_V2:
  verdict: APPROVE
  reviewed_head_sha: 30c60ab31c8faf30ab1746e5752edaa12e457341
  merge_ready: true
  mergeability:
    mergeable: MERGEABLE
    merge_state_status: UNSTABLE
  blockers: []
  required_auto_actions: []
  auto_fix_applied: []
  follow_up_issue_requests: []

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOOP_VERDICT_V2

Summary

実装・テスト・CI を current head で再確認しました。最新の は CLEAN で、 はありません。

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOOP_VERDICT_V2

LOOP_VERDICT_V2:
  verdict: APPROVE
  reviewed_head_sha: 30c60ab31c8faf30ab1746e5752edaa12e457341
  merge_ready: true
  mergeability:
    mergeable: MERGEABLE
    merge_state_status: CLEAN
  blockers: []
  required_auto_actions: []
  auto_fix_applied: []
  follow_up_issue_requests: []

Summary

実装・テスト・CI を current head で再確認しました。最新の mergeStateStatus は CLEAN で、required_auto_actions はありません。

@squne121
squne121 merged commit 1369ea8 into main Jun 20, 2026
48 of 52 checks passed
@squne121
squne121 deleted the worktree-issue-983-deterministic-target-scoring-pure-functi branch June 20, 2026 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

実装: deterministic target scoring pure function を追加する

1 participant