Skip to content

実装: session manifest hook の issue-402 hard-code を除去し issue identity を動的解決する #821

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "#816"
goal_ref: "impl-review-loop 系の決定論的 gate 自動化と compact verdict 化により token/context 浪費を削減する"
change_kind: code

Runtime Verification Applicability

decision: not_applicable
reason: "Vitest 単体テスト(pnpm test)で完結する。runtime UI / simulation 動作確認は不要"

Parent Issue

#816

Parent Goal Ref

Current Validated Scope

  • .claude/hooks/generate_session_manifest_from_hook.mjs の phaseInstanceId 生成(185 行付近)にある issue-402 hard-code を除去する
  • issue identity を「hook stdin payload → branch 名 → worktree path → 解決不能なら sentinel」の優先順で動的解決する
  • tests/agent-session-manifest*.test.ts に identity 解決の回帰テストを追加する

Remaining Parent Gaps

Identity Resolution Policy

unknown_identity_policy:
  option: schema_preserving_sentinel
  phase_instance_id_when_unknown: "issue-0:<main_loop>:<seq>"
  issue_number_field_when_unknown: omitted
  note: "issue-0 は未解決 Issue を示すローカル sentinel。実際の GitHub Issue 番号ではない"

payload_trusted_keys:
  allowed:
    - hookCtx.issue_number
    - hookCtx.issue?.number
    - hookCtx.issueNumber
    - hookCtx.loop?.issue_number
  forbidden:
    - "JSON.stringify(hookCtx) からの正規表現全文検索"
    - "hookCtx.tool_input?.command からの抽出"
    - "last_assistant_message からの抽出"
    - "transcript_path からの抽出"

branch_worktree_regex:
  pattern: "/(?:^|[/_-])issue-([1-9][0-9]*)(?=$|[/_-])/"
  rationale: "token 境界付き regex により notissue-821 や issue-000 を誤検出しない"

producer_cli_policy:
  when_resolved: "phase_instance_id=issue-<N>:<phase>:<seq> かつ --issue <N> を producer CLI に渡す"
  when_unresolved: "phase_instance_id=issue-0:<phase>:<seq>、--issue は渡さない"

Outcome

generate_session_manifest_from_hook.mjs から issue-402 literal が除去され、phaseInstanceId が実行中の Issue / branch から動的解決(解決不能時は issue-0 sentinel)される実装と回帰テストが 1 PR で追加された状態。

In Scope

  • issue-402 hard-code の除去と動的解決ロジックの実装
    • 優先順: hook stdin payload(trusted keys のみ)→ branch 名 → worktree path → issue-0 sentinel
    • branch/worktree 抽出は token 境界付き regex /(?:^|[/_-])issue-([1-9][0-9]*)(?=$|[/_-])/ に限定
    • 解決できた場合は --phase-instance-id issue-<N>:<phase>:<seq> と --issue <N> の両方を producer CLI に渡す
    • 解決不能時は phase_instance_id=issue-0:<phase>:<seq>、--issue は渡さない
  • unknown を許容する manifest schema 上の扱いを既存テストと整合させる(schema_preserving_sentinel 方式を採用)
  • 動的解決の各経路を検証する Vitest テスト追加(AC2 参照)
  • 必要に応じて scripts/generate-session-manifest.mjs 側の共有ロジック調整(identity 解決を共通化する場合のみ)

Out of Scope

  • session manifest schema 自体の改版(キー追加・改名)
  • hook の登録設定(.claude/settings.json)の変更
  • 他の hook(secret guard / Japanese guard)の変更
  • schema revision(unknown:<main_loop>:<seq> 形式の導入)は別 Issue

Acceptance Criteria

  • AC1: generate_session_manifest_from_hook.mjs 内の issue-402 literal が 0 件である
  • AC2: identity 動的解決の回帰テストが追加され PASS する。最低限以下の 8 ケースをカバーすること:
    1. payload issue_number: 821 が最優先され phase_instance_id=issue-821:impl:NNN かつ issue_number=821 になる
    2. payload がない場合、branch worktree-issue-821-session-manifest から 821 を抽出する
    3. branch もない場合、cwd / worktree path .claude/worktrees/issue-821-... から 821 を抽出する
    4. payload と branch が衝突した場合、payload が勝つ
    5. tool_input.command: "gh issue view 402" は現在 Issue として採用しない
    6. issue_number: 0、"000821"、負数、小数、空文字は無効として fallback に進む
    7. 解決不能時は phase_instance_id=issue-0:<phase>:<seq>、manifest root に issue_number フィールドが存在しない
    8. 既存の payload digest / lock / duplicate skip が退行しない
  • AC3: 既存テストスイートが破壊されていない
  • AC4: TypeScript 型エラーがない

Verification Commands

# AC1
$ ! rg -q "issue-402" .claude/hooks/generate_session_manifest_from_hook.mjs
# AC2
$ pnpm test
# AC3
$ pnpm test
# AC4
$ pnpm typecheck

Allowed Paths

  • .claude/hooks/generate_session_manifest_from_hook.mjs
  • scripts/generate-session-manifest.mjs
  • tests/agent-session-manifest.test.ts
  • tests/agent-session-manifest-check.test.ts
  • tests/agent-session-manifest-phase-instance-id.test.ts
  • tests/agent-session-manifest-producer.test.ts
  • tests/fixtures/agent-session-manifest/

Stop Conditions

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

Required Skills

  • Node.js(ESM / hook stdin 処理)
  • Vitest

Scope Delta(任意)

N/A

Delivery Rule

  • 1 Issue = 1 PR、worktree で実装、Draft PR 既定

Notes for Reviewer

  • issue-402 hard-code が意図的な fixture 由来か実運用 bug かを実装着手時にまず git blame で確認し、fixture 由来なら本 Issue の方針(動的解決)と矛盾しないことを PR 本文に記録する
  • hook payload に issue number が常に含まれる保証はないため、issue-0 sentinel 許容は必須とする
  • B1 決定: schema_preserving_sentinel(issue-0 sentinel)を採用。schema revision は別 Issue とする
  • B2 決定: trusted_keys を Identity Resolution Policy に明記。任意文字列スキャンは禁止
  • B3 決定: resolved issue では --issue <N> も producer CLI に渡す
  • B4 決定: token 境界付き regex /(?:^|[/_-])issue-([1-9][0-9]*)(?=$|[/_-])/ に限定

Activity

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

    @squne121
    OwnerAuthor

    結論: REQUEST_CHANGES

    Issue #821 は方向性は正しいですが、このまま AI 実装に渡すと高確率で contract 破綻します。最大の問題は、Issue が「解決不能なら unknown」を要求している一方で、現行 phase_instance_id schema / producer validation は unknown を受け付けず、許容形式は issue-[0-9]+:<phase>:<seq> または ci:<slug>:<run_id>:<run_attempt> だけです。しかも #821 は schema 改版を Out of Scope にしているため、実装者が正しく従う道が曖昧です。

    確認した事実

    Issue #821 はコメント 0 件で、親 #816 の child issue です。親 #816 は generate_session_manifest_from_hook.mjs の issue-402 hard-code により artifact identity が実行中 Issue とズレることを token/context 浪費ホットスポットとして明示しています。

    現行 hook は実際に phaseInstanceId を issue-402:${phaseInfo.mainLoop}:${seqNum} と固定生成しています。さらに producer CLI 呼び出しでは --phase-instance-id は渡しますが、--issue は渡していません。producer 側は --issue が渡された場合だけ manifest に issue_number を入れるため、現状は phase ID だけが issue-402 を名乗る不完全な identity になっています。

    この hook は #402 / PR #426 で導入され、#797 / PR #852 で payload digest throttle と lock/atomic rename が追加されています。#797 は明示的に「issue identity hard-code 除去は #821 のスコープ」として残しているため、#821 は既存の throttle / lock 実装を壊さず identity 部分だけを直すべきです。

    Claude Code hook の仕様上、command hook は JSON input を stdin で受け取り、共通入力として session_id、transcript_path、cwd、hook_event_name などを受け取ります。PostToolUse は tool 成功後に発火し、tool_input / tool_response を含むため、任意のコマンド文字列から issue number を拾う設計は injection / 誤検出リスクがあります。([Claude API Docs]1) ([Claude API Docs]1)

    Blockers

    B1. unknown fallback の仕様が現行 schema と矛盾している

    #821 は「解決不能なら unknown」を要求していますが、現行 schema と producer は unknown:impl:001 のような値を拒否します。issue-0:impl:001 は regex 上は通る可能性がありますが、これは schema の穴を使うだけで、「unknown を許容する」という contract にはなっていません。#547 では phase_instance_id の拡張が明示的に schema / validator / help 文言の変更対象として扱われ、local 実行 ID 生成変更は out of scope とされていました。

    修正要求: #821 に以下のどちらかを明記してください。

    unknown_identity_policy:
      option: schema_preserving_sentinel
      phase_instance_id_when_unknown: "issue-0:<main_loop>:<seq>"
      issue_number_field_when_unknown: omitted
      note: "issue-0 is a local unresolved-issue sentinel, not a real GitHub issue"

    または、別 Issue に分割して schema を拡張します。

    unknown_identity_policy:
      option: schema_revision
      new_phase_instance_id_format: "unknown:<main_loop>:<seq>"
      required_changes:
        - docs/schemas/agent-session-manifest.schema.json
        - scripts/generate-session-manifest.mjs
        - phase_instance_id tests

    現状の #821 は schema revision を Out of Scope にしているため、実装前にこの判断が必要です。

    B2. payload からの issue number 抽出元が未定義

    「hook stdin payload → branch 名 → worktree path」の優先順はよいですが、payload のどの field を信頼するかが未定義です。Claude Code の標準 hook input には issue number は標準項目として出ていないため、tool_input.command や last_assistant_message を全文検索する実装に流れる危険があります。これは gh issue view 402 のような単なるコマンド中の数値を現在 Issue と誤認します。([Claude API Docs]1) ([Claude API Docs]1)

    修正要求: 信頼する payload key を限定してください。例:

    hookCtx.issue_number
    hookCtx.issue?.number
    hookCtx.issueNumber
    hookCtx.loop?.issue_number

    逆に、以下は禁止にすべきです。

    JSON.stringify(hookCtx).match(/issue[- #](\d+)/)
    hookCtx.tool_input?.command からの抽出
    last_assistant_message からの抽出
    transcript_path からの抽出

    B3. known issue の場合は --issue も渡すべき

    現在は phase_instance_id だけが issue を名乗り、manifest root の issue_number は欠落します。#821 の目的が artifact identity のズレ修正なら、解決できた場合は --phase-instance-id issue-821:impl:NNN だけでなく、--issue 821 も producer に渡すべきです。producer は --issue があると manifest.issue_number を入れる実装になっています。

    実装方針はこうです。

    const identity = resolveIssueIdentity(hookCtx)
    
    const phaseInstanceIssuePart = identity.issueNumber
      ? `issue-${identity.issueNumber}`
      : 'issue-0' // contract で明示した場合のみ
    
    const phaseInstanceId = `${phaseInstanceIssuePart}:${phaseInfo.mainLoop}:${seqNum}`
    
    if (identity.issueNumber) {
      producerArgs.push('--issue', identity.issueNumber)
    }

    B4. branch / worktree path 抽出は token 境界付き regex に限定すべき

    Git branch 名は slash や dash を含められるため、単純な includes("issue-") や /issue-(\d+)/ は誤検出しやすいです。Git の refname は slash による階層化を許す一方、禁止文字や .lock などの制約もあります。つまり branch 名は自由度が高く、resolver 側で「issue token」として安全に切る必要があります。(Git)

    推奨:

    const ISSUE_TOKEN_RE = /(?:^|[/_-])issue-([1-9][0-9]*)(?=$|[/_-])/
    
    function extractIssueToken(value) {
      const match = ISSUE_TOKEN_RE.exec(String(value ?? ''))
      return match ? match[1] : null
    }

    これなら worktree-issue-821-session-manifest は拾えますが、notissue-821 や issue-000 は拾いません。

    追加すべきテスト

    #821 の AC2 は「回帰テスト追加」だけでは弱いです。最低限、以下を固定してください。

    1. payload issue_number: 821 が最優先され、phase_instance_id=issue-821:impl:NNN かつ issue_number=821 になる。
    2. payload がない場合、branch worktree-issue-821-session-manifest から 821 を抽出する。
    3. branch もない場合、cwd / worktree path .claude/worktrees/issue-821-... から抽出する。
    4. payload と branch が衝突した場合、payload が勝つ。
    5. tool_input.command: "gh issue view 402" は現在 Issue として採用しない。
    6. issue_number: 0、"000821"、負数、小数、空文字は無効として fallback に進む。
    7. 解決不能時の期待値を contract で決めた上で検証する。issue-0 sentinel を使うなら --issue は渡さない。
    8. 既存の payload digest / lock / duplicate skip が退行しない。

    実装対象としての最終評価

    小変更に見えますが、実際には identity semantics の修正です。issue-402 literal を置換するだけなら簡単ですが、unknown の扱いを決めずに実装すると、schema validation failure か、意味的に嘘の manifest を生成する可能性があります。

    採用条件は以下です。

    verdict: REQUEST_CHANGES
    must_fix_before_implementation:
      - unknown fallback の schema-preserving sentinel または schema revision 方針を明文化
      - payload から信頼する issue number key を限定
      - known issue では --issue も producer に渡す
      - arbitrary string scan を禁止
      - branch/worktree path regex と優先順位をテストで固定

    この修正を入れれば、#821 は親 #816 の目的に合う良い child issue になります。現状のままでは、AI 実装者が「unknown をどう表現するか」を推測で決めることになり、1 Issue = 1 PR の contract としては不十分です。

  3. squne121 commented on Jun 13, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  4. squne121 commented on Jun 13, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-06-13T04:51:30Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/821
      body_sha256: "sha256:3f7421585e8d071eda81902972012da70e1a093a10d4abfa0f49aa27ada142ad"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
  5. squne121 commented on Jun 13, 2026

    @squne121
    OwnerAuthor

    Contract Snapshot (2026-06-13T04:57:00Z)

    • Outcome: generate_session_manifest_from_hook.mjs から issue-402 literal が除去され、phaseInstanceId が実行中の Issue / branch から動的解決される実装と回帰テストが 1 PR で追加された状態。
    • Acceptance Criteria:
      • AC1: issue-402 literal が 0 件
      • AC2: identity 動的解決の回帰テスト(8 ケース)が追加・PASS
      • AC3: 既存テストスイートが破壊されていない
      • AC4: TypeScript 型エラーがない
    • Verification Commands: ! rg -q "issue-402" ..., pnpm test, pnpm test, pnpm typecheck
    • Allowed Paths: .claude/hooks/generate_session_manifest_from_hook.mjs, scripts/generate-session-manifest.mjs, tests/agent-session-manifest*.test.ts, tests/fixtures/agent-session-manifest/
    • Worktree: .claude/worktrees/issue-821-session-manifest-hook-issue-402-hard-cod
    • Branch: worktree-issue-821-session-manifest-hook-issue-402-hard-cod
    • VC preflight: baseline fail = 1, 想定外 pass = 0, 実行不可 = 0, regression_gate pass = 3
    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-06-13T04:57:00Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/821
      body_sha256: "sha256:3f7421585e8d071eda81902972012da70e1a093a10d4abfa0f49aa27ada142ad"
      checks:
        template_compliance: pass
        state_label: ok
        allowed_paths_present: pass
        vc_present: pass
        stop_conditions_complete: pass
        blockers: pass
        runtime_verification_applicability: not_applicable
        vc_preflight:
          passed: true
          vc_failed_as_expected: 1
          vc_passed_unexpectedly: 0
          vc_unrunnable: 0
          vc_expected_pass: 3
          vc_skipped: 0
          status: pass
          classifications:
            - ac: AC1
              command: "! rg -q \"issue-402\" .claude/hooks/generate_session_manifest_from_hook.mjs"
              exit_code: null
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC2
              command: "pnpm test"
              exit_code: 0
              classification: expected_pass
              category: regression_gate
              scope_class: regression_gate
              confidence: low
              decision: go
            - ac: AC3
              command: "pnpm test"
              exit_code: 0
              classification: expected_pass
              category: regression_gate
              scope_class: regression_gate
              confidence: low
              decision: go
            - ac: AC4
              command: "pnpm typecheck"
              exit_code: 0
              classification: expected_pass
              category: regression_gate
              scope_class: regression_gate
              confidence: low
              decision: go
        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
          blocked_reasons: []
        worktree_branch_collision: clear
      next_action: implement_issue
      blocked_reasons: []
      warnings: []
  6. squne121 commented on Jun 13, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-06-13T05:06:34Z)

    • PR: fix: remove issue-402 hard-code from hook; resolve issue identity dynamically #861
    • Worktree: .claude/worktrees/issue-821-session-manifest-hook-issue-402-hard-cod
    • Branch: worktree-issue-821-session-manifest-hook-issue-402-hard-cod
    • Verification: typecheck PASS / lint PASS / test 556 PASS / build PASS
    • AC1: issue-402 literal 0件 ✅
    • AC2: identity 解決テスト 15 ケース追加 PASS ✅
    • AC3: 既存テストスイート破壊なし ✅
    • AC4: TypeScript 型エラーなし ✅
    • 後続: PR レビュー(pr-review-judge)→ マージ → post-merge-cleanup
  7. squne121 commented on Jun 13, 2026

    @squne121
    OwnerAuthor

    post-merge-cleanup: 完了 (2026-06-13T06:35:00Z)

    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      schema_version: 1
      materialized_by: post-merge-cleanup
      follow_up_issues: []
      note_only_observations: []

    cleanup 詳細

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