Skip to content

実装: agent_session_manifest/v1 producer を .claude/settings.json hooks と .github/workflows で自動 invoke する #402

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "#242"
goal_ref: "既存 scripts/generate-session-manifest.mjs を Claude Code hook と GitHub Actions から安全に起動できる deterministic wiring を追加し、manifest producer provenance を automated lifecycle に載せる"
change_kind: workflow

Parent Issue

#242

Parent Goal Ref

  • Goal: scripts/generate-session-manifest.mjs を manual invocation 依存から外し、hook / CI から deterministic に artifact-only 生成できる状態へ進める
  • Desired Destination: agent session manifest が Stop / SubagentStop / scoped PostToolUse / GitHub Actions artifact から安全に生成され、public transcript / comment へ漏れない

Current Validated Scope

  • .claude/settings.json の hook wiring と existing session_recording_policy_guard.sh との順序固定
  • .claude/hooks/generate_session_manifest_from_hook.mjs と対応 test による hook stdin JSON -> producer CLI 引数変換
  • .github/workflows/session-manifest.yml の artifact-only / read-only permission CI wiring
  • docs/dev/session-recording-policy.md の private artifact / prohibited channels / lifecycle semantics 更新

Remaining Parent Gaps

  • upstream security boundary は #412 が担当する(Secret 値を measurement pipeline に到達させない)
  • manifest validation gate を required check に昇格する enforcement は別 follow-up
  • blocked session 用 manifest を残すかどうかの設計は別 follow-up

Outcome

manifest producer が wrapper 経由で Stop / SubagentStop / scoped PostToolUse と GitHub Actions artifact workflow から deterministic かつ stdout-silent に起動され、private artifact 以外へ manifest 本文やローカル絶対パスを出さない状態。

In Scope

  • .claude/settings.json
    • Stop / SubagentStop に manifest producer hook を追加
    • existing session_recording_policy_guard.sh と producer hook の順序を固定
    • PostToolUse は matcher で対象 tool を限定する
    • SessionStart は invocation 対象に含めない
  • .claude/hooks/generate_session_manifest_from_hook.mjs
    • stdin hook JSON を受け取り、producer CLI 必須引数へ安全に変換する
    • stdout に manifest JSON を出さず、artifact file へ atomic write する
    • transcript_path / cwd の絶対パスを public output に含めない
    • duplicate hash skip / event-scoped filename を扱う
  • .claude/hooks/tests/**
    • wrapper unit/smoke test
    • settings.json structural test
  • .github/workflows/session-manifest.yml
    • push / pull_request trigger
    • permissions: contents: read
    • actions/checkout の persist-credentials: false
    • actions/upload-artifact による private artifact upload
    • pull_request_target / comment write を禁止
  • docs/dev/session-recording-policy.md
    • private channel = GitHub Actions artifact only を明文化
    • manifest を Issue / PR comment / workflow log / git commit に出さない方針を明文化

Out of Scope

  • producer field / producer.kind schema 追加(#401 / #377 で完了済み)
  • Secret / token management 上流統制(#412)
  • manifest validation gate を CI required check に昇格する enforcement
  • blocked session manifest の別設計
  • pull_request_target を使った mutation / comment 投稿

Acceptance Criteria

  • AC1: .claude/settings.json が scripts/generate-session-manifest.mjs 直呼びではなく .claude/hooks/generate_session_manifest_from_hook.mjs を参照する
  • AC2: wrapper は hook stdin JSON から producer CLI 必須引数を構成し、stdout に manifest 本文を出さない
  • AC3: SessionStart は hook invocation 対象に含まれない
  • AC4: PostToolUse は matcher で対象 tool を限定し、全 tool call へ無条件発火しない
  • AC5: Stop / SubagentStop では session_recording_policy_guard.sh が producer hook より先に評価されることを structural test で検証できる
  • AC6: wrapper は transcript_path / cwd の絶対パスを public output に含めず、artifact file へ atomic write と duplicate skip を行う
  • AC7: .github/workflows/session-manifest.yml は push / pull_request trigger、permissions: contents: read、persist-credentials: false、pull_request_target 不使用を満たす
  • AC8: workflow artifact は actions/upload-artifact@v4 以上、if-no-files-found: error、retention-days 明示、private-agent-session-manifest prefix を満たす
  • AC9: workflow は manifest JSON 本文を log / Issue comment / PR comment に出力しない
  • AC10: docs/dev/session-recording-policy.md に hook + CI lifecycle、private artifact channel、禁止チャネル、および #412 との境界が明記される

Verification Commands

# AC1
rg -n 'generate_session_manifest_from_hook|generate-session-manifest' .claude/settings.json

# AC2
test -f .claude/hooks/generate_session_manifest_from_hook.mjs
# preflight-scope: pr_review_only
uv run pytest .claude/hooks/tests/ -q -k "generate_session_manifest_from_hook and stdout"

# AC3
! rg -n 'SessionStart' .claude/settings.json

# AC4
# preflight-scope: pr_review_only
uv run pytest .claude/hooks/tests/ -q -k "post_tool_use and matcher"

# AC5
# preflight-scope: pr_review_only
uv run pytest .claude/hooks/tests/ -q -k "hook_config and policy_guard_order"

# AC6
# preflight-scope: pr_review_only
uv run pytest .claude/hooks/tests/ -q -k "transcript_path or cwd or atomic_write or duplicate_skip"

# AC7
python3 -c "import sys, yaml; w=yaml.safe_load(open('.github/workflows/session-manifest.yml')); on=w.get('on', {}); txt=open('.github/workflows/session-manifest.yml').read(); assert 'push' in on and 'pull_request' in on; assert w.get('permissions') in ({'contents':'read'}, {'contents': 'read'}); assert 'pull_request_target' not in txt; print('PASS')"
# preflight-scope: pr_review_only
rg -n 'persist-credentials:\s*false' .github/workflows/session-manifest.yml

# AC8
python3 -c "import yaml; w=yaml.safe_load(open('.github/workflows/session-manifest.yml')); steps=[s for j in (w.get('jobs') or {}).values() for s in j.get('steps', []) if str(s.get('uses','')).startswith('actions/upload-artifact@')]; assert len(steps)==1; step=steps[0]; assert step['with']['if-no-files-found']=='error'; assert 'retention-days' in step['with']; assert 'private-agent-session-manifest' in step['with']['name']; print('PASS')"

# AC9
! rg -n 'gh issue comment|gh pr comment|echo .*manifest|cat .*manifest' .github/workflows/session-manifest.yml .claude/hooks/generate_session_manifest_from_hook.mjs

# AC10
rg -n '#412|private channel|GitHub Actions artifact only|Issue / PR comment|workflow log' docs/dev/session-recording-policy.md

Allowed Paths

  • .claude/settings.json
  • .claude/hooks/generate_session_manifest_from_hook.mjs
  • .claude/hooks/tests/
  • .github/workflows/session-manifest.yml
  • docs/dev/session-recording-policy.md

Runtime Verification Applicability

  • decision: not_applicable
  • reason: This issue implements hook wiring and CI workflow configuration. There is no user-facing runtime requiring interactive app execution. All VC verification is deterministic (file existence checks, pytest unit tests, YAML structure parsing).

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約を越えて Secret / token management 上流統制まで同時に実装する必要が出た場合(#412 に分離)
  • 新規 Issue の起票が必要と判断した場合(blocked session manifest など別 concern が独立した場合)
  • 後続 Phase / 別スコープへの波及が判明した場合(validation gate required-check 化など)
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・workflow write permission 追加が必要になった場合

Required Skills

  • Claude Code hooks / settings.json
  • GitHub Actions workflow authoring
  • Artifact provenance / privacy boundary design

Background

Notes for Reviewer

  • #412 は upstream security sibling であり、本 Issueはその boundary を前提に hook / CI wiring へ限定する
  • SessionStart は context 混入リスクが高いため対象外に寄せた。必要なら local-only lifecycle marker 専用の別 Issue とする
  • private channel は GitHub Actions artifact only を意味し、git commit / Issue comment / PR comment / workflow log は禁止チャネルとして扱う

Delivery Rule

  • 1 Issue = 1 PR
  • worktree は .claude/worktrees/issue-<番号>-<slug>/
  • Draft PR 既定

Source

source: issue_refinement_loop
anchor_comment_urls:
  - "https://github.com/squne121/loop-protocol/issues/402#issuecomment-4540234028"
  - "https://github.com/squne121/loop-protocol/issues/402#issuecomment-4540292983"
  - "https://github.com/squne121/loop-protocol/issues/402#issuecomment-4540747789"
dedupe_key: "377-followup-hook-ci-wiring"
security_sibling_issue: "#412"
created_by: codex
created_at: "2026-05-26T00:00:00Z"

Activity

  1. added
    kind/implementation
    area/ai-ops
    on May 25, 2026
  2. squne121 commented on May 26, 2026

    @squne121
    OwnerAuthor

    結論

    #402 は必要ですが、このまま実装 Issue として回すなら REQUEST_CHANGES です。
    理由は、Issue が「hook/CI wiring」と言いつつ、実際に必要な 入力変換 wrapper、hook event ごとの副作用制御、artifact 公開境界、CI 権限、既存 guard との順序制御 が不足しているためです。

    #377 は既に closed/completed で、PR #404 により scripts/generate-session-manifest.mjs / validator / extractor が実装済みです。#402 はその後段として妥当です。
    ただし、#402 の本文は一部 stale です。現行 schema にはすでに producer.kind があり、script_generated | hook_generated | github_action_generated を enum として持っています。したがって「Schema producer field declaration は別 follow-up」という前提は更新が必要です。

    関連 Issue / PR から見た位置づけ

    #242 は session recording policy / Kill Switch の SSOT で、public full transcript 禁止、GitHub comment 上の raw transcript 禁止、unknown visibility fail-closed を定めています。
    #324 は policy checker の CI 統合だけを完了し、deterministic manifest producer や manifest validation gate は out of scope としています。
    #325 は Stop / SubagentStop に session_recording_policy_guard.sh を追加済みで、既に .claude/settings.json には Stop / SubagentStop hooks が存在します。
    #377 / PR #404 は script-only producer を実装済みで、hook wiring / CI integration は意図的に未実装でした。

    つまり #402 の責務は「producer を作る」ではなく、既存 producer を lifecycle event / GitHub Actions から安全に呼び出せる入出力境界を作ることです。

    Blockers

    B1. hook から producer を直接呼べない

    現行 scripts/generate-session-manifest.mjs は CLI 引数必須です。--repository, --phase-main-loop, --phase-instance-id, --actor-type, --actor-name, --evidence-source-kind, --evidence-source-ref, --evidence-visibility が必須になっています。

    一方、Claude hook は JSON context を stdin で渡します。hook event から CLI 引数へ変換する wrapper がなければ、.claude/settings.json で直接 scripts/generate-session-manifest.mjs を呼ぶだけでは動きません。Claude Code の hook reference でも command hook は stdin で JSON context を受け取ると説明されています。

    修正案: Allowed Paths に以下を明示追加してください。

    .claude/hooks/generate_session_manifest_from_hook.mjs
    .claude/hooks/tests/test_generate_session_manifest_from_hook.py

    wrapper の責務は最低限これです。

    stdin hook JSON
    ↓
    session_id / cwd / hook_event_name / transcript_path を読む
    ↓
    transcript_path は保存しない、または local_only/private_artifact に限定
    ↓
    repo, issue/pr, phase を安全に推定または環境変数で受け取る
    ↓
    node scripts/generate-session-manifest.mjs ... を引数付きで起動
    ↓
    stdout は Claude に流さず、artifact file に書く

    B2. SessionStart hook を含める設計が危険

    #402 は SessionStart を hook lifecycle event に含めています。しかし Claude Code docs では、SessionStart の stdout は Claude の context に追加されます。また SessionStart は blocking / decision control ではなく context-only 扱いです。

    つまり SessionStart で manifest を stdout に出すと、manifest が会話 context / transcript に混入します。さらに SessionStart input には transcript_path のようなローカル絶対パスが含まれます。
    これは #242 の public transcript / local path 境界と衝突しやすいです。

    修正案: SessionStart は原則 out of scope に落とすか、以下を AC に追加してください。

    • SessionStart hook は stdout に manifest を出力しない
    • SessionStart hook は context 追加を行わない
    • transcript_path / cwd の絶対パスを manifest に保存しない
    • SessionStart では lifecycle marker だけを local_only に保存し、authoritative manifest は Stop / CI で生成する

    B3. PostToolUse は無制限発火するため、artifact spam / race condition が起きる

    Claude hooks は PostToolUse が tool call 成功後に毎回発火します。Claude docs でも lifecycle は tool call ごとに PreToolUse / PostToolUse を含むとされています。

    #402 は「PostToolUse / Stop / SubagentStop / SessionStart lifecycle events invoke」としていますが、PostToolUse を全 tool に対して直接 manifest generation すると、以下が起きます。

    • 1 session で多数の manifest artifact が生成される
    • 同一 phase_instance_id への上書き race
    • Bash / Read / Grep など不要な tool call でも manifest が増える
    • Stop hook と PostToolUse hook が同じ出力先を競合する

    修正案: PostToolUse は次のように限定すべきです。

    {
    "PostToolUse": [
    {
    "matcher": "Edit|Write|MultiEdit|Bash",
    "hooks": [
    {
    "type": "command",
    "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/generate_session_manifest_from_hook.mjs",
    "args": ["--event", "PostToolUse"],
    "timeout": 30
    }
    ]
    }
    ]
    }

    さらに wrapper 側で以下を必須にしてください。

    • lockfile または atomic write: tmp file → fsync/rename
    • event_id / run_id / timestamp を含む一意出力名
    • same hash の場合 skip
    • stdout silent
    • stderr は non-secret のみ

    B4. 既存 Stop/SubagentStop guard との順序制御が不足

    現行 .claude/settings.json には Stop / SubagentStop で session_recording_policy_guard.sh が登録済みです。
    #325 の設計では、この guard は fail 時に exit 2 で Claude を block する安全機構です。
    Claude docs でも Stop / SubagentStop の exit code 2 は stopping を防ぐ blocking behavior です。

    #402 が同じ Stop / SubagentStop に producer を追加する場合、順序が重要です。

    producer → guard:
    producer が artifact を生成した後に guard が block する可能性がある。
    block された session の manifest が authoritative に見える危険。

    guard → producer:
    guard が block した場合 producer が走らず、失敗 session の manifest が残らない。

    どちらも一長一短です。Issue 本文は「execution order documented or verified non-conflicting」としか書いておらず、十分ではありません。

    修正案: AC9 を次に置換してください。

    AC9: Stop/SubagentStop では session_recording_policy_guard.sh と manifest producer の順序が structural test で検証される。

    • policy guard が先に実行される場合: block 時は manifest を生成しないことを明記
    • producer が先に実行される場合: block verdict / blocked_by_policy_guard を manifest に記録する後続更新手段を持つこと
    • どちらの設計でも、exit 2 の stderr に manifest JSON を出さない

    実装としては、policy guard を先に置き、producer は guard pass 後に実行が安全です。失敗時 manifest が必要なら別 Issue で「blocked session manifest」を設計した方がよいです。

    B5. GitHub Actions artifact を「private channel」と呼ぶだけでは不十分

    #402 は workflow artifact を「private channel outside push protection」としています。しかし GitHub Actions artifact は workflow run に紐づく保存物であり、upload-artifact でアップロードされ、retention-days を設定できます。
    また GitHub Actions の GITHUB_TOKEN 権限は permissions で明示制御でき、未指定権限は none になります。

    現行 ci.yml は permissions: contents: read、checkout は persist-credentials: false で比較的安全な設定です。
    #402 の新 workflow もこの方針に合わせるべきです。

    修正案: .github/workflows/session-manifest.yml の AC に以下を追加してください。

    permissions:
    contents: read

    jobs:
    session-manifest:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
    with:
    persist-credentials: false
    - uses: pnpm/action-setup@v6
    with:
    version: 11
    - uses: actions/setup-node@v6
    with:
    node-version: 22
    cache: pnpm
    - run: pnpm install --frozen-lockfile
    - run: node scripts/generate-session-manifest.mjs ...
    - uses: actions/upload-artifact@v4
    with:
    name: private-agent-session-manifest-${{ github.run_id }}
    path: agent-session-manifest-artifacts/
    retention-days: 5
    if-no-files-found: error

    さらに「private channel」の定義を明文化してください。

    private channel = GitHub Actions artifact only.
    禁止:

    • git commit
    • GitHub Issue / PR comment
    • workflow log への manifest 本文出力
    • public_github_comment visibility

    B6. CI workflow の pull_request 入力は fork PR を考慮すべき

    GitHub docs では、fork からの pull_request workflow は通常 write token を得られず、write permissions は read-only に落ちます。
    #402 の workflow は artifact upload だけなら大きな権限は不要ですが、将来 Issue/PR comment へ投稿する設計に拡張されると危険です。

    修正案: #402 の Out of Scope に次を明記してください。

    • pull_request_target は使用禁止
    • Issue / PR comment への投稿は本 Issue では禁止
    • GITHUB_TOKEN write permission は付与しない
    • fork PR では secrets を参照しない

    Major Risks

    M1. producer.kind と actor/evidence の整合が Issue 本文で古い

    現行 producer script は evidence.source_kind から producer.kind を導出しています。artifact → script_generated, hook_jsonl → hook_generated, ci_check → github_action_generated です。
    #402 は「Producer kind = hook_generated」「Workflow = github_action_generated」と書いていますが、schema producer field を optional dependency のように扱っているため、現在の main と齟齬があります。

    修正案: #402 の optional_depends_on: ["377-followup-schema-producer-field"] は削除し、Current Validated Scope に以下を追加。

    schema_status:
    producer_field: present_on_main
    producer_kind_enum:
    - script_generated
    - hook_generated
    - github_action_generated

    M2. AC6 の artifact name 検証が弱い

    grep -n "actions/upload-artifact|artifact-name" では artifact-name という存在しない key を探しており、upload-artifact の実際の key は with.name / with.path です。GitHub Docs の例も with: name: ... path: ... です。

    修正案: Verification Command を structural validation に変更してください。

    node - <<'NODE'
    const fs = require('fs')
    const yaml = require('yaml')
    const w = yaml.parse(fs.readFileSync('.github/workflows/session-manifest.yml', 'utf8'))
    const jobs = Object.values(w.jobs || {})
    const uploadSteps = jobs.flatMap(j => j.steps || []).filter(s => String(s.uses || '').startsWith('actions/upload-artifact@'))
    if (uploadSteps.length !== 1) throw new Error('expected exactly one upload-artifact step')
    const step = uploadSteps[0]
    if (!step.with?.name?.includes('private-agent-session-manifest')) throw new Error('artifact name must be private-agent-session-manifest*')
    if (!step.with?.path) throw new Error('artifact path required')
    if (step.with['if-no-files-found'] !== 'error') throw new Error('if-no-files-found must be error')
    NODE

    M3. .claude/settings.json の validation が grep ベースで弱い

    #402 の AC1 / AC2 / AC7 は jq と grep 中心です。既存 hook と新 hook の順序、exec form、timeout、args、matcher は grep では検証できません。

    修正案: .claude/hooks/tests/test_generate_session_manifest_hook_config.py を追加し、次を structural assertion してください。

    • Stop / SubagentStop に policy guard と producer hook が両方存在
    • policy guard と producer hook の順序が意図通り
    • command は ${CLAUDE_PROJECT_DIR}/... の絶対 project path
    • args は配列
    • timeout は 30〜120 秒
    • PostToolUse は matcher を持つ
    • SessionStart を入れるなら stdout silent wrapper のみ

    Issue 本文の具体修正案

    Machine-Readable Contract

    issue_kind: implementation
    parent_issue: "#242"
    depends_on: "#377"
    related_issues: ["#325", "#324", "#404"]
    dedupe_key: "377-followup-hook-ci-wiring"
    schema_status:
    producer_field: present_on_main
    producer_kind_enum:
    - script_generated
    - hook_generated
    - github_action_generated

    In Scope の置換案

    • .claude/settings.json

      • Stop / SubagentStop に manifest producer hook を追加
      • PostToolUse は matcher で Edit|Write|MultiEdit|Bash 等に限定
      • SessionStart は原則除外。含める場合は stdout silent / local_only marker のみ
    • .claude/hooks/generate_session_manifest_from_hook.mjs

      • stdin hook JSON を受け取り、producer CLI 引数へ安全に変換
      • transcript_path / cwd の絶対パスを public output に含めない
      • stdout に manifest を出さない
      • artifact file に atomic write
      • duplicate hash skip
    • .github/workflows/session-manifest.yml

      • permissions: contents: read
      • checkout persist-credentials: false
      • pull_request_target 使用禁止
      • workflow artifact のみ。comment 投稿禁止
      • retention-days を明示
    • tests

      • hook wrapper unit/smoke test
      • settings.json structural test
      • workflow yaml structural test

    Acceptance Criteria 追加案

    AC11: Hook wrapper は sample Stop/SubagentStop/PostToolUse stdin JSON から valid manifest を生成し、stdout へ manifest 本文を出さない。

    AC12: Hook wrapper は transcript_path / cwd / /tmp / /Users / /home を public_github_comment visibility の manifest に含めない。

    AC13: .claude/settings.json では existing session_recording_policy_guard.sh と producer hook の順序が structural test で検証される。

    AC14: PostToolUse hook は matcher で対象 tool を限定し、全 tool call に対して無条件発火しない。

    AC15: Workflow は permissions: contents: read、actions/checkout の persist-credentials: false、pull_request_target 不使用を満たす。

    AC16: Workflow artifact は actions/upload-artifact@v4 以上、if-no-files-found: error、retention-days 明示、artifact name prefix private-agent-session-manifest を満たす。

    AC17: Workflow logs に manifest JSON 本文を出力しない。

    最終判断

    #402 は Close ではなく修正して実装すべき Issue です。
    ただし現在の本文は「producer script を lifecycle に呼ばせる」粒度に留まっており、実装時に事故りやすいです。

    実装順は以下が妥当です。

    1. 実装: agent_session_manifest/v1 producer を .claude/settings.json hooks と .github/workflows で自動 invoke する #402 本文を更新し、現行 schema の producer field 存在を反映する。

    2. hook 直呼びではなく .claude/hooks/generate_session_manifest_from_hook.mjs を追加する。

    3. Stop/SubagentStop では既存 policy guard との順序を structural test で固定する。

    4. PostToolUse は matcher + atomic write + duplicate skip を必須化する。

    5. GitHub Actions は artifact-only / read-only permission / no pull_request_target に限定する。

    6. grep VC を structural tests に置換する。

    この修正を入れれば、#402 は #242 / #324 / #325 / #377 / PR #404 の後続として筋が通ります。

  3. squne121 commented on May 26, 2026

    @squne121
    OwnerAuthor

    人間コメント。
    ClaudeCodeの運用効果測定のためToken使用量、SubAgent発火などの振る舞いを自動で測定しGithubへ出力できる仕組みを作っている認識。
    しかしSecretの取り扱いについてOpenに流出させないようにSecretの検知やKillSwitch機能をつけている認識。
    Secret流出対策機能は下流の対策と認識している。
    上流での対策としてGithubでのセキュアなSecret管理やClaudeCodeが人間が設定したSecretを読み出せないようにする仕組み(コマンド権限管理やhook)などは設定できないか検討してIssue案を作成してほしい。
    PublishやBooleanでSecretが設定されていることは確認できてもSecretそのものは読み出せないようにする方法を知りたいし運用に取り入れたい。

  4. squne121 commented on May 26, 2026

    @squne121
    OwnerAuthor

    結論:#402 とは別 Issue に切り出すべきです。
    #402 は manifest producer の hook / CI wiring が主目的で、本文でも Secret / token management と push protection / secret scanning は out of scope と明記されています。 そのため、人間コメントの論点は「下流の漏洩検知」ではなく、Claude Code / GitHub Actions が Secret 値へ到達できないようにする上流統制として別 Issue 化するのが妥当です。

    GitHub Secrets については、API / UI 上は secret 名、作成日時、更新日時、visibility、選択 repository などは取得できるが、secret 値そのものは返らない設計です。GitHub REST API も “without revealing their encrypted values” として secret list / get を提供し、response 例にも secret value は含まれていません。 一方、workflow 内で ${{ secrets.X }} を env や action input に渡した瞬間、その job のプロセスからは値として扱えるため、「存在確認だけに使う」「Claude Code / manifest producer へ渡さない」が上流対策になります。GitHub Actions では secret が未設定なら参照結果は空文字になります。

    Claude Code 側は、.claude/settings.json の permissions.deny で .env や secrets/** の Read を拒否できます。公式 docs でも sensitive files を Claude Code から除外する用途として permissions.deny が示されています。 また、managed settings なら allowManagedPermissionRulesOnly や disableBypassPermissionsMode により、ユーザー・project 側の緩い許可や bypass mode を抑制できます。 Hook では stdin JSON を検査し、危険な Bash / Read / Env 操作を exit 2 でブロックできます。Claude Code docs では exit code 2 が blocking error として扱われ、PreToolUse は tool call を防止できます。

    起票案

    実装: Claude Code / GitHub Actions の Secret 到達面を上流で制限する secure-secret-boundary を導入する

    Machine-Readable Contract

    issue_kind: implementation
    parent_issue: "#242"
    related_issues: ["#402", "#325", "#324"]
    dedupe_key: "secure-secret-boundary-for-agent-session-measurement"
    area: ai-ops/security
    
    背景
    
    #402 では Claude Code の運用効果測定のため、Token 使用量、SubAgent 発火、hook / CI 起点の agent_session_manifest を GitHub Actions artifact へ出力する仕組みを作ろうとしている。
    
    一方、Secret 流出対策として Secret 検知や Kill Switch を入れるだけでは、Secret がいったん Claude Code / hook / producer / CI job に到達した後の下流対策に偏る。
    
    本 Issue では、上流対策として以下を検討・導入する。
    
    GitHub Secrets の値そのものを Claude Code / manifest producer / workflow logs / GitHub comment に渡さない
    
    GitHub Secrets は「設定済みかどうか」「visibility / selected repo policy」だけを確認対象にする
    
    Claude Code が .env / credentials / secrets directory / GitHub secret dump 相当へ Read / Bash 経由で到達できないようにする
    
    hook / permission / sandbox / workflow permissions により Secret 到達面を狭める
    
    
    現状認識
    
    GitHub Actions Secrets は、list / get API で secret 名・visibility・created_at・updated_at 等は確認できるが、値そのものは返らない。したがって、運用では secret value を取得・出力・manifest 化する必要はない。
    
    ただし、workflow 内で ${{ secrets.SECRET_NAME }} を env や action input に渡すと、その job のプロセスからは値として利用できる。Claude Code / manifest producer / hook に secret env を渡す設計にすると、下流の redaction / Kill Switch に依存する危険がある。
    
    Goal
    
    Claude Code 運用効果測定のための manifest / telemetry pipeline において、Secret 値が以下へ到達しないことを構造的に保証する。
    
    Claude Code context
    
    Claude transcript
    
    .claude/hooks/** stdout / stderr
    
    scripts/generate-session-manifest.mjs
    
    GitHub Actions workflow logs
    
    GitHub Issue / PR comment
    
    Git committed files
    
    uploaded manifest artifact
    
    
    In Scope
    
    .claude/settings.json
    
    permissions.deny による sensitive path Read 拒否
    
    .env, .env.*, secrets/**, credential files, local token stores の deny
    
    必要なら Bash deny / ask rule の追加
    
    
    .claude/hooks/**
    
    PreToolUse guard の追加または既存 guard 拡張
    
    Secret 読み取り・環境変数 dump・credential file cat を block
    
    env, printenv, set, export -p, gh secret, cat .env 等の扱いを明示
    
    
    .github/workflows/**
    
    manifest / measurement workflow に secrets context を渡さない
    
    permissions を最小化する
    
    pull_request_target を禁止する
    
    workflow logs に secret 存在確認以外を出さない
    
    
    docs/dev/session-recording-policy.md
    
    Secret boundary policy を明文化
    
    「Secret value 不可視」「存在・boolean・metadata のみ可」を定義
    
    GitHub Secrets / Variables / Environment secrets の使い分けを定義
    
    
    tests
    
    settings.json structural test
    
    workflow structural test
    
    hook guard smoke test
    
    
    
    Out of Scope
    
    Secret 値の復号・取得・表示
    
    Secret 値を manifest に保存する設計
    
    GitHub Issue / PR comment への Secret 関連 raw dump
    
    pull_request_target を使った自動 comment / mutation
    
    cloud provider credential の直接管理
    
    Secret scanning / push protection そのものの導入
    
    これは別 Issue として扱う
    
    
    
    Proposed Policy
    
    P1. Secret value must never be an input to measurement
    
    measurement / manifest pipeline は secret value を入力にしてはならない。
    
    禁止:
    
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
    
    ただし、Secret が設定されているかどうかの boolean 化は許容する。
    
    env:
      HAS_OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY != '' }}
    
    manifest へ保存してよいのは以下のみ。
    
    {
      "secret_policy": {
        "required_secret_names": ["OPENAI_API_KEY"],
        "presence": {
          "OPENAI_API_KEY": true
        },
        "value_exposed": false
      }
    }
    
    P2. GitHub Secret metadata is allowed; value is forbidden
    
    許可:
    
    secret name
    
    created_at
    
    updated_at
    
    visibility
    
    selected repository policy
    
    environment name
    
    required / optional
    
    present / absent boolean
    
    
    禁止:
    
    secret value
    
    encrypted_value
    
    masked-looking raw value
    
    base64 / hex / partial prefix / suffix
    
    hash of secret value
    
    辞書攻撃・照合用途になり得るため禁止
    
    
    
    P3. Claude Code must not read local secret files
    
    .claude/settings.json に最低限以下を追加する。
    
    {
      "permissions": {
        "deny": [
          "Read(./.env)",
          "Read(./.env.*)",
          "Read(./secrets/**)",
          "Read(./config/credentials.json)",
          "Read(./credentials/**)",
          "Read(./.aws/**)",
          "Read(./.gcp/**)",
          "Read(./.azure/**)"
        ],
        "ask": [
          "Bash(gh secret *)",
          "Bash(printenv *)",
          "Bash(env *)",
          "Bash(set *)",
          "Bash(export -p *)",
          "Bash(cat .env*)",
          "Bash(grep * .env*)"
        ]
      }
    }
    
    より強い設計では、ask ではなく deny とし、許可が必要な場合だけ人間が明示的に一時解除する。
    
    P4. PreToolUse hook must block high-risk secret access
    
    .claude/hooks/secret_boundary_guard.sh を追加する。
    
    対象:
    
    cat .env
    
    grep, rg, awk, sed による .env / secrets/** 読み取り
    
    printenv, env, set, export -p
    
    gh secret set 以外の gh secret 参照系
    
    gh api /repos/*/actions/secrets* の濫用
    
    base64, xxd, openssl 等による credential file の変換出力
    
    GitHub comment / issue body / artifact への secret-like data 出力
    
    
    block 時は exit 2 を返す。stderr には Secret 値・ファイル内容・環境変数値を含めない。
    
    P5. GitHub Actions permissions must be read-only by default
    
    manifest / measurement workflow は以下を満たす。
    
    permissions:
      contents: read
    
    または、可能なら:
    
    permissions: {}
    
    checkout が必要な場合のみ contents: read を使う。
    
    禁止:
    
    permissions: write-all
    permissions:
      issues: write
      pull-requests: write
    
    Issue / PR comment 投稿が必要になった場合は、別 Issue で review する。
    
    P6. pull_request_target must be forbidden
    
    禁止:
    
    on:
      pull_request_target:
    
    理由:
    
    fork 由来の untrusted input と write token / secrets の組み合わせが危険
    
    measurement pipeline は artifact-only に閉じるべき
    
    
    許可:
    
    on:
      pull_request:
      push:
    
    ただし fork PR では secrets を参照しない。
    
    P7. Secret presence check must be non-exfiltrating
    
    Secret が設定されていることを確認する場合、値ではなく boolean のみを扱う。
    
    例:
    
    - name: Check required secret presence
      env:
        HAS_ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY != '' }}
      run: |
        if [ "$HAS_ANTHROPIC_API_KEY" != "true" ]; then
          echo "ANTHROPIC_API_KEY is not configured"
          exit 1
        fi
        echo "ANTHROPIC_API_KEY is configured"
    
    禁止:
    
    echo "$ANTHROPIC_API_KEY"
    echo "${ANTHROPIC_API_KEY:0:4}"
    node -e 'console.log(process.env.ANTHROPIC_API_KEY)'
    
    Acceptance Criteria
    
    <!-- runtime-verification: true -->AC1: .claude/settings.json に .env, .env.*, secrets/**, credential path の permissions.deny がある
    
    AC2: Claude Code が sensitive path を Read できないことを structural test で検証する
    
    AC3: PreToolUse hook が cat .env, printenv, env, gh secret 参照系を block する
    
    AC4: hook block 時の stderr に secret-like value / env dump / file content が含まれない
    
    AC5: manifest / measurement workflow が ${{ secrets.* }} を value として env / input に渡さない
    
    AC6: workflow で許可される secrets context 利用は ${{ secrets.NAME != '' }} 形式の presence boolean のみ
    
    AC7: workflow は permissions: contents: read または permissions: {} を使い、write-all を使わない
    
    AC8: workflow は pull_request_target を使わない
    
    AC9: workflow は Issue / PR comment へ manifest / secret metadata を投稿しない
    
    AC10: manifest schema または producer output に secret_policy.value_exposed: false 相当の明示フィールドがある
    
    AC11: manifest に secret value、partial value、hash value、base64 value が含まれない
    
    AC12: docs に「GitHub Secret は値を読めない。運用上も値を pipeline に渡さない。presence / metadata のみ扱う」と明記される
    
    
    Verification Commands
    
    # settings.json syntax
    jq . .claude/settings.json > /dev/null
    
    # sensitive Read deny rules
    jq -e '
      .permissions.deny as $deny |
      ($deny | index("Read(./.env)")) and
      ($deny | index("Read(./.env.*)")) and
      ($deny | index("Read(./secrets/**)"))
    ' .claude/settings.json
    
    # workflow must not use pull_request_target
    ! grep -R "pull_request_target" .github/workflows/
    
    # workflow must not pass secret values directly
    ! grep -R '\${{ *secrets\.[A-Za-z0-9_]* *}}' .github/workflows/
    
    # boolean presence check is allowed
    grep -R '\${{ *secrets\.[A-Za-z0-9_]* *!= *'\'''\'' *}}' .github/workflows/ || true
    
    # no write-all
    ! grep -R "write-all" .github/workflows/
    
    # no comment write permissions in measurement workflows
    ! grep -R "issues: write\|pull-requests: write" .github/workflows/session-manifest.yml
    
    # hook exists
    test -x .claude/hooks/secret_boundary_guard.sh
    
    # hook smoke test: env dump should block
    printf '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"printenv"}}' \
      | .claude/hooks/secret_boundary_guard.sh
    test "$?" -eq 2
    
    Allowed Paths
    
    .claude/settings.json
    
    .claude/hooks/secret_boundary_guard.sh
    
    .claude/hooks/tests/**
    
    .github/workflows/session-manifest.yml
    
    .github/workflows/** only if measurement workflow shares reusable policy
    
    docs/dev/session-recording-policy.md
    
    scripts/** only for structural validation scripts related to secret boundary
    
    
    Stop Conditions
    
    Secret 値の取得・復号・表示が必要になる
    
    workflow に ${{ secrets.NAME }} を value として渡す必要がある
    
    pull_request_target が必要になる
    
    issues: write / pull-requests: write が必要になる
    
    GitHub comment への出力が必要になる
    
    Claude Code の bypass permission mode に依存する
    
    Secret scanning / push protection 本体の導入が必要になる
    
    別 Issue に分離する
    
    
    
    Implementation Notes
    
    GitHub Secrets の API / UI で扱うのは metadata と presence のみ。
    
    Secret 値は workflow step の env / input に渡さない。
    
    Claude Code の permissions.deny は file tool の Read 抑止に使う。
    
    Bash 経由の迂回は PreToolUse hook で止める。
    
    managed settings が使える環境では allowManagedPermissionRulesOnly と disableBypassPermissionsMode を優先する。
    
    #402 の manifest producer は secret value を入力にしない。
    
    #402 の artifact は private artifact であっても secret value 保存は禁止する。
    
    
    ## #402 への人間コメント返答案
    
    ```md
    指摘は妥当です。#402 は manifest producer の hook / CI wiring が主責務であり、Secret / token management は本文上も out of scope になっているため、この論点は別 security Issue に切り出すべきです。
    
    特に、現状の Kill Switch / Secret 検知は「出力されそうになった後」の下流対策です。追加で必要なのは、Claude Code / hook / producer / GitHub Actions job が Secret 値へ到達しないようにする上流対策です。
    
    Issue 化する内容は以下です。
    
    - GitHub Secrets は値を読めない前提を運用に取り込む
      - secret name / visibility / selected repo / updated_at / present boolean のみ扱う
      - secret value / partial value / hash / base64 は扱わない
    - workflow では `${{ secrets.NAME }}` を env / input に渡さない
      - 許容するのは `${{ secrets.NAME != '' }}` による presence boolean のみ
    - Claude Code 側で `.env`, `.env.*`, `secrets/**`, credential files を `permissions.deny` する
    - Bash 経由の迂回を PreToolUse hook で block する
      - `cat .env`
      - `printenv`
      - `env`
      - `set`
      - `export -p`
      - `gh secret` 参照系
    - GitHub Actions は `permissions: contents: read` または `permissions: {}` に限定する
    - `pull_request_target`, `write-all`, `issues: write`, `pull-requests: write` は本 pipeline では禁止する
    - manifest / workflow artifact / GitHub comment / logs に Secret 値を出さない
    
    したがって #402 はそのまま修正対象にせず、上記を `secure-secret-boundary-for-agent-session-measurement` のような sibling Issue として起票し、#402 はその Issue を security dependency として参照する形がよいです。
  5. squne121 commented on May 26, 2026

    @squne121
    OwnerAuthor

    issue-refinement-loop: 完了 (2026-05-26T00:00:00Z)

    • iteration: 1
    • verdict: approve
    • termination_reason: approved
    • 改善履歴:
      • implementation template に沿って #402 本文を全面正規化
      • stale だった schema 前提(producer field follow-up 前提)を #401 / #377 反映後の現実に更新
      • hook 直呼び不可、SessionStart 除外、PostToolUse matcher、policy guard 順序、artifact-only CI 境界を AC / VC へ明文化
      • Secret / token management 上流統制を sibling security issue へ分離
    • 次アクション: issue-contract-review を実行し、#412 を upstream security sibling として参照したまま着手前 preflight に進む
    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      follow_up_issues:
        - request_dedupe_key: "secure-secret-boundary-for-agent-session-measurement"
          issue_number: 412
          issue_url: "https://github.com/squne121/loop-protocol/issues/412"
          status: created
      note_only_observations: []
  6. squne121 commented on May 27, 2026

    @squne121
    OwnerAuthor

    Contract Review: BLOCKED (2026-05-27T20:17:04Z)

    不足項目

    VC preflight で以下が blocked / human_judgment に分類されました:

    AC コマンド category decision 理由
    AC2 uv run pytest ... -k "generate_session_manifest_from_hook and stdout" regression_gate blocked exit 5 (no tests collected) — 新規 test 関数未実装
    AC4 uv run pytest ... -k "post_tool_use and matcher" regression_gate blocked exit 5 (no tests collected) — 新規 test 関数未実装
    AC5 uv run pytest ... -k "hook_config and policy_guard_order" regression_gate blocked exit 5 (no tests collected) — 新規 test 関数未実装
    AC6 uv run pytest ... -k "transcript_path or cwd or ..." regression_gate blocked exit 5 (no tests collected) — 新規 test 関数未実装
    AC7 rg -n 'persist-credentials:\s*false' .github/workflows/session-manifest.yml unknown human_judgment exit 2 (file not found) — 新規 workflow ファイル未作成

    分析

    これらは 実装対象の新規ファイル/テストが存在しないことによる期待通りの baseline 失敗 です。uv run pytest が regression_gate に分類されたため、exit 5 (no tests collected) が false-positive blocked になっています。

    対処

    VC に # preflight-scope: pr_review_only マーカーを追加することで、これらのコマンドを pr-review-judge での検証対象として分類し直します。

    推奨アクション

    impl-review-loop が VC マーカーを追加して再実行します。

  7. squne121 commented on May 27, 2026

    @squne121
    OwnerAuthor

    Contract Snapshot (2026-05-27T20:18:51Z)

    • Outcome: manifest producer wrapper が Stop / SubagentStop / scoped PostToolUse と GitHub Actions artifact workflow から deterministic かつ stdout-silent に起動され、private artifact 以外へ manifest 本文やローカル絶対パスを出さない状態
    • Acceptance Criteria: AC1〜AC10(10 件)
    • Verification Commands: 12 コマンド(baseline_fail: 7, skipped/pr_review_only: 5)
    • Allowed Paths:
      • .claude/settings.json
      • .claude/hooks/generate_session_manifest_from_hook.mjs
      • .claude/hooks/tests/
      • .github/workflows/session-manifest.yml
      • docs/dev/session-recording-policy.md
    • Worktree: .claude/worktrees/issue-402-agent-session-manifest-v1-producer-claud
    • Branch: worktree-issue-402-agent-session-manifest-v1-producer-claud
    • VC preflight: baseline fail expected = 7, unexpected pass = 0, unrunnable = 0, skipped (pr_review_only) = 5
    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: 2026-05-27T20:18:51Z
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/402
      checks:
        template_compliance: pass
        state_label: ok
        allowed_paths_present: pass
        vc_present: pass
        stop_conditions_complete: pass
        vc_preflight:
          passed: true
          vc_failed_as_expected: 7
          vc_passed_unexpectedly: 0
          vc_unrunnable: 0
          vc_expected_pass: 0
          vc_skipped: 5
          classifications:
            - ac: AC1
              command: "rg -n 'generate_session_manifest_from_hook|generate-session-manifest' .claude/settings.json"
              exit_code: 1
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC2
              command: "test -f .claude/hooks/generate_session_manifest_from_hook.mjs"
              exit_code: 1
              classification: expected_fail
              category: file_not_found_expected
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC2
              command: "uv run pytest .claude/hooks/tests/ -q -k 'generate_session_manifest_from_hook and stdout'"
              exit_code: 5
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: high
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: "新規テスト関数 — baseline では未実装のため pr_review_only でスキップ"
              runtime_verification_required: false
            - ac: AC3
              command: "! rg -n 'SessionStart' .claude/settings.json"
              exit_code: null
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC4
              command: "uv run pytest .claude/hooks/tests/ -q -k 'post_tool_use and matcher'"
              exit_code: 5
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: high
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: "新規テスト関数 — baseline では未実装のため pr_review_only でスキップ"
              runtime_verification_required: false
            - ac: AC5
              command: "uv run pytest .claude/hooks/tests/ -q -k 'hook_config and policy_guard_order'"
              exit_code: 5
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: high
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: "新規テスト関数 — baseline では未実装のため pr_review_only でスキップ"
              runtime_verification_required: false
            - ac: AC6
              command: "uv run pytest .claude/hooks/tests/ -q -k 'transcript_path or cwd or atomic_write or duplicate_skip'"
              exit_code: 5
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: high
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: "新規テスト関数 — baseline では未実装のため pr_review_only でスキップ"
              runtime_verification_required: false
            - ac: AC7
              command: "python3 -c \"import sys, yaml; ...\""
              exit_code: 1
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC7
              command: "rg -n 'persist-credentials:\s*false' .github/workflows/session-manifest.yml"
              exit_code: 2
              classification: skipped
              category: preflight_scope_pr_review_only
              scope_class: pr_review_only
              confidence: high
              decision: go
              verification_owner: pr-review-judge
              deferred_reason: "新規 workflow ファイル未作成 — file not found は baseline で期待通り"
              runtime_verification_required: false
            - ac: AC8
              command: "python3 -c \"import yaml; ...\""
              exit_code: 1
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC9
              command: "! rg -n 'gh issue comment|gh pr comment|echo .*manifest|cat .*manifest' ..."
              exit_code: null
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              decision: go
            - ac: AC10
              command: "rg -n '#412|private channel|GitHub Actions artifact only|...' docs/dev/session-recording-policy.md"
              exit_code: 1
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              confidence: high
              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
          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:
        - "Issue lacks phase/implementation label (has kind/implementation) — routing note only, not a blocker"
  8. squne121 commented on May 27, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-05-27T20:29:24Z)

    • PR: feat(#402): wire agent_session_manifest/v1 producer to hooks and CI #426
    • Worktree: .claude/worktrees/issue-402-agent-session-manifest-v1-producer-claud
    • Branch: worktree-issue-402-agent-session-manifest-v1-producer-claud
    • Verification: 4/4 PASS (typecheck/lint/test/build) + 8 pytest PASS + AC1-AC10 VC PASS
    • 後続: PR レビュー(pr-review-judge)→ マージ → post-merge-cleanup
  9. added 5 commits that reference this issue on May 27, 2026
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

    area/ai-opskind/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions