Skip to content

実装: SortieResult から報酬を算出する RewardSystem を追加する #737

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "#733"
goal_ref: "M3: Loop MVP Gate — terminal SortieResult から reward_formula_version: 1 の報酬を算出し resources へ exactly-once で反映する RewardSystem を追加する"
change_kind: code

Parent Issue

#733

Parent Goal Ref

  • Goal: M3: Loop MVP Gate (v0.3.x) として sortie 結果から報酬を獲得し localStorage へ進行を永続化して reload 後に復元する
  • Desired Destination: src/systems/RewardSystem.ts が terminal SortieResult から reward を pure に算出し、progress.resources への state transition を exactly-once で提供する

Current Validated Scope

  • src/state/GameState.ts には ProgressState { stageLabel, resources, weaponPower }、SortieResult discriminated union(outcome: 'victory' | 'defeat' | 'timeout' / endReason / durationMs / kills / shotsFired / playerHpRemaining)が実装済み
  • src/state/GameState.ts の GameSnapshot は schemaVersion: 1 を持つが、reward claim 用の runtime token / latch / consumed ledger は未実装
  • src/systems/SortieSystem.ts は terminal SortieResult を生成して state.sortie に格納するが、sortie lifecycle terminal transition event を識別する applicationId / consumed token / rewardApplied 相当は未実装
  • src/systems/CombatSystem.ts は damage / defeat を担当し、progress.resources を直接 mutate しない責務境界を維持している
  • docs/product/features/resource.md は reward_formula_version: 1、RESOURCE_CAP = 9_999_999、PER_SORTIE_REWARD_CAP = 500、victory / defeat / timeout の reward 差分、invalid 値処理、exactly-once 単位が value identity ではなく 1 sortie lifecycle の terminal transition event であることを normative に定義している
  • docs/product/features/persistence.md は SortieResult を永続化しないこと、reload 後に復元されるのは progression snapshot のみであること、reload 後の再 claim 不可は save / reload integration の責務であることを定義している
  • src/systems/RewardSystem.ts と tests/reward-system.test.ts は未作成

Remaining Parent Gaps

Outcome

src/systems/RewardSystem.ts が RewardSystem.calculate(result) と RewardSystem.claim(state, applicationId, result) を export し、calculate() は terminal SortieResult から reward_formula_version: 1 の RewardQuote を pure に算出し、claim() は同一 applicationId に対して progress.resources への saturated addition を最大 1 回だけ行う。tests/reward-system.test.ts には victory / defeat / timeout の exact formula、per-sortie cap、RESOURCE_CAP への saturated addition、invalid 値 fallback、same-token double-claim 防止、same-payload different-token claim を含む regression test が追加され、pnpm typecheck / pnpm lint / pnpm test / pnpm build が通る状態にする。

In Scope

  • src/systems/RewardSystem.ts 新規作成
  • RewardSystem.calculate(result: SortieResult): RewardQuote の実装
  • RewardSystem.claim(state: GameState, applicationId: RewardApplicationId, result: SortieResult): RewardClaimResult の実装
  • REWARD_FORMULA_VERSION = 1、RESOURCE_CAP = 9_999_999、PER_SORTIE_REWARD_CAP = 500 の単一定義
  • victory / defeat / timeout の exact reward formula 実装
  • reward delta と resourcesAfter の non-negative safe integer / clamp / saturated addition 実装
  • src/state/GameState.ts への runtime-only reward claim ledger / token 消費状態の追加(applicationId 重複適用防止に必要な最小範囲)
  • same-token double-claim 防止
  • same-payload different-token claim を正当加算として扱う決定論テスト
  • tests/reward-system.test.ts 新規作成
  • src/systems/index.ts の export 追加(必要な場合のみ)

Out of Scope

  • SortieSystem.ts 側で terminal transition token を生成する wiring
  • debrief / preparation UI や button 連打ハンドリングそのもの
  • localStorage への保存 wiring
  • reload 後の再 claim 不可の end-to-end 証明
  • storage failure handling
  • CombatSystem による resources の直接 mutate
  • weapon upgrade / resource 消費ロジック(M4 スコープ)
  • reward coefficient の最終 tuning

Acceptance Criteria

  • AC1: src/systems/RewardSystem.ts が RewardSystem.calculate() と RewardSystem.claim() を export する
  • AC2: RewardSystem.calculate() は terminal SortieResult だけから RewardQuote を pure に算出し、同一入力から同一出力を返す
  • AC3: victory / defeat / timeout の reward が docs/product/features/resource.md の exact formula に一致する
  • AC4: reward delta は PER_SORTIE_REWARD_CAP = 500 で clamp され、resourcesAfter は RESOURCE_CAP = 9_999_999 への saturated addition になる
  • AC5: invalid 値(NaN / Infinity / 負値 / 小数 / unsafe integer)を含む result または resourcesBefore でも reward / resources を壊さず、spec に沿った fallback を行う
  • AC6: RewardSystem.claim() は同一 applicationId を 2 回以上渡しても progress.resources を最大 1 回しか加算しない
  • AC7: 同一 payload の別 sortie を表す異なる applicationId では、同じ SortieResult 内容でも別 reward application として加算される
  • AC8: CombatSystem は progress.resources を直接 mutate しない既存責務境界を破壊しない
  • AC9: tests/reward-system.test.ts が victory / defeat / timeout exact value、cap、invalid fallback、same-token double-claim、same-payload different-token claim を検証する
  • AC10: pnpm typecheck / pnpm lint / pnpm test / pnpm build が通る

Verification Commands

# AC1
$ test -f src/systems/RewardSystem.ts

# AC2
# preflight-scope: pr_review_only
$ rg -n "pure|RewardQuote|formulaVersion" src/systems/RewardSystem.ts tests/reward-system.test.ts

# AC3
# preflight-scope: pr_review_only
$ rg -n "victory|defeat|timeout" tests/reward-system.test.ts
# preflight-scope: pr_review_only
$ rg -n "100|10|30|kills \\* 5|playerHpRemaining" tests/reward-system.test.ts

# AC4
# preflight-scope: pr_review_only
$ rg -n "PER_SORTIE_REWARD_CAP|RESOURCE_CAP|saturated" src/systems/RewardSystem.ts tests/reward-system.test.ts

# AC5
# preflight-scope: pr_review_only
$ rg -n "NaN|Infinity|fraction|negative|unsafe" tests/reward-system.test.ts

# AC6
# preflight-scope: pr_review_only
$ rg -n "applicationId|already-claimed|double-claim|same token" src/systems/RewardSystem.ts tests/reward-system.test.ts

# AC7
# preflight-scope: pr_review_only
$ rg -n "different token|different applicationId|same payload" tests/reward-system.test.ts

# AC8
# preflight-scope: pr_review_only
$ rg -n "progress\\.resources" src/systems/CombatSystem.ts

# AC9
$ test -f tests/reward-system.test.ts

# AC10
# preflight-scope: pr_review_only
$ pnpm typecheck
# preflight-scope: pr_review_only
$ pnpm lint
# preflight-scope: pr_review_only
$ pnpm test
# preflight-scope: pr_review_only
$ pnpm build

Stop Conditions

Runtime Verification Applicability

Allowed Paths

  • src/systems/RewardSystem.ts
  • src/state/GameState.ts
  • src/systems/index.ts
  • tests/reward-system.test.ts

Required Skills

  • TypeScript / TSC strict
  • ECS(state / systems 分離)
  • deterministic state transition 設計
  • Vitest BDD

Activity

  1. added
    phase/implementation
    agent/implementer
    enhancement
    on Jun 7, 2026
  2. added 2 commits that reference this issue on Jun 7, 2026
  3. squne121 commented on Jun 8, 2026

    @squne121
    OwnerAuthor

    判定

    CHANGES REQUESTED。#737 はこのまま実装に入ると危険です。
    理由は、#737 本文の「同一 SortieResult → 一度だけ反映」という表現が、すでに #735 / PR #748 / resource.md で修正された lifecycle terminal transition event 単位の exactly-once とズレているためです。値同一性で二重加算を防ぐ実装に誘導すると、同一 payload の別 sortie を誤って握り潰すか、逆に同一 sortie の clone/re-render/retry を二重加算します。#737 は現在 open で、公開ページ上では related PR / branch はまだありません。(GitHub)

    確認した主対象は #737、parent #733、#735 と merged PR #748、#736/#738/#739、現行 resource.md / persistence.md、GameState.ts / SortieSystem.ts、および localStorage / Vite 配布 / Playwright 検証まわりの公式ドキュメントです。


    1. 最大の欠陥: 「同一 result」の定義が実装者を壊す

    #737 は RewardSystem.ts を作り、SortieResult から決定論的に報酬を計算し、progress.resources に一度だけ反映することを要求しています。In Scope でも「同一 result の反映は一度のみ」、AC4 でも「報酬反映は progress.resources に対して一度のみ」と書かれています。(GitHub)

    しかし、これはそのままでは不十分です。PR #748 のレビューで、exactly-once の単位は object identity でも JSON.stringify(result) でも shallow equality でもなく、1 sortie lifecycle の terminal transition event とする必要がある、と明確に指摘されています。同一内容の SortieResult が別 sortie で発生し得るため、値ベース重複排除は正当な報酬まで落とします。(GitHub)
    その後の PR 対応でも、この点は反映済みです。resource.md は「value identity ではなく terminal transition event」「同一 payload の別 sortie は別 application」「JSON.stringify / shallow equality 禁止」「rewardApplied latch または consumed token」を要求しています。(GitHub)

    要求修正: #737 の本文から「同一 result」という曖昧語を削り、次に置き換えるべきです。

    RewardSystem.calculate(result: SortieResult): RewardQuote
    RewardSystem.claim(state: GameState, applicationId: RewardApplicationId, result: SortieResult): RewardClaimResult
    

    calculate() は完全 pure。claim() は applicationId / consumed token / rewardApplied latch による state transition です。parent #733 も、#737 は RewardSystem.calculate() と RewardSystem.claim() を分け、apply-once の実装根拠を持つことを child contract としています。(GitHub)


    2. #737 の Allowed Paths では、正しい exactly-once を完結できない可能性が高い

    現行 SortieSystem.ts は terminal 到達時に result を作って state.sortie = terminalState へ入れていますが、そこに sortie instance id、terminal transition id、pending reward、claimed flag のような識別子はありません。SortieState も terminal state に result を持つだけです。(GitHub)

    一方で #737 の Allowed Paths は RewardSystem.ts、GameState.ts、systems/index.ts、tests/reward-system.test.ts のみです。SortieSystem.ts は含まれていません。(GitHub)
    parent #733 は、再 claim・ダブルクリック・reload 跨ぎの二重加算防止に、pendingReward / claimed flag / lastClaimedSortieId 相当の識別子を #737 / #738 契約に含めると明記しています。(GitHub)

    敵対的に見ると、ここは stop condition です。
    #737 が lifecycle token を生成・消費する責務まで持つなら、Allowed Paths に src/systems/SortieSystem.ts を追加しないと不自然です。逆に #737 を純粋な calculate() と token-aware claim() の API 定義までに絞るなら、terminal token の生成と debrief wiring は #738 に明示的に defer すべきです。


    3. reload 後の二重 claim は #737 だけでは証明できない

    #737 は localStorage wiring を Out of Scope にしています。(GitHub)
    しかし parent #733 の Additional AC は、claim 済み reward が reload 後に再 claim 可能にならないことまで要求しています。(GitHub)

    この reload 境界は #739 の責務です。#739 は報酬確定後に progression snapshot を localStorage へ保存し、page reload 後に resources を復元する保存ポイントを wiring する issue です。さらに #739 は #736、#738、#621 の完了を前提にしています。(GitHub)
    persistence.md も、SortieResult は localStorage に書かず、reload 後に復元されるのは適用済みの progression snapshot のみで、SortieResult を再構築・再計算しない、と定めています。(GitHub)

    要求修正: #737 の AC4 は「同一 runtime terminal transition に対する in-memory claim は一度のみ」に狭める。reload 後の再 claim 不可は #739 / #740 の integration / E2E に移す。#737 単体で reload exactly-once を満たしたと主張してはいけません。


    4. 報酬式はすでに resource.md が正本。実装で再解釈してはいけない

    resource.md は reward_formula_version: 1 の固定値を定義済みです。base reward は victory 100、defeat 10、timeout 30、kill bonus は kills * 5、victory のみ playerHpRemaining * 1、per-sortie cap は 500 です。(GitHub)

    resources 側は non-negative safe integer、初期値 0、RESOURCE_CAP = 9_999_999、overflow は cap clamp、負値 / NaN / Infinity / 小数は invalid fallback 0 と定義されています。(GitHub)
    parent #733 も、resources は有限非負整数、RESOURCE_CAP 上限、saturated addition、reward が NaN / Infinity / 負値 / 小数を返さないことを AC にしています。(GitHub)

    要求修正: #737 の RewardSystem.ts には、少なくとも以下を明示的に export するべきです。

    export const REWARD_FORMULA_VERSION = 1 as const
    export const RESOURCE_CAP = 9_999_999
    export const PER_SORTIE_REWARD_CAP = 500
    

    さらに、テストは「victory / defeat / timeout の差がある」だけでは弱いです。以下の exact value を検証すべきです。

    victory: 100 + kills * 5 + playerHpRemaining
    defeat: 10 + kills * 5
    timeout: 30 + kills * 5
    rewardDelta: clamp(rawDelta, 0, 500)
    resourcesAfter: clamp(validResourcesBefore + rewardDelta, 0, 9_999_999)
    

    Math.floor(NaN) は NaN を返すため、kills や playerHpRemaining に poisoned value が入った時点で計算結果が壊れます。TypeScript の型だけに依存せず、unknown as SortieResult で NaN / Infinity / negative / fraction を流すテストを追加してください。


    5. timeout は independent outcome。#738 側がまだ古い

    現行 GameState.ts の SortieResult は outcome: 'victory' | 'defeat' | 'timeout' の discriminated union です。timeout は endReason: 'timeout' を持つ独立 variant です。(GitHub)
    SortieSystem.ts も defeat > victory > timeout の優先順位で terminal 判定し、timeout branch では outcome: 'timeout' / endReason: 'timeout' を作っています。(GitHub)
    resource.md も、timeout を defeat と混同してはならない neutral terminal と定めています。(GitHub)

    ところが #738 の Current Validated Scope は SortieStatus = 'idle' | 'running' | 'victory' | 'defeat' | 'ended' と記載しており、timeout が抜けています。Outcome / AC1 も victory / defeat 到達後の debrief だけを明記しています。(GitHub)

    要求修正: #738 の issue contract を修正し、victory | defeat | timeout 全 terminal が debrief に入ることを AC に入れるべきです。#737 が timeout reward を正しく計算しても、#738 が timeout を debrief / save path に流さなければ M3 loop は壊れます。


    6. calculate() と claim() の責務分離が必須

    README は systems が DOM / Canvas API に依存しないこと、更新は fixed timestep 60Hz で進めることをアーキテクチャ方針にしています。(GitHub)
    parent #733 も、storage アクセスは adapter に隔離し、systems 層・60Hz update loop から呼ばないと定めています。(GitHub)

    したがって、#737 の RewardSystem.ts は localStorage、document、Canvas、wall-clock、乱数に触ってはいけません。
    calculate() は SortieResult → RewardQuote の pure function。claim() は GameState の progress.resources を変更する唯一の state transition。保存は #739、storage failure は #621、runtime E2E は #740 です。

    推奨戻り値は例として次です。

    type RewardQuote = Readonly<{
      formulaVersion: 1
      outcome: SortieResult['outcome']
      base: number
      killBonus: number
      hpBonus: number
      delta: number
    }>
    

    type RewardClaimResult =
    | { ok: true; quote: RewardQuote; resourcesBefore: number; resourcesAfter: number }
    | { ok: false; reason: 'not-terminal' | 'already-claimed' | 'invalid-result' }

    例外 throw より union result の方が、UI / debrief / save failure の後続設計と接続しやすいです。


    7. GameSnapshot / ProgressState の混同に注意

    現行 ProgressState は stageLabel, resources, weaponPower だけです。GameSnapshot は schemaVersion, resources, weaponPower, playerMaxHp を持ちます。createGameSnapshot() もこの 4 フィールドを返します。(GitHub)
    #736 は、schemaVersion missing は legacy v0 migration、unknown は null fallback、resources は non-negative safe integer、overflow は RESOURCE_CAP clamp、SortieResult は永続化しない、と契約修正しています。(GitHub)

    要求修正: #737 で pendingReward / rewardApplied / lastClaimedSortieId 相当を足す場合、それが runtime-only なのか、snapshot に含むのかを明示してください。現行 persistence.md は SortieResult や sortie runtime を永続化しない設計です。pendingReward を snapshot に入れると、その設計と衝突します。(GitHub)

    現実的には、#737 は runtime-only latch / consumed token を使い、保存されるのは claim 後の resources だけにするのが安全です。


    8. localStorage / 配布物まわりの調査結果を反映すべき点

    #737 自体は storage を触らないべきですが、exactly-once の設計は storage と配布環境の制約を前提にしておく必要があります。

    MDN によると localStorage は origin 単位で分割され、同じ origin の document は同じ localStorage 領域を共有します。また file: URL の localStorage 要件は未定義で、SecurityError が発生し得ます。(MDNウェブドキュメント)
    Web Storage は同期 API なので、set/get/remove は他の JavaScript 実行をブロックし得ます。毎 tick 保存しない #739 の方針は妥当です。(MDNウェブドキュメント)
    容量面では Web Storage は全ブラウザで最大 10 MiB、localStorage は origin あたり 5 MiB とされ、上限到達時は QuotaExceededError を try/catch で扱うべきです。(MDNウェブドキュメント)

    Vite の本番ビルドは vite build により静的ホスティング向け bundle を生成します。Vite の static deploy docs は既定出力を dist とし、vite preview は dist を http://localhost:4173 で配信するローカル確認用サーバーで、本番サーバーではないと明記しています。(vitejs)
    したがって、M3 の runtime smoke test は file:// ではなく HTTP origin 上で実施する必要があります。これは parent #733 の dist/ を HTTP origin 経由で smoke test する AC とも一致します。(GitHub)

    また、PR #748 のレビューでも指摘されている通り、GitHub Pages の /loop-protocol/ 本番と /loop-protocol/pr-748/ preview は同一 origin になり得るため、同じ loop-protocol.mvp.save key を共有します。persistence.md はこのリスクを反映し、E2E / preview では test 前に key clear、必要なら preview key suffix を検討するとしています。(GitHub)


    9. Verification Commands が弱すぎる

    #737 の verification は rg -n "victory|defeat|timeout" や rg -n "二重|once|already|applied" のような grep が多いです。(GitHub)
    これは仕様語をコメントに書けば通ります。敵対的には、次の破損実装でも grep は通ります。

    if (JSON.stringify(result) === state.lastRewardResultJson) return

    これは同一 payload の別 sortie を潰すため、resource.md の禁止事項に反します。(GitHub)

    最低限、tests/reward-system.test.ts は次を検証してください。

    分類 必須テスト
    formula victory / defeat / timeout の exact value
    cap per-sortie cap 500、RESOURCE_CAP = 9_999_999 への saturated addition
    invalid NaN / Infinity / negative / fraction / huge number が reward/resource を壊さない
    exactly-once 同一 applicationId を 2 回 claim しても 1 回だけ加算
    別 sortie 同一 payload でも異なる applicationId なら 2 回加算
    clone 同一 sortie の cloned result でも token が同じなら再加算されない
    purity calculate() は state を mutate しない
    boundary RewardSystem.ts は DOM / Canvas / localStorage を import しない

    Playwright は browser context ごとに isolation され、storage state には localStorage snapshot も含まれます。#740 の E2E では、この性質を使って HTTP origin 上の localStorage を実際に inspect するのが妥当です。(Playwright)


    10. #737 本文への具体的な修正案

    #737 は以下のように contract を修正してから実装すべきです。

    ## Outcome
    RewardSystem は terminal SortieResult から reward_formula_version: 1 の RewardQuote を pure に算出する。
    RewardSystem.claim は 1 sortie lifecycle の terminal transition event を表す applicationId / consumed token を単位に、ProgressState.resources へ exactly-once で saturated addition する。
    値同一性、JSON.stringify、shallow equality による重複排除は禁止する。
    同一 payload の別 sortie は別 reward application として加算される。
    

    In Scope

    • RewardSystem.calculate(result): RewardQuote
    • RewardSystem.claim(state, applicationId, result): RewardClaimResult
    • RESOURCE_CAP / PER_SORTIE_REWARD_CAP / REWARD_FORMULA_VERSION の単一定義
    • victory / defeat / timeout の formula exact value
    • reward delta と resourcesAfter の safe integer / non-negative / cap invariant
    • runtime-only claim latch または consumed transition token
    • 同一 token double-claim 防止
    • 同一 payload different token の二重ではない正当加算

    Out of Scope

    • localStorage 保存 wiring
    • reload 後の復元 E2E
    • storage failure handling
    • debrief UI
    • upgrade / resource 消費

    Stop Conditions

    • terminal transition id を生成するため SortieSystem.ts の変更が必要なら、Allowed Paths を改訂するか #738 に defer する
    • pendingReward / claimed state を snapshot に永続化したくなった場合は、persistence.md と衝突するため新規 contract review が必要

    最終レビューコメント案

    CHANGES REQUESTED.
    #737 は RewardSystem 実装 issue として方向性は正しいが、現本文の「同一 result」のまま実装すると value identity / JSON stringify / shallow equality による誤った idempotency 実装を誘発する。resource.md と PR #748 の修正後契約に合わせ、exactly-once の単位を 1 sortie lifecycle の terminal transition event に修正すること。
    calculate() と claim() を分離し、calculate() は pure、claim() は consumed token / rewardApplied latch による state transition とすること。
    reload 後の再 claim 不可は #737 単体では証明できないため、#739 / #740 の integration / E2E へ明示的に渡すこと。
    timeout は independent outcome であり defeat と混同しないこと。#738 側の contract も timeout terminal を debrief 対象に修正しないと、#737 が正しくても M3 loop が破綻する。
    #737 の verification は grep ではなく exact formula、cap、invalid value、same-token double claim、same-payload different-token claim を unit test で検証すること。

    ## 判定

    CHANGES REQUESTED。#737 はこのまま実装に入ると危険です。
    理由は、#737 本文の「同一 SortieResult → 一度だけ反映」という表現が、すでに #735 / PR #748 / resource.md で修正された lifecycle terminal transition event 単位の exactly-once とズレているためです。値同一性で二重加算を防ぐ実装に誘導すると、同一 payload の別 sortie を誤って握り潰すか、逆に同一 sortie の clone/re-render/retry を二重加算します。#737 は現在 open で、公開ページ上では related PR / branch はまだありません。([GitHub]1)

    確認した主対象は #737、parent #733、#735 と merged PR #748、#736/#738/#739、現行 resource.md / persistence.md、GameState.ts / SortieSystem.ts、および localStorage / Vite 配布 / Playwright 検証まわりの公式ドキュメントです。


    1. 最大の欠陥: 「同一 result」の定義が実装者を壊す

    #737 は RewardSystem.ts を作り、SortieResult から決定論的に報酬を計算し、progress.resources に一度だけ反映することを要求しています。In Scope でも「同一 result の反映は一度のみ」、AC4 でも「報酬反映は progress.resources に対して一度のみ」と書かれています。([GitHub]1)

    しかし、これはそのままでは不十分です。PR #748 のレビューで、exactly-once の単位は object identity でも JSON.stringify(result) でも shallow equality でもなく、1 sortie lifecycle の terminal transition event とする必要がある、と明確に指摘されています。同一内容の SortieResult が別 sortie で発生し得るため、値ベース重複排除は正当な報酬まで落とします。([GitHub]2)
    その後の PR 対応でも、この点は反映済みです。resource.md は「value identity ではなく terminal transition event」「同一 payload の別 sortie は別 application」「JSON.stringify / shallow equality 禁止」「rewardApplied latch または consumed token」を要求しています。([GitHub]2)

    要求修正: #737 の本文から「同一 result」という曖昧語を削り、次に置き換えるべきです。

    RewardSystem.calculate(result: SortieResult): RewardQuote
    RewardSystem.claim(state: GameState, applicationId: RewardApplicationId, result: SortieResult): RewardClaimResult

    calculate() は完全 pure。claim() は applicationId / consumed token / rewardApplied latch による state transition です。parent #733 も、#737 は RewardSystem.calculate() と RewardSystem.claim() を分け、apply-once の実装根拠を持つことを child contract としています。([GitHub]3)


    2. #737 の Allowed Paths では、正しい exactly-once を完結できない可能性が高い

    現行 SortieSystem.ts は terminal 到達時に result を作って state.sortie = terminalState へ入れていますが、そこに sortie instance id、terminal transition id、pending reward、claimed flag のような識別子はありません。SortieState も terminal state に result を持つだけです。([GitHub]4)

    一方で #737 の Allowed Paths は RewardSystem.ts、GameState.ts、systems/index.ts、tests/reward-system.test.ts のみです。SortieSystem.ts は含まれていません。([GitHub]1)
    parent #733 は、再 claim・ダブルクリック・reload 跨ぎの二重加算防止に、pendingReward / claimed flag / lastClaimedSortieId 相当の識別子を #737 / #738 契約に含めると明記しています。([GitHub]3)

    敵対的に見ると、ここは stop condition です。
    #737 が lifecycle token を生成・消費する責務まで持つなら、Allowed Paths に src/systems/SortieSystem.ts を追加しないと不自然です。逆に #737 を純粋な calculate() と token-aware claim() の API 定義までに絞るなら、terminal token の生成と debrief wiring は #738 に明示的に defer すべきです。


    3. reload 後の二重 claim は #737 だけでは証明できない

    #737 は localStorage wiring を Out of Scope にしています。([GitHub]1)
    しかし parent #733 の Additional AC は、claim 済み reward が reload 後に再 claim 可能にならないことまで要求しています。([GitHub]3)

    この reload 境界は #739 の責務です。#739 は報酬確定後に progression snapshot を localStorage へ保存し、page reload 後に resources を復元する保存ポイントを wiring する issue です。さらに #739 は #736、#738、#621 の完了を前提にしています。([GitHub]5)
    persistence.md も、SortieResult は localStorage に書かず、reload 後に復元されるのは適用済みの progression snapshot のみで、SortieResult を再構築・再計算しない、と定めています。([GitHub]6)

    要求修正: #737 の AC4 は「同一 runtime terminal transition に対する in-memory claim は一度のみ」に狭める。reload 後の再 claim 不可は #739 / #740 の integration / E2E に移す。#737 単体で reload exactly-once を満たしたと主張してはいけません。


    4. 報酬式はすでに resource.md が正本。実装で再解釈してはいけない

    resource.md は reward_formula_version: 1 の固定値を定義済みです。base reward は victory 100、defeat 10、timeout 30、kill bonus は kills * 5、victory のみ playerHpRemaining * 1、per-sortie cap は 500 です。([GitHub]7)

    resources 側は non-negative safe integer、初期値 0、RESOURCE_CAP = 9_999_999、overflow は cap clamp、負値 / NaN / Infinity / 小数は invalid fallback 0 と定義されています。([GitHub]7)
    parent #733 も、resources は有限非負整数、RESOURCE_CAP 上限、saturated addition、reward が NaN / Infinity / 負値 / 小数を返さないことを AC にしています。([GitHub]3)

    要求修正: #737 の RewardSystem.ts には、少なくとも以下を明示的に export するべきです。

    export const REWARD_FORMULA_VERSION = 1 as const
    export const RESOURCE_CAP = 9_999_999
    export const PER_SORTIE_REWARD_CAP = 500

    さらに、テストは「victory / defeat / timeout の差がある」だけでは弱いです。以下の exact value を検証すべきです。

    victory: 100 + kills * 5 + playerHpRemaining
    defeat: 10 + kills * 5
    timeout: 30 + kills * 5
    rewardDelta: clamp(rawDelta, 0, 500)
    resourcesAfter: clamp(validResourcesBefore + rewardDelta, 0, 9_999_999)

    Math.floor(NaN) は NaN を返すため、kills や playerHpRemaining に poisoned value が入った時点で計算結果が壊れます。TypeScript の型だけに依存せず、unknown as SortieResult で NaN / Infinity / negative / fraction を流すテストを追加してください。


    5. timeout は independent outcome。#738 側がまだ古い

    現行 GameState.ts の SortieResult は outcome: 'victory' | 'defeat' | 'timeout' の discriminated union です。timeout は endReason: 'timeout' を持つ独立 variant です。([GitHub]8)
    SortieSystem.ts も defeat > victory > timeout の優先順位で terminal 判定し、timeout branch では outcome: 'timeout' / endReason: 'timeout' を作っています。([GitHub]4)
    resource.md も、timeout を defeat と混同してはならない neutral terminal と定めています。([GitHub]7)

    ところが #738 の Current Validated Scope は SortieStatus = 'idle' | 'running' | 'victory' | 'defeat' | 'ended' と記載しており、timeout が抜けています。Outcome / AC1 も victory / defeat 到達後の debrief だけを明記しています。([GitHub]9)

    要求修正: #738 の issue contract を修正し、victory | defeat | timeout 全 terminal が debrief に入ることを AC に入れるべきです。#737 が timeout reward を正しく計算しても、#738 が timeout を debrief / save path に流さなければ M3 loop は壊れます。


    6. calculate() と claim() の責務分離が必須

    README は systems が DOM / Canvas API に依存しないこと、更新は fixed timestep 60Hz で進めることをアーキテクチャ方針にしています。([GitHub]10)
    parent #733 も、storage アクセスは adapter に隔離し、systems 層・60Hz update loop から呼ばないと定めています。([GitHub]3)

    したがって、#737 の RewardSystem.ts は localStorage、document、Canvas、wall-clock、乱数に触ってはいけません。
    calculate() は SortieResult → RewardQuote の pure function。claim() は GameState の progress.resources を変更する唯一の state transition。保存は #739、storage failure は #621、runtime E2E は #740 です。

    推奨戻り値は例として次です。

    type RewardQuote = Readonly<{
      formulaVersion: 1
      outcome: SortieResult['outcome']
      base: number
      killBonus: number
      hpBonus: number
      delta: number
    }>
    
    type RewardClaimResult =
      | { ok: true; quote: RewardQuote; resourcesBefore: number; resourcesAfter: number }
      | { ok: false; reason: 'not-terminal' | 'already-claimed' | 'invalid-result' }

    例外 throw より union result の方が、UI / debrief / save failure の後続設計と接続しやすいです。


    7. GameSnapshot / ProgressState の混同に注意

    現行 ProgressState は stageLabel, resources, weaponPower だけです。GameSnapshot は schemaVersion, resources, weaponPower, playerMaxHp を持ちます。createGameSnapshot() もこの 4 フィールドを返します。([GitHub]8)
    #736 は、schemaVersion missing は legacy v0 migration、unknown は null fallback、resources は non-negative safe integer、overflow は RESOURCE_CAP clamp、SortieResult は永続化しない、と契約修正しています。([GitHub]11)

    要求修正: #737 で pendingReward / rewardApplied / lastClaimedSortieId 相当を足す場合、それが runtime-only なのか、snapshot に含むのかを明示してください。現行 persistence.md は SortieResult や sortie runtime を永続化しない設計です。pendingReward を snapshot に入れると、その設計と衝突します。([GitHub]6)

    現実的には、#737 は runtime-only latch / consumed token を使い、保存されるのは claim 後の resources だけにするのが安全です。


    8. localStorage / 配布物まわりの調査結果を反映すべき点

    #737 自体は storage を触らないべきですが、exactly-once の設計は storage と配布環境の制約を前提にしておく必要があります。

    MDN によると localStorage は origin 単位で分割され、同じ origin の document は同じ localStorage 領域を共有します。また file: URL の localStorage 要件は未定義で、SecurityError が発生し得ます。([MDNウェブドキュメント]12)
    Web Storage は同期 API なので、set/get/remove は他の JavaScript 実行をブロックし得ます。毎 tick 保存しない #739 の方針は妥当です。([MDNウェブドキュメント]13)
    容量面では Web Storage は全ブラウザで最大 10 MiB、localStorage は origin あたり 5 MiB とされ、上限到達時は QuotaExceededError を try/catch で扱うべきです。([MDNウェブドキュメント]14)

    Vite の本番ビルドは vite build により静的ホスティング向け bundle を生成します。Vite の static deploy docs は既定出力を dist とし、vite preview は dist を http://localhost:4173 で配信するローカル確認用サーバーで、本番サーバーではないと明記しています。([vitejs]15)
    したがって、M3 の runtime smoke test は file:// ではなく HTTP origin 上で実施する必要があります。これは parent #733 の dist/ を HTTP origin 経由で smoke test する AC とも一致します。([GitHub]3)

    また、PR #748 のレビューでも指摘されている通り、GitHub Pages の /loop-protocol/ 本番と /loop-protocol/pr-748/ preview は同一 origin になり得るため、同じ loop-protocol.mvp.save key を共有します。persistence.md はこのリスクを反映し、E2E / preview では test 前に key clear、必要なら preview key suffix を検討するとしています。([GitHub]2)


    9. Verification Commands が弱すぎる

    #737 の verification は rg -n "victory|defeat|timeout" や rg -n "二重|once|already|applied" のような grep が多いです。([GitHub]1)
    これは仕様語をコメントに書けば通ります。敵対的には、次の破損実装でも grep は通ります。

    if (JSON.stringify(result) === state.lastRewardResultJson) return

    これは同一 payload の別 sortie を潰すため、resource.md の禁止事項に反します。([GitHub]7)

    最低限、tests/reward-system.test.ts は次を検証してください。

    分類 必須テスト
    formula victory / defeat / timeout の exact value
    cap per-sortie cap 500、RESOURCE_CAP = 9_999_999 への saturated addition
    invalid NaN / Infinity / negative / fraction / huge number が reward/resource を壊さない
    exactly-once 同一 applicationId を 2 回 claim しても 1 回だけ加算
    別 sortie 同一 payload でも異なる applicationId なら 2 回加算
    clone 同一 sortie の cloned result でも token が同じなら再加算されない
    purity calculate() は state を mutate しない
    boundary RewardSystem.ts は DOM / Canvas / localStorage を import しない

    Playwright は browser context ごとに isolation され、storage state には localStorage snapshot も含まれます。#740 の E2E では、この性質を使って HTTP origin 上の localStorage を実際に inspect するのが妥当です。(Playwright)


    10. #737 本文への具体的な修正案

    #737 は以下のように contract を修正してから実装すべきです。

    ## Outcome
    RewardSystem は terminal SortieResult から reward_formula_version: 1 の RewardQuote を pure に算出する。
    RewardSystem.claim は 1 sortie lifecycle の terminal transition event を表す applicationId / consumed token を単位に、ProgressState.resources へ exactly-once で saturated addition する。
    値同一性、JSON.stringify、shallow equality による重複排除は禁止する。
    同一 payload の別 sortie は別 reward application として加算される。
    
    ## In Scope
    - RewardSystem.calculate(result): RewardQuote
    - RewardSystem.claim(state, applicationId, result): RewardClaimResult
    - RESOURCE_CAP / PER_SORTIE_REWARD_CAP / REWARD_FORMULA_VERSION の単一定義
    - victory / defeat / timeout の formula exact value
    - reward delta と resourcesAfter の safe integer / non-negative / cap invariant
    - runtime-only claim latch または consumed transition token
    - 同一 token double-claim 防止
    - 同一 payload different token の二重ではない正当加算
    
    ## Out of Scope
    - localStorage 保存 wiring
    - reload 後の復元 E2E
    - storage failure handling
    - debrief UI
    - upgrade / resource 消費
    
    ## Stop Conditions
    - terminal transition id を生成するため SortieSystem.ts の変更が必要なら、Allowed Paths を改訂するか #738 に defer する
    - pendingReward / claimed state を snapshot に永続化したくなった場合は、persistence.md と衝突するため新規 contract review が必要

    最終レビューコメント案

    CHANGES REQUESTED.
    #737 は RewardSystem 実装 issue として方向性は正しいが、現本文の「同一 result」のまま実装すると value identity / JSON stringify / shallow equality による誤った idempotency 実装を誘発する。resource.md と PR #748 の修正後契約に合わせ、exactly-once の単位を 1 sortie lifecycle の terminal transition event に修正すること。
    calculate() と claim() を分離し、calculate() は pure、claim() は consumed token / rewardApplied latch による state transition とすること。
    reload 後の再 claim 不可は #737 単体では証明できないため、#739 / #740 の integration / E2E へ明示的に渡すこと。
    timeout は independent outcome であり defeat と混同しないこと。#738 側の contract も timeout terminal を debrief 対象に修正しないと、#737 が正しくても M3 loop が破綻する。
    #737 の verification は grep ではなく exact formula、cap、invalid value、same-token double claim、same-payload different-token claim を unit test で検証すること。

  4. squne121 commented on Jun 8, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  5. squne121 commented on Jun 8, 2026

    @squne121
    OwnerAuthor

    Contract Snapshot (2026-06-08T21:56:30Z)

    • Outcome: RewardSystem が terminal SortieResult から reward を pure に算出し、同一 applicationId に対する progress.resources 反映を exactly-once で提供する。
    • Acceptance Criteria: AC1-AC10 を issue 本文どおり確認対象とする。
    • Verification Commands: baseline fail 2 件、pr_review_only 12 件。
    • Allowed Paths: src/systems/RewardSystem.ts, src/state/GameState.ts, src/systems/index.ts, tests/reward-system.test.ts
    • Worktree: .claude/worktrees/issue-737-reward-system
    • Branch: worktree-issue-737-reward-system
    • VC preflight: baseline fail = 2, 想定外 pass = 0, 実行不可 = 0, human_judgment = 0
    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: 2026-06-08T21:56:30Z
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/737
      checks:
        template_compliance: pass
        state_label: ok
        allowed_paths_present: pass
        vc_present: pass
        stop_conditions_complete: pass
        vc_preflight:
          status: pass
          passed: true
          vc_failed_as_expected: 2
          vc_passed_unexpectedly: 0
          vc_unrunnable: 0
          vc_expected_pass: 0
          vc_skipped: 12
          vc_human_judgment: 0
          classifications:
            - ac: AC1
              command: test -f src/systems/RewardSystem.ts
              exit_code: 1
              classification: expected_fail
              category: file_not_found_expected
              scope_class: baseline_fail_expected
              confidence: high
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
            - ac: AC2
              command: rg -n "pure|RewardQuote|formulaVersion" src/systems/RewardSystem.ts tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC3
              command: rg -n "victory|defeat|timeout" tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC3
              command: rg -n "100|10|30|kills \* 5|playerHpRemaining" tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC4
              command: rg -n "PER_SORTIE_REWARD_CAP|RESOURCE_CAP|saturated" src/systems/RewardSystem.ts tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC5
              command: rg -n "NaN|Infinity|fraction|negative|unsafe" tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC6
              command: rg -n "applicationId|already-claimed|double-claim|same token" src/systems/RewardSystem.ts tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC7
              command: rg -n "different token|different applicationId|same payload" tests/reward-system.test.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC8
              command: rg -n "progress\.resources" src/systems/CombatSystem.ts
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC9
              command: test -f tests/reward-system.test.ts
              exit_code: 1
              classification: expected_fail
              category: file_not_found_expected
              scope_class: baseline_fail_expected
              confidence: high
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
            - ac: AC10
              command: pnpm typecheck
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC10
              command: pnpm lint
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC10
              command: pnpm test
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
            - ac: AC10
              command: pnpm build
              exit_code: null
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: low
              evidence:
                stdout_excerpt: 
                stderr_excerpt: 
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: VC marked pr_review_only; verification deferred to PR review
              runtime_verification_required: false
        ac_verifiability: pass
        product_spec_check:
          applicability: not_applicable
          decision: pass
          triggers:
            docs_product_allowed_paths: false
            tasks_md_mentioned: false
            specify_artifact_mentioned: false
            generated_task_mentioned: false
            product_spec_context_present: false
          conditions:
            docs_product_requires_spec_evidence:
              status: pass
              evidence: []
            tasks_md_not_direct_source:
              status: pass
              evidence: []
            specify_not_canonical:
              status: pass
              evidence: []
            diff_first_rationale_present:
              status: pass
              evidence: []
            generated_task_trace_present:
              status: pass
              evidence: []
            task_dependencies_materialized:
              status: pass
              evidence: []
          blocked_reasons: []
        worktree_branch_collision: clear
      next_action: implement_issue
      blocked_reasons: []
      warnings:
        - 12 verification commands are deferred as pr_review_only and must be re-evaluated in PR review.
    body_sha256: sha256:80f86aa49f5434ca6283647b411be3fc31f63e8abc451eb5f96e0d43d55c4880
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/implementation

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions