Skip to content

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

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "975"
goal_ref: "deterministic target scoring pure function を追加し、candidate filter・tie-break・score tuple を unit test で固定する"
change_kind: code
ssot_sections: ["§8", "§8.5"]
stage: 4
blocked_by: [981, 982]
dedupe_key: "follow-up:squne121/loop-protocol:pr/978:stage4"

この stage の詳細契約は docs/product/features/unit-operations-and-npc-behavior.md §8(候補フィルタ/tie-break/score tuple), §8.5 が SSOT である。本文の AC/Allowed Paths/VC はそれと矛盾しない。

Parent Issue

#975

関連 PR: #978(docs(#975): define unit operations and NPC behavior SSOT, merged)

Parent Goal Ref

  • Goal: §8 の candidate filter・tie-break(entityId ASC)・assist_player/enemy_chaser score tuple を pure function として実装し unit test を付ける
  • Desired Destination: targeting scoring pure function が src/systems/ に存在し、同一入力で同一出力が unit test で証明された状態

Current Validated Scope

  • src/systems/ に新規 targeting モジュールを追加する(ファイル名は実装者に委ねる)
  • tests/ に targeting unit test を追加する

Remaining Parent Gaps

  • stage5: ally_basic NPC state と semi-autonomous behavior(本 Issue 完了後)
  • stage6: existing enemy_chaser を new taxonomy へ非破壊移行(本 Issue 完了後)
  • stage7: assist_player DOM command affordance と Canvas visual cue(stage3/5 完了後)
  • stage8: assist_player playtest self-explanation test と evidence policy(stage7 完了後)

Blocked by

stage2(#981)— CommandIntent/Faction/TargetingPolicy 型が src/state に存在することを前提とする
stage3(#982)— CommandIntent buffer が存在することを前提とする

Outcome

§8 の candidate filter・tie-break(entityId ASC)・assist_player/enemy_chaser score tuple を pure function として実装し unit test を付ける。randomness/wall-clock/render/DOM/frame-rate 依存なし。

In Scope

  • src/systems/ への targeting モジュール追加
  • candidate filter(defeated/同faction/arena外/stale 除外)
  • tie-break(entityId ASC)
  • §8.3/§8.4 の score tuple
  • threatToPlayer は §8.5 の 3 案から 1 つ選び式を明記
  • tests/ への unit test 追加

Out of Scope

  • ally collection・behavior runtime の実装(stage5 の責務)
  • enemy_chaser の taxonomy 移行(stage6 の責務)
  • DOM affordance / Canvas cue(stage7 の責務)
  • randomness・wall-clock・render・DOM・frame-rate への依存

Acceptance Criteria

  • AC1: defeated/同faction/arena外/stale な candidate を除外する
  • AC2: 最終 tie-break が entityId ASC である
  • AC3: §8.3/§8.4 の score tuple 順に従う
  • AC4: threatToPlayer は §8.5 の 3 案から 1 つ選び式を明記し、randomness/wall-clock/render/DOM/frame-rate 依存なし
  • AC5: 同一入力で同一出力を確認する deterministic unit test が通る

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合

Required Skills

  • TypeScript / TSC strict
  • ECS(state / systems 分離)
  • deterministic pure function 設計

Verification Commands

実装前は targeting モジュールが未作成のため AC1〜AC5 の rg/test は baseline-fail する。

# AC1
# baseline-expect: fail
$ pnpm test
# AC2
# baseline-expect: fail
$ rg -e entityId src/systems
$ rg -e threatToPlayer src/systems
$ rg -e commandIntentMatch src/systems
# AC3
$ rg -e entityId src/systems
$ rg -e threatToPlayer src/systems
$ rg -e commandIntentMatch src/systems
# AC4
# baseline-expect: pass
$ rg "Date\.now" src/systems
# baseline-expect: pass
$ rg "performance\.now" src/systems
# baseline-expect: fail
$ rg "Math\.random" src/systems
# AC5
$ pnpm typecheck

Allowed Paths

  • src/systems/(新規 targeting モジュール)
  • tests/

Runtime Verification Applicability

Source

Activity

  1. added
    phase/implementation
    agent/implementer
    enhancement
    triage-required
    on Jun 18, 2026
  2. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    判定

    REQUEST_CHANGES / Issue contract 修正後に着手可。

    #983 の方向性自体は妥当です。#978 で作られた SSOT の §8 / §8.5 を stage4 として実装し、target scoring を pure function として固定するのは、後続の #984 ally_basic と #985 enemy_chaser migration の前提として必要です。#983 は open、コメントは空です。

    ただし、現状の #983 をそのまま Claude Code / Codex に渡すと、曖昧なスコア関数だけ作って終わる可能性が高いです。特に、entityId ASC の型、stale target の出力契約、threatToPlayer の式、入力 snapshot、sort mutation、#982 との接続境界が弱いです。

    主要ブロッカー

    1. blocked_by と RVA が古い

    #983 はまだ blocked_by: [981, 982] としていますが、#981 は closed/completed で、PR #988 により 5 型が src/state/GameState.ts に追加済みです。
    #982 も closed/completed で、CommandIntent buffer / KeyZ mapping / TTL contract が実装済み扱いになっています。

    修正案:

    blocked_by: []
    preconditions:
      - "#981 is closed by PR #988; Faction / CommandIntent / TargetingPolicy are exported from src/state/GameState.ts"
      - "#982 is closed; CommandIntentRuntimeState / BufferedCommandIntent exist"
      - "Stage4 consumes a deterministic snapshot input and does not read DOM/InputEvent/render state directly"

    また、#983 の Runtime Verification Applicability は deferred_destination: "#981" になっていますが、これは明らかに不整合です。stage4 は pure function + unit test で閉じるため、runtime verification: not_applicable または少なくとも deferred_destination: 本 Issue 実装完了時 に直すべきです。

    2. pure function の公開 API が未定義

    SSOT は targeting を pure function とし、同一入力で同一結果を要求しています。
    しかし #983 は「src/systems/ に新規 targeting モジュール」としか書いておらず、関数名、入力 snapshot、戻り値、stale target の扱いが未定義です。

    推奨 contract:

    // src/systems/TargetingSystem.ts
    
    export type TargetEntitySnapshot = Readonly<{
      entityId: string
      faction: Faction
      x: number
      y: number
      defeated?: boolean
      destroyed?: boolean
      isPlayer?: boolean
    }>
    
    export type TargetingActorSnapshot = Readonly<{
      entityId: string
      faction: Faction
      x: number
      y: number
      targetingPolicy: TargetingPolicy
    }>
    
    export type TargetSelectionInput = Readonly<{
      actor: TargetingActorSnapshot
      candidates: readonly TargetEntitySnapshot[]
      player: Readonly<{ entityId: string; x: number; y: number }>
      arena: Readonly<{ width: number; height: number }>
      commandIntent: CommandIntent
      commandIntentActive: boolean
      previousTargetId: string | null
      threatMode: 'binary_hostile_near_player'
      nearPlayerRadiusPx: number
    }>
    
    export type TargetSelectionResult = Readonly<{
      selectedTargetId: string | null
      clearedStaleTargetId: string | null
      scoredCandidates: readonly ScoredTarget[]
    }>

    重要なのは、GameState を直接読まないことです。stage4 は後続 stage5/6 のための scoring kernel であり、ally runtime や enemy migration に結合しすぎると分割が崩れます。

    3. entityId ASC が曖昧

    SSOT は最終 tie-break を entityId ASC としています。
    ただし現行 EnemyState.id は number、PlayerState.id は EntityId で、初期値は player-alpha です。

    このままだと、1 と 'player-alpha' の比較、敵 ID と player ID の比較、将来 ally ID の比較で実装が割れます。

    修正要求:

    Entity ID ordering:
    - Targeting input uses canonical string `entityId`.
    - The comparator compares canonical ASCII strings using `<` / `>`.
    - Runtime numeric enemy ids must be adapted before scoring, e.g. `enemy:000001`.
    - The final comparator must not return 0 for distinct candidates.

    これを入れないと、「entityId ASC」は見た目だけ deterministic で、実装者ごとに別の ordering になります。

    4. threatToPlayer は実装者に選ばせない方がよい

    SSOT §8.5 は threatToPlayer を 3 案から 1 つ選ぶ、としています。候補は inverse distance、projected time-to-contact、binary hostile-near-player です。

    #983 では binary hostile-near-player flag を固定するのが最も安全です。

    threatToPlayer =
      candidate.faction === 'enemy' &&
      distanceSq(candidate, player) <= nearPlayerRadiusPx * nearPlayerRadiusPx
        ? 1
        : 0

    理由は単純です。inverse distance は距離 0 の扱いに epsilon が必要で、projected time-to-contact は速度・進行方向が入力に必要です。現行 EnemyState は速度を持ちますが、ally / generic target snapshot にはまだ速度契約がありません。
    stage4 では binary の方が後続の #984 / #985 に安全に渡せます。

    5. stale target の扱いが出力契約になっていない

    SSOT は「stale target IDs cleared before scoring」と書いています。
    しかし #983 の AC は「stale を除外」程度で、呼び出し元が stale を検知できる戻り値になっていません。

    修正要求:

    export type TargetSelectionResult = Readonly<{
      selectedTargetId: string | null
      clearedStaleTargetId: string | null
      scoredCandidates: readonly ScoredTarget[]
    }>

    previousTargetId が candidates に存在しない場合、clearedStaleTargetId にその ID を返す。これで stage5/6 が「前ターゲットが消えたので再取得した」と判断できます。

    6. JS sort の罠を Issue に明記すべき

    target scoring は sort/comparator 実装になりがちです。Array.prototype.sort() は in-place mutation で、元配列を変更します。非破壊にするには toSorted() または shallow copy が必要です。また comparator は pure / reflexive / anti-symmetric / transitive な well-formed comparator である必要があり、壊れた comparator の挙動は engine 間で一致しません。ECMAScript 2019 以降 sort は stable ですが、#983 は最終 tie-break を持つべきなので、stable sort の入力順に依存してはいけません。([MDN Web Docs]1)

    修正要求:

    Comparator contract:
    - Do not mutate the input `candidates` array.
    - Sort a projected/scored copy only.
    - Comparator must be total and well-formed.
    - Distinct candidates must be distinguishable by final `targetEntityId ASC`.
    - Tests must prove reversed input order produces the same selected target.

    #982 との接続上の注意

    #982 の型・helper は存在します。BufferedCommandIntent / CommandIntentRuntimeState、isBufferedCommandIntentActive、sampleAssistPlayerIntent、tickCommandIntentRuntime は GameState.ts にあります。

    ただし、私が確認した runSortieSimulationStep の範囲では、sample_assist_player を sampleAssistPlayerIntent に接続する処理や tickCommandIntentRuntime の呼び出しは見えていません。現行順序は movement → spawn → enemy AI → combat → projectile → collision → sortie → tick increment です。

    したがって #983 では、state.commandIntentRuntime を直接読みに行くのではなく、commandIntent と commandIntentActive を snapshot input として受け取る pure functionにしてください。これなら #982 の統合状態に依存せず、stage5/6 が安全に使えます。

    必須テスト

    最低限、以下がないと merge しない方がよいです。

    Required tests:
    - defeated / destroyed candidates are filtered.
    - same-faction candidates are filtered.
    - outside-arena candidates are filtered.
    - previousTargetId が存在しない場合、clearedStaleTargetId を返す。
    - assist_player tuple order:
      commandIntentMatch DESC →
      threatToPlayer DESC →
      distanceToPlayer ASC →
      distanceToAlly ASC →
      targetEntityId ASC
    - enemy_chaser tuple order:
      isPlayer DESC →
      distanceToPlayer ASC →
      targetEntityId ASC
    - 同点時、入力順を反転しても同じ targetEntityId を選ぶ。
    - candidates 配列と candidate object を mutate しない。
    - binary threat formula の境界:
      inside / on boundary / outside / player と同座標。
    - commandIntentMatch は `commandIntent === 'assist_player' && commandIntentActive === true` のときだけ 1。
    - Date.now / performance.now / Math.random / DOM / Canvas / window / document を使わない。

    Verification Commands 修正版

    #983 の現行 VC は弱いです。特に禁止語 rg は、裸で実行すると「見つかったら成功」になるため逆です。#981 のレビューでも同じ問題が指摘されています。

    推奨:

    # AC1-AC5 targeted unit tests
    pnpm test -- tests/systems/targeting-system.test.ts
    
    # module exists and exports stable API
    test -f src/systems/TargetingSystem.ts
    rg -n "selectTarget|scoreTargetCandidates|threatToPlayer|commandIntentMatch|targetEntityId" src/systems/TargetingSystem.ts
    
    # forbidden dependencies: absence check must expect rg exit code 1
    bash -lc 'set +e; rg -n "Date\\.now|performance\\.now|Math\\.random|window\\.|document\\.|HTMLCanvasElement|CanvasRenderingContext2D" src/systems/TargetingSystem.ts; status=$?; test "$status" -eq 1'
    
    # canonical gates
    pnpm typecheck
    pnpm lint
    pnpm test
    pnpm build
    uv run pytest .claude/skills/gemini-cli-headless-delegation/tests/test_model_routing.py

    Allowed Paths 修正版

    現行の tests/ は広すぎます。stage5/6 と衝突しやすいので絞るべきです。

    ## Allowed Paths
    
    - `src/systems/TargetingSystem.ts`
    - `src/systems/index.ts`(re-export が必要な場合のみ)
    - `tests/systems/targeting-system.test.ts`

    Evidence / 配布物

    #983 は pure system + unit test の stage なので、Pages preview、スクリーンショット、viewport / DPR / browser zoom 証跡は不要です。SSOT の Evidence / Distribution Policy は UI / playtest follow-up PR に必須であり、docs-only や pure-system PR には境界があります。

    ただし PR body には通常の証跡として、commit SHA、GitHub Actions run ID、実行した gate の結果は残すべきです。

    GitHub に貼るレビューコメント案

    REQUEST_CHANGES / Issue contract 修正後に着手可。
    
    #983 の stage4 方向性は妥当。#978 SSOT §8 / §8.5 の targeting policy を pure function + unit test として固定するのは、後続 #984 ally_basic と #985 enemy_chaser migration の前提として必要。
    
    ただし現 Issue contract のまま実装 agent に渡すと、曖昧な score helper だけ作って終わる危険が高い。
    
    Blockers:
    
    1. `blocked_by: [981, 982]` が古い。#981 は PR #988 で closed、#982 も closed。`blocked_by: []` とし、preconditions に「#981/#982 完了済み」「Stage4 は deterministic snapshot input を受け取る」と明記する。
    2. Runtime Verification Applicability の `deferred_destination: "#981"` は不整合。pure function + unit test で閉じるため `not_applicable` または本 Issue 内完了条件へ修正する。
    3. public API が未定義。`src/systems/TargetingSystem.ts`、`selectTarget(input)`、`scoreTargetCandidates(input)`、`TargetSelectionInput`、`TargetSelectionResult` を固定する。
    4. `entityId ASC` が曖昧。number/string 混在を避け、canonical string `entityId` の total order を定義する。distinct candidates で comparator が 0 を返さないこと。
    5. `threatToPlayer` は実装者に選ばせず、stage4 MVP は `binary_hostile_near_player` に固定する。inverse distance / time-to-contact は後続で拡張。
    6. stale target は「除外」だけでなく `clearedStaleTargetId` として返す契約にする。
    7. `Array.prototype.sort()` は input mutation の危険があるため、scored copy のみ sort する。入力配列が mutate されない unit test を必須にする。
    8. Stage4 は `GameState` / DOM / render / InputEvent を直接読まない。`commandIntent` と `commandIntentActive` は snapshot input として受け取る。
    9. Allowed Paths は `src/systems/TargetingSystem.ts`, `src/systems/index.ts`(必要時のみ), `tests/systems/targeting-system.test.ts` に狭める。
    10. VC は targeted test + canonical gates にする。禁止語 `rg` は exit code 1 を期待する absence check にする。
    
    推奨 threat formula:
    
    ```ts
    threatToPlayer =
      candidate.faction === 'enemy' &&
      distanceSq(candidate, player) <= nearPlayerRadiusPx * nearPlayerRadiusPx
        ? 1
        : 0

    Required tests:

    • defeated / destroyed / same faction / outside arena / stale target filter
    • assist_player score tuple order
    • enemy_chaser score tuple order
    • input order reversed でも同じ selectedTargetId
    • candidates / candidate object を mutate しない
    • commandIntentMatch は assist_player かつ active のときだけ 1
    • Date.now / performance.now / Math.random / DOM / Canvas / window / document 不使用
    • pnpm typecheck, pnpm lint, pnpm test, pnpm build, Gemini routing pytest
    
    この修正を入れれば、#983 は **後続 #984/#985 に渡せる安定した targeting kernel** になります。現状のままでは、stage4 の成果物が stage5/6 の実装時に再設計される可能性が高いです。
    
  3. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  4. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-06-20T17:25:44Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/983
      body_sha256: "sha256:f7506e4e690b2a3d93febaca9f2994b51f248b7fd05eaaef62dae96e7e972984"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent/implementerenhancementphase/implementationtriage-required

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions