Skip to content

実装: observation source reason_codes を non-free-form code に制限する #1259

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "#1153"
goal_ref: "anchor comment #4865350141 の REQUEST_CHANGES に従い、observation source reason_codes を free-form text ではなく closed non-free-form code contract に制限する"
change_kind: mixed

Parent Issue

#1153

Parent Goal Ref

  • Goal: public-safe observation source projection を covert channel なしで ChatGPT retrospective 導線へ接続する
  • Desired Destination: public_safety.observation_sources[].safety.reason_codes が自然言語・指示文・path 断片・secret-looking fragment を運ばない closed contract になり、public projection の allowlist を維持できる状態

Current Validated Scope

  • observation source adapter / final validator / retro index / docs / schema / tests で public_safety.observation_sources[].safety.reason_codes を同一 contract に揃える
  • closed allowed_codes + regex invariant を明文化し、regex に合うだけの free-form snake_case text を通さない
  • negative fixture で regex-valid だが意味的に不正な code を fail-closed にする

Remaining Parent Gaps

  • host preflight / distribution / Cloud pilot / Latitude install provenance gate は別 child issue で扱う
  • entirecli_safety.reason_codes の policy 変更は別 scope のまま維持する

Outcome

public_safety.observation_sources[].safety.reason_codes が allowed_codes に列挙された code だけを受け付ける closed contract になり、各 code は ^[a-z][a-z0-9_]{0,79}$ と max_length_per_item: 80 を invariant として満たす。unknown code、free-form text、prompt-injection-like phrase、secret-looking fragment、local-path-like value は adapter / schema / final validator / retro index の各層で fail-closed になり、availability: unavailable では source_unavailable、capability_verdict: partial かつ availability: available では partial_projection の semantic constraint が維持される状態。

In Scope

  • 対象 field を public_safety.observation_sources[].safety.reason_codes に限定する
  • reason_codes_contract を closed allowed_codes + regex invariant として定義する
  • allowed_codes は現行 observation source semantics に必要な code のみを列挙し、unknown code policy を blocked または同等の fail-closed に固定する
  • syntax_pattern: ^[a-z][a-z0-9_]{0,79}$
  • max_items: 32
  • max_length_per_item: 80
  • free_form_text: forbidden
  • adapter が invalid input を silently drop / coerce / dedupe / sanitize せず rejection する contract に揃える
  • schema / docs / adapter / validate-final-report.mjs / retro-index-builder.mjs / tests の semantics を一致させる
  • source_unavailable と partial_projection の auto-added semantics を schema または runtime validator で明示的に維持する
  • reason code violation を observation-source-specific な runtime / blocked reason に分類する
  • negative fixture で regex-valid prompt-injection-like code、natural language、path-looking value、secret-looking fragment、too many items、too long item を reject する

Out of Scope

  • public_safety.observation_sources[].safety.reason_codes 以外の field 再設計
  • entirecli_safety.reason_codes の policy 変更
  • real telemetry 実走
  • Cloud pilot / marker / retention / follow-up materialization
  • scripts/lib/agent-run-report-validation.mjs への共通 scan 追加

Acceptance Criteria

  • AC1: public_safety.observation_sources[].safety.reason_codes が free-form string list ではなく allowed_codes による closed contract になる
  • AC2: 各 allowed code に ^[a-z][a-z0-9_]{0,79}$ と max_length_per_item: 80 の invariant が適用される
  • AC3: max_items: 32 が schema / docs / tests に反映される
  • AC4: unknown code が adapter / schema / final validator / retro index の各層で fail-closed になる
  • AC5: adapter が invalid reason code input を silently drop / coerce / dedupe / sanitize せず rejection する
  • AC6: availability: unavailable の observation source では source_unavailable が required になる
  • AC7: capability_verdict: partial かつ availability: available の observation source では partial_projection が required になる
  • AC8: reason code contract violation が digest mismatch と別の observation-source-specific reason で分類される
  • AC9: negative fixture に regex-valid prompt-injection-like code、natural language、HTML/Markdown breakout、path-looking value、secret-looking fragment、too many items、too long item、uppercase / punctuation drift が含まれる
  • AC10: entirecli_safety.reason_codes はこの issue の scope に含めない
  • AC11: scripts/lib/agent-run-report-validation.mjs が必要になった場合は scope widening ではなく stop condition 扱いになる

Runtime Verification Applicability

runtime_verification_applicability:
  decision: not_applicable
  status: not_applicable
  reason: "Issue refinement only。runtime telemetry 実走や外部サービス検証はこの issue の out-of-scope。"
  evidence_expectation:
    - "static contract / schema / validator / test scope の整合だけを扱う"
    - "Cloud pilot / Latitude distribution / real telemetry run は別 child issue で扱う"

Verification Commands

# AC1
$ pnpm typecheck
# AC2
$ pnpm lint
# AC3
# baseline-expect: fail
$ pnpm test
# AC4
$ pnpm build
# AC5
# baseline-expect: pass
$ rg -n "reason_codes" scripts/agent-logs/lib/observation-source-adapter.mjs
# AC6
# baseline-expect: pass
$ rg -n "source_unavailable" docs/schemas/agent-run-report.schema.json
# AC7
# baseline-expect: pass
$ rg -n "partial_projection" docs/schemas/agent-run-report.schema.json
# AC8
# baseline-expect: pass
$ rg -n "reason_codes" scripts/agent-logs/lib/retro-index-builder.mjs
# AC9
# baseline-expect: pass
$ test -f tests/agent-logs/observation-source-adapter.test.ts
# AC10
# baseline-expect: pass
$ test -f tests/agent-logs/entirecli-report-field.test.ts
# AC11
# baseline-expect: pass
$ test -f scripts/lib/agent-run-report-validation.mjs

Allowed Paths

  • scripts/agent-logs/lib/observation-source-adapter.mjs
  • scripts/agent-logs/lib/validate-final-report.mjs
  • scripts/agent-logs/lib/retro-index-builder.mjs
  • docs/dev/agent-run-report.md
  • docs/schemas/agent-run-report.schema.json
  • tests/agent-run-report-schema.test.ts
  • tests/agent-logs/**
  • tests/fixtures/agent-run-report/**

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • scripts/lib/agent-run-report-validation.mjs への共通 scan 追加が必要と判明した場合
  • public_safety.observation_sources[].safety.reason_codes 以外の field policy 変更が必要になった場合
  • entirecli_safety.reason_codes 側の policy 変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • raw prompt / raw trace / local absolute path / credential value を reason code 判定のために読む必要が生じた場合

Required Skills

  • Node.js validation pipeline
  • JSON Schema / Ajv
  • public-safe projection design

Scope Delta(任意)

  • closed enum または regex を closed allowed_codes + regex invariant に置換
  • public_safety.observation_sources[].safety.reason_codes 専用 scope を明示
  • shared validator 追加は scope widening 扱いにせず stop condition に固定

Activity

  1. added
    phase/implementation
    agent/implementer
    enhancement
    on Jul 1, 2026
  2. squne121 commented on Jul 2, 2026

    @squne121
    OwnerAuthor

    判定

    REQUEST_CHANGES(Issue 仕様の補強必須)。

    #1259 の方向性は正しいです。observation source reason_codes を free-form text から外し、public-safe projection の covert channel を潰す必要があります。ただし、現状の Issue 記述は 「regex による見た目の制限」と「closed contract による意味集合の制限」を混同しているため、このまま実装すると ignore_previous_instructions や home_alice_claude_settings_local_json のような snake_case 化された自然文・指示・path 断片が通る余地があります。#1259 自体にコメントはなく、実装 PR もまだ確認できていないため、これは Issue 契約段階での敵対的レビューです。

    参照した文脈

    #1259 は、親 #1153 の「private observation plane から public-safe な agent_run_report/v1 / agent_retro_index/v1 へ正規化し、GitHub 経由で ChatGPT retrospective を可能にする」流れの一部です。親 Issue は raw prompt・tool I/O・system prompt 等を private 側に閉じ、public 側には validated summary / metrics / opaque evidence reference だけを出す設計です。

    関連する実装分割はかなり明確です。#1222 / PR #1243 が public_safety.observation_sources[] と observation source schema admission を追加し、source_kind / capability_verdict / availability / projection_mode / safety.verdict を strict enum にしています。 #1223 / PR #1247 は adapter と runtime gate を接続し、raw payload ではなく allowlist projection を agent_run_report/v1 に入れる C1 実装でした。 PR #1247 は finalize-agent-run.mjs から observation-source-adapter.mjs を通し、validate-final-report.mjs と retro-index-builder.mjs で missing / empty / duplicate / raw 値 / unavailable metrics drift を fail-closed にしたと主張しています。

    #1245 は CHATGPT_RETRO_CONTEXT_V1 marker 導線と single-source projection 前提を整理し、unsupported / unverified を availability: unavailable として扱う方針を固定しています。 #1261 は Latitude distribution / argv / remote cleanup gate を別スコープに切り出しており、floating npx -y @latitude-data/claude-code-telemetry、exact semver、dist integrity、tarball digest、entrypoint/preload/hook digest、argv exposure などを扱います。#1259 はここへ踏み込まず、reason code の public-safe contract に限定すべきです。

    Blocker 1: 「closed enum または regex」は安全要件として弱い

    #1259 は reason_codes を ^[a-z][a-z0-9_]{0,79}$ に合う code だけにする、としています。これは必要条件としては妥当ですが、十分条件ではありません。Issue の目的は、自然言語・secret-looking fragment・local-path-like value を public projection に載せないことです。

    JSON Schema の pattern は文字列が正規表現にマッチするかを制限するだけで、意味集合を閉じません。また、pattern は通常「部分一致」なので、完全一致にするには ^...$ anchor が必要です。([JSON Schema]1) 一方、enum は許可される値そのものを有限集合として定義します。(JSON Schema)

    したがって、#1259 の contract は次のように修正すべきです。

    reason_codes_contract:
      representation: string_code_array
      syntax_pattern: "^[a-z][a-z0-9_]{0,79}$"
      max_items: 32
      max_length_per_item: 80
      allowed_codes:
        - source_unavailable
        - partial_projection
        - synthetic_only_evidence
        - host_inventory_only
      unknown_code_policy: blocked
      free_form_text: forbidden
    

    「closed enum または regex」ではなく、closed registry + regex invariant にしてください。regex だけだと、ignore_previous_instructions、read_home_alice_claude_settings_local_json、ghp_deadbeef_token_like のような値が構文上は通ります。これは #1259 の covert channel 対策として不十分です。

    Blocker 2: 現行 adapter は reason_codes を fail-closed にしていない

    現行 observation-source-adapter.mjs では uniqueSortedStrings() が values ?? [] から string だけを拾い、空文字を落とし、重複排除して sort します。型不正・非配列・重複・空文字・unknown code を fail せず、黙って正規化してしまう構造です。

    normalizeSafety() でも reason_codes は uniqueSortedStrings(safety.reason_codes) の結果をほぼそのまま返しており、pattern、max items、max length、allowlist、unknown policy を見ていません。 その後、source_unavailable と partial_projection は auto-add されますが、入力側の不正 code を落とす処理ではありません。

    ここは sanitization ではなく rejection に変えるべきです。特に reason_codes: ["ignore_previous_instructions"] を adapter が一瞬でも projection digest 対象に入れる設計は避けるべきです。public report の最終 schema validation で落ちるとしても、adapter 単体の contract としては fail-open です。

    推奨実装は、adapter 内に共有関数を置く形です。

    const OBSERVATION_REASON_CODE_PATTERN = /^[a-z][a-z0-9_]{0,79}$/u
    const OBSERVATION_REASON_CODE_MAX_ITEMS = 32
    const OBSERVATION_REASON_CODES = new Set([
      'source_unavailable',
      'partial_projection',
      'synthetic_only_evidence',
      'host_inventory_only',
    ])
    
    function normalizeObservationReasonCodes(value, path) {
      if (!Array.isArray(value)) {
        throw runtimeError('observation_source.reason_codes_type', `${path} must be an array`)
      }
      if (value.length > OBSERVATION_REASON_CODE_MAX_ITEMS) {
        throw runtimeError('observation_source.reason_codes_too_many', `${path} must contain at most 32 items`)
      }
    
      const seen = new Set()
      const normalized = []
    
      for (const [index, code] of value.entries()) {
        const itemPath = `${path}[${index}]`
        if (typeof code !== 'string') {
          throw runtimeError('observation_source.reason_code_type', `${itemPath} must be a string`)
        }
        if (!OBSERVATION_REASON_CODE_PATTERN.test(code)) {
          throw runtimeError('observation_source.reason_code_pattern', `${itemPath} must match ^[a-z][a-z0-9_]{0,79}$`)
        }
        if (!OBSERVATION_REASON_CODES.has(code)) {
          throw runtimeError('observation_source.reason_code_unknown', `${itemPath} is not an allowed observation source reason code`)
        }
        if (seen.has(code)) {
          throw runtimeError('observation_source.reason_code_duplicate', `${itemPath} duplicates ${code}`)
        }
        seen.add(code)
        normalized.push(code)
      }
    
      return normalized.sort()
    }
    

    重複は uniqueItems 相当で落とせますが、adapter 入力では「黙って dedupe」ではなく fail-closed が安全です。JSON Schema でも maxItems と uniqueItems は array 長と重複制約の標準的な指定です。(JSON Schema)

    Blocker 3: schema は enum だが、#1259 の AC をまだ満たしていない

    現行 schema の observationSourceSafety.reason_codes は array + uniqueItems: true + item enum です。許可値は partial_projection、synthetic_only_evidence、host_inventory_only、source_unavailable の 4 つです。 これは closed enum としては良い方向です。

    ただし #1259 の acceptance criteria にある allowed_pattern、max_items: 32、max_length_per_item: 80 は schema にまだありません。string length は JSON Schema の maxLength で表現できます。(JSON Schema)

    schema 側は最低限こうするべきです。

    "observationSourceReasonCode": {
      "type": "string",
      "maxLength": 80,
      "pattern": "^[a-z][a-z0-9_]{0,79}$",
      "enum": [
        "partial_projection",
        "synthetic_only_evidence",
        "host_inventory_only",
        "source_unavailable"
      ]
    }
    

    さらに、reason_codes array には maxItems: 32 を入れてください。

    "reason_codes": {
      "type": "array",
      "maxItems": 32,
      "uniqueItems": true,
      "items": {
        "$ref": "#/$defs/observationSourceReasonCode"
      }
    }
    

    enum があるため pattern/maxLength は重複に見えますが、#1259 が「code contract」を文書化するなら invariant として入れる価値があります。将来 enum が増えても syntax policy が崩れません。

    Blocker 4: auto-added code の意味制約が schema/runtime で片側にしかない

    adapter は availability === 'unavailable' のとき source_unavailable を追加し、capability_verdict === 'partial' && availability === 'available' のとき partial_projection を追加します。 docs も unavailable では metrics null と source_unavailable 補完を説明しています。

    しかし schema の conditional は、partial + available の場合に reason_codes の minItems: 1 だけを要求しており、partial_projection そのものを要求していません。 unavailable の場合に source_unavailable を contains で要求する条件も見当たりません。

    攻撃者または壊れた producer が digest を再計算して、availability: unavailable なのに reason_codes: [] の report を作る場合、adapter を通らない経路では semantic drift が起きます。validateObservationSourceProjection() は digest/ref/evidence_mode を検査しますが、reason code の意味制約は見ていません。

    対策はどちらかです。

    1. schema に contains: { "const": "source_unavailable" } / contains: { "const": "partial_projection" } を追加する。
    2. validateObservationSourceProjection() に reason code semantic check を追加し、validate-final-report と retro-index-builder の両方で同じ blocker reason に落とす。

    防御層としては両方が望ましいです。

    Blocker 5: retro-index 側の error taxonomy が #1259 と合っていない

    validate-final-report.mjs は public surface で observation_sources missing / empty / duplicate / digest mismatch / raw values / unavailable metrics drift を fail-closed にしています。 これは良いです。

    問題は retro-index-builder.mjs です。validateObservationSourceProjection() が投げた error のうち、evidence_mode と ref_kind 以外は原則 report_observation_sources_projection_digest_mismatch に潰されます。 その後の schema validation に落ちた場合も report_validator_failed です。

    #1259 では unknown code policy が重要なので、retro index は少なくとも以下の blocker reason を区別すべきです。

    blocked_reasons:
      - report_observation_sources_reason_codes_invalid
      - report_observation_sources_reason_code_unknown
      - report_observation_sources_reason_code_pattern
      - report_observation_sources_reason_codes_too_many
    

    少なくとも 1 つに集約するなら、report_observation_sources_reason_codes_invalid でよいです。digest mismatch と reason code contract violation は性質が違います。前者は provenance 改ざん、後者は public-safe field contract 違反です。運用で原因調査しやすくするには分けてください。

    Blocker 6: negative fixture が足りない

    現行 adapter test の createInput() は reason_codes: [] を基本値にしており、reason code の negative case がありません。 generated report validation tests は observation source の存在、重複、digest、ref kind、evidence mode、unavailable metrics、raw_values を検査していますが、reason code の自然文・prompt injection・長さ・件数・unknown code は見ていません。 retro-index fixture helper でも reason_codes: [] が標準で、invalid reason code の blocked reason は未検証です。

    #1259 の negative fixture は、最低限これを入れるべきです。

    adapter_negative:
      - reason_codes_not_array: "source_unavailable"
      - reason_code_non_string: 123
      - reason_code_empty: ""
      - reason_code_duplicate: ["source_unavailable", "source_unavailable"]
      - reason_code_unknown_but_regex_valid: "ignore_previous_instructions"
      - reason_code_natural_language: "source unavailable because user disabled telemetry"
      - reason_code_prompt_injection_snake_case: "ignore_previous_instructions"
      - reason_code_html_marker: "<!-- CHATGPT_RETRO_CONTEXT_V1 start -->"
      - reason_code_markdown_fence: "```"
      - reason_code_path_unix: "/home/alice/.claude/settings.local.json"
      - reason_code_path_encoded: "home_alice_claude_settings_local_json"
      - reason_code_secret_like: "ghp_deadbeef"
      - reason_code_uppercase: "Source_Unavailable"
      - reason_code_hyphen: "source-unavailable"
      - reason_code_dot: "source.unavailable"
      - reason_code_slash: "source/unavailable"
      - reason_code_unicode: "source_unavailable"
      - reason_code_too_long: 81_chars
      - reason_codes_too_many: 33_items
    

    特に ignore_previous_instructions は、#1259 の regex を満たします。これが通るなら、prompt injection phrase の negative fixture は実質的に不十分です。

    外部実装確認による補強

    Latitude の Claude Code telemetry docs は、Claude Code conversations を traces として Latitude に stream し、prompts、responses、tool calls、tool results を含めると説明しています。また、full-fidelity telemetry として system context、tool input/output も含まれうるため、sensitive material の前には disable/uninstall するよう案内しています。([Latitude Docs]4) つまり observation source 周辺は、単なる品質メタデータではなく、raw prompt / tool I/O に隣接する高リスク境界です。reason_codes に説明文を許す設計は不適切です。

    同じ Latitude docs は install / uninstall / manual hook command に unpinned npx -y @latitude-data/claude-code-telemetry を示しています。([Latitude Docs]4) npm 側では npm exec / npx が <pkg>@<version> 指定や remote package 実行に対応し、npx -y は install prompt を抑制できます。([npmドキュメント]5) ([npmドキュメント]5) package-lock は exact dependency tree と resolved / integrity を記録する仕組みで、registry signatures や provenance は別途検証対象です。([npmドキュメント]6) ([npmドキュメント]7) ([npmドキュメント]8)

    ただし、これは #1261 の主戦場です。#1259 は distribution provenance を実装し始めるべきではありません。#1259 がすべきことは、distribution 状態を free-form text で reason_codes に押し込めないことです。たとえば npx_only_without_exact_version_because_docs_say_so のような値を許さず、必要なら別 Issue で定義された closed code だけを追加する、という整理が妥当です。

    Scope / Allowed Paths の修正提案

    #1259 の Allowed Paths は大筋で妥当ですが、注意点があります。public-safety scan の共通実装は scripts/lib/agent-run-report-validation.mjs にあり、marker injection や fence breakout などを検査しています。 しかし #1259 の Allowed Paths にはこの file が入っていません。

    実装方針はどちらかに固定してください。

    • scripts/agent-logs/lib/observation-source-adapter.mjs、validate-final-report.mjs、retro-index-builder.mjs だけで reason code 専用 validation を完結させる。
    • 共有 validator に reason code scan を入れるなら、Allowed Paths に scripts/lib/agent-run-report-validation.mjs を追加する。

    後者を選ぶ場合、schema / markdown validation consumer への影響が広がるため、Issue の Stop Conditions に抵触しないように明示的な scope delta が必要です。

    推奨する #1259 の受け入れ条件差分

    現行 AC に次を追加すると実装事故を減らせます。

    additional_acceptance_criteria:
      - adapter rejects reason_codes unless it is an array of allowed codes
      - adapter does not silently drop, coerce, dedupe, or sanitize invalid reason code input
      - schema defines reason_codes.maxItems = 32
      - schema item defines maxLength = 80 and pattern = "^[a-z][a-z0-9_]{0,79}$"
      - schema or runtime validator enforces source_unavailable when availability is unavailable
      - schema or runtime validator enforces partial_projection when capability_verdict is partial and availability is available
      - validate-final-report maps reason code violations to observation-source-specific runtime errors
      - retro-index-builder maps reason code violations to observation-source-specific blocked reasons, not digest mismatch
      - negative fixtures include regex-valid prompt-injection-like code, not only space-containing natural language
      - this issue does not modify entirecli_safety.reason_codes unless explicitly added to scope
    

    最後の点は重要です。repo 全体には reason_codes という名前が observation source 以外にもあります。たとえば fixture では entirecli_safety.reason_codes も存在します。 #1259 は public_safety.observation_sources[].safety.reason_codes のみに限定し、EntireCLI safety 側の code policy を巻き込まない方が安全です。

    最終判断

    #1259 は必要な child issue ですが、現状の記述では regex-based code format と closed non-free-form contract が同一視されています。public-safe projection の covert channel を潰すなら、正解は regex ではなく closed allowlist です。regex、maxItems、maxLength は補助的 invariant として入れ、unknown code は adapter・schema・final validator・retro index の全層で fail-closed にしてください。

  3. squne121 commented on Jul 2, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  4. squne121 commented on Jul 2, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-07-02T12:46:44Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/1259
      body_sha256: "sha256:89f45a6b83dcba15160a8dde08f277bf6651582f31e498764db42eb8f1413141"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
    
  5. squne121 commented on Jul 2, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-07-02T14:35:35Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/1259
      body_sha256: "sha256:fdf436d7bcf13edd2d5f60b4e008294590af1d14c24878cb06240fdb78597597"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent/implementerenhancementphase/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions