diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Analysis_Stage_2_S2_00_v.1.md b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Analysis_Stage_2_S2_00_v.1.md
new file mode 100644
index 00000000..f0175b15
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Analysis_Stage_2_S2_00_v.1.md
@@ -0,0 +1,314 @@
+# Stage_2_S2_00.yml(v6) 분석서
+
+분석 기준일: 2026-10-02(KST). 분석 대상은 이 문서와 같은 폴더의 [Stage_2_S2_00.yml](./Stage_2_S2_00.yml)이며, Agent 이름은 `Stage_2_S2_00_v6`, Agent version은 `6.0.0`, algorithm version은 `s2_00_direct_ingress/6.0.0`이다. 대상 YAML의 SHA-256은 `63b5158eb2bb77524401ca3d15bb21c3740644c14ffa4728564354ff0db5b4a3`이다.
+
+분석의 우선 근거는 현행 YAML의 실제 코드·상수·task procedure이다. 실행 근거는 앞선 workspace 실행에서 다운로드한 v6 결과 5개를 이번 분석에서 다시 읽고 hash를 확인한 자료와 [Stage 2 작업 기록](../../../MEMORY.md)의 v6 항목이다. 기존 분석서나 개정 전략의 목표를 현행 구현으로 간주하지 않는다. S2_10~40의 YAML·자산 schema는 분석 기준에 포함하지 않았다. 이번 분석에서는 YAML 수정이나 workspace 재실행을 수행하지 않았다.
+
+## Executive Summary
+
+S2_00 v6은 Stage 1 사건 결과의 root와 배포 자산의 root를 직접 받아, 동일 workspace의 원본을 읽고 검증한 뒤 후속 작업이 읽을 수 있는 사건 context와 review 원장을 저장하는 단일 비 LLM Agent이다. 기본 사건 root는 `.`, 배포 root는 `Default_Agent`이다. 별도 request 파일이나 `request_id`·`attempt_id`를 만들지 않고, 독립 실행된 Stage 1 결과를 `prev`로 찾는 방식에도 의존하지 않는다.
+
+YAML에 등록된 실행 task는 `Task_S2_00_deterministic_ingress` 하나다. 이 task가 Code Executor의 `run_code`에 inline Python을 전달하고, Python이 Localdocs MCP를 통해 파일을 읽고 쓴다. C00·C05·C10·C15는 코드 안에서 수행하는 기능 구분이며 별도 task·LLM prompt·MCP 호출 단위가 아니다.
+
+주요 결과는 입력 목록, 입력 검증 보고서, review·issue 원장, 사건 context, 마지막 완료 상태의 5개 JSON이다. 기본 저장 위치는 workspace Root 기준 `stage2_runs/from-stage1/s2_00/v6/`이다. 차단 상태에서는 사건 context 대신 기술 진단 파일을 저장한다. 정상·차단 결과 모두 마지막 status를 완료 표지로 사용하며, 기존 완료 결과와 내용이 정확히 같을 때만 재사용한다.
+
+앞선 `10월_1일_구성` workspace 실행은 task `COMPLETED`, `exit_code=0`, `READY_WITH_ISSUES`, `PUBLISHED_STATUS_LAST`로 종료됐다. 다운로드한 결과의 검증 항목은 PASS 19개, FAIL 0개, UNEVALUABLE 2개다. 사건 context에는 증거 30개, 이벤트 71개, BO 57개, fact 57개, LES 47개, 신호 occurrence 475개와 cluster 46개가 들어 있다. review occurrence 1,128개를 보존했고, 이 중 1,126개는 `UNRESOLVED`, 2개는 `CONDITIONAL`이다.
+
+이 성공은 원본을 읽어 검증·구조화하고 결과를 저장하는 workspace 테스트의 성공이다. YAML의 허용 모드는 `WORKSPACE_EXECUTION_TEST`, 정책 분류는 `DEV_FIXTURE_RELEASE`로 유지되어 있다. producer 미확인 WARNING 11건, 원본 seal의 확인 불가, 신호 schema 검사 조건, 동일 출력 root의 동시 writer, 후속 Agent와의 연결은 별도 확인 범위로 남아 있다.
+
+근거: `run_inline_mcp`, `execute_ingress`, `publish_result` 및 다운로드한 `ingress_status.json`·`intake_report.json`·`case_context.json`·`issue_ledger.base.json`.
+
+## 전체 작업 DAG와 책임 경계
+
+### YAML에 등록된 실제 DAG
+
+```mermaid
+flowchart LR
+ IN["IN"] --> T["Task_S2_00_deterministic_ingress
Code Executor run_code"]
+ T --> OUT["OUT"]
+```
+
+Stage는 `S2_00` 하나이며 `prevs: []`, `nexts: []`이다. task procedure의 `IN.nexts`가 단일 task를 가리키고, task는 `IN`을 기다린 뒤 `OUT`으로 연결된다. `OUT`은 이 task를 기다린다. `IN`·`OUT`은 procedure 경계 노드이고 별도 코드 실행 task가 아니다. Stage 1이나 S2_10을 자동 실행시키는 DAG edge는 없다.
+
+### 단일 task 내부의 처리 흐름
+
+```mermaid
+flowchart TD
+ R["사건·배포 root 및 실행 모드 검증"] --> A["backend workspace context로 Localdocs initialize"]
+ A --> H["Stage 1 원본·신호·선택된 배포 자산 hydration"]
+ H --> V["입력 계약·schema·hash·SG01·보존 관계 검증"]
+ V --> N["review occurrence 정규화 및 처리 상태 판정"]
+ N --> B{"BLOCKED인가"}
+ B -- "아니오" --> C["원본 member·명시적 관계·cluster·bundle 구성"]
+ B -- "예" --> D["technical_diagnostic 구성"]
+ C --> O["상태별 결과 5개 및 provenance·출력 계약 검증"]
+ D --> O
+ O --> S["읽은 원격 원본을 재독해 최초 bytes와 비교"]
+ S --> P["기존 출력 충돌 확인"]
+ P --> W["비 status 파일 쓰기·read-back 후 status 기록
또는 동일 완료 결과 재사용"]
+ W --> E["stdout receipt 및 exit code"]
+```
+
+위 흐름의 역할은 다음처럼 나뉜다. C00~C15는 이해를 위한 대응표이며, 실행 순서가 네 개의 독립 task로 분리되는 것은 아니다.
+
+| 기능 구분 | 실제 책임 | 주요 구현 |
+|---|---|---|
+| C00 | 원본 확보, 고정 입력·정책·schema·producer·transaction·hash·gate·보존 관계 확인 | `hydrate_stage1`, `validate_ingress_contracts`, `expand_stage2_signal_all`, `verify_cross_artifact_seals`, `check_conservation` |
+| C05 | 원본의 정확한 배열 위치 판독, JSON pointer·값 digest·원문 projection 보존, review 정규화 | `_source_record_locations`, `_record_locations_for_signal`, `_provenance`, `normalize_review_items` |
+| C10 | 명시적인 원본 참조로 member를 연결하고 claim-neutral cluster 및 후보 의존 관계 구성 | `compile_case_context`, `_tarjan_scc` |
+| C15 | cluster bundle·scheduling wave·결과 파일 구성, 원본 재독, 출력 검증·발행 | `compile_case_context`, `validate_output_files`, `verify_remote_stability`, `publish_result` |
+
+### 시스템별 책임 경계
+
+| 구성 요소 | 담당 책임 | S2_00 코드가 대신 수행하지 않는 사항 |
+|---|---|---|
+| Stage 1 | 사건 원본·증거·BO·LES·fact·signal·review 결과 작성 | S2_00은 Stage 1 자료를 수정하거나 Stage 1 task를 재실행하지 않는다 |
+| Agent backend | YAML task 실행, backend 변수 치환, workspace 실행 context 제공 | S2_00은 사용자 입력 문장에서 사건 root를 추론하지 않는다 |
+| Code Executor | inline Python 실행, 지정 requirements·network·timeout 적용 | YAML 자체에 여러 Python 작업을 병렬 실행하는 task fan-out은 없다 |
+| Localdocs | workspace 파일 읽기·쓰기와 디렉터리 저장 처리 | Python 임시 디렉터리와 원격 출력의 동시성 제어는 다른 문제다 |
+| S2_00 Python | 원본 해석·검증, 구조화, 자체 출력 계약, status-last 발행 | 청구권 확정·증거의 법적 평가·소장 작성·다음 Agent dispatch는 수행하지 않는다 |
+| 후속 소비자 | 저장된 상태·hash·context·review를 읽고 후속 작업에 사용 | 어떤 후속 Agent가 어떻게 소비하는지는 이 YAML에 연결되어 있지 않다 |
+
+근거: YAML의 `Stages`·`task_procedure`, `run_inline_mcp`, `execute_ingress`, `compile_case_context`.
+
+## 실제 실행단위와 prompt 구성
+
+### 실행 설정
+
+| 항목 | 현행 값·동작 |
+|---|---|
+| Agent / Stage / task | `Stage_2_S2_00_v6` / `S2_00` / `Task_S2_00_deterministic_ingress` |
+| 실행 클래스 | `NON-LLM-DETERMINISTIC` |
+| 외부 실행 도구 | `mcp: code-executor`, `tool_name: run_code` |
+| 언어·requirements | `python`, `httpx==0.28.1` |
+| 실행 network·timeout | `agent-network`, 300초 |
+| Code Executor endpoint | `https://code-executor.mcp.eroomai.com/mcp` |
+| Localdocs endpoint | `http://mcp-localdocs:8012/mcp` |
+| 실행 entrypoint | `raise SystemExit(run_inline_mcp())` |
+| 구현 크기 | 분석 시점 YAML 3,064행, inline Python 2,992행 |
+
+### prompt의 실제 형태
+
+이 YAML에는 LLM에게 사건 내용을 전달하는 `system_prompt`·`user_prompt`·모델 선택 설정이 없다. Agent·Stage·task의 `description`은 작업 설명이고, 작업의 실제 명세는 `parameters.code`의 Python 및 그 안의 `SOURCE_POLICY`다. 따라서 자연어 사용자 입력을 바꾼다고 Python의 기본 root나 출력 계약이 바뀌지 않는다. root 변경은 inline 상수 또는 `run_inline_mcp(run_root, deployment_root)`의 인자를 통해 이루어진다.
+
+`SOURCE_POLICY`는 16개 고정 원본과 신호 payload family, 배포 의존 hash pin, adapter 결정, review 상태 매핑, 정책 분류·크기 제한을 inline JSON으로 보유한다. 외부 Stage 2 release 파일을 읽어 이 정책을 대체하는 흐름은 없다. YAML의 metadata는 설명·계약 표시이고, 실제 파일 선택·판정·저장 동작은 코드에 구현되어 있다.
+
+Localdocs 세션은 backend가 치환한 `{{__user_hash__}}`·`{{__workspace_hash__}}`를 `initialize.clientInfo`에 전달해 구성한다. 코드가 새 token이나 workspace 식별값을 발급하는 것은 아니다. 값이 미치환 상태이거나 hash 형식이 맞지 않으면 초기화 전에 실패한다. MCP protocol은 `2025-03-26`을 요구하며 session ID를 유지한 뒤 `notifications/initialized`를 보낸다.
+
+파일 접근은 `read_binary_doc`와 `write_binary_file`로 수행한다. 읽기 응답은 binary envelope의 Base64를 원본 bytes로 복원한다. JSON/SSE 응답과 일반 MCP 오류 외에, Localdocs가 정상 content block으로 돌려주는 `Error: Document not found: ...`도 구별한다. 누락 파일과 도구 실패를 JSON 파싱 오류로 혼동하지 않는 것이 v6의 실제 실행을 가능하게 한 수정 중 하나다.
+
+직접 LLM 호출이 없으므로 S2_00 자체의 사건 추론 토큰은 발생시키지 않는다. 다만 backend가 큰 inline 코드를 어떻게 전달·기록·과금하는지, requirements 준비 비용 및 전체 파이프라인 토큰 절감 효과는 이 YAML 분석만으로 확정할 수 없다.
+
+근거: task `parameters`, `SOURCE_POLICY`, `_InlineLocaldocs`, `_inline_tool_text`, `_context_hash`, `run_inline_mcp`.
+
+## In & Out 설명
+
+### In: 직접 전달되는 두 root와 실행 context
+
+| 입력 | 기본값 | 의미 |
+|---|---|---|
+| `STAGE1_RUN_ROOT` | `.` | 인증된 workspace Root에 있는 Stage 1 사건 결과의 기준 경로 |
+| `STAGE1_DEPLOYMENT_ROOT` | `Default_Agent` | Stage 1 배포 registry·schema·domain config의 기준 경로 |
+| backend user/workspace hash | backend 치환값 | Localdocs에서 접근할 user·workspace context |
+| `EXECUTION_MODE` | `WORKSPACE_EXECUTION_TEST` | 현행 YAML에서 허용하는 유일한 실행 모드 |
+
+root는 검증된 상대 경로로 취급하며 절대 경로·상위 경로 이동·미치환 템플릿을 허용하지 않는다. 사건 root `.`는 workspace 전체를 기준으로 삼기 위한 예외다. 실제 읽기는 고정 입력 경로와 signal manifest가 지정한 경로에 한정된다. 배포 root와 출력 경로의 겹침은 거절한다.
+
+### In: 고정 Stage 1 원본 16개
+
+아래 경로는 모두 사건 root에 상대적이다. 논리 입력 이름은 코드가 원본을 찾는 내부 key이며 새로운 요청 ID가 아니다.
+
+| 논리 입력 | 파일 경로 | 주요 용도·판독 구조 |
+|---|---|---|
+| `evidence_indexed` | `evidence_indexed.json` | `items[]`의 증거; 기존 ID는 `evidence_index` |
+| `evidence_event_candidates` | `evidence_event_candidates.json` | `items[]/event_candidates[]`의 이벤트; 기존 ID는 `candidate_id` |
+| `client_goal` | `client_goal.json` | 목표·제약·당사자 등 사건 운영 context |
+| `domain_screening` | `routing/domain_screening.json` | domain screening 결과 |
+| `domain_activation_manifest` | `routing/domain_activation_manifest.json` | 활성·지원·감시 domain 등 routing 근거 |
+| `b1_evidence_indexed_gate` | `quality_gates/B1_evidence_indexed_gate.json` | 증거 gate·review·진행 허용 여부 |
+| `b2_event_candidates_gate` | `quality_gates/B2_event_candidates_gate.json` | 이벤트 gate 및 최종 item·candidate 개수 |
+| `stage1_part1_soft_gate_handoff` | `quality_gates/stage1_part1_soft_gate_handoff.json` | flat review handoff와 7개 digest guard |
+| `bo` | `BO.json` | 최상위 배열; `BO_ID`와 source provenance |
+| `signal_manifest` | `signals/signal_manifest.json` | 신호 파일 목록·hash·kind·count 및 `stage2: ["ALL"]` |
+| `stage1_part2_review_handoff` | `quality_gates/stage1_part2_review_handoff.json` | flat review handoff |
+| `legal_effect_structures` | `legal_effect_structures.json` | `structure_records[]`, BO 참조 및 역색인 |
+| `stage1_part3_review_handoff` | `quality_gates/stage1_part3_review_handoff.json` | 동명 wrapper 안의 review·`counts.review_items`·finalizer |
+| `fact_ledger_base` | `Fact_Ledger_base.json` | 최상위 배열; `fact_id`·`source_bo_id`·domain effects·calculation requests |
+| `fact_ledger_writer_report` | `stage1_tmp/fact_ledger/fact_ledger_writer_report.json` | fact 개수·domain coverage·calculation readiness·최종 raw hash |
+| `stage1_part4_review_handoff` | `quality_gates/stage1_part4_review_handoff.json` | 동명 wrapper 안의 review·`counts.review_items`·finalizer |
+
+목록의 모든 고정 입력을 요구한다. 누락 입력별 criticality·impact scope를 기록하지만, 현행 `execute_ingress`는 고정 입력 집합이 완전하지 않으면 전역 `BLOCKED`로 처리한다. 일부 cluster만 남겨 정상 context를 발행하는 경로는 없다.
+
+### In: signal manifest로 확장하는 입력
+
+`downstream_read_sets.stage2`는 정확히 `["ALL"]`이어야 한다. `files[i].path`는 `signals/` 접두사가 없는 상대 경로이며, 실제 원본은 `<사건 root>/signals/`에서 읽는다. 파일 순서와 occurrence를 보존하며 중복 파일 행, 미승인 kind, hash·개수 불일치는 검출한다.
+
+| 신호 kind·형태 | 처리 방식 |
+|---|---|
+| `canonical` | 의미 자료로 읽는다. SG01은 `domain_activation_manifest.domain_entries[]`, 일반 정본은 `records[]`를 occurrence로 취급한다 |
+| `domain_signal` | `domain_signal_envelope` 안의 `element_fact_candidates[]`·`opposing_fact_candidates[]`·`defense_candidates[]`를 순서대로 펼친다 |
+| `compatibility_view` | 파일·hash·개수·registry 관계를 검증하지만 의미 occurrence에 다시 합치지 않는다 |
+
+성공한 실행에서는 신호 파일 30개를 읽었다. 정본 13개, domain signal 14개, compatibility view 3개이며, 의미 occurrence는 475개다. `USED`·`UNUSED`·`UNMAPPED` 모두 보존한다. SG01의 routing 원본과 signal 원본은 별도로 읽고, 승인된 17개 필드의 의미 projection을 비교한다.
+
+### Out: 결과 파일과 저장 위치
+
+기본 출력 root는 다음과 같다.
+
+```text
+workspace Root/
+└── stage2_runs/from-stage1/s2_00/v6/
+ ├── ingress/
+ │ ├── stage1_input_manifest.json
+ │ ├── intake_report.json
+ │ └── ingress_status.json
+ ├── review/
+ │ └── issue_ledger.base.json
+ └── context/
+ └── case_context.json
+```
+
+사건 root가 `.` 이외의 상대 폴더이면 `stage2_runs/from-stage1//s2_00/v6/`에 저장한다. `v6`는 고정 구현 개정 폴더이며 실행마다 새로 발급하는 ID가 아니다.
+
+| 결과물 | 포함 내용 |
+|---|---|
+| `ingress/stage1_input_manifest.json` | 고정 입력·동적 신호의 논리 이름, 원본 경로·raw hash·byte length·검증 상태와 읽은 배포 자산 목록 |
+| `ingress/intake_report.json` | 보존·join·digest 검증 결과, 발견한 issues, 입력별 계약 판정 |
+| `review/issue_ledger.base.json` | review의 원문 content·정확한 출처·원본 status/severity·정규화 partition·blocking, 보존 상태, 기술 issues |
+| `context/case_context.json` | 원본 member와 관계, 후보 의존·미해결 참조, cluster·bundle·wave, 목표·routing·신호·review 참조, 객체·당사자·slot 관측 참조, 활성 profile |
+| `ingress/ingress_status.json` | 처리 status·두 root·algorithm/schema·실행 모드·정책, 읽은 원본·배포 파일의 hash, 나머지 4개 결과의 hash·byte length와 완료 표지 |
+
+`BLOCKED`이면 `context/case_context.json`을 발행하지 않고 `ingress/technical_diagnostic.json`으로 대체한다. 이 경우에도 파일 수는 5개다. root·인증·hydration·발행 단계의 예외로 `FAILED`가 되면 이 5개 파일을 반드시 만든다는 보장은 없다.
+
+### 상태·stdout·재실행
+
+| 상태·발행 값 | 실제 의미 |
+|---|---|
+| `READY` | 차단 사유 없이 context를 만들 수 있고 코드가 집계하는 issues·미해결 review·원본 seal 미확인이 없는 상태 |
+| `READY_WITH_ISSUES` | context와 결과를 발행할 수 있으나 WARNING·미해결 review·확인 불가 seal 등이 남음 |
+| `BLOCKED` | 필수 입력·검증·상위 gate/review·context 구성에서 차단; 정상 context 없이 진단 결과를 발행 |
+| `FAILED` | 실행 wrapper가 잡은 runtime·transport·root·인증·발행 등 예외; stdout error로 종료 |
+| `PUBLISHED_STATUS_LAST` | 비 status 파일 4개를 write/read-back한 후 status를 마지막에 기록 |
+| `REUSED_COMPLETED_OUTPUT` | 기존 status와 결과 전체가 새 계산 결과와 byte 단위로 동일함을 확인해 재사용 |
+
+`READY`·`READY_WITH_ISSUES` receipt는 `ok=true`, exit code 0이다. `BLOCKED`는 진단 파일이 저장되어도 `ok=false`, exit code 2이며 `FAILED`도 exit code 2다. receipt에는 status·output root·publication·status hash 등이 들어가고, 별도 request ID는 없다. JSON 결과는 canonical 직렬화 후 newline을 붙여 동일성 비교에 사용한다.
+
+완료 status가 있으면 status bytes와 결과 파일 전체를 비교한다. 다른 입력·버전·내용은 `EXISTING_OUTPUT_CONFLICT`, 결과 손상은 `EXISTING_OUTPUT_CORRUPT`로 거절한다. status 없이 일부 결과가 있으면 `PARTIAL_OUTPUT_CONFLICT`로 거절한다. 동일 사건 root에서 입력을 변경한 재실행은 자동 overwrite나 새 실행 폴더 생성으로 처리되지 않는다.
+
+근거: `DEFAULT_SOURCE_CONTRACTS`, `validate_direct_roots`, `expand_stage2_signal_all`, `execute_ingress`, `validate_output_files`, `publish_result`, `run_inline_mcp`.
+
+## 작업용 고정 자산
+
+### YAML 내부에 고정된 자산
+
+| 자산 | 역할·경계 |
+|---|---|
+| inline Python | 파일 접근·검증·정규화·graph·발행의 실제 구현. 별도 Python 모듈을 배포 폴더에서 import하지 않는다 |
+| `SOURCE_POLICY.stage1_sources` | 16개 고정 입력과 `signal_payload_family`의 정확한 집합·경로·adapter·schema·producer 기대값 |
+| `SOURCE_POLICY.dependency_locks.stage1` | Stage 1 자산 55개에 대한 경로·SHA-256 pin의 허용 목록 |
+| `adapter_decisions` | 원본 envelope, signal ALL, dual SG01, P1~P4 handoff, BO·fact, domain config, review mapping, 제한된 signal writer alias의 계약 |
+| `ROW_KEYS`·review key·관계 kind 상수 | 허용 배열 위치와 review 탐색 범위, 명시적 관계·후보 의존의 판독 범위 |
+| 자체 출력 validator | 상태별 5개 파일, 상위 필드 집합·버전·root·artifact hash 등의 계약 |
+
+현재 `SOURCE_POLICY`는 `DEV_FIXTURE_RELEASE`이며, 배포 lock의 snapshot date는 `2026-08-29`이다. 55개는 전체 Stage 1 runtime release를 증명하는 목록이 아니라 이 구현이 참조할 수 있도록 고정한 범위다. lock에는 `full_stage1_runtime_release_status: STAGE1_NOT_RELEASE_READY`도 남아 있다. 이 표시는 현행 workspace 실행 성공과 서로 다른 수준의 정보다.
+
+### Stage 1 배포 root에서 읽는 자산
+
+| 자산군 | lock 범위 | 실제 선택 방식 |
+|---|---|---|
+| registry·manifest | `runtime_manifest.json`, `domains/_registry_index.json`, `signals/signal_registry.v2.json`의 3개 | registry 2개는 기본으로 읽음. `runtime_manifest.json`은 pin 목록에 있으나 기본 hydration의 필수 읽기 대상은 아님 |
+| domain config | `domains//domain_config.json` 26개 | activation의 `active_domain_ids`에 들어 있는 config만 읽음 |
+| platform·signal schema | schema 및 공통 schema 26개 | 4개 고정 입력 schema ref, signal registry가 선언한 schema·domain envelope, 그들의 외부 `$ref`를 따라 선택 |
+
+26개 config의 domain은 `E-00~E-21`, `EC-00`, `X1~X3`다. 기본으로 schema ref가 있는 고정 입력은 routing activation, signal manifest, LES, fact ledger의 4개다. 나머지 고정 입력은 adapter의 필수 shape·key 확인과 개별 보존 검증을 사용한다.
+
+선택된 모든 배포 자산은 inline pin과 raw hash가 같아야 한다. 필요한 자산이 허용 목록에 없거나 hash가 다르면 hydration에서 실패한다. schema의 외부 참조는 이 로컬 허용 목록 안에서 하나의 자산으로 결속하며 외부 URL에서 schema를 내려받지 않는다.
+
+성공한 실행의 배포 자산은 35개였다. registry 2개, 활성 domain config 14개, schema 19개(공통 schema 2개 포함)이다. 사건 원본 16개와 신호 파일 30개를 합해 읽은 고유 파일은 81개다. 선언된 55개 전체를 매번 읽는 구조가 아니다.
+
+Stage 2의 별도 prompt library·renderer·dispatch schema·S2_10~40 자산은 읽지 않는다. domain config는 `active_profiles`로 보존되지만, config의 element·defense·calculation slot을 법적 판단으로 채워 넣는 실행기는 이 YAML에 없다.
+
+### 크기·보존 경계
+
+원본 한 파일은 32 MiB, hydration의 고유 입력 합계는 256 MiB까지 허용한다. strict JSON 판독은 중복 key·비표준 상수·잘못된 UTF-8 등을 거절하고, 중첩 깊이 96·item 한도 1,000,000을 사용한다. 로컬 snapshot은 경로·symlink·파일 상태 변경을 검사하고 raw SHA-256을 보유한다.
+
+코드 실행별 `TemporaryDirectory`는 hydration을 격리하고 종료 시 정리된다. 임시 폴더의 고유 이름은 출력 root나 요청 ID로 노출하지 않는다. 이 임시 작업 격리는 원격 저장소의 동일 root 동시 발행 문제를 해결하는 장치는 아니다.
+
+근거: `SOURCE_POLICY`, `hydrate_stage1`, `_schema_dependencies`, `load_json_strict`, `open_bounded_snapshot`.
+
+## Upstream/Downstream 설명
+
+### Upstream: Stage 1 결과·배포와의 결속
+
+| Stage 1 영역 | 주로 넘겨받는 자료 | S2_00이 확인하는 연결 |
+|---|---|---|
+| Part 1 | 목표·screening·activation·증거·이벤트·B1/B2 gate·P1 handoff | P1의 7개 raw digest, 증거·이벤트 참조, B2 최종 item·candidate 개수, 진행 허용 여부 |
+| Part 2 | BO·signal manifest 및 payload·P2 handoff | BO↔fact source BO multiset, BO provenance의 event 참조, 신호 파일·occurrence 보존, registry 및 SG01 대응 |
+| Part 3 | LES·P3 handoff | LES의 BO join·중복 ID·역색인·route count, P3 review count·finalizer, 기존 signal transaction 참조 |
+| Part 4 | fact ledger·writer report·P4 handoff | fact ID 순서, v8 확장 필드, writer report의 개수·coverage·readiness·최종 hash, P4 review count·finalizer |
+
+이 연결은 같은 workspace에서 파일을 읽는 자료 의존이다. YAML의 `prevs`가 Stage 1을 기다리거나 Stage 1의 실행 완료를 자동 입증하지 않는다. producer 기대값은 정책에 기록되어 있으며 원본의 제공값과 비교한다. P3·P4는 `created_by`가 최초 작성자이고 `finalized_by`가 최종 writer이므로 wrapper의 producer 판독에서 후자를 우선한다. signal writer alias는 승인된 한 쌍에만 적용한다.
+
+원본에 producer가 없으면 원본에 값을 보충하지 않고 `PRODUCER_ID_UNEVALUABLE` WARNING으로 남긴다. 고정 입력의 `raw_hash_source`는 현행 정책에서 모두 `UNAVAILABLE_DEV`이므로 별도 완료 seal로 전부 입증했다고 해석할 수 없다. 대신 실제 제공된 P1 digest·신호 manifest hash·fact writer hash를 각 기능에서 검증하고, 읽은 bytes 자체도 출력 manifest와 status에 남긴다.
+
+### Downstream: 저장된 파일을 통한 자체 handoff
+
+후속 소비자는 `ingress_status.json`의 상태와 artifact 목록·hash를 확인한 뒤, `context/case_context.json`과 `review/issue_ledger.base.json`을 읽을 수 있다. 이 문장의 소비 순서는 status-last 계약에 따른 권장 해석이며, 실제 후속 Agent가 이 순서로 읽는다는 것은 이 YAML에서 검증하지 않았다.
+
+context의 member는 BO·FACT·LES·EVIDENCE·EVENT다. 각 member는 기존 Stage 1 ID, 원문 projection, 필드별 provenance를 갖는다. 출처는 `logical_artifact_id`·정확한 `json_pointer`·원본 값의 canonical digest로 연결되며, 파일 경로·raw file hash는 입력 manifest에서 찾는다. projection은 schema·producer·metadata 등 일부 상위 key를 제외하고 나머지 값을 담으며, 제외된 값은 원본 pointer로 접근한다. 원본 전체를 output 폴더에 복제하는 방식은 아니다. `active_profiles.sha256`도 파싱된 config의 canonical digest이며, 배포 원본 bytes의 hash는 manifest의 `deployment_sources`와 구분해 읽어야 한다.
+
+cluster는 원본 참조 graph의 연결 성분이다. fact→BO, fact→evidence/event, LES→BO, BO→event, event→evidence 및 명시적인 fact 관계를 사용한다. 단순히 같은 domain이나 같은 당사자라는 이유만으로 새로운 edge를 만들지는 않는다. 다만 같은 증거에 연결된 여러 fact는 한 cluster로 합쳐질 수 있으므로 cluster를 독립 청구권이나 청구별 최종 그룹으로 해석해서는 안 된다.
+
+각 cluster의 `bundle`은 `member_refs`·`signal_indexes`·`review_refs`를 제공한다. 후보 관계 중 허용된 kind만 cluster 의존 edge로 사용하며, SCC를 묶어 scheduling wave를 계산한다. 이는 실행 순서를 설명하는 자료이지 backend task를 실제로 생성·병렬 dispatch하는 기능이 아니다.
+
+기존 원본 ID·transaction ID는 재사용한다. `CL-001` 형태의 cluster 참조와 signal occurrence용 파생 참조는 결과 내부 자료를 연결하는 값이다. 새 request·attempt·run ID를 생성하는 것과 구별된다. 소비자가 기존 S2_10~40 schema를 반드시 요구하는지, 변환이 필요한지 또는 새 소비 계약을 사용할지는 이번 분석의 확인 범위 밖이다.
+
+근거: `validate_ingress_contracts`, `check_conservation`, `bind_signal_occurrences`, `compile_case_context`, `publish_result`.
+
+## 구현과 계약 사이 확인사항 및 잔여 한계
+
+### 확인된 실행 근거와 그 범위
+
+| 확인 항목 | 확인 내용·범위 |
+|---|---|
+| 현행 구현 식별 | YAML hash `63b5158e…b5b4a3`, Agent v6, algorithm 6.0.0을 다시 확인 |
+| 실제 workspace 실행 | 앞선 실행에서 `10월_1일_구성`의 단일 task COMPLETED, exit 0, READY_WITH_ISSUES, PUBLISHED_STATUS_LAST |
+| 실행 시간 | 앞선 UI 전체 시간 5.1초, Code Executor 반환 시간 약 2.402초. 일반 성능 보장은 아님 |
+| 결과 파일 | 당시 내려받은 5개 결과를 재열람하고 status와 나머지 4개 artifact hash·byte length를 이번 분석에서 재검증 |
+| 최종 status hash | `7ea037548ea729275ce4f791d7ae2ada2d381427f1971ea6f30ccc3e4041eed3` |
+| 검증 집계 | PASS 19, FAIL 0, UNEVALUABLE 2. 후자는 LES 선언 총수·event disposition으로, 원본 미제공 값을 추정하지 않음 |
+| context 보존 | member 262개 = BO 57 + FACT 57 + LES 47 + EVIDENCE 30 + EVENT 71; 관계 385개, 미해결 참조 0 |
+| 신호·review | 신호 475개 = USED 240 + UNUSED 27 + UNMAPPED 208; review 1,128개 = UNRESOLVED 1,126 + CONDITIONAL 2 |
+| scheduling | cluster 46개, 후보 의존 관계 0개, wave 1개. scheduling 기능 전체의 다양한 graph 사례를 이 한 실행이 입증하지 않음 |
+| 앞선 회귀 검증 | 수정 세션 기록상 기존·실제 MCP 응답 시험 51건과 캡처 원본·변조 거부 시험 7건 통과. 이번 문서 작성에서 이 시험을 새로 실행한 것은 아님 |
+
+### 계약 문구와 실제 실행을 구별해야 하는 사항
+
+| 확인사항 | 현행 구현·관측 근거 | 의미와 잔여 범위 |
+|---|---|---|
+| 전역 완료 seal | `execute_ingress`는 별도 `completion_seal`·`contract_manifest`를 주입하지 않으며 고정 입력 16개 seal 상태는 모두 UNEVALUABLE | P1·신호·writer의 개별 hash 검증 및 원본 재독과 전체 run의 승인·완료 seal은 다르다 |
+| 신호별 JSON Schema 실행 조건 | registry schema는 읽지만, payload 검사는 manifest 행의 `schema`·`schema_path`가 문자열일 때 실행 | 성공한 manifest의 30개 행에는 이 두 필드가 없어 그 루프의 payload schema 검사는 수행되지 않았다. hash·count·registry·SG01 검증 성공을 모든 신호의 schema 검증 성공으로 확대하면 안 된다 |
+| schema·adapter 검사의 강도 | 고정 입력 4개는 schema ref를 사용하고 나머지는 shape·key와 별도 검증 사용; inline validator는 구현된 JSON Schema keyword 범위를 처리 | 모든 원본에 동일한 full schema 검사가 적용되지 않는다. 범용 JSON Schema 표준 전체 준수나 모든 의미 규칙 검증을 입증한 것은 아니다 |
+| review 보존과 해결 | 같은 내용도 원본 경로·pointer가 다르면 별도 occurrence로 보존; 현재 1,126건 UNRESOLVED | 1,128건은 고유 법률 쟁점 수가 아니다. handoff의 FINALIZED를 review 해결로 바꾸지 않으며 사건 판단·review 해소는 남아 있다 |
+| review unknown·blocking 표현 | 미등록 status/severity는 UNMAPPED로 보존하나 해당 매핑만으로 개별 issue를 추가하지는 않음. explicit blocking은 blocked 배열·boolean·BLOCKED status 및 BLOCKING/CRITICAL/FATAL severity 등 특정 표현으로 판정 | 정책의 unknown-value issue 문구와 실제 issue 생성은 구분해야 한다. `BLOCK` severity나 `blocks_final_drafting`만으로 S2_00 전역 차단을 자동 판정한다고 볼 수 없다 |
+| 신호 UNMAPPED | `signal_id`가 없는 occurrence는 참조 binding이 있어도 UNMAPPED로 분류; 실제 208개 보존 | 파일·개수 보존 성공과 모든 신호의 의미 식별·활용 완료는 다르다. 새 signal ID를 임의 발급해 해결하지 않는다 |
+| graph·slot 범위 | 명시적 참조 graph와 관측된 slot만 보존. profile은 담지만 slot 판정 엔진은 없음 | 공유 증거 연결을 청구권 동일성으로 볼 수 없고, 추론 관계·요건 충족·반박 slot·법적 선후 의존을 새로 확정하지 않는다 |
+| 자산 lock의 범위 | 허용 55개 중 필요한 35개를 읽은 실행; config는 active domain에 한정 | 전체 Stage 1 배포 봉인, 비활성 profile 검증, supporting/monitor config 전체 로딩의 성공을 의미하지 않는다 |
+| 출력 schema | 닫힌 상위 필드·버전·root·상태별 파일 집합·hash를 검사하고 provenance를 재검증 | 모든 중첩 출력 값에 독립적인 외부 JSON Schema 검증을 적용하는 구조는 아니다 |
+| 결과 버전 표시 | Agent·algorithm은 v6/6.0.0, 결과의 `schema_version`은 `stage2_s2_00_direct.v4` | algorithm 개정과 결과 구조 버전은 분리되어 있다. schema_version만 보고 실행 구현을 v4로 오인하면 안 된다 |
+| 전략과 현행 코드 차이 | 전략 v3의 `prev` 연결 및 개정 폴더 없는 출력 예시와 달리 현행은 직접 Localdocs 읽기·고정 `v6` 폴더 사용 | 실제 실행·경로의 판단 기준은 현행 YAML이다. `v6`는 이전 진단 보존을 위한 고정 개정 경로이며 새 실행 ID가 아니다 |
+
+### 실행·발행의 잔여 한계
+
+1. **workspace 테스트 모드만 허용한다.** 실행 성공 이후에도 정책은 DEV이며 생산 모드가 허용된 것이 아니다. Agent metadata의 `IMPLEMENTED_OFFLINE_VERIFIED`는 inline 표시이고, 실제 live 성공은 별도 실행 자료가 입증한다.
+2. **status-last는 논리적 완료 경계다.** 각 파일을 write/read-back한 뒤 status를 쓰지만, 여러 파일을 한 번에 원격 atomic transaction으로 commit하지 않는다. status 기록 뒤 read-back이 실패하면 원격 status가 존재하면서 wrapper는 FAILED를 반환할 수도 있다.
+3. **같은 출력 root의 동시 writer는 미검증이다.** 코드에 원격 lock·CAS·transaction이 없고, 존재 확인과 쓰기 사이의 경합을 임시 디렉터리만으로 막지 않는다.
+4. **재실행 복구는 자동화하지 않는다.** 동일 완료 결과는 재사용하지만 변경 입력·충돌·부분 결과는 거절한다. 정리·복구·별도 출력 위치 결정은 현행 코드의 자동 처리 범위가 아니다.
+5. **원본 재독은 시간 구간 전체의 snapshot을 보장하지 않는다.** 최초 bytes와 발행 직전 재독 bytes를 비교하지만, 재독 이후의 변경이나 서로 다른 파일 사이의 동일 시점 일관성을 원격 transaction으로 보장하지 않는다.
+6. **오류 위치에 따라 진단 파일이 없을 수 있다.** `execute_ingress` 내부에서 처리된 차단은 5개 진단 결과를 만들지만 hydration·인증·일부 입력 계약 함수·출력 검증·발행에서 바깥 wrapper로 전파된 예외는 FAILED stdout으로 끝날 수 있다.
+7. **Downstream 통합은 별도 확인 대상이다.** `nexts: []`이며 task dispatch나 소비자 schema binding이 없다. 결과가 저장됐다는 사실만으로 다음 Stage 2 Agent의 실행 가능성을 확정할 수 없다.
+8. **시간·토큰 경제성은 한 실행의 수치로 일반화하지 않는다.** 직접 파일 재사용과 단일 비 LLM task는 불필요한 전달층을 줄인다. 그러나 이 YAML은 큰 inline 정책·코드, 원본 2회 읽기, 검증·provenance·review projection을 유지하므로 비용·latency 전체를 별도 측정해야 한다.
+
+분석 결론은 현행 v6이 Stage 1 직접 인계 원칙을 구현하여, 관측한 workspace에서 원본 검증·구조화·자체 결과 발행을 성공적으로 수행했다는 것이다. 동시에 저장된 미해결 항목, 조건부로 수행되는 계약 검사, 원격 발행·후속 소비의 경계는 그대로 남아 있다.
+
+주요 코드 위치: `validate_ingress_contracts`(YAML 1019행), `expand_stage2_signal_all`(1347행), `check_conservation`(1701행), `hydrate_stage1`(2574행), `normalize_review_items`(2679행), `compile_case_context`(2738행), `execute_ingress`(2897행), `validate_output_files`(2978행), `publish_result`(3007행), `run_inline_mcp`(3025행). 행 번호는 위 SHA-256으로 식별한 분석 시점 YAML을 기준으로 한다.
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml
index 593248b1..a66951b3 100644
--- a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml
@@ -1,21 +1,24 @@
Agent:
- name: Stage_2_S2_00_v3
- version: 3.0.0
- description: Stage 1 사건·배포 root와 {{prev.###}} 결과물 참조를 직접 받아 C00 검증, C05 원본 보존·정규화, C10 claim-neutral cluster,
- C15 묶음·status-last 발행을 단일 비 LLM task로 수행한다.
+ name: Stage_2_S2_00_v6
+ version: 6.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
metadata:
workflow_id: S2_00
execution_class: NON-LLM-DETERMINISTIC
execution_authority: MCP_CODE_EXECUTOR_INLINE
- implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
- algorithm_version: s2_00_direct_ingress/3.0.0
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED
+ algorithm_version: s2_00_direct_ingress/6.0.0
input_contract:
- stage1_run_root_ref: '{{prev.stage1_run_root_ref}}'
- stage1_deployment_root_ref: '{{prev.stage1_deployment_root_ref}}'
- stage1_result_reference: '{{prev.###}}; ### = Stage 1 결과물 파일'
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
source_contract_authority: parameters.code::SOURCE_POLICY
output_contract:
- root: stage2_runs/from-stage1//s2_00/
+ root: stage2_runs/from-stage1/s2_00/v6/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/v6/
+ revision_scope: Fixed implementation revision directory; no per-run ID; prior v5 diagnostics preserved.
states:
- READY
- READY_WITH_ISSUES
@@ -23,12 +26,14 @@ Agent:
normal_artifact_count: 5
status_last: ingress/ingress_status.json
publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
- execution_admission: DEV_FIXTURE_RELEASE
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
Stages:
- name: S2_00
- description: 두 root 직접 전달과 Stage 1 결과물 참조 사용. 별도 준비 task 없이 한 run_code에서 원본·배포 검증, 의미 보존, cluster/bundle 구성,
- 자체 출력 검증 및 마지막 status 발행.
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
prevs: []
nexts: []
tools:
@@ -41,8 +46,8 @@ Agent:
url: https://code-executor.mcp.eroomai.com/mcp
tasks:
- task_name: Task_S2_00_deterministic_ingress
- description: backend Python 환경이 제공하는 {{prev.###}} 원본 결과물을 재사용한다. 필요한 배포·원본 검증만 수행하고 자체 5개 정상 산출물 또는 차단 진단을
- 발행한다. 기존 DEV release의 실제 사건 발행 금지를 유지한다.
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
mcp: code-executor
tool_name: run_code
parameters:
@@ -54,7 +59,7 @@ Agent:
#!/usr/bin/env python3
"""S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
- Stage 1 results are supplied through the backend's prev file references.
+ Stage 1 original files are read from directly supplied workspace roots.
This module owns its contract; no downstream Agent or output schema is loaded.
MCP transport follows the required Code Executor notebook and SKILL guide.
"""
@@ -79,15 +84,19 @@ Agent:
import unicodedata
from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
- ALGORITHM_VERSION = "s2_00_direct_ingress/3.0.0"
+ ALGORITHM_VERSION = "s2_00_direct_ingress/6.0.0"
LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
MCP_PROTOCOL_VERSION = "2025-03-26"
INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
- INLINE_CLIENT_VERSION = "3.0.0"
+ INLINE_CLIENT_VERSION = "5.0.0"
INLINE_USER_HASH = r"""{{__user_hash__}}"""
INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
- RAW_RUN_ROOT = r"""{{prev.stage1_run_root_ref}}"""
- RAW_DEPLOYMENT_ROOT = r"""{{prev.stage1_deployment_root_ref}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
MAX_FILE_BYTES = 32 * 1024 * 1024
@@ -974,7 +983,7 @@ Agent:
):
nested = document.get(wrapper)
if isinstance(nested, dict):
- for key in ("created_by", "finalized_by"):
+ for key in ("finalized_by", "created_by"):
value = nested.get(key)
if isinstance(value, str) and value:
return value
@@ -1249,7 +1258,7 @@ Agent:
code = "PRODUCER_ID_UNEVALUABLE"
row["reason_codes"].append(code)
row["issue_codes"].append(code)
- issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ issues.append(_issue(code, severity="WARNING", impact_scope="CLUSTER", source_refs=[logical_id]))
elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
code = "PRODUCER_ID_MISMATCH"
row["reason_codes"].append(code)
@@ -1319,15 +1328,7 @@ Agent:
def _records_from_signal_document(document: Any) -> list[Any]:
- if isinstance(document, list):
- return list(document)
- if isinstance(document, dict):
- for key in ("signals", "records", "items"):
- value = document.get(key)
- if isinstance(value, list):
- return list(value)
- return [document]
- return [document]
+ return [v for _,v in _record_locations_for_signal(document)]
def _record_signal_id(record: Any) -> str | None:
@@ -1376,7 +1377,7 @@ Agent:
if isinstance(row, dict) and isinstance(row.get("file"), str)
}
compatibility_files = {
- str(path)
+ str(path) if str(path).startswith("compatibility_views/") else "compatibility_views/"+str(path)
for path in (signal_registry or {}).get("compatibility_views", [])
if isinstance(path, str)
}
@@ -1548,17 +1549,17 @@ Agent:
"bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
"structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
"domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
- "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
- "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_index", "evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"candidate_id", "event_id", "id"})),
}
link_keys = {
- "fact_id": ("fact_id", "fact_ids"),
+ "fact_id": ("fact_id", "fact_ids", "source_fact_ids"),
"source_bo_id": ("source_bo_id", "source_bo_ids"),
"bo_id": ("bo_id", "bo_ids"),
"structure_id": ("structure_id", "structure_ids"),
"domain_id": ("domain_id", "domain_ids"),
- "evidence_id": ("evidence_id", "evidence_ids"),
- "event_id": ("event_id", "event_ids"),
+ "evidence_id": ("evidence_index", "evidence_id", "evidence_ids", "evidence_refs", "source_evidence_indexes"),
+ "event_id": ("candidate_id", "event_id", "event_ids", "source_event_candidate_ids"),
}
for occurrence in signal_all.get("record_occurrences", []):
signal_id = occurrence.get("signal_id")
@@ -1914,16 +1915,16 @@ Agent:
details={"index_present": index_present, "route_count_errors": route_count_errors},
)
evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
- event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ event_rows = [v for _,v in _source_record_locations("evidence_event_candidates", documents.get("evidence_event_candidates"))]
evidence_ids = [
- str(row.get("evidence_id", row.get("id")))
+ str(row.get("evidence_index", row.get("evidence_id", row.get("id"))))
for row in evidence_rows
- if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ if isinstance(row, dict) and (row.get("evidence_index") is not None or row.get("evidence_id") is not None or row.get("id") is not None)
]
event_ids = [
- str(row.get("event_id", row.get("id")))
+ str(row.get("candidate_id", row.get("event_id", row.get("id"))))
for row in event_rows
- if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ if isinstance(row, dict) and (row.get("candidate_id") is not None or row.get("event_id") is not None or row.get("id") is not None)
]
fact_evidence_refs: list[str] = []
fact_event_refs: list[str] = []
@@ -1940,14 +1941,14 @@ Agent:
for row in event_rows:
if not isinstance(row, dict):
continue
- evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ evidence_values = [row["source_evidence_index"]] if row.get("source_evidence_index") is not None else row.get("evidence_refs", row.get("evidence_ids", []))
if isinstance(evidence_values, list):
event_evidence_refs.extend(str(ref) for ref in evidence_values)
evidence_failures = sorted(
set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
)
duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
- evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids and len(evidence_ids)==len(evidence_rows)
add_check(
"EVIDENCE_REFERENCE_CONSERVATION",
evidence_pass,
@@ -1958,9 +1959,13 @@ Agent:
source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
)
+ for bo in bo_rows:
+ if isinstance(bo,dict) and isinstance(bo.get('provenance'),dict):
+ refs=bo['provenance'].get('source_event_candidate_ids',[])
+ if isinstance(refs,list):fact_event_refs.extend(str(v) for v in refs)
event_failures = sorted(set(fact_event_refs) - set(event_ids))
duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
- event_pass = not event_failures and not duplicate_event_ids
+ event_pass = not event_failures and not duplicate_event_ids and len(event_ids)==len(event_rows)
add_check(
"EVENT_REFERENCE_CONSERVATION",
event_pass,
@@ -1971,6 +1976,14 @@ Agent:
source_refs=["evidence_event_candidates", "fact_ledger_base"],
details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
)
+ # B2 seals evidence-item and event-candidate counts, not a disposition enum.
+ b2_counts=documents.get('b2_event_candidates_gate', {})
+ b2_counts=b2_counts.get('conservation') if isinstance(b2_counts,dict) else None
+ event_document=documents.get('evidence_event_candidates')
+ if isinstance(b2_counts,dict):
+ item_count=len(event_document['items']) if isinstance(event_document,dict) and isinstance(event_document.get('items'),list) else len(event_rows)
+ passed=b2_counts.get('final_candidates')==len(event_rows) and b2_counts.get('final_items')==item_count
+ add_check('B2_EVENT_CANDIDATE_COUNT',passed,[item_count,len(event_rows)],[b2_counts.get('final_items'),b2_counts.get('final_candidates')],issue_code='B2_EVENT_CANDIDATE_COUNT_MISMATCH',impact_scope='EVIDENCE',source_refs=['evidence_event_candidates','b2_event_candidates_gate'])
disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
b2_gate = documents.get("b2_event_candidates_gate")
declared_dispositions = None
@@ -2211,28 +2224,39 @@ Agent:
return response
- def _inline_tool_text(result: Mapping[str, Any], tool_name: str) -> str:
- if result.get("isError") is True:
- content = result.get("content")
- rendered = canonical_json_bytes(content).decode("utf-8", errors="replace") if content is not None else ""
- lowered = rendered.lower()
- code = (
- "LOCALDOCS_NOT_FOUND"
- if any(marker in lowered for marker in ("not found", "does not exist", "no such file"))
- else "MCP_TOOL_ERROR"
- )
- raise IngressError(code, f"localdocs {tool_name} returned isError=true")
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str, logical_path: str | None = None) -> str:
+ """Handle both MCP isError and Localdocs' returned plain-text errors."""
content = result.get("content")
if not isinstance(content, list) or len(content) != 1:
raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
block = content[0]
if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
- return block["text"]
+ text = block["text"]
+ stripped = text.strip()
+ # Localdocs returns error strings as normal tool results (isError=false).
+ # Recognize only error prefixes; never inspect JSON/source contents for markers.
+ plain_error = re.match(r"^Error(?:\s+[^:\n]+)?:", stripped, re.IGNORECASE) is not None
+ if result.get("isError") is True or plain_error:
+ missing = re.match(r"^Error:\s*(?:Document|File) not found:\s*(.+)$", stripped, re.IGNORECASE)
+ if missing and logical_path is not None and missing.group(1) != logical_path:
+ raise IngressError("LOCALDOCS_ERROR_PATH_MISMATCH", "missing-file response names another path", details={"tool": tool_name, "path": logical_path})
+ flagged_missing = result.get("isError") is True and stripped.lower() in {"not found", "no such file", "does not exist"}
+ code = "LOCALDOCS_NOT_FOUND" if missing or flagged_missing else "MCP_TOOL_ERROR"
+ details = {"tool": tool_name}
+ if logical_path is not None:
+ details["path"] = logical_path
+ raise IngressError(code, f"localdocs {tool_name} reported a tool failure", details=details)
+ if not stripped:
+ raise IngressError("MCP_TOOL_EMPTY", "localdocs returned an empty text result", details={"tool": tool_name, "path": logical_path})
+ return text
def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
- value = load_json_strict(text)
+ try:
+ value = load_json_strict(text)
+ except IngressError as exc:
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "read_binary_doc returned an invalid JSON envelope", details={"tool": "read_binary_doc", "path": logical_path, "cause": exc.code}) from exc
if isinstance(value, dict) and "results" in value:
results = value.get("results")
if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
@@ -2265,11 +2289,8 @@ Agent:
client: Any | None = None,
timeout_seconds: int = 60,
) -> None:
- self.user_hash = _inline_sha256(user_hash, code="USER_CONTEXT_HASH_INVALID")
- self.workspace_hash = _inline_sha256(
- workspace_hash,
- code="WORKSPACE_CONTEXT_HASH_INVALID",
- )
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
if client is None:
try:
import httpx # type: ignore
@@ -2374,7 +2395,7 @@ Agent:
def read_binary(self, logical_path: str) -> bytes:
path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
result = self.call("read_binary_doc", {"doc_name": path})
- return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc"), path)
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc", path), path)
def read_binary_optional(self, logical_path: str) -> bytes | None:
try:
@@ -2391,7 +2412,7 @@ Agent:
"write_binary_file",
{"path": path, "content_base64": encoded, "overwrite": overwrite},
)
- _inline_tool_text(result, "write_binary_file")
+ _inline_tool_text(result, "write_binary_file", path)
observed = self.read_binary(path)
if observed != payload:
raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
@@ -2401,24 +2422,6 @@ Agent:
SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
- RAW_STAGE1_RESULTS = {
- 'evidence_indexed': r"""{{prev.evidence_indexed.json}}""",
- 'evidence_event_candidates': r"""{{prev.evidence_event_candidates.json}}""",
- 'client_goal': r"""{{prev.client_goal.json}}""",
- 'domain_screening': r"""{{prev.routing/domain_screening.json}}""",
- 'domain_activation_manifest': r"""{{prev.routing/domain_activation_manifest.json}}""",
- 'b1_evidence_indexed_gate': r"""{{prev.quality_gates/B1_evidence_indexed_gate.json}}""",
- 'b2_event_candidates_gate': r"""{{prev.quality_gates/B2_event_candidates_gate.json}}""",
- 'stage1_part1_soft_gate_handoff': r"""{{prev.quality_gates/stage1_part1_soft_gate_handoff.json}}""",
- 'bo': r"""{{prev.BO.json}}""",
- 'signal_manifest': r"""{{prev.signals/signal_manifest.json}}""",
- 'stage1_part2_review_handoff': r"""{{prev.quality_gates/stage1_part2_review_handoff.json}}""",
- 'legal_effect_structures': r"""{{prev.legal_effect_structures.json}}""",
- 'stage1_part3_review_handoff': r"""{{prev.quality_gates/stage1_part3_review_handoff.json}}""",
- 'fact_ledger_base': r"""{{prev.Fact_Ledger_base.json}}""",
- 'fact_ledger_writer_report': r"""{{prev.stage1_tmp/fact_ledger/fact_ledger_writer_report.json}}""",
- 'stage1_part4_review_handoff': r"""{{prev.quality_gates/stage1_part4_review_handoff.json}}""",
- }
STATUS_PATH = "ingress/ingress_status.json"
@@ -2457,68 +2460,75 @@ Agent:
return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+ def _source_record_locations(logical: str, document: Any) -> list[tuple[str, Any]]:
+ rows=_row_locations(document,ROW_KEYS[logical])
+ if logical != 'evidence_event_candidates' or not isinstance(document,dict) or document.get('schema_version')!='evidence_event_candidates.v1':return rows
+ events=[]
+ for pointer,item in rows:
+ if not isinstance(item,dict) or not isinstance(item.get('event_candidates'),list):
+ raise IngressError('EVENT_CANDIDATE_ROWS_SHAPE','evidence item event_candidates must be an array')
+ events.extend((f'{pointer}/event_candidates/{i}',v) for i,v in enumerate(item['event_candidates']))
+ return events
+
def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
if document is None:
return []
return [row for _, row in _row_locations(document, keys)]
- def _json_value(raw: Any) -> Any:
- if not isinstance(raw, (str, bytes)):
- return raw
- if isinstance(raw, str) and re.fullmatch(r"\s*\{\{[^{}]+\}\}\s*", raw):
- raise IngressError("PREV_REFERENCE_UNRESOLVED", "required backend result reference was not resolved")
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
try:
- return load_json_strict(raw)
- except IngressError:
- if isinstance(raw, str) and raw.strip() and not raw.lstrip().startswith(("{", "[", '"')):
- return raw.strip()
- raise
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
result = {
- "stage1_run_root_ref": _inline_relative_path(_json_value(run_root), code="STAGE1_RUN_ROOT_INVALID"),
- "stage1_deployment_root_ref": _inline_relative_path(_json_value(deployment_root), code="STAGE1_DEPLOYMENT_ROOT_INVALID"),
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
}
- output = f"stage2_runs/from-stage1/{result['stage1_run_root_ref']}/s2_00"
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00/v6" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00/v6"
out = PurePosixPath(output)
- for value in result.values():
- original = PurePosixPath(value)
- if out == original or original in out.parents or out in original.parents:
- raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source roots must be disjoint")
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
result["output_root"] = output
return result
- def _previous_source(value: Any, expected_path: str) -> tuple[bytes | None, Any | None]:
- """Return exact bytes when supplied; otherwise retain parsed value for comparison."""
- if isinstance(value, bytes):
- load_json_strict(value)
- return value, None
- parsed = _json_value(value)
- if isinstance(parsed, dict) and "content_base64" in parsed:
- return _inline_binary_envelope(canonical_json_bytes(parsed).decode(), expected_path), None
- if isinstance(parsed, dict) and set(parsed).issubset({"path", "content", "text", "name", "doc_name", "sha256", "byte_length"}):
- supplied_path = parsed.get("path", parsed.get("doc_name", parsed.get("name")))
- if supplied_path is not None and supplied_path != expected_path:
- raise IngressError("PREV_SOURCE_PATH_MISMATCH", "backend result names a different source file")
- content = parsed.get("content", parsed.get("text"))
- if isinstance(content, str):
- raw = content.encode("utf-8")
- load_json_strict(raw)
- return raw, None
- if content is not None:
- return None, content
- if supplied_path is not None:
- return None, None
- if isinstance(parsed, str):
- if parsed != expected_path:
- raise IngressError("PREV_SOURCE_PATH_MISMATCH", "backend result names a different source file")
- return None, None
- if isinstance(parsed, (dict, list)):
- return None, parsed
- raise IngressError("PREV_SOURCE_SHAPE", "backend result must provide source JSON, raw bytes, or its exact path")
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
@@ -2561,8 +2571,8 @@ Agent:
return dependencies
- def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], stage1_results: Mapping[str, Any], policy: Mapping[str, Any]) -> dict[str, Any]:
- """Reuse prev results; fetch only missing raw bytes and needed upstream dependencies."""
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
stage1_root = temp_root / "stage1"
deployment_root = temp_root / "deployment"
stage1_root.mkdir(); deployment_root.mkdir()
@@ -2586,17 +2596,12 @@ Agent:
for contract in DEFAULT_SOURCE_CONTRACTS:
logical = contract["logical_input_id"]
relative = contract["path"]
- logical_path = f"{roots['stage1_run_root_ref']}/{relative}"
- if logical not in stage1_results:
- raise IngressError("PREV_SOURCE_MISSING", "required Stage 1 result reference is missing", logical_input_id=logical)
- exact, parsed = _previous_source(stage1_results[logical], logical_path)
- raw = exact if exact is not None else localdocs.read_binary_optional(logical_path)
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
if raw is None:
- issues.append(_issue("SOURCE_MISSING", source_refs=[logical]))
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
continue
value = load_json_strict(raw)
- if parsed is not None and not _json_equal(value, parsed):
- raise IngressError("PREV_SOURCE_CONTENT_MISMATCH", "backend result differs from the original file", logical_input_id=logical)
remember(logical_path, raw)
_copy_to_temp(stage1_root, relative, raw)
documents[logical] = value
@@ -2613,17 +2618,8 @@ Agent:
if relative.startswith("signals/"):
raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
relative = f"signals/{relative}"
- path = f"{roots['stage1_run_root_ref']}/{relative}"
- # A dynamic file is an existing Stage 1 path selected by its manifest.
- # Provided raw results can be reused; no new result-list request is created.
- provided = stage1_results.get(relative)
- if provided is not None:
- exact, parsed = _previous_source(provided, path)
- else:
- exact, parsed = None, None
- raw = exact if exact is not None else localdocs.read_binary(path)
- if parsed is not None and not _json_equal(load_json_strict(raw), parsed):
- raise IngressError("PREV_SOURCE_CONTENT_MISMATCH", "dynamic result differs from its source")
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
remember(path, raw)
_copy_to_temp(stage1_root, relative, raw)
locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
@@ -2645,7 +2641,7 @@ Agent:
if row is None:
raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
- path = f"{roots['stage1_deployment_root_ref']}/{relative}"
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
raw = localdocs.read_binary(path)
if hashlib.sha256(raw).hexdigest() != expected:
raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
@@ -2705,7 +2701,7 @@ Agent:
found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
if not found or not isinstance(handoff_items, list):
adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
- elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ elif decision.get('count_field_required') is True and (wrapper.get('counts', {}).get('review_items') if isinstance(wrapper.get('counts'), dict) else wrapper.get('review_item_count')) != len(handoff_items):
adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
for logical, document in sorted(review_documents.items()):
stage_match = re.search(r"part([1-4])", logical)
@@ -2743,10 +2739,10 @@ Agent:
"""Normalize original records once and group only explicit source relationships."""
members = []
lookup = {}
- identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_index", "evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("candidate_id", "event_id", "id"))}
raw_rows = {}
for logical, keys in ROW_KEYS.items():
- for pointer, value in _row_locations(documents[logical], keys):
+ for pointer, value in _source_record_locations(logical, documents[logical]):
if not isinstance(value, dict):
raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
kind, id_keys = identities[logical]
@@ -2793,7 +2789,12 @@ Agent:
if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
elif member['kind']=='LES':
for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='BO':
+ prov=row.get('provenance',{})
+ if isinstance(prov,dict) and isinstance(prov.get('source_event_candidate_ids'),list):
+ for i,identifier in enumerate(prov['source_event_candidate_ids']):edge(ref,'EVENT',identifier,'SOURCE_EVENT_ATTACHMENT',f'{pointer}/provenance/source_event_candidate_ids/{i}')
elif member['kind']=='EVENT':
+ if row.get('source_evidence_index') is not None:edge(ref,'EVIDENCE',row['source_evidence_index'],'SAME_EVIDENCE_REF',f'{pointer}/source_evidence_index')
key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
if key:
for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
@@ -2837,7 +2838,7 @@ Agent:
tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
if tokens & bound_ids:selected.append(index)
cluster['signal_indexes']=selected
- cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','source_fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_index','evidence_id','evidence_ids','evidence_refs','source_evidence_indexes','candidate_id','event_id','event_ids','source_event_candidate_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
slot_links=[]; party_object_refs=[]
for logical,document in documents.items():
@@ -2853,15 +2854,25 @@ Agent:
def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
- rows=_records_from_signal_document(document)
if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
- if not isinstance(document,dict):return []
- if rows == [document]:return [('',document)]
- candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
- if len(candidates)!=1:
- raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
- p,v=candidates[0]
- return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+ if not isinstance(document,dict):
+ raise IngressError('SIGNAL_RECORD_SHAPE','signal document must be an array or object')
+ # Match signal_compiler._file_state: SG01 counts domain entries; domain
+ # envelopes count the three candidate arrays, not the envelope itself.
+ if isinstance(document.get('domain_activation_manifest'),dict):
+ inner=document['domain_activation_manifest'];keys=('domain_entries',);prefix='/domain_activation_manifest'
+ elif isinstance(document.get('domain_signal_envelope'),dict):
+ inner=document['domain_signal_envelope'];keys=('element_fact_candidates','opposing_fact_candidates','defense_candidates');prefix='/domain_signal_envelope'
+ else:
+ inner=document;prefix=''
+ keys=tuple(k for k in ('signals','records','items','actio_case_signals','case_liability_signals','bo_legal_effect_routes') if isinstance(inner.get(k),list))
+ if len(keys)>1:raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','multiple signal record arrays')
+ if not keys:return [('',document)]
+ result=[]
+ for key in keys:
+ if not isinstance(inner.get(key),list):raise IngressError('SIGNAL_RECORD_SHAPE','required signal array is missing: '+key)
+ result.extend((f'{prefix}/{key}/{i}',v) for i,v in enumerate(inner[key]))
+ return result
def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
@@ -2883,10 +2894,9 @@ Agent:
return sorted(rows,key=canonical_digest)
- def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, fixture: bool = False) -> dict[str, Any]:
- """Pure C00-C15 core. Fixture evaluation never enables remote publication."""
- if not fixture and policy.get('release_class')=='DEV_FIXTURE_RELEASE':
- raise IngressError('DEV_FIXTURE_REAL_RUN_FORBIDDEN','DEV fixture admission cannot publish a real case')
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
contracts=resolve_stage1_sources(hydrated['stage1_root'])
ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
@@ -2945,7 +2955,7 @@ Agent:
except IngressError as exc:
issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
_validate_provenance(reviews['normalized_occurrences'],documents)
- header={'schema_version':'stage2_s2_00_direct.v3','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
@@ -2969,7 +2979,7 @@ Agent:
status=load_json_strict(files.get(STATUS_PATH,b''))
allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
- common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref'}
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
fields={
'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
@@ -2981,7 +2991,9 @@ Agent:
for path,raw in files.items():
value=load_json_strict(raw)
if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
- if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v3':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
rows=status['artifacts']
@@ -3007,36 +3019,31 @@ Agent:
for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
publication='PUBLISHED_STATUS_LAST'
- return {'ok':status['status']!='BLOCKED','status':status['status'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
- def run_inline_mcp(run_root: Any = RAW_RUN_ROOT, deployment_root: Any = RAW_DEPLOYMENT_ROOT, *, stage1_results: Mapping[str,Any] | None = None, client: Any | None = None) -> int:
- localdocs=None
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
try:
- roots=validate_direct_roots(run_root,deployment_root)
- supplied=RAW_STAGE1_RESULTS if stage1_results is None else stage1_results
- # Validate all required references before making a remote call.
- for row in DEFAULT_SOURCE_CONTRACTS:
- logical=row['logical_input_id']
- if logical not in supplied:raise IngressError('PREV_SOURCE_MISSING','required backend result is absent',logical_input_id=logical)
- _previous_source(supplied[logical],f"{roots['stage1_run_root_ref']}/{row['path']}")
- if SOURCE_POLICY['release_class']=='DEV_FIXTURE_RELEASE':raise IngressError('DEV_FIXTURE_REAL_RUN_FORBIDDEN','DEV fixture admission cannot publish a real case')
- localdocs=_InlineLocaldocs(INLINE_USER_HASH,INLINE_WORKSPACE_HASH,client=client)
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
localdocs.initialize()
- with tempfile.TemporaryDirectory(prefix='liti-s2-00-') as directory:
- hydrated=hydrate_stage1(localdocs,Path(directory),roots,supplied,SOURCE_POLICY)
- result=execute_ingress(hydrated,roots,policy=SOURCE_POLICY)
- verify_remote_stability(localdocs,hydrated['observed'])
- receipt=publish_result(localdocs,roots,result['files'])
- print(json.dumps(receipt,ensure_ascii=False,separators=(',',':')))
- return 0 if receipt['ok'] else 2
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
except Exception as exc:
- error=exc.as_dict() if isinstance(exc,IngressError) else {'code':'S2_00_RUNTIME_ERROR','message':str(exc)}
- # Failure does not assert that a status already written remotely is absent.
- print(json.dumps({'ok':False,'status':'FAILED','error':error},ensure_ascii=False,separators=(',',':')))
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
return 2
finally:
- if localdocs is not None:localdocs.close()
+ if localdocs is not None:
+ localdocs.close()
if __name__ == '__main__':
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.1.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.1.yml
new file mode 100644
index 00000000..593248b1
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.1.yml
@@ -0,0 +1,3057 @@
+Agent:
+ name: Stage_2_S2_00_v3
+ version: 3.0.0
+ description: Stage 1 사건·배포 root와 {{prev.###}} 결과물 참조를 직접 받아 C00 검증, C05 원본 보존·정규화, C10 claim-neutral cluster,
+ C15 묶음·status-last 발행을 단일 비 LLM task로 수행한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
+ algorithm_version: s2_00_direct_ingress/3.0.0
+ input_contract:
+ stage1_run_root_ref: '{{prev.stage1_run_root_ref}}'
+ stage1_deployment_root_ref: '{{prev.stage1_deployment_root_ref}}'
+ stage1_result_reference: '{{prev.###}}; ### = Stage 1 결과물 파일'
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1//s2_00/
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: DEV_FIXTURE_RELEASE
+ standalone_contract: true
+ Stages:
+ - name: S2_00
+ description: 두 root 직접 전달과 Stage 1 결과물 참조 사용. 별도 준비 task 없이 한 run_code에서 원본·배포 검증, 의미 보존, cluster/bundle 구성,
+ 자체 출력 검증 및 마지막 status 발행.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: backend Python 환경이 제공하는 {{prev.###}} 원본 결과물을 재사용한다. 필요한 배포·원본 검증만 수행하고 자체 5개 정상 산출물 또는 차단 진단을
+ 발행한다. 기존 DEV release의 실제 사건 발행 금지를 유지한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 results are supplied through the backend's prev file references.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/3.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "3.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ RAW_RUN_ROOT = r"""{{prev.stage1_run_root_ref}}"""
+ RAW_DEPLOYMENT_ROOT = r"""{{prev.stage1_deployment_root_ref}}"""
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("created_by", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ if isinstance(document, list):
+ return list(document)
+ if isinstance(document, dict):
+ for key in ("signals", "records", "items"):
+ value = document.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return [document]
+ return [document]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_id", "evidence_ids"),
+ "event_id": ("event_id", "event_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ evidence_ids = [
+ str(row.get("evidence_id", row.get("id")))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("event_id", row.get("id")))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str) -> str:
+ if result.get("isError") is True:
+ content = result.get("content")
+ rendered = canonical_json_bytes(content).decode("utf-8", errors="replace") if content is not None else ""
+ lowered = rendered.lower()
+ code = (
+ "LOCALDOCS_NOT_FOUND"
+ if any(marker in lowered for marker in ("not found", "does not exist", "no such file"))
+ else "MCP_TOOL_ERROR"
+ )
+ raise IngressError(code, f"localdocs {tool_name} returned isError=true")
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ return block["text"]
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ value = load_json_strict(text)
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _inline_sha256(user_hash, code="USER_CONTEXT_HASH_INVALID")
+ self.workspace_hash = _inline_sha256(
+ workspace_hash,
+ code="WORKSPACE_CONTEXT_HASH_INVALID",
+ )
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc"), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file")
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+ RAW_STAGE1_RESULTS = {
+ 'evidence_indexed': r"""{{prev.evidence_indexed.json}}""",
+ 'evidence_event_candidates': r"""{{prev.evidence_event_candidates.json}}""",
+ 'client_goal': r"""{{prev.client_goal.json}}""",
+ 'domain_screening': r"""{{prev.routing/domain_screening.json}}""",
+ 'domain_activation_manifest': r"""{{prev.routing/domain_activation_manifest.json}}""",
+ 'b1_evidence_indexed_gate': r"""{{prev.quality_gates/B1_evidence_indexed_gate.json}}""",
+ 'b2_event_candidates_gate': r"""{{prev.quality_gates/B2_event_candidates_gate.json}}""",
+ 'stage1_part1_soft_gate_handoff': r"""{{prev.quality_gates/stage1_part1_soft_gate_handoff.json}}""",
+ 'bo': r"""{{prev.BO.json}}""",
+ 'signal_manifest': r"""{{prev.signals/signal_manifest.json}}""",
+ 'stage1_part2_review_handoff': r"""{{prev.quality_gates/stage1_part2_review_handoff.json}}""",
+ 'legal_effect_structures': r"""{{prev.legal_effect_structures.json}}""",
+ 'stage1_part3_review_handoff': r"""{{prev.quality_gates/stage1_part3_review_handoff.json}}""",
+ 'fact_ledger_base': r"""{{prev.Fact_Ledger_base.json}}""",
+ 'fact_ledger_writer_report': r"""{{prev.stage1_tmp/fact_ledger/fact_ledger_writer_report.json}}""",
+ 'stage1_part4_review_handoff': r"""{{prev.quality_gates/stage1_part4_review_handoff.json}}""",
+ }
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+ def _json_value(raw: Any) -> Any:
+ if not isinstance(raw, (str, bytes)):
+ return raw
+ if isinstance(raw, str) and re.fullmatch(r"\s*\{\{[^{}]+\}\}\s*", raw):
+ raise IngressError("PREV_REFERENCE_UNRESOLVED", "required backend result reference was not resolved")
+ try:
+ return load_json_strict(raw)
+ except IngressError:
+ if isinstance(raw, str) and raw.strip() and not raw.lstrip().startswith(("{", "[", '"')):
+ return raw.strip()
+ raise
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _inline_relative_path(_json_value(run_root), code="STAGE1_RUN_ROOT_INVALID"),
+ "stage1_deployment_root_ref": _inline_relative_path(_json_value(deployment_root), code="STAGE1_DEPLOYMENT_ROOT_INVALID"),
+ }
+ output = f"stage2_runs/from-stage1/{result['stage1_run_root_ref']}/s2_00"
+ out = PurePosixPath(output)
+ for value in result.values():
+ original = PurePosixPath(value)
+ if out == original or original in out.parents or out in original.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source roots must be disjoint")
+ result["output_root"] = output
+ return result
+
+
+ def _previous_source(value: Any, expected_path: str) -> tuple[bytes | None, Any | None]:
+ """Return exact bytes when supplied; otherwise retain parsed value for comparison."""
+ if isinstance(value, bytes):
+ load_json_strict(value)
+ return value, None
+ parsed = _json_value(value)
+ if isinstance(parsed, dict) and "content_base64" in parsed:
+ return _inline_binary_envelope(canonical_json_bytes(parsed).decode(), expected_path), None
+ if isinstance(parsed, dict) and set(parsed).issubset({"path", "content", "text", "name", "doc_name", "sha256", "byte_length"}):
+ supplied_path = parsed.get("path", parsed.get("doc_name", parsed.get("name")))
+ if supplied_path is not None and supplied_path != expected_path:
+ raise IngressError("PREV_SOURCE_PATH_MISMATCH", "backend result names a different source file")
+ content = parsed.get("content", parsed.get("text"))
+ if isinstance(content, str):
+ raw = content.encode("utf-8")
+ load_json_strict(raw)
+ return raw, None
+ if content is not None:
+ return None, content
+ if supplied_path is not None:
+ return None, None
+ if isinstance(parsed, str):
+ if parsed != expected_path:
+ raise IngressError("PREV_SOURCE_PATH_MISMATCH", "backend result names a different source file")
+ return None, None
+ if isinstance(parsed, (dict, list)):
+ return None, parsed
+ raise IngressError("PREV_SOURCE_SHAPE", "backend result must provide source JSON, raw bytes, or its exact path")
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], stage1_results: Mapping[str, Any], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Reuse prev results; fetch only missing raw bytes and needed upstream dependencies."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = f"{roots['stage1_run_root_ref']}/{relative}"
+ if logical not in stage1_results:
+ raise IngressError("PREV_SOURCE_MISSING", "required Stage 1 result reference is missing", logical_input_id=logical)
+ exact, parsed = _previous_source(stage1_results[logical], logical_path)
+ raw = exact if exact is not None else localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical]))
+ continue
+ value = load_json_strict(raw)
+ if parsed is not None and not _json_equal(value, parsed):
+ raise IngressError("PREV_SOURCE_CONTENT_MISMATCH", "backend result differs from the original file", logical_input_id=logical)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = f"{roots['stage1_run_root_ref']}/{relative}"
+ # A dynamic file is an existing Stage 1 path selected by its manifest.
+ # Provided raw results can be reused; no new result-list request is created.
+ provided = stage1_results.get(relative)
+ if provided is not None:
+ exact, parsed = _previous_source(provided, path)
+ else:
+ exact, parsed = None, None
+ raw = exact if exact is not None else localdocs.read_binary(path)
+ if parsed is not None and not _json_equal(load_json_strict(raw), parsed):
+ raise IngressError("PREV_SOURCE_CONTENT_MISMATCH", "dynamic result differs from its source")
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = f"{roots['stage1_deployment_root_ref']}/{relative}"
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _row_locations(documents[logical], keys):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='EVENT':
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ rows=_records_from_signal_document(document)
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):return []
+ if rows == [document]:return [('',document)]
+ candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
+ if len(candidates)!=1:
+ raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
+ p,v=candidates[0]
+ return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, fixture: bool = False) -> dict[str, Any]:
+ """Pure C00-C15 core. Fixture evaluation never enables remote publication."""
+ if not fixture and policy.get('release_class')=='DEV_FIXTURE_RELEASE':
+ raise IngressError('DEV_FIXTURE_REAL_RUN_FORBIDDEN','DEV fixture admission cannot publish a real case')
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'schema_version':'stage2_s2_00_direct.v3','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v3':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = RAW_RUN_ROOT, deployment_root: Any = RAW_DEPLOYMENT_ROOT, *, stage1_results: Mapping[str,Any] | None = None, client: Any | None = None) -> int:
+ localdocs=None
+ try:
+ roots=validate_direct_roots(run_root,deployment_root)
+ supplied=RAW_STAGE1_RESULTS if stage1_results is None else stage1_results
+ # Validate all required references before making a remote call.
+ for row in DEFAULT_SOURCE_CONTRACTS:
+ logical=row['logical_input_id']
+ if logical not in supplied:raise IngressError('PREV_SOURCE_MISSING','required backend result is absent',logical_input_id=logical)
+ _previous_source(supplied[logical],f"{roots['stage1_run_root_ref']}/{row['path']}")
+ if SOURCE_POLICY['release_class']=='DEV_FIXTURE_RELEASE':raise IngressError('DEV_FIXTURE_REAL_RUN_FORBIDDEN','DEV fixture admission cannot publish a real case')
+ localdocs=_InlineLocaldocs(INLINE_USER_HASH,INLINE_WORKSPACE_HASH,client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix='liti-s2-00-') as directory:
+ hydrated=hydrate_stage1(localdocs,Path(directory),roots,supplied,SOURCE_POLICY)
+ result=execute_ingress(hydrated,roots,policy=SOURCE_POLICY)
+ verify_remote_stability(localdocs,hydrated['observed'])
+ receipt=publish_result(localdocs,roots,result['files'])
+ print(json.dumps(receipt,ensure_ascii=False,separators=(',',':')))
+ return 0 if receipt['ok'] else 2
+ except Exception as exc:
+ error=exc.as_dict() if isinstance(exc,IngressError) else {'code':'S2_00_RUNTIME_ERROR','message':str(exc)}
+ # Failure does not assert that a status already written remotely is absent.
+ print(json.dumps({'ok':False,'status':'FAILED','error':error},ensure_ascii=False,separators=(',',':')))
+ return 2
+ finally:
+ if localdocs is not None:localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.2.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.2.yml
new file mode 100644
index 00000000..1c61eaf2
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.2.yml
@@ -0,0 +1,3023 @@
+Agent:
+ name: Stage_2_S2_00_v4
+ version: 4.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
+ algorithm_version: s2_00_direct_ingress/4.0.0
+ input_contract:
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1/s2_00/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
+ standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
+ Stages:
+ - name: S2_00
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 original files are read from directly supplied workspace roots.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/4.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "4.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("created_by", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ if isinstance(document, list):
+ return list(document)
+ if isinstance(document, dict):
+ for key in ("signals", "records", "items"):
+ value = document.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return [document]
+ return [document]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_id", "evidence_ids"),
+ "event_id": ("event_id", "event_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ evidence_ids = [
+ str(row.get("evidence_id", row.get("id")))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("event_id", row.get("id")))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str) -> str:
+ if result.get("isError") is True:
+ content = result.get("content")
+ rendered = canonical_json_bytes(content).decode("utf-8", errors="replace") if content is not None else ""
+ lowered = rendered.lower()
+ code = (
+ "LOCALDOCS_NOT_FOUND"
+ if any(marker in lowered for marker in ("not found", "does not exist", "no such file"))
+ else "MCP_TOOL_ERROR"
+ )
+ raise IngressError(code, f"localdocs {tool_name} returned isError=true")
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ return block["text"]
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ value = load_json_strict(text)
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc"), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file")
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
+ try:
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
+ }
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00"
+ out = PurePosixPath(output)
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
+ result["output_root"] = output
+ return result
+
+
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
+ continue
+ value = load_json_strict(raw)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _row_locations(documents[logical], keys):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='EVENT':
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ rows=_records_from_signal_document(document)
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):return []
+ if rows == [document]:return [('',document)]
+ candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
+ if len(candidates)!=1:
+ raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
+ p,v=candidates[0]
+ return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
+ try:
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
+ except Exception as exc:
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
+ return 2
+ finally:
+ if localdocs is not None:
+ localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.3.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.3.yml
new file mode 100644
index 00000000..8943f1f8
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.3.yml
@@ -0,0 +1,3034 @@
+Agent:
+ name: Stage_2_S2_00_v5
+ version: 5.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
+ algorithm_version: s2_00_direct_ingress/5.0.0
+ input_contract:
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1/s2_00/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
+ standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
+ Stages:
+ - name: S2_00
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 original files are read from directly supplied workspace roots.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/5.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "5.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("created_by", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ if isinstance(document, list):
+ return list(document)
+ if isinstance(document, dict):
+ for key in ("signals", "records", "items"):
+ value = document.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return [document]
+ return [document]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_id", "evidence_ids"),
+ "event_id": ("event_id", "event_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ evidence_ids = [
+ str(row.get("evidence_id", row.get("id")))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("event_id", row.get("id")))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str, logical_path: str | None = None) -> str:
+ """Handle both MCP isError and Localdocs' returned plain-text errors."""
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ text = block["text"]
+ stripped = text.strip()
+ # Localdocs returns error strings as normal tool results (isError=false).
+ # Recognize only error prefixes; never inspect JSON/source contents for markers.
+ plain_error = re.match(r"^Error(?:\s+[^:\n]+)?:", stripped, re.IGNORECASE) is not None
+ if result.get("isError") is True or plain_error:
+ missing = re.match(r"^Error:\s*(?:Document|File) not found:\s*(.+)$", stripped, re.IGNORECASE)
+ if missing and logical_path is not None and missing.group(1) != logical_path:
+ raise IngressError("LOCALDOCS_ERROR_PATH_MISMATCH", "missing-file response names another path", details={"tool": tool_name, "path": logical_path})
+ flagged_missing = result.get("isError") is True and stripped.lower() in {"not found", "no such file", "does not exist"}
+ code = "LOCALDOCS_NOT_FOUND" if missing or flagged_missing else "MCP_TOOL_ERROR"
+ details = {"tool": tool_name}
+ if logical_path is not None:
+ details["path"] = logical_path
+ raise IngressError(code, f"localdocs {tool_name} reported a tool failure", details=details)
+ if not stripped:
+ raise IngressError("MCP_TOOL_EMPTY", "localdocs returned an empty text result", details={"tool": tool_name, "path": logical_path})
+ return text
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ try:
+ value = load_json_strict(text)
+ except IngressError as exc:
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "read_binary_doc returned an invalid JSON envelope", details={"tool": "read_binary_doc", "path": logical_path, "cause": exc.code}) from exc
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc", path), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file", path)
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
+ try:
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
+ }
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00"
+ out = PurePosixPath(output)
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
+ result["output_root"] = output
+ return result
+
+
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
+ continue
+ value = load_json_strict(raw)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _row_locations(documents[logical], keys):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='EVENT':
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ rows=_records_from_signal_document(document)
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):return []
+ if rows == [document]:return [('',document)]
+ candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
+ if len(candidates)!=1:
+ raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
+ p,v=candidates[0]
+ return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
+ try:
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
+ except Exception as exc:
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
+ return 2
+ finally:
+ if localdocs is not None:
+ localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md
index 4acdee55..73004a78 100644
--- a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md
@@ -16,6 +16,29 @@
- 하위 에이전트(subagents)를 사용하여 핵심 테마와 교훈을 식별하고 MEMORY.md에 섹션으로 저장하라.
- 향후 세션 시작 시 MEMORY.md의 이전 섹션을 참조하라.
+## 2026-10-02 — S2_00 v6 현행 코드·입출력·책임 경계 분석서
+
+한 줄 요약: `agent_scripts/Analysis_Stage_2_S2_00_v.1.md`에 요청한 7개 목차로 현행 v6을 분석했다. 작업 DAG·자산·상태·검증 범위는 전략의 선언보다 실제 호출 경로를 기준으로 판독해야 한다.
+
+- 단일 task 안의 C00~C15, 16개 고정 입력·manifest 신호, 배포 pin 55개와 선택 로딩, 자체 결과 5개 및 status-last·동일 완료본 재사용을 정리했다. 당시 다운로드한 실행 결과의 hash를 다시 대조했고 YAML·복제본의 hash는 보존했다.
+- 성공한 manifest에는 `schema/schema_path`가 없어 신호별 payload schema 루프가 실행되지 않는 점, 고정 입력 16개 seal의 UNEVALUABLE, 미해결 review·UNMAPPED 신호 보존, config·slot·cluster의 의미 범위, 동시 writer·복구·후속 소비 계약의 미검증을 명시했다. 문서 7개 상위 목차·코드 행 번호·로컬 링크·fence를 확인했으며 YAML 변경이나 workspace 재실행은 하지 않았다.
+
+## 2026-10-02 — S2_00 v6 실제 MCP·Stage 1 원본 판독 오류 수정 및 workspace 실행 성공
+
+한 줄 요약: 자체 fixture가 실제 Localdocs 오류 문자열과 Stage 1 v.8 배열·count 구조를 반영하지 않아 파싱 실패·오차단이 발생했다. 실제 서버 함수와 다운로드한 원본으로 재현·수정하고 workspace에서 결과 파일까지 대조해야 실행 성공을 확인할 수 있다.
+
+- Localdocs `read_binary_doc`의 `isError=false`인 `Error: Document not found: ...`를 JSON으로 파싱하던 오류를 수정했다. 누락은 해당 경로의 `LOCALDOCS_NOT_FOUND`로 구분하고 일반 도구 오류·잘못된 binary envelope는 도구명·경로를 포함해 보고한다. 이후 증거 `evidence_index`, `/items/*/event_candidates/*`·`candidate_id`, SG01 `domain_entries`, domain signal 3개 candidate 배열, compatibility view prefix, P3·P4 `counts.review_items`·`finalized_by`를 실제 Stage 1 writer 계약에 맞췄다. BO→event→evidence 연결과 B2 선언 개수 검증을 추가했으며 hash·누락·중복·review 차단 검증은 유지했다.
+- 기존·실제 서버 응답 시험 51건 및 캡처한 Stage 1 원본·변조 거부 시험 7건, YAML·Python 3.11/3.12 문법 검증을 통과했다. `10월_1일_구성`에 현행 YAML을 `Stage_2_S2_00_v6`로 등록·실행하여 task `COMPLETED`, `exit_code=0`, `READY_WITH_ISSUES`, `PUBLISHED_STATUS_LAST`를 확인했다(전체 5.1초, code executor 2.402초). 고정 출력 `stage2_runs/from-stage1/s2_00/v6/`의 5개 파일을 다운로드했고 status SHA-256 `7ea037548ea729275ce4f791d7ae2ada2d381427f1971ea6f30ccc3e4041eed3`, 나머지 4개 artifact hash·byte length, 읽은 원본·배포 파일 81개 hash를 모두 대조했다. 검증은 PASS 19·FAIL 0·UNEVALUABLE 2이며 미제공 LES 선언 총수·event disposition은 추정하지 않았다. producer 정보가 원본에 없는 11건은 WARNING으로 남기고 기존 review 1,128건을 그대로 보존한다. context는 증거 30·event 71·BO 57·fact 57·LES 47, 신호 475, cluster 46, 미해결 참조 0이다. 실행 성공은 이 workspace 테스트에 한정한다.
+- v4 원본은 `agent_scripts/Stage_2_S2_00_10_02_v.2.yml`, 중간 v5는 `agent_scripts/Stage_2_S2_00_10_02_v.3.yml`로 보존했다. 현행 `agent_scripts/Stage_2_S2_00.yml`은 overwrite했고 복제본은 본 폴더 `Stage_2_S2_00_v.6.yml`이다. v5 원격 진단을 보존하기 위해 출력만 고정 개정 폴더 `v6`로 구분했으며 별도 request/attempt ID를 만들지 않았다. Stage 1 원본·배포 및 S2_10~40은 수정하지 않았다.
+
+## 2026-10-02 — S2_00 YAML v4 실제 입력 연결 개정
+
+한 줄 요약: v3의 미치환 `prev` root·파일 참조를 제거하고, `run_inline_mcp`에 사건·배포 root를 직접 전달하여 인증된 localdocs에서 Stage 1 원본을 읽는 v4로 개정했다. 선행 task 없는 standalone 실행에 `prev` 결과가 자동 연결된다고 가정하지 않는 것이 핵심이다.
+
+- Stage 1 v.8의 상대 저장 경로에 맞춰 기본 사건 root는 `.`(인증된 workspace), 배포 root는 `Default_Agent`로 명시한다. 다른 위치는 inline 상수 또는 함수 인자로 직접 지정한다. backend 치환은 문서화된 `__user_hash__`·`__workspace_hash__`만 사용하며, root·인증 미치환 오류는 해당 입력 이름을 표시한다. request/attempt ID·준비 task·control 파일을 추가하지 않았다.
+- DEV 정책은 그대로 기록하되 `WORKSPACE_EXECUTION_TEST`만 허용하여 실행 테스트 산출물에 모드·정책 분류를 남긴다. 생산 모드는 계속 차단하며 원본·배포 pin·schema·signal/review 보존·두 read-pass·status-last·충돌 시 덮어쓰기 금지 검증을 유지한다. 기본 인자 그대로의 JSON/SSE 모의 실행을 포함한 44건과 YAML/DAG·Python 3.11/3.12 문법을 통과했다. 실제 backend 재등록·원격 실행·생산 배포 승인은 수행하지 않았다.
+- 직전 v3는 `Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00_10_02_v.1.yml`로 byte-identical 보존하고 현행 YAML을 overwrite했다. 개정 복제본은 본 폴더 `Stage_2_S2_00_v.4.yml`이다. 이번 변경은 지정된 YAML 3개·MEMORY에 한정하며 S2_10~40·전략서·SKILL·notebook·release/mirror는 보존한다.
+
## 2026-10-02 — S2_00 YAML v3 직접 인계 구현
한 줄 요약: 전략 v3·지정 SKILL·Code Executor notebook에 따라 S2_00을 단일 deterministic ingress로 개정했다. Stage 1 사건·배포 root와 `{{prev.###}}` 결과물을 직접 재사용하며 별도 request/attempt/run ID와 준비 task를 제거한다.
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.4.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.4.yml
new file mode 100644
index 00000000..1c61eaf2
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.4.yml
@@ -0,0 +1,3023 @@
+Agent:
+ name: Stage_2_S2_00_v4
+ version: 4.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
+ algorithm_version: s2_00_direct_ingress/4.0.0
+ input_contract:
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1/s2_00/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
+ standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
+ Stages:
+ - name: S2_00
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 original files are read from directly supplied workspace roots.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/4.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "4.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("created_by", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ if isinstance(document, list):
+ return list(document)
+ if isinstance(document, dict):
+ for key in ("signals", "records", "items"):
+ value = document.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return [document]
+ return [document]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_id", "evidence_ids"),
+ "event_id": ("event_id", "event_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ evidence_ids = [
+ str(row.get("evidence_id", row.get("id")))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("event_id", row.get("id")))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str) -> str:
+ if result.get("isError") is True:
+ content = result.get("content")
+ rendered = canonical_json_bytes(content).decode("utf-8", errors="replace") if content is not None else ""
+ lowered = rendered.lower()
+ code = (
+ "LOCALDOCS_NOT_FOUND"
+ if any(marker in lowered for marker in ("not found", "does not exist", "no such file"))
+ else "MCP_TOOL_ERROR"
+ )
+ raise IngressError(code, f"localdocs {tool_name} returned isError=true")
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ return block["text"]
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ value = load_json_strict(text)
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc"), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file")
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
+ try:
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
+ }
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00"
+ out = PurePosixPath(output)
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
+ result["output_root"] = output
+ return result
+
+
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
+ continue
+ value = load_json_strict(raw)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _row_locations(documents[logical], keys):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='EVENT':
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ rows=_records_from_signal_document(document)
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):return []
+ if rows == [document]:return [('',document)]
+ candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
+ if len(candidates)!=1:
+ raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
+ p,v=candidates[0]
+ return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
+ try:
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
+ except Exception as exc:
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
+ return 2
+ finally:
+ if localdocs is not None:
+ localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.5.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.5.yml
new file mode 100644
index 00000000..8943f1f8
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.5.yml
@@ -0,0 +1,3034 @@
+Agent:
+ name: Stage_2_S2_00_v5
+ version: 5.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED_LIVE_NOT_RUN
+ algorithm_version: s2_00_direct_ingress/5.0.0
+ input_contract:
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1/s2_00/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
+ standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
+ Stages:
+ - name: S2_00
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 original files are read from directly supplied workspace roots.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/5.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "5.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("created_by", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ if isinstance(document, list):
+ return list(document)
+ if isinstance(document, dict):
+ for key in ("signals", "records", "items"):
+ value = document.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return [document]
+ return [document]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_id", "evidence_ids"),
+ "event_id": ("event_id", "event_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = _array_rows(documents.get("evidence_event_candidates"), ("events", "event_candidates", "rows", "items"))
+ evidence_ids = [
+ str(row.get("evidence_id", row.get("id")))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("event_id", row.get("id")))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str, logical_path: str | None = None) -> str:
+ """Handle both MCP isError and Localdocs' returned plain-text errors."""
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ text = block["text"]
+ stripped = text.strip()
+ # Localdocs returns error strings as normal tool results (isError=false).
+ # Recognize only error prefixes; never inspect JSON/source contents for markers.
+ plain_error = re.match(r"^Error(?:\s+[^:\n]+)?:", stripped, re.IGNORECASE) is not None
+ if result.get("isError") is True or plain_error:
+ missing = re.match(r"^Error:\s*(?:Document|File) not found:\s*(.+)$", stripped, re.IGNORECASE)
+ if missing and logical_path is not None and missing.group(1) != logical_path:
+ raise IngressError("LOCALDOCS_ERROR_PATH_MISMATCH", "missing-file response names another path", details={"tool": tool_name, "path": logical_path})
+ flagged_missing = result.get("isError") is True and stripped.lower() in {"not found", "no such file", "does not exist"}
+ code = "LOCALDOCS_NOT_FOUND" if missing or flagged_missing else "MCP_TOOL_ERROR"
+ details = {"tool": tool_name}
+ if logical_path is not None:
+ details["path"] = logical_path
+ raise IngressError(code, f"localdocs {tool_name} reported a tool failure", details=details)
+ if not stripped:
+ raise IngressError("MCP_TOOL_EMPTY", "localdocs returned an empty text result", details={"tool": tool_name, "path": logical_path})
+ return text
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ try:
+ value = load_json_strict(text)
+ except IngressError as exc:
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "read_binary_doc returned an invalid JSON envelope", details={"tool": "read_binary_doc", "path": logical_path, "cause": exc.code}) from exc
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc", path), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file", path)
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
+ try:
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
+ }
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00"
+ out = PurePosixPath(output)
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
+ result["output_root"] = output
+ return result
+
+
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
+ continue
+ value = load_json_strict(raw)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and wrapper.get('review_item_count') != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _row_locations(documents[logical], keys):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='EVENT':
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_id','evidence_ids','event_id','event_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ rows=_records_from_signal_document(document)
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):return []
+ if rows == [document]:return [('',document)]
+ candidates=[(p,v) for p,v in _walk_values(document) if isinstance(v,list) and v==rows]
+ if len(candidates)!=1:
+ raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','signal record array cannot be located uniquely')
+ p,v=candidates[0]
+ return [(f'{p}/{i}',item) for i,item in enumerate(v)]
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
+ try:
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
+ except Exception as exc:
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
+ return 2
+ finally:
+ if localdocs is not None:
+ localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress
diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.6.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.6.yml
new file mode 100644
index 00000000..a66951b3
--- /dev/null
+++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Stage_2_S2_00_v.6.yml
@@ -0,0 +1,3064 @@
+Agent:
+ name: Stage_2_S2_00_v6
+ version: 6.0.0
+ description: Stage 1 사건·배포 root를 직접 받아 인증된 workspace의 원본을 읽고 C00–C15를 단일 비 LLM task로 실행 테스트한다. prev 선행 task·별도
+ 요청 ID 없이 자체 결과를 검증하고 status를 마지막에 기록한다.
+ metadata:
+ workflow_id: S2_00
+ execution_class: NON-LLM-DETERMINISTIC
+ execution_authority: MCP_CODE_EXECUTOR_INLINE
+ implementation_status: IMPLEMENTED_OFFLINE_VERIFIED
+ algorithm_version: s2_00_direct_ingress/6.0.0
+ input_contract:
+ stage1_run_root_ref: .
+ stage1_deployment_root_ref: Default_Agent
+ root_authority: parameters.code::STAGE1_RUN_ROOT, STAGE1_DEPLOYMENT_ROOT; run_inline_mcp direct arguments
+ workspace_scope: backend __user_hash__ and __workspace_hash__
+ source_access: localdocs read_binary_doc of original files at supplied roots; no cross-Agent prev dependency
+ source_contract_authority: parameters.code::SOURCE_POLICY
+ output_contract:
+ root: stage2_runs/from-stage1/s2_00/v6/ when case root is .; otherwise stage2_runs/from-stage1//s2_00/v6/
+ revision_scope: Fixed implementation revision directory; no per-run ID; prior v5 diagnostics preserved.
+ states:
+ - READY
+ - READY_WITH_ISSUES
+ - BLOCKED
+ normal_artifact_count: 5
+ status_last: ingress/ingress_status.json
+ publication_semantics: STATUS_LAST_LOGICAL_COMMIT; SAME_ROOT_CONCURRENT_WRITERS_UNVERIFIED
+ execution_admission: WORKSPACE_EXECUTION_TEST_ONLY; DEV_PRODUCTION_PUBLICATION_FORBIDDEN
+ standalone_contract: true
+ execution_mode: WORKSPACE_EXECUTION_TEST
+ source_policy_release_class: DEV_FIXTURE_RELEASE
+ Stages:
+ - name: S2_00
+ description: Stage 1 결과를 저장한 동일 workspace에서 실행한다. 사건 root .·배포 root Default_Agent를 직접 전달하며, 다른 위치는 inline 상수
+ 또는 함수 인자로 지정한다. 별도 준비 task·request 파일·prev 치환 없이 원본을 읽고 검증한다.
+ prevs: []
+ nexts: []
+ tools:
+ mcpServers:
+ localdocs:
+ type: streamable-http
+ url: http://mcp-localdocs:8012/mcp
+ code-executor:
+ type: streamable-http
+ url: https://code-executor.mcp.eroomai.com/mcp
+ tasks:
+ - task_name: Task_S2_00_deterministic_ingress
+ description: 인증된 localdocs에서 Stage 1 원본 16개·manifest 신호와 필요한 배포 의존을 읽어 C00–C15 실행 테스트를 수행한다. DEV는 생산 배포 승인으로
+ 취급하지 않으며 workspace 테스트 산출물에 실행 모드와 정책 분류를 기록한다.
+ mcp: code-executor
+ tool_name: run_code
+ parameters:
+ language: python
+ requirements: httpx==0.28.1
+ network: agent-network
+ timeout: 300
+ code: |
+ #!/usr/bin/env python3
+ """S2_00 direct Stage 1 ingress; one deterministic Code Executor task.
+
+ Stage 1 original files are read from directly supplied workspace roots.
+ This module owns its contract; no downstream Agent or output schema is loaded.
+ MCP transport follows the required Code Executor notebook and SKILL guide.
+ """
+ from __future__ import annotations
+ import base64
+ import binascii
+ from collections import Counter, defaultdict
+ import contextlib
+ from dataclasses import dataclass
+ import hashlib
+ import io
+ import itertools
+ import json
+ import math
+ import os
+ from pathlib import Path, PurePosixPath
+ import posixpath
+ import re
+ import stat
+ import sys
+ import tempfile
+ import unicodedata
+ from typing import Any, Callable, Iterable, Mapping, MutableMapping, Sequence
+
+ ALGORITHM_VERSION = "s2_00_direct_ingress/6.0.0"
+ LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp"
+ MCP_PROTOCOL_VERSION = "2025-03-26"
+ INLINE_CLIENT_NAME = "liti-stage2-s2-00-direct"
+ INLINE_CLIENT_VERSION = "5.0.0"
+ INLINE_USER_HASH = r"""{{__user_hash__}}"""
+ INLINE_WORKSPACE_HASH = r"""{{__workspace_hash__}}"""
+ # Direct caller configuration; paths are relative to the authenticated workspace.
+ # Stage 1 v.8 writes its result files at workspace root. A nested case root can
+ # be passed to run_inline_mcp without a predecessor task or a control file.
+ STAGE1_RUN_ROOT = "."
+ STAGE1_DEPLOYMENT_ROOT = "Default_Agent"
+ EXECUTION_MODE = "WORKSPACE_EXECUTION_TEST"
+
+
+ MAX_FILE_BYTES = 32 * 1024 * 1024
+
+
+ MAX_RUN_BYTES = 256 * 1024 * 1024
+
+
+ MAX_JSON_DEPTH = 96
+
+
+ MAX_JSON_ITEMS = 1_000_000
+
+
+ SEMANTIC_SIGNAL_KINDS = frozenset({"canonical", "domain_signal"})
+
+
+ HARD_RELATION_KINDS = frozenset(
+ {
+ "SAME_BO_ID",
+ "SOURCE_BO_ATTACHMENT",
+ "SAME_EVIDENCE_REF",
+ "SAME_EVENT_REF",
+ "EXPLICIT_CASE_RELATION",
+ }
+ )
+
+
+ CANDIDATE_RELATION_KINDS = frozenset(
+ {"claim_precondition", "accessory_of", "incompatible_with", "EXPLICIT_DEPENDENCY"}
+ )
+
+
+ P1_DIGEST_KEYS = {
+ "evidence_indexed_sha256": "evidence_indexed",
+ "evidence_event_candidates_sha256": "evidence_event_candidates",
+ "b1_gate_sha256": "b1_evidence_indexed_gate",
+ "b2_gate_sha256": "b2_event_candidates_gate",
+ "screening_sha256": "domain_screening",
+ "activation_manifest_sha256": "domain_activation_manifest",
+ "registry_index_sha256": "stage1_domain_registry_index",
+ }
+
+
+ REQUIREMENT_CLASS_ENUM = {
+ "identity_backbone": "IDENTITY_BACKBONE",
+ "routing_profile_backbone": "ROUTING_PROFILE_BACKBONE",
+ "evidence_scope": "EVIDENCE_EVENT_SCOPE",
+ "event_scope": "EVIDENCE_EVENT_SCOPE",
+ "integrity_corroborator": "INTEGRITY_CORROBORATOR",
+ "optimization_context": "OPTIMIZATION_CONTEXT",
+ }
+
+
+ ADAPTER_IDS = {
+ "evidence_indexed": "S2A-EVIDENCE-V3-ENVELOPE-V1",
+ "evidence_event_candidates": "S2A-EVENTS-V1-ENVELOPE-V1",
+ "client_goal": "S2A-CLIENT-GOAL-V8-V1",
+ "domain_screening": "S2A-DOMAIN-SCREENING-V1",
+ "domain_activation_manifest": "S2A-DUAL-SG01-V1",
+ "b1_evidence_indexed_gate": "S2A-B1-GATE-V1",
+ "b2_event_candidates_gate": "S2A-B2-GATE-V1",
+ "stage1_part1_soft_gate_handoff": "S2A-P1-HANDOFF-FLAT-V1",
+ "bo": "S2A-BO-V8-LIST-V1",
+ "signal_manifest": "S2A-SIGNAL-ALL-V1",
+ "stage1_part2_review_handoff": "S2A-P2-HANDOFF-FLAT-V1",
+ "legal_effect_structures": "S2A-LES-CURRENT-V8-V1",
+ "stage1_part3_review_handoff": "S2A-P3-HANDOFF-WRAPPED-V1",
+ "fact_ledger_base": "S2A-FACT-LEDGER-CURRENT-V8-V1",
+ "fact_ledger_writer_report": "S2A-FACT-LEDGER-WRITER-REPORT-V1",
+ "stage1_part4_review_handoff": "S2A-P4-HANDOFF-WRAPPED-V1",
+ }
+
+
+ SG01_PROJECTION_FIELDS: tuple[str, ...] = (
+ "schema_version",
+ "signal_id",
+ "status",
+ "registry_version",
+ "registry_index_sha256",
+ "screening_sha256",
+ "domain_entries",
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ "unrouted_material",
+ "conservation_gate",
+ "fail_open_policy",
+ "review_items",
+ "contract_guards",
+ )
+
+
+ SG01_SET_FIELDS = frozenset(
+ {
+ "active_domain_ids",
+ "supporting_domain_ids",
+ "monitor_domain_ids",
+ "expected_runnable_domain_ids",
+ "required_calculation_domains",
+ }
+ )
+
+
+ _RAW_VALUE_UNSET = object()
+
+
+ DEFAULT_SOURCE_CONTRACTS: tuple[dict[str, Any], ...] = (
+ {"logical_input_id": "evidence_indexed", "path": "evidence_indexed.json", "criticality": "evidence_scope"},
+ {"logical_input_id": "evidence_event_candidates", "path": "evidence_event_candidates.json", "criticality": "event_scope"},
+ {"logical_input_id": "client_goal", "path": "client_goal.json", "criticality": "optimization_context"},
+ {"logical_input_id": "domain_screening", "path": "routing/domain_screening.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "domain_activation_manifest", "path": "routing/domain_activation_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "b1_evidence_indexed_gate", "path": "quality_gates/B1_evidence_indexed_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "b2_event_candidates_gate", "path": "quality_gates/B2_event_candidates_gate.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part1_soft_gate_handoff", "path": "quality_gates/stage1_part1_soft_gate_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "bo", "path": "BO.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "signal_manifest", "path": "signals/signal_manifest.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part2_review_handoff", "path": "quality_gates/stage1_part2_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "legal_effect_structures", "path": "legal_effect_structures.json", "criticality": "routing_profile_backbone"},
+ {"logical_input_id": "stage1_part3_review_handoff", "path": "quality_gates/stage1_part3_review_handoff.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "fact_ledger_base", "path": "Fact_Ledger_base.json", "criticality": "identity_backbone"},
+ {"logical_input_id": "fact_ledger_writer_report", "path": "stage1_tmp/fact_ledger/fact_ledger_writer_report.json", "criticality": "integrity_corroborator"},
+ {"logical_input_id": "stage1_part4_review_handoff", "path": "quality_gates/stage1_part4_review_handoff.json", "criticality": "integrity_corroborator"},
+ )
+
+
+ class IngressError(RuntimeError):
+ """A machine-readable deterministic ingress failure."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ logical_input_id: str | None = None,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.logical_input_id = logical_input_id
+ self.details = dict(details or {})
+
+ def as_dict(self) -> dict[str, Any]:
+ result: dict[str, Any] = {"code": self.code, "message": str(self)}
+ if self.logical_input_id is not None:
+ result["logical_input_id"] = self.logical_input_id
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+ @dataclass(frozen=True, slots=True)
+ class Snapshot:
+ logical_input_id: str
+ relative_path: str
+ resolved_path: str
+ raw: bytes
+ raw_sha256: str
+ byte_length: int
+ device: int
+ inode: int
+ mtime_ns: int
+
+
+ def _reject_constant(value: str) -> None:
+ raise ValueError(f"non-finite JSON number is forbidden: {value}")
+
+
+ def _pairs_without_duplicates(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+
+ def _walk_json_limits(value: Any, *, max_depth: int, max_items: int) -> int:
+ count = 0
+ stack: list[tuple[Any, int]] = [(value, 1)]
+ while stack:
+ current, depth = stack.pop()
+ if depth > max_depth:
+ raise IngressError("JSON_DEPTH_LIMIT", "JSON nesting depth exceeded")
+ if isinstance(current, dict):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current.values())
+ elif isinstance(current, list):
+ count += len(current)
+ stack.extend((item, depth + 1) for item in current)
+ if count > max_items:
+ raise IngressError("JSON_ITEM_LIMIT", "JSON aggregate item limit exceeded")
+ return count
+
+
+ def load_json_strict(
+ source: Snapshot | bytes | bytearray | memoryview | str,
+ *,
+ max_depth: int = MAX_JSON_DEPTH,
+ max_items: int = MAX_JSON_ITEMS,
+ ) -> Any:
+ """Parse one UTF-8 JSON value, rejecting duplicate keys and non-finite numbers."""
+
+ if isinstance(source, Snapshot):
+ raw = source.raw
+ elif isinstance(source, str):
+ raw = source.encode("utf-8")
+ else:
+ raw = bytes(source)
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("INVALID_UTF8", "JSON source is not strict UTF-8") from exc
+ try:
+ value = json.loads(
+ text,
+ object_pairs_hook=_pairs_without_duplicates,
+ parse_constant=_reject_constant,
+ )
+ except (json.JSONDecodeError, ValueError) as exc:
+ message = str(exc)
+ code = "DUPLICATE_JSON_KEY" if "duplicate JSON key" in message else "STRICT_JSON_PARSE_FAILED"
+ raise IngressError(code, message) from exc
+ _walk_json_limits(value, max_depth=max_depth, max_items=max_items)
+ return value
+
+
+ def canonical_json_bytes(value: Any) -> bytes:
+ """Return the project canonical parsed representation without normalizing strings."""
+
+ def reject_nonfinite(item: Any) -> None:
+ if isinstance(item, float) and not math.isfinite(item):
+ raise IngressError("NON_FINITE_NUMBER", "NaN and Infinity are forbidden")
+ if isinstance(item, dict):
+ for nested in item.values():
+ reject_nonfinite(nested)
+ elif isinstance(item, (list, tuple)):
+ for nested in item:
+ reject_nonfinite(nested)
+
+ reject_nonfinite(value)
+ try:
+ rendered = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ except (TypeError, ValueError) as exc:
+ raise IngressError("CANONICAL_SERIALIZATION_FAILED", str(exc)) from exc
+ return (rendered + "\n").encode("utf-8")
+
+
+ def canonical_digest(value: Any) -> str:
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
+
+
+ class _SchemaViolation(ValueError):
+ """Internal deterministic JSON Schema validation failure."""
+
+
+ def _json_equal(left: Any, right: Any) -> bool:
+ try:
+ return canonical_json_bytes(left) == canonical_json_bytes(right)
+ except IngressError:
+ return False
+
+
+ def _schema_pointer(document: Mapping[str, Any], fragment: str) -> Mapping[str, Any]:
+ if fragment in {"", "#"}:
+ return document
+ pointer = fragment[1:] if fragment.startswith("#") else fragment
+ if not pointer.startswith("/"):
+ raise _SchemaViolation(f"unsupported schema fragment: {fragment}")
+ current: Any = document
+ for token in pointer[1:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(current, dict) or key not in current:
+ raise _SchemaViolation(f"unresolved schema pointer: {fragment}")
+ current = current[key]
+ if not isinstance(current, dict):
+ raise _SchemaViolation(f"schema pointer is not an object: {fragment}")
+ return current
+
+
+ def _schema_type_matches(value: Any, expected: str) -> bool:
+ return {
+ "object": isinstance(value, dict),
+ "array": isinstance(value, list),
+ "string": isinstance(value, str),
+ "integer": isinstance(value, int) and not isinstance(value, bool),
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
+ "boolean": isinstance(value, bool),
+ "null": value is None,
+ }.get(expected, False)
+
+
+ def _validate_schema_node(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> None:
+ reference = schema.get("$ref")
+ if isinstance(reference, str):
+ if reference.startswith("#"):
+ target_root = root_schema
+ fragment = reference
+ else:
+ name, separator, tail = reference.partition("#")
+ target_root = schema_documents.get(name)
+ if target_root is None:
+ raise _SchemaViolation(f"{instance_path}: external schema ref is not release-local: {reference}")
+ fragment = f"#{tail}" if separator else "#"
+ _validate_schema_node(
+ value,
+ _schema_pointer(target_root, fragment),
+ root_schema=target_root,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ raise _SchemaViolation(f"{instance_path}: const mismatch")
+ if "enum" in schema and not any(_json_equal(value, candidate) for candidate in schema["enum"]):
+ raise _SchemaViolation(f"{instance_path}: enum mismatch")
+ forbidden = schema.get("not")
+ if isinstance(forbidden, dict) and _schema_branch_matches(
+ value,
+ forbidden,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ ):
+ raise _SchemaViolation(f"{instance_path}: forbidden schema branch matched")
+ expected_type = schema.get("type")
+ if expected_type is not None:
+ alternatives = [expected_type] if isinstance(expected_type, str) else list(expected_type)
+ if not any(_schema_type_matches(value, item) for item in alternatives):
+ raise _SchemaViolation(f"{instance_path}: expected type {alternatives}")
+ for keyword in ("oneOf", "anyOf"):
+ branches = schema.get(keyword)
+ if isinstance(branches, list):
+ matches = 0
+ for branch in branches:
+ try:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ matches += 1
+ except _SchemaViolation:
+ continue
+ required_matches = 1 if keyword == "oneOf" else None
+ if (required_matches is not None and matches != required_matches) or (keyword == "anyOf" and matches == 0):
+ raise _SchemaViolation(f"{instance_path}: {keyword} matched {matches} branches")
+ all_of = schema.get("allOf")
+ if isinstance(all_of, list):
+ for branch in all_of:
+ _validate_schema_node(
+ value,
+ branch,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ condition = schema.get("if")
+ if isinstance(condition, dict):
+ condition_matches = True
+ try:
+ _validate_schema_node(
+ value,
+ condition,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ except _SchemaViolation:
+ condition_matches = False
+ selected = schema.get("then" if condition_matches else "else")
+ if isinstance(selected, dict):
+ _validate_schema_node(
+ value,
+ selected,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ if isinstance(value, dict):
+ minimum_properties = schema.get("minProperties")
+ maximum_properties = schema.get("maxProperties")
+ if isinstance(minimum_properties, int) and len(value) < minimum_properties:
+ raise _SchemaViolation(f"{instance_path}: minProperties {minimum_properties}")
+ if isinstance(maximum_properties, int) and len(value) > maximum_properties:
+ raise _SchemaViolation(f"{instance_path}: maxProperties {maximum_properties}")
+ required = schema.get("required", [])
+ if isinstance(required, list):
+ missing = [key for key in required if key not in value]
+ if missing:
+ raise _SchemaViolation(f"{instance_path}: missing required keys {missing}")
+ properties = schema.get("properties", {})
+ if isinstance(properties, dict):
+ pattern_properties = schema.get("patternProperties", {})
+ matched_by_pattern: set[str] = set()
+ if isinstance(pattern_properties, dict):
+ for key, child_value in value.items():
+ for pattern_text, child_schema in pattern_properties.items():
+ if re.search(pattern_text, key) is not None and isinstance(child_schema, dict):
+ matched_by_pattern.add(key)
+ _validate_schema_node(
+ child_value,
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ extras = sorted(set(value) - set(properties) - matched_by_pattern)
+ additional = schema.get("additionalProperties")
+ if additional is False:
+ if extras:
+ raise _SchemaViolation(f"{instance_path}: additional properties {extras}")
+ elif isinstance(additional, dict):
+ for key in extras:
+ _validate_schema_node(
+ value[key],
+ additional,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ for key, child_schema in properties.items():
+ if key in value and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[key],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{key}",
+ )
+ if isinstance(value, list):
+ minimum = schema.get("minItems")
+ maximum = schema.get("maxItems")
+ if isinstance(minimum, int) and len(value) < minimum:
+ raise _SchemaViolation(f"{instance_path}: minItems {minimum}")
+ if isinstance(maximum, int) and len(value) > maximum:
+ raise _SchemaViolation(f"{instance_path}: maxItems {maximum}")
+ if schema.get("uniqueItems") is True:
+ digests = [canonical_digest(item) for item in value]
+ if len(digests) != len(set(digests)):
+ raise _SchemaViolation(f"{instance_path}: duplicate array items")
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ for index, child_schema in enumerate(prefix_items):
+ if index < len(value) and isinstance(child_schema, dict):
+ _validate_schema_node(
+ value[index],
+ child_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ item_schema = schema.get("items")
+ if item_schema is False and isinstance(prefix_items, list) and len(value) > len(prefix_items):
+ raise _SchemaViolation(f"{instance_path}: additional array items are forbidden")
+ if isinstance(item_schema, dict):
+ start = len(prefix_items) if isinstance(prefix_items, list) else 0
+ for index, item in enumerate(value[start:], start=start):
+ _validate_schema_node(
+ item,
+ item_schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ contains = schema.get("contains")
+ if isinstance(contains, dict):
+ if not any(
+ _schema_branch_matches(
+ item,
+ contains,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=f"{instance_path}/{index}",
+ )
+ for index, item in enumerate(value)
+ ):
+ raise _SchemaViolation(f"{instance_path}: contains did not match")
+ if isinstance(value, str):
+ min_length = schema.get("minLength")
+ if isinstance(min_length, int) and len(value) < min_length:
+ raise _SchemaViolation(f"{instance_path}: minLength {min_length}")
+ max_length = schema.get("maxLength")
+ if isinstance(max_length, int) and len(value) > max_length:
+ raise _SchemaViolation(f"{instance_path}: maxLength {max_length}")
+ pattern = schema.get("pattern")
+ if isinstance(pattern, str) and re.search(pattern, value) is None:
+ raise _SchemaViolation(f"{instance_path}: pattern mismatch")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ minimum = schema.get("minimum")
+ if isinstance(minimum, (int, float)) and value < minimum:
+ raise _SchemaViolation(f"{instance_path}: minimum {minimum}")
+ maximum = schema.get("maximum")
+ if isinstance(maximum, (int, float)) and value > maximum:
+ raise _SchemaViolation(f"{instance_path}: maximum {maximum}")
+
+
+ def _schema_branch_matches(
+ value: Any,
+ schema: Mapping[str, Any],
+ *,
+ root_schema: Mapping[str, Any],
+ schema_documents: Mapping[str, Mapping[str, Any]],
+ instance_path: str,
+ ) -> bool:
+ try:
+ _validate_schema_node(
+ value,
+ schema,
+ root_schema=root_schema,
+ schema_documents=schema_documents,
+ instance_path=instance_path,
+ )
+ return True
+ except _SchemaViolation:
+ return False
+
+
+ def _safe_relative_path(relative_path: str) -> PurePosixPath:
+ if not isinstance(relative_path, str) or not relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "source path must be a non-empty string")
+ if "\x00" in relative_path or "\\" in relative_path:
+ raise IngressError("INVALID_SOURCE_PATH", "NUL and backslash are forbidden in logical paths")
+ logical = PurePosixPath(relative_path)
+ if logical.is_absolute() or any(part in {"", ".", ".."} for part in logical.parts):
+ raise IngressError("PATH_TRAVERSAL", f"unsafe relative path: {relative_path}")
+ return logical
+
+
+ def _assert_no_symlink_components(root: Path, logical: PurePosixPath) -> None:
+ current = root
+ for part in logical.parts:
+ current = current / part
+ try:
+ current_stat = current.lstat()
+ except FileNotFoundError:
+ return
+ if stat.S_ISLNK(current_stat.st_mode):
+ raise IngressError("SYMLINK_ESCAPE", f"symlink component rejected: {logical}")
+
+
+ def open_bounded_snapshot(
+ approved_root: str | os.PathLike[str],
+ relative_path: str,
+ *,
+ logical_input_id: str = "anonymous",
+ max_bytes: int = MAX_FILE_BYTES,
+ require_single_link: bool = True,
+ ) -> Snapshot:
+ """Read one regular file once from one descriptor and verify post-read identity."""
+
+ root_arg = Path(approved_root)
+ if root_arg.is_symlink():
+ raise IngressError("SYMLINK_ROOT_REJECTED", "approved root itself may not be a symlink")
+ try:
+ root = root_arg.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("APPROVED_ROOT_MISSING", "approved root does not exist") from exc
+ if not root.is_dir():
+ raise IngressError("APPROVED_ROOT_NOT_DIRECTORY", "approved root must be a directory")
+ logical = _safe_relative_path(relative_path)
+ _assert_no_symlink_components(root, logical)
+ candidate = root.joinpath(*logical.parts)
+ try:
+ resolved = candidate.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_MISSING", f"source is missing: {relative_path}", logical_input_id=logical_input_id) from exc
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise IngressError("PATH_ESCAPE", f"resolved source escaped approved root: {relative_path}") from exc
+ flags = os.O_RDONLY
+ if hasattr(os, "O_CLOEXEC"):
+ flags |= os.O_CLOEXEC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(candidate, flags)
+ except OSError as exc:
+ raise IngressError("SOURCE_OPEN_FAILED", f"unable to open source: {relative_path}") from exc
+ try:
+ before = os.fstat(descriptor)
+ if not stat.S_ISREG(before.st_mode):
+ raise IngressError("NON_REGULAR_SOURCE", f"source is not a regular file: {relative_path}")
+ if require_single_link and before.st_nlink != 1:
+ raise IngressError("HARDLINK_POLICY_VIOLATION", f"source link count is {before.st_nlink}")
+ if before.st_size > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = os.read(descriptor, min(1024 * 1024, max_bytes + 1 - total))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > max_bytes:
+ raise IngressError("SOURCE_SIZE_LIMIT", f"source exceeds {max_bytes} bytes")
+ after = os.fstat(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
+ path_after = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError as exc:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", "source disappeared after snapshot") from exc
+ identity_before = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
+ identity_after = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
+ path_identity = (path_after.st_dev, path_after.st_ino, path_after.st_size, path_after.st_mtime_ns)
+ if identity_before != identity_after or identity_after != path_identity:
+ raise IngressError("SOURCE_SNAPSHOT_CHANGED", f"source changed during snapshot: {relative_path}")
+ raw = b"".join(chunks)
+ return Snapshot(
+ logical_input_id=logical_input_id,
+ relative_path=logical.as_posix(),
+ resolved_path=str(resolved),
+ raw=raw,
+ raw_sha256=hashlib.sha256(raw).hexdigest(),
+ byte_length=len(raw),
+ device=after.st_dev,
+ inode=after.st_ino,
+ mtime_ns=after.st_mtime_ns,
+ )
+
+
+ def resolve_stage1_sources(
+ stage1_run_root: str | os.PathLike[str],
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Resolve only approved logical kinds; a relocation manifest cannot invent kinds."""
+
+ root = Path(stage1_run_root).resolve(strict=True)
+ if not root.is_dir():
+ raise IngressError("STAGE1_ROOT_NOT_DIRECTORY", "Stage 1 run root must be a directory")
+ contracts = [dict(row) for row in DEFAULT_SOURCE_CONTRACTS]
+ overrides = dict((contract_manifest or {}).get("path_overrides", {}))
+ approved_ids = {row["logical_input_id"] for row in contracts}
+ invented = sorted(set(overrides) - approved_ids)
+ if invented:
+ raise IngressError("UNAPPROVED_LOGICAL_KIND", "relocation manifest invented logical kinds", details={"ids": invented})
+ seen_paths: set[str] = set()
+ for row in contracts:
+ path = overrides.get(row["logical_input_id"], row["path"])
+ safe = _safe_relative_path(path).as_posix()
+ if safe in seen_paths:
+ raise IngressError("DUPLICATE_LOGICAL_MAPPING", f"duplicate physical mapping: {safe}")
+ seen_paths.add(safe)
+ row["expected_path"] = row.pop("path")
+ row["observed_path"] = safe
+ row["resolution_source"] = (
+ "RELEASE_BOUND_CONTRACT_MANIFEST"
+ if row["logical_input_id"] in overrides
+ else "DEFAULT_EXACT_PATH"
+ )
+ return contracts
+
+
+ def _issue(
+ code: str,
+ *,
+ impact_scope: str = "GLOBAL",
+ source_refs: Sequence[str] = (),
+ severity: str = "ERROR",
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "issue_code": code,
+ "severity": severity,
+ "impact_scope": impact_scope,
+ "scope_refs": sorted(set(source_refs)),
+ "source_contract_row_refs": sorted(set(source_refs)),
+ "reason_codes": [code],
+ "downstream_allowed_actions": [],
+ "message": message or code,
+ }
+
+
+ def _shape_required(value: Any, keys: Sequence[str]) -> list[str]:
+ if not isinstance(value, dict):
+ return list(keys)
+ return [key for key in keys if key not in value]
+
+
+ def _json_pointer_value(document: Any, pointer: str | None) -> tuple[bool, Any]:
+ if pointer in {None, ""}:
+ return (pointer == "", document)
+ if not isinstance(pointer, str) or not pointer.startswith("/"):
+ return False, None
+ current = document
+ for raw_token in pointer[1:].split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ elif isinstance(current, list) and token.isdigit() and int(token) < len(current):
+ current = current[int(token)]
+ else:
+ return False, None
+ return True, current
+
+
+ def _release_stage1_source_rows(release_lock: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ rows = release_lock.get("stage1_sources")
+ if not isinstance(rows, list):
+ dependency = release_lock.get("dependency_locks", {}).get("stage1", {})
+ rows = dependency.get("stage1_sources") if isinstance(dependency, dict) else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+ def _adapter_decision(release_lock: Mapping[str, Any], adapter_id: str) -> Mapping[str, Any] | None:
+ for row in release_lock.get("adapter_decisions", []):
+ if isinstance(row, dict) and row.get("adapter_id") == adapter_id and isinstance(row.get("decision"), dict):
+ return row["decision"]
+ return None
+
+
+ def _closed_adapter_shape_errors(
+ document: Any,
+ *,
+ logical_id: str,
+ adapter_id: str,
+ required_keys: Sequence[str],
+ release_lock: Mapping[str, Any],
+ ) -> list[str]:
+ errors: list[str] = []
+ if required_keys:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, required_keys))
+ decision = _adapter_decision(release_lock, adapter_id)
+ if decision is not None:
+ root_shape = decision.get("root_shape")
+ if root_shape == "ARRAY" and not isinstance(document, list):
+ errors.append("root must be an array")
+ elif root_shape == "OBJECT_ENVELOPE" and not isinstance(document, dict):
+ errors.append("root must be an object envelope")
+ if isinstance(document, dict):
+ errors.extend(
+ f"missing root key {key}"
+ for key in _shape_required(document, decision.get("required_root_fields", []))
+ )
+ if isinstance(document, list):
+ required_item_fields = decision.get("required_item_fields", decision.get("required_row_fields", []))
+ if isinstance(required_item_fields, list):
+ for index, item in enumerate(document):
+ for key in _shape_required(item, required_item_fields):
+ errors.append(f"row {index} missing {key}")
+ if decision is None:
+ fallback_required: dict[str, tuple[str, ...]] = {
+ "evidence_indexed": ("schema_contract_version", "items"),
+ "evidence_event_candidates": ("schema_version", "items"),
+ "domain_activation_manifest": SG01_PROJECTION_FIELDS,
+ "signal_manifest": ("downstream_read_sets", "files"),
+ "legal_effect_structures": ("schema_version", "structure_records"),
+ "fact_ledger_writer_report": (
+ "schema_version",
+ "row_count",
+ "gate_firings",
+ "domain_effect_coverage",
+ "calculation_readiness",
+ "blocked_review_items",
+ "conservation",
+ "final_sha256",
+ ),
+ }
+ fallback = fallback_required.get(logical_id, ())
+ if fallback:
+ errors.extend(f"missing root key {key}" for key in _shape_required(document, fallback))
+ if logical_id in {"bo", "fact_ledger_base"} and not isinstance(document, list):
+ errors.append("root must be an array")
+ return sorted(set(errors))
+
+
+ def _schema_document_index(deployment_documents: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ result: dict[str, Mapping[str, Any]] = {}
+ for path, document in deployment_documents.items():
+ if not isinstance(document, dict):
+ continue
+ result[path] = document
+ result[PurePosixPath(path).name] = document
+ schema_id = document.get("$id")
+ if isinstance(schema_id, str):
+ result[schema_id] = document
+ return result
+
+
+ def _source_hash_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ digest = row.get("raw_sha256", row.get("sha256"))
+ if not isinstance(digest, str) or re.fullmatch(r"[A-Fa-f0-9]{64}", digest) is None:
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = digest.lower()
+ return result
+
+
+ def _source_producer_index(document: Mapping[str, Any] | None) -> dict[str, str]:
+ """Index producer evidence carried by a bounded completion/manifest row."""
+
+ result: dict[str, str] = {}
+ if not isinstance(document, dict):
+ return result
+ candidate_arrays: list[Any] = []
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(document.get(key), list):
+ candidate_arrays.append(document[key])
+ for wrapper in ("completion_seal", "manifest", "payload", "data"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("source_rows", "sources", "artifacts", "files", "entries"):
+ if isinstance(nested.get(key), list):
+ candidate_arrays.append(nested[key])
+ for rows in candidate_arrays:
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ producer = next(
+ (
+ row.get(key)
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by")
+ if isinstance(row.get(key), str) and row.get(key)
+ ),
+ None,
+ )
+ if not isinstance(producer, str):
+ continue
+ for key in ("logical_input_id", "path", "observed_path", "logical_id"):
+ identifier = row.get(key)
+ if isinstance(identifier, str) and identifier:
+ result[identifier] = producer
+ return result
+
+
+ def _producer_value(document: Any) -> str | None:
+ if not isinstance(document, dict):
+ return None
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = document.get(key)
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("metadata", "meta", "handoff", "payload"):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("producer_id", "created_by", "writer_id", "writer", "finalized_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ # P3/P4 are closed one-key wrappers in the Stage 1 v8 handoff contract.
+ for wrapper in (
+ "stage1_part3_review_handoff",
+ "stage1_part4_review_handoff",
+ ):
+ nested = document.get(wrapper)
+ if isinstance(nested, dict):
+ for key in ("finalized_by", "created_by"):
+ value = nested.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+ def _producer_matches(
+ observed: str,
+ expected: str,
+ alias_id: str | None,
+ release_lock: Mapping[str, Any],
+ ) -> bool:
+ if observed == expected:
+ return True
+ if alias_id is None:
+ return False
+ decision = _adapter_decision(release_lock, alias_id)
+ if decision is None or decision.get("bidirectional_match_allowed") is not True:
+ return False
+ pair = {decision.get("schema_writer_id"), decision.get("orchestration_producer_id")}
+ return {observed, expected} == pair
+
+
+ def _identity_ref(document: Any, pointer: str | None, logical_id: str) -> dict[str, Any]:
+ if pointer is None:
+ return {"value": None, "disposition": "NOT_APPLICABLE", "source_ref": logical_id}
+ found, value = _json_pointer_value(document, pointer)
+ if not found or value is None:
+ return {"value": None, "disposition": "MISSING", "source_ref": f"{logical_id}#{pointer}"}
+ return {"value": str(value), "disposition": "OBSERVED", "source_ref": f"{logical_id}#{pointer}"}
+
+
+ def validate_ingress_contracts(
+ snapshots: Mapping[str, Snapshot],
+ contracts: Sequence[Mapping[str, Any]],
+ release_lock: Mapping[str, Any],
+ *,
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ deployment_documents: Mapping[str, Any] | None = None,
+ completion_seal: Mapping[str, Any] | None = None,
+ contract_manifest: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Strictly parse sources and verify release-bound schema, producer, identity, and seal rows."""
+
+ documents: dict[str, Any] = {}
+ rows: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ deployment_documents = deployment_documents or {}
+ deployment_by_path = {snapshot.relative_path: snapshot for snapshot in deployment_snapshots.values()}
+ schema_documents = _schema_document_index(deployment_documents)
+ release_source_rows = _release_stage1_source_rows(release_lock)
+ release_ids = [str(row.get("logical_input_id")) for row in release_source_rows]
+ duplicate_release_ids = sorted(key for key, count in Counter(release_ids).items() if count > 1)
+ if duplicate_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_DUPLICATE",
+ "release stage1_sources contains duplicate logical_input_id rows",
+ details={"logical_input_ids": duplicate_release_ids},
+ )
+ expected_fixed = {
+ str(row["logical_input_id"]): str(row["path"])
+ for row in DEFAULT_SOURCE_CONTRACTS
+ }
+ expected_release_ids = set(expected_fixed) | {"signal_payload_family"}
+ observed_release_ids = set(release_ids)
+ if observed_release_ids != expected_release_ids:
+ raise IngressError(
+ "RELEASE_SOURCE_CONTRACT_SET_MISMATCH",
+ "release stage1_sources must be the exact 16 fixed inputs plus signal_payload_family",
+ details={
+ "missing": sorted(expected_release_ids - observed_release_ids),
+ "extra": sorted(observed_release_ids - expected_release_ids),
+ },
+ )
+ release_rows = {str(row.get("logical_input_id")): row for row in release_source_rows}
+ for logical_id, expected_path in expected_fixed.items():
+ release_row = release_rows[logical_id]
+ if release_row.get("path") != expected_path or release_row.get("path_rule") not in {None, ""}:
+ raise IngressError(
+ "RELEASE_SOURCE_FIXED_PATH_MISMATCH",
+ f"fixed source path contract mismatch: {logical_id}",
+ )
+ signal_family = release_rows["signal_payload_family"]
+ if (
+ signal_family.get("path") is not None
+ or signal_family.get("path_rule") != "signals/"
+ or signal_family.get("adapter_id") != "S2A-SIGNAL-ALL-V1"
+ or signal_family.get("raw_hash_source") != "MANIFEST_ROW"
+ ):
+ raise IngressError(
+ "SIGNAL_PAYLOAD_FAMILY_CONTRACT_MISMATCH",
+ "signal_payload_family must use the approved manifest-expanded path contract",
+ )
+ completion_hashes = _source_hash_index(completion_seal)
+ manifest_hashes = _source_hash_index(contract_manifest)
+ completion_producers = _source_producer_index(completion_seal)
+ manifest_producers = _source_producer_index(contract_manifest)
+ for contract in contracts:
+ logical_id = str(contract["logical_input_id"])
+ snapshot = snapshots.get(logical_id)
+ release_row = release_rows.get(logical_id)
+ contract_missing = release_row is None
+ release_row = release_row or {}
+ alias_value = release_row.get("producer_alias", release_row.get("producer_alias_id"))
+ alias_id = str(alias_value) if isinstance(alias_value, str) else None
+ schema_ref = release_row.get("schema_ref") if isinstance(release_row.get("schema_ref"), dict) else None
+ row = {
+ "logical_input_id": logical_id,
+ "requirement_class": REQUIREMENT_CLASS_ENUM.get(
+ str(contract.get("criticality")),
+ "INTEGRITY_CORROBORATOR",
+ ),
+ "expected_path": contract.get("expected_path"),
+ "observed_path": contract.get("observed_path"),
+ "resolution_source": contract.get("resolution_source"),
+ "schema_id": schema_ref.get("$id") if schema_ref else release_row.get("schema_id"),
+ "schema_sha256": schema_ref.get("sha256") if schema_ref else release_row.get("schema_sha256"),
+ "producer_id": release_row.get("producer_id"),
+ "producer_alias_id": alias_id,
+ "adapter_id": release_row.get("adapter_id", ADAPTER_IDS.get(logical_id, "S2A-UNBOUND-V1")),
+ "run_identity_ref": release_row.get("run_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "transaction_identity_ref": release_row.get("transaction_identity_ref", {"value": None, "disposition": "MISSING", "source_ref": logical_id}),
+ "scope_refs": [logical_id],
+ "source_contract_row_refs": [logical_id],
+ "reason_codes": [],
+ "downstream_allowed_actions": [],
+ "issue_codes": [],
+ }
+ if contract_missing:
+ code = "RELEASE_SOURCE_CONTRACT_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ declared_path = release_row.get("path")
+ if isinstance(declared_path, str) and declared_path != contract.get("expected_path"):
+ code = "RELEASE_SOURCE_PATH_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if snapshot is None:
+ row.update(
+ {
+ "raw_sha256": None,
+ "byte_length": 0,
+ "parse_status": "NOT_OBSERVED",
+ "schema_status": "UNEVALUABLE",
+ "seal_status": "UNEVALUABLE",
+ "scope_technical_disposition": "UNAVAILABLE",
+ "impact_scope": "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER",
+ }
+ )
+ code = "SOURCE_MISSING"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope=row["impact_scope"], source_refs=[logical_id]))
+ rows.append(row)
+ continue
+ row["raw_sha256"] = snapshot.raw_sha256
+ row["byte_length"] = snapshot.byte_length
+ try:
+ document = load_json_strict(
+ snapshot,
+ max_depth=int(release_lock.get("limits", {}).get("max_json_depth", MAX_JSON_DEPTH)),
+ max_items=int(release_lock.get("limits", {}).get("max_json_items", MAX_JSON_ITEMS)),
+ )
+ documents[logical_id] = document
+ row["parse_status"] = "PASS"
+ except IngressError as exc:
+ row["parse_status"] = "FAIL"
+ row["schema_status"] = "UNEVALUABLE"
+ row["seal_status"] = "UNEVALUABLE"
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ row["reason_codes"].append(exc.code)
+ row["issue_codes"].append(exc.code)
+ issues.append(_issue(exc.code, impact_scope=row["impact_scope"], source_refs=[logical_id], message=str(exc)))
+ rows.append(row)
+ continue
+ expected_adapter = ADAPTER_IDS.get(logical_id)
+ if expected_adapter is not None and release_row.get("adapter_id") not in {None, expected_adapter}:
+ code = "ADAPTER_ID_MISMATCH"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if schema_ref is not None:
+ schema_path = schema_ref.get("path")
+ schema_snapshot = deployment_by_path.get(schema_path) if isinstance(schema_path, str) else None
+ schema_document = deployment_documents.get(schema_path) if isinstance(schema_path, str) else None
+ expected_schema_hash = schema_ref.get("sha256")
+ expected_schema_id = schema_ref.get("$id")
+ if schema_snapshot is None or not isinstance(schema_document, dict):
+ schema_error = "SCHEMA_REF_NOT_IN_BOUNDED_DEPLOYMENT"
+ elif not isinstance(expected_schema_hash, str) or schema_snapshot.raw_sha256 != expected_schema_hash.lower():
+ schema_error = "SCHEMA_HASH_MISMATCH"
+ elif expected_schema_id is not None and schema_document.get("$id") != expected_schema_id:
+ schema_error = "SCHEMA_ID_MISMATCH"
+ else:
+ schema_error = None
+ try:
+ _validate_schema_node(
+ document,
+ schema_document,
+ root_schema=schema_document,
+ schema_documents=schema_documents,
+ instance_path=logical_id,
+ )
+ except _SchemaViolation as exc:
+ schema_error = "SOURCE_SCHEMA_VALIDATION_FAILED"
+ issues.append(
+ _issue(
+ schema_error,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message=str(exc),
+ )
+ )
+ if schema_error is not None:
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(schema_error)
+ row["issue_codes"].append(schema_error)
+ if schema_error != "SOURCE_SCHEMA_VALIDATION_FAILED":
+ issues.append(_issue(schema_error, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["schema_status"] = "PASS"
+ else:
+ adapter_errors = _closed_adapter_shape_errors(
+ document,
+ logical_id=logical_id,
+ adapter_id=str(row["adapter_id"]),
+ required_keys=release_row.get("required_keys", []),
+ release_lock=release_lock,
+ )
+ if contract_missing:
+ row["schema_status"] = "UNEVALUABLE"
+ elif adapter_errors:
+ code = "ADAPTER_REQUIRED_KEY_MISSING"
+ row["schema_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(
+ _issue(
+ code,
+ impact_scope="CLUSTER",
+ source_refs=[logical_id],
+ message="; ".join(adapter_errors),
+ )
+ )
+ else:
+ row["schema_status"] = "PASS"
+ expected_producer = release_row.get("producer_id")
+ document_producer = _producer_value(document)
+ sealed_producer = (
+ completion_producers.get(logical_id)
+ or completion_producers.get(str(contract.get("observed_path")))
+ or manifest_producers.get(logical_id)
+ or manifest_producers.get(str(contract.get("observed_path")))
+ )
+ if (
+ document_producer is not None
+ and sealed_producer is not None
+ and document_producer != sealed_producer
+ ):
+ code = "PRODUCER_EVIDENCE_CONFLICT"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ observed_producer = document_producer or sealed_producer
+ if isinstance(expected_producer, str):
+ if observed_producer is None:
+ code = "PRODUCER_ID_UNEVALUABLE"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, severity="WARNING", impact_scope="CLUSTER", source_refs=[logical_id]))
+ elif not _producer_matches(observed_producer, expected_producer, alias_id, release_lock):
+ code = "PRODUCER_ID_MISMATCH"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ row["run_identity_ref"] = _identity_ref(document, release_row.get("run_identity_pointer"), logical_id)
+ row["transaction_identity_ref"] = _identity_ref(
+ document,
+ release_row.get("transaction_identity_pointer"),
+ logical_id,
+ )
+ raw_hash_source = str(release_row.get("raw_hash_source", "NONE"))
+ if raw_hash_source in {"CASE_RUN_COMPLETION_SEAL", "COMPLETION_SEAL", "COMPLETION_SEAL_ROW"}:
+ expected_hash = completion_hashes.get(logical_id) or completion_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"CONTRACT_MANIFEST", "CONTRACT_MANIFEST_ROW", "MANIFEST_ROW"}:
+ expected_hash = manifest_hashes.get(logical_id) or manifest_hashes.get(str(contract.get("observed_path")))
+ elif raw_hash_source in {"COMPLETION_SEAL_OR_CONTRACT_MANIFEST", "SEALED_ROW"}:
+ expected_hash = (
+ completion_hashes.get(logical_id)
+ or completion_hashes.get(str(contract.get("observed_path")))
+ or manifest_hashes.get(logical_id)
+ or manifest_hashes.get(str(contract.get("observed_path")))
+ )
+ elif raw_hash_source in {"UNAVAILABLE_DEV", "NONE"}:
+ expected_hash = None
+ else:
+ expected_hash = None
+ code = "RAW_HASH_SOURCE_UNAPPROVED"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ code = "RAW_HASH_MISMATCH"
+ row["seal_status"] = "FAIL"
+ row["reason_codes"].append(code)
+ row["issue_codes"].append(code)
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=[logical_id]))
+ else:
+ row["seal_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ row["scope_technical_disposition"] = (
+ "UNAVAILABLE"
+ if contract_missing or any(code in row["issue_codes"] for code in {"RAW_HASH_MISMATCH", "SCHEMA_HASH_MISMATCH", "SCHEMA_ID_MISMATCH"})
+ else "AVAILABLE"
+ if not row["issue_codes"]
+ else "AVAILABLE_WITH_ISSUES"
+ )
+ row["impact_scope"] = "GLOBAL" if contract.get("criticality") == "identity_backbone" else "CLUSTER"
+ rows.append(row)
+ for identity_kind, field in (
+ ("RUN", "run_identity_ref"),
+ ("TRANSACTION", "transaction_identity_ref"),
+ ):
+ observed_values = {
+ str(row[field]["value"])
+ for row in rows
+ if row[field].get("disposition") == "OBSERVED" and row[field].get("value") is not None
+ }
+ if len(observed_values) > 1:
+ code = f"{identity_kind}_IDENTITY_CONFLICT"
+ issues.append(_issue(code, impact_scope="GLOBAL", source_refs=sorted(observed_values)))
+ for row in rows:
+ if row[field].get("disposition") == "OBSERVED":
+ row["issue_codes"] = sorted(set(row["issue_codes"] + [code]))
+ row["reason_codes"] = sorted(set(row["reason_codes"] + [code]))
+ row["scope_technical_disposition"] = "UNAVAILABLE"
+ return {"documents": documents, "source_contract_rows": rows, "issues": issues}
+
+
+ def _records_from_signal_document(document: Any) -> list[Any]:
+ return [v for _,v in _record_locations_for_signal(document)]
+
+
+ def _record_signal_id(record: Any) -> str | None:
+ if not isinstance(record, dict):
+ return None
+ value = record.get("signal_id")
+ if isinstance(value, str) and value:
+ return value
+ for wrapper in ("domain_activation_manifest", "payload", "data"):
+ nested = record.get(wrapper)
+ if isinstance(nested, dict) and isinstance(nested.get("signal_id"), str):
+ return nested["signal_id"]
+ return None
+
+
+ def expand_stage2_signal_all(
+ stage1_run_root: str | os.PathLike[str],
+ signal_manifest: Mapping[str, Any],
+ *,
+ max_file_bytes: int = MAX_FILE_BYTES,
+ max_total_bytes: int = MAX_RUN_BYTES,
+ signal_registry: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Expand Stage 2 ALL while separating semantic and integrity-only universes."""
+
+ downstream = signal_manifest.get("downstream_read_sets", {})
+ stage2 = downstream.get("stage2", []) if isinstance(downstream, dict) else []
+ if stage2 != ["ALL"]:
+ raise IngressError("SIGNAL_ALL_CONTRACT", "downstream_read_sets.stage2 must equal ['ALL']")
+ files = signal_manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest files must be an array")
+ transaction_id = str(signal_manifest.get("manifest_transaction_id", signal_manifest.get("transaction_id", "MISSING")))
+ file_rows: list[dict[str, Any]] = []
+ semantic_rows: list[dict[str, Any]] = []
+ integrity_rows: list[dict[str, Any]] = []
+ occurrences: list[dict[str, Any]] = []
+ payload_snapshots: list[Snapshot] = []
+ issues: list[dict[str, Any]] = []
+ path_counter: Counter[str] = Counter()
+ parsed_documents: dict[str, Any] = {}
+ aggregate_bytes = 0
+ registry_entries = {
+ str(row.get("file")): row
+ for row in (signal_registry or {}).get("entries", [])
+ if isinstance(row, dict) and isinstance(row.get("file"), str)
+ }
+ compatibility_files = {
+ str(path) if str(path).startswith("compatibility_views/") else "compatibility_views/"+str(path)
+ for path in (signal_registry or {}).get("compatibility_views", [])
+ if isinstance(path, str)
+ }
+ domain_envelope_schema = (signal_registry or {}).get("domain_envelope")
+ observed_registry_files: set[str] = set()
+ for index, entry in enumerate(files):
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", f"invalid signal file row at index {index}")
+ relative_payload = _safe_relative_path(entry["path"]).as_posix()
+ if relative_payload.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "manifest file path must not include signals/ prefix")
+ physical = f"signals/{relative_payload}"
+ snapshot = open_bounded_snapshot(
+ stage1_run_root,
+ physical,
+ logical_input_id=f"signal_file:{index}",
+ max_bytes=max_file_bytes,
+ )
+ document = load_json_strict(snapshot)
+ payload_snapshots.append(snapshot)
+ aggregate_bytes += snapshot.byte_length
+ if aggregate_bytes > max_total_bytes:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "signal ALL payloads exceed remaining run byte budget")
+ parsed_documents[relative_payload] = document
+ kind = entry.get("kind", "canonical")
+ if kind not in SEMANTIC_SIGNAL_KINDS | {"compatibility_view"}:
+ raise IngressError("SIGNAL_KIND_UNAPPROVED", f"unapproved signal file kind: {kind}")
+ semantic = kind in SEMANTIC_SIGNAL_KINDS
+ expected_hash = entry.get(
+ "file_sha256", entry.get("sha256", entry.get("raw_sha256"))
+ )
+ row = {
+ "manifest_index": index,
+ "file_path": relative_payload,
+ "physical_path": physical,
+ "kind": kind,
+ "raw_sha256": snapshot.raw_sha256,
+ "byte_length": snapshot.byte_length,
+ "semantic": semantic,
+ "manifest_declared_record_count": entry.get("record_count"),
+ }
+ if expected_hash is not None and expected_hash != snapshot.raw_sha256:
+ row["hash_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_FILE_HASH_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["hash_status"] = "PASS" if expected_hash else "UNEVALUABLE"
+ records = _records_from_signal_document(document)
+ row["observed_record_count"] = len(records)
+ declared_count = entry.get("record_count")
+ if isinstance(declared_count, int) and declared_count != len(records):
+ row["record_count_status"] = "FAIL"
+ issues.append(_issue("SIGNAL_RECORD_COUNT_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ else:
+ row["record_count_status"] = "PASS" if isinstance(declared_count, int) else "UNEVALUABLE"
+ registry_row = registry_entries.get(relative_payload)
+ if kind == "canonical":
+ if signal_registry is not None and registry_row is None:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif registry_row is not None:
+ observed_registry_files.add(relative_payload)
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if declared_schema is not None and declared_schema != registry_row.get("schema"):
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "compatibility_view":
+ if relative_payload in registry_entries:
+ issues.append(_issue("SIGNAL_COMPATIBILITY_SUBSTITUTION", impact_scope="SIGNAL", source_refs=[physical]))
+ if signal_registry is not None and relative_payload not in compatibility_files:
+ issues.append(_issue("SIGNAL_REGISTRY_COVERAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ elif kind == "domain_signal":
+ declared_schema = entry.get("schema", entry.get("schema_path"))
+ if signal_registry is not None and declared_schema not in {None, domain_envelope_schema}:
+ issues.append(_issue("SIGNAL_SCHEMA_LINEAGE_MISMATCH", impact_scope="SIGNAL", source_refs=[physical]))
+ file_rows.append(row)
+ path_counter[relative_payload] += 1
+ if semantic:
+ semantic_rows.append(row)
+ for record_ordinal, record in enumerate(records):
+ signal_id = _record_signal_id(record)
+ occurrence_key = [transaction_id, relative_payload, record_ordinal, signal_id]
+ occurrences.append(
+ {
+ "occurrence_key": occurrence_key,
+ "occurrence_ref": f"SIGO-{canonical_digest(occurrence_key)[:24]}",
+ "manifest_transaction_id": transaction_id,
+ "file_path": relative_payload,
+ "record_ordinal": record_ordinal,
+ "signal_id": signal_id,
+ "disposition": "UNMAPPED" if signal_id is None else "UNUSED",
+ "binding_refs": [],
+ "raw_record_sha256": canonical_digest(record),
+ "record": record,
+ }
+ )
+ else:
+ integrity_rows.append(row)
+ duplicates = sorted(path for path, count in path_counter.items() if count > 1)
+ if duplicates:
+ issues.append(_issue("SIGNAL_ALL_DUPLICATE_FILE_ROW", impact_scope="SIGNAL", source_refs=duplicates))
+ manifest_counter = Counter((i, row["file_path"], row["kind"]) for i, row in enumerate(file_rows))
+ partition_counter = Counter((row["manifest_index"], row["file_path"], row["kind"]) for row in semantic_rows + integrity_rows)
+ missing_registry_files = sorted(set(registry_entries) - observed_registry_files) if signal_registry is not None else []
+ if missing_registry_files:
+ issues.append(
+ _issue(
+ "SIGNAL_REGISTRY_COVERAGE_MISMATCH",
+ impact_scope="SIGNAL",
+ source_refs=[f"signals/{path}" for path in missing_registry_files],
+ )
+ )
+ file_conservation = (
+ manifest_counter == partition_counter
+ and not duplicates
+ and not missing_registry_files
+ and not any(row["hash_status"] == "FAIL" or row["record_count_status"] == "FAIL" for row in file_rows)
+ )
+ record_counter = Counter(tuple(row["occurrence_key"]) for row in occurrences)
+ partitioned_record_counter = Counter(
+ tuple(row["occurrence_key"])
+ for row in occurrences
+ if row["disposition"] in {"USED", "UNUSED", "UNMAPPED"}
+ )
+ record_conservation = record_counter == partitioned_record_counter
+ return {
+ "manifest_transaction_id": transaction_id,
+ "ordered_file_rows": file_rows,
+ "semantic_file_rows": semantic_rows,
+ "integrity_only_file_rows": integrity_rows,
+ "record_occurrences": occurrences,
+ "used_record_occurrences": [],
+ "unused_record_occurrences": [row for row in occurrences if row["disposition"] == "UNUSED"],
+ "unmapped_record_occurrences": [row for row in occurrences if row["disposition"] == "UNMAPPED"],
+ "_parsed_documents_by_path": parsed_documents,
+ "_payload_snapshots": payload_snapshots,
+ "file_conservation_pass": file_conservation,
+ "record_conservation_pass": record_conservation,
+ "aggregate_payload_bytes": aggregate_bytes,
+ "issues": issues,
+ }
+
+
+ def _collect_values_for_keys(value: Any, keys: frozenset[str]) -> set[str]:
+ result: set[str] = set()
+ stack = [value]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, child in current.items():
+ if key in keys:
+ if isinstance(child, list):
+ result.update(str(item) for item in child if item is not None)
+ elif child is not None:
+ result.add(str(child))
+ stack.append(child)
+ elif isinstance(current, list):
+ stack.extend(current)
+ return result
+
+
+ def bind_signal_occurrences(signal_all: MutableMapping[str, Any], documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Bind each semantic signal occurrence to explicit Stage 1 references without deduplication."""
+
+ explicit_signal_ids = _collect_values_for_keys(
+ documents,
+ frozenset({"signal_id", "signal_ids", "signal_refs", "emitted_signal_ids", "required_signal_ids"}),
+ )
+ known_refs = {
+ "fact_id": _collect_values_for_keys(documents.get("fact_ledger_base"), frozenset({"fact_id"})),
+ "source_bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "source_bo_id", "source_bo_ids"})),
+ "bo_id": _collect_values_for_keys(documents, frozenset({"BO_ID", "bo_id"})),
+ "structure_id": _collect_values_for_keys(documents.get("legal_effect_structures"), frozenset({"structure_id"})),
+ "domain_id": _collect_values_for_keys(documents, frozenset({"domain_id", "domain_ids", "active_domain_ids"})),
+ "evidence_id": _collect_values_for_keys(documents.get("evidence_indexed"), frozenset({"evidence_index", "evidence_id", "id"})),
+ "event_id": _collect_values_for_keys(documents.get("evidence_event_candidates"), frozenset({"candidate_id", "event_id", "id"})),
+ }
+ link_keys = {
+ "fact_id": ("fact_id", "fact_ids", "source_fact_ids"),
+ "source_bo_id": ("source_bo_id", "source_bo_ids"),
+ "bo_id": ("bo_id", "bo_ids"),
+ "structure_id": ("structure_id", "structure_ids"),
+ "domain_id": ("domain_id", "domain_ids"),
+ "evidence_id": ("evidence_index", "evidence_id", "evidence_ids", "evidence_refs", "source_evidence_indexes"),
+ "event_id": ("candidate_id", "event_id", "event_ids", "source_event_candidate_ids"),
+ }
+ for occurrence in signal_all.get("record_occurrences", []):
+ signal_id = occurrence.get("signal_id")
+ record = occurrence.get("record")
+ bindings: set[str] = set()
+ if isinstance(signal_id, str) and signal_id in explicit_signal_ids:
+ bindings.add(f"signal_id:{signal_id}")
+ for ref_kind, candidate_keys in link_keys.items():
+ observed = _collect_values_for_keys(record, frozenset(candidate_keys))
+ for ref in sorted(observed & known_refs[ref_kind]):
+ bindings.add(f"{ref_kind}:{ref}")
+ if not isinstance(signal_id, str) or not signal_id:
+ occurrence["disposition"] = "UNMAPPED"
+ elif bindings:
+ occurrence["disposition"] = "USED"
+ else:
+ occurrence["disposition"] = "UNUSED"
+ occurrence["binding_refs"] = sorted(bindings)
+ for disposition, key in (
+ ("USED", "used_record_occurrences"),
+ ("UNUSED", "unused_record_occurrences"),
+ ("UNMAPPED", "unmapped_record_occurrences"),
+ ):
+ signal_all[key] = [
+ row for row in signal_all.get("record_occurrences", []) if row.get("disposition") == disposition
+ ]
+ source_counter = Counter(tuple(row["occurrence_key"]) for row in signal_all.get("record_occurrences", []))
+ partition_counter = Counter(
+ tuple(row["occurrence_key"])
+ for key in ("used_record_occurrences", "unused_record_occurrences", "unmapped_record_occurrences")
+ for row in signal_all[key]
+ )
+ signal_all["record_conservation_pass"] = source_counter == partition_counter
+ return dict(signal_all)
+
+
+ def _activation_payload(value: Mapping[str, Any]) -> Mapping[str, Any]:
+ for key in ("domain_activation_manifest", "activation", "payload", "data"):
+ nested = value.get(key)
+ if isinstance(nested, dict) and any(field in nested for field in SG01_PROJECTION_FIELDS):
+ return nested
+ return value
+
+
+ def verify_activation_projection(
+ routing_activation: Mapping[str, Any],
+ signal_activation: Mapping[str, Any],
+ *,
+ routing_raw_sha256: str | None = None,
+ signal_raw_sha256: str | None = None,
+ ) -> dict[str, Any]:
+ """Compare approved semantic SG-01 projection while retaining both raw hashes."""
+
+ left = _activation_payload(routing_activation)
+ right = _activation_payload(signal_activation)
+ missing_left = [field for field in SG01_PROJECTION_FIELDS if field not in left]
+ missing_right = [field for field in SG01_PROJECTION_FIELDS if field not in right]
+ if missing_left or missing_right:
+ raise IngressError(
+ "SG01_PROJECTION_SHAPE",
+ "both activation artifacts must expose the complete approved 17-field projection",
+ details={"routing_missing": missing_left, "signal_missing": missing_right},
+ )
+
+ def project(value: Mapping[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for field in SG01_PROJECTION_FIELDS:
+ child = value[field]
+ if field in SG01_SET_FIELDS:
+ if not isinstance(child, list):
+ raise IngressError("SG01_PROJECTION_SHAPE", f"{field} must be an array")
+ child = sorted({canonical_json_bytes(item): item for item in child}.values(), key=canonical_json_bytes)
+ result[field] = child
+ return result
+
+ left_projection = project(left)
+ right_projection = project(right)
+ if left_projection != right_projection:
+ raise IngressError(
+ "SG01_SEMANTIC_DRIFT",
+ "routing activation and signal SG-01 semantic projections differ",
+ details={"routing_projection": left_projection, "signal_projection": right_projection},
+ )
+ return {
+ "status": "PASS",
+ "projection": left_projection,
+ "projection_sha256": canonical_digest(left_projection),
+ "routing_raw_sha256": routing_raw_sha256,
+ "signal_raw_sha256": signal_raw_sha256,
+ "compared_keys": list(SG01_PROJECTION_FIELDS),
+ }
+
+
+ def verify_cross_artifact_seals(
+ documents: Mapping[str, Any],
+ snapshots: Mapping[str, Snapshot],
+ deployment_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Recompute the P1 guard and current-v8 producer invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ deployment_snapshots = deployment_snapshots or {}
+ p1 = documents.get("stage1_part1_soft_gate_handoff")
+ if isinstance(p1, dict):
+ digest_guard = p1.get("digest_guard")
+ if not isinstance(digest_guard, dict):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff"]))
+ digest_guard = {}
+ elif any(key not in digest_guard for key in P1_DIGEST_KEYS):
+ issues.append(_issue("P1_SEVEN_KEY_MISSING", source_refs=["stage1_part1_soft_gate_handoff#digest_guard"]))
+ for digest_key, logical_id in P1_DIGEST_KEYS.items():
+ source = snapshots.get(logical_id) or deployment_snapshots.get(logical_id)
+ observed = source.raw_sha256 if source else None
+ expected = digest_guard.get(digest_key)
+ passed = expected is not None and observed is not None and expected == observed
+ checks.append({"check_id": f"P1:{digest_key}", "status": "PASS" if passed else "UNEVALUABLE" if source is None else "FAIL"})
+ if expected is not None and observed is not None and not passed:
+ issues.append(_issue("P1_DIGEST_MISMATCH", source_refs=[logical_id]))
+ else:
+ issues.append(_issue("P1_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part1_soft_gate_handoff"]))
+ p2 = documents.get("stage1_part2_review_handoff")
+ if p2 is not None and not isinstance(p2, dict):
+ issues.append(_issue("P2_HANDOFF_NOT_FLAT_OBJECT", source_refs=["stage1_part2_review_handoff"]))
+ for stage in (3, 4):
+ logical = f"stage1_part{stage}_review_handoff"
+ value = documents.get(logical)
+ if value is not None:
+ wrapper_present = isinstance(value, dict) and isinstance(value.get(logical), dict)
+ if not wrapper_present:
+ issues.append(_issue(f"P{stage}_WRAPPER_MISSING", source_refs=[logical]))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ for index, row in enumerate(ledger_rows):
+ if not isinstance(row, dict) or "domain_effects" not in row or "calculation_requests" not in row:
+ issues.append(_issue("CURRENT_V8_LEDGER_EXTENSION_MISSING", impact_scope="FACT", source_refs=[f"fact_ledger_base#/{index}"]))
+ return {"checks": checks, "issues": issues, "passed": not any(item["severity"] == "ERROR" for item in issues)}
+
+
+ def check_conservation(
+ documents: Mapping[str, Any],
+ *,
+ signal_all: Mapping[str, Any] | None = None,
+ normalized_reviews: Mapping[str, Any] | None = None,
+ source_snapshots: Mapping[str, Snapshot] | None = None,
+ ) -> dict[str, Any]:
+ """Independently compute core set, cardinality, and multiset invariants."""
+
+ checks: list[dict[str, Any]] = []
+ issues: list[dict[str, Any]] = []
+ source_snapshots = source_snapshots or {}
+
+ def add_check(
+ check_id: str,
+ passed: bool | None,
+ left: Sequence[Any] | Counter[Any] | None,
+ right: Sequence[Any] | Counter[Any] | None,
+ *,
+ issue_code: str,
+ impact_scope: str,
+ source_refs: Sequence[str],
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ left_counter = left if isinstance(left, Counter) else Counter(canonical_digest(value) for value in (left or []))
+ right_counter = right if isinstance(right, Counter) else Counter(canonical_digest(value) for value in (right or []))
+ row: dict[str, Any] = {
+ "check_id": check_id,
+ "status": "UNEVALUABLE" if passed is None else "PASS" if passed else "FAIL",
+ "left_count": sum(left_counter.values()) if left is not None else None,
+ "right_count": sum(right_counter.values()) if right is not None else None,
+ "left_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in left_counter.items())) if left is not None else None,
+ "right_counter_digest": canonical_digest(sorted((canonical_digest(key), count) for key, count in right_counter.items())) if right is not None else None,
+ }
+ if details:
+ row.update(details)
+ checks.append(row)
+ if passed is False:
+ issues.append(_issue(issue_code, impact_scope=impact_scope, source_refs=source_refs))
+
+ bo_rows = _array_rows(documents.get("bo"), ("business_objects", "BO", "rows", "items"))
+ ledger_rows = _array_rows(documents.get("fact_ledger_base"), ("facts", "fact_ledger", "rows", "items"))
+ bo_ids = [str(row["BO_ID"]) for row in bo_rows if isinstance(row, dict) and row.get("BO_ID") is not None]
+ source_bo_ids = [
+ str(row["source_bo_id"])
+ for row in ledger_rows
+ if isinstance(row, dict) and row.get("source_bo_id") is not None
+ ]
+ missing_bo_id_rows = [index for index, row in enumerate(bo_rows) if not isinstance(row, dict) or row.get("BO_ID") is None]
+ missing_source_bo_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("source_bo_id") is None
+ ]
+ bo_pass = (
+ not missing_bo_id_rows
+ and not missing_source_bo_rows
+ and Counter(bo_ids) == Counter(source_bo_ids)
+ )
+ add_check(
+ "BO_FACT_MULTISET",
+ bo_pass,
+ bo_ids,
+ source_bo_ids,
+ issue_code="BO_FACT_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["bo", "fact_ledger_base"],
+ details={
+ "missing_bo_id_rows": missing_bo_id_rows,
+ "missing_source_bo_id_rows": missing_source_bo_rows,
+ "duplicate_bo_ids": sorted(key for key, count in Counter(bo_ids).items() if count > 1),
+ "dangling_source_bo_ids": sorted(set(source_bo_ids) - set(bo_ids)),
+ },
+ )
+ missing_fact_id_rows = [
+ index for index, row in enumerate(ledger_rows) if not isinstance(row, dict) or row.get("fact_id") is None
+ ]
+ fact_ids = [str(row["fact_id"]) for row in ledger_rows if isinstance(row, dict) and row.get("fact_id") is not None]
+ expected_fact_ids = [f"F-{index:03d}" for index in range(1, len(ledger_rows) + 1)]
+ fact_pass = not missing_fact_id_rows and fact_ids == expected_fact_ids and len(fact_ids) == len(set(fact_ids))
+ add_check(
+ "FACT_ID_SEQUENCE",
+ fact_pass,
+ fact_ids,
+ expected_fact_ids,
+ issue_code="FACT_ID_CONSERVATION_FAILED",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_fact_id_rows": missing_fact_id_rows, "observed": fact_ids},
+ )
+ extension_missing = [
+ index
+ for index, row in enumerate(ledger_rows)
+ if not isinstance(row, dict)
+ or not isinstance(row.get("domain_effects"), dict)
+ or not isinstance(row.get("calculation_requests"), list)
+ ]
+ add_check(
+ "CURRENT_V8_LEDGER_EXTENSIONS",
+ not extension_missing,
+ list(range(len(ledger_rows))),
+ [index for index in range(len(ledger_rows)) if index not in extension_missing],
+ issue_code="CURRENT_V8_LEDGER_EXTENSION_MISSING",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base"],
+ details={"missing_row_indices": extension_missing},
+ )
+ les_rows = _array_rows(
+ documents.get("legal_effect_structures"),
+ ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ )
+ dangling_les: list[str] = []
+ les_ids: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = row.get("structure_id", row.get("legal_effect_structure_id"))
+ if structure_id is not None:
+ les_ids.append(str(structure_id))
+ refs = row.get("source_bo_ids", [])
+ if isinstance(refs, list):
+ dangling_les.extend(str(ref) for ref in refs if ref not in set(bo_ids))
+ duplicate_les_ids = sorted(key for key, count in Counter(les_ids).items() if count > 1)
+ les_pass = not dangling_les and not duplicate_les_ids and len(les_ids) == len(les_rows)
+ add_check(
+ "LES_BO_JOIN",
+ les_pass,
+ [str(row.get("structure_id", row.get("legal_effect_structure_id"))) for row in les_rows if isinstance(row, dict)],
+ les_ids,
+ issue_code="LES_BO_JOIN_FAILED",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "bo"],
+ details={"dangling_refs": sorted(dangling_les), "duplicate_structure_ids": duplicate_les_ids},
+ )
+ declared_les_count = None
+ les_document = documents.get("legal_effect_structures")
+ if isinstance(les_document, dict):
+ for key in ("declared_structure_count", "structure_count", "record_count"):
+ if isinstance(les_document.get(key), int):
+ declared_les_count = int(les_document[key])
+ break
+ declared_les_pass = None if declared_les_count is None else declared_les_count == len(les_rows)
+ add_check(
+ "LES_DECLARED_ACTUAL_COUNT",
+ declared_les_pass,
+ [None] * declared_les_count if declared_les_count is not None else None,
+ [None] * len(les_rows),
+ issue_code="LES_DECLARED_COUNT_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures"],
+ )
+ actual_domain_index: dict[str, list[str]] = defaultdict(list)
+ actual_bo_index: dict[str, list[str]] = defaultdict(list)
+ ledger_structure_refs: list[tuple[str, str, str]] = []
+ ledger_type_refs: list[tuple[str, str, str]] = []
+ actual_structure_refs: list[tuple[str, str, str]] = []
+ actual_type_refs: list[tuple[str, str, str]] = []
+ route_count_errors: list[str] = []
+ for row in les_rows:
+ if not isinstance(row, dict):
+ continue
+ structure_id = str(row.get("structure_id", row.get("legal_effect_structure_id", "MISSING")))
+ domain_id = str(row.get("domain_id", "MISSING"))
+ type_id = str(row.get("type_id", row.get("type", "MISSING")))
+ actual_domain_index[domain_id].append(structure_id)
+ source_ids = row.get("source_bo_ids", [])
+ if isinstance(source_ids, list):
+ for bo_id in source_ids:
+ actual_bo_index[str(bo_id)].append(structure_id)
+ actual_structure_refs.append((str(bo_id), domain_id, structure_id))
+ actual_type_refs.append((str(bo_id), domain_id, type_id))
+ routes = row.get("routes", [])
+ if isinstance(routes, list) and row.get("route_count", len(routes)) != len(routes):
+ route_count_errors.append(structure_id)
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ bo_id = str(row.get("source_bo_id", "MISSING"))
+ effects = row.get("domain_effects", {})
+ if not isinstance(effects, dict):
+ continue
+ for domain_id, effect in effects.items():
+ if not isinstance(effect, dict):
+ continue
+ for structure_id in effect.get("structure_ids", []) if isinstance(effect.get("structure_ids"), list) else []:
+ ledger_structure_refs.append((bo_id, str(domain_id), str(structure_id)))
+ for type_id in effect.get("type_ids", []) if isinstance(effect.get("type_ids"), list) else []:
+ ledger_type_refs.append((bo_id, str(domain_id), str(type_id)))
+ structure_index = les_document.get("structure_index", {}) if isinstance(les_document, dict) else {}
+ index_present = isinstance(structure_index, dict) and bool(structure_index)
+ index_ok = True
+ if index_present:
+ declared_by_domain = structure_index.get("by_domain_id", {})
+ declared_by_bo = structure_index.get("by_bo_id", {})
+ index_ok = (
+ isinstance(declared_by_domain, dict)
+ and isinstance(declared_by_bo, dict)
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_domain.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_domain_index.items()}
+ and {str(key): Counter(map(str, value)) for key, value in declared_by_bo.items() if isinstance(value, list)}
+ == {key: Counter(value) for key, value in actual_bo_index.items()}
+ )
+ reverse_ok = (
+ (not ledger_structure_refs or Counter(ledger_structure_refs) == Counter(actual_structure_refs))
+ and (not ledger_type_refs or Counter(ledger_type_refs) == Counter(actual_type_refs))
+ and not route_count_errors
+ and index_ok
+ )
+ add_check(
+ "LES_REVERSE_INDEX",
+ reverse_ok,
+ ledger_structure_refs + ledger_type_refs,
+ actual_structure_refs + actual_type_refs,
+ issue_code="LES_REVERSE_INDEX_MISMATCH",
+ impact_scope="CLUSTER",
+ source_refs=["legal_effect_structures", "fact_ledger_base"],
+ details={"index_present": index_present, "route_count_errors": route_count_errors},
+ )
+ evidence_rows = _array_rows(documents.get("evidence_indexed"), ("evidence", "evidence_items", "rows", "items"))
+ event_rows = [v for _,v in _source_record_locations("evidence_event_candidates", documents.get("evidence_event_candidates"))]
+ evidence_ids = [
+ str(row.get("evidence_index", row.get("evidence_id", row.get("id"))))
+ for row in evidence_rows
+ if isinstance(row, dict) and (row.get("evidence_index") is not None or row.get("evidence_id") is not None or row.get("id") is not None)
+ ]
+ event_ids = [
+ str(row.get("candidate_id", row.get("event_id", row.get("id"))))
+ for row in event_rows
+ if isinstance(row, dict) and (row.get("candidate_id") is not None or row.get("event_id") is not None or row.get("id") is not None)
+ ]
+ fact_evidence_refs: list[str] = []
+ fact_event_refs: list[str] = []
+ event_evidence_refs: list[str] = []
+ for row in ledger_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = row.get("evidence_refs", row.get("evidence_ids", []))
+ event_values = row.get("event_refs", row.get("event_ids", []))
+ if isinstance(evidence_values, list):
+ fact_evidence_refs.extend(str(ref) for ref in evidence_values)
+ if isinstance(event_values, list):
+ fact_event_refs.extend(str(ref) for ref in event_values)
+ for row in event_rows:
+ if not isinstance(row, dict):
+ continue
+ evidence_values = [row["source_evidence_index"]] if row.get("source_evidence_index") is not None else row.get("evidence_refs", row.get("evidence_ids", []))
+ if isinstance(evidence_values, list):
+ event_evidence_refs.extend(str(ref) for ref in evidence_values)
+ evidence_failures = sorted(
+ set(fact_evidence_refs + event_evidence_refs) - set(evidence_ids)
+ )
+ duplicate_evidence_ids = sorted(key for key, count in Counter(evidence_ids).items() if count > 1)
+ evidence_pass = not evidence_failures and not duplicate_evidence_ids and len(evidence_ids)==len(evidence_rows)
+ add_check(
+ "EVIDENCE_REFERENCE_CONSERVATION",
+ evidence_pass,
+ fact_evidence_refs + event_evidence_refs,
+ evidence_ids,
+ issue_code="EVIDENCE_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_indexed", "fact_ledger_base", "evidence_event_candidates"],
+ details={"dangling_refs": evidence_failures, "duplicate_evidence_ids": duplicate_evidence_ids},
+ )
+ for bo in bo_rows:
+ if isinstance(bo,dict) and isinstance(bo.get('provenance'),dict):
+ refs=bo['provenance'].get('source_event_candidate_ids',[])
+ if isinstance(refs,list):fact_event_refs.extend(str(v) for v in refs)
+ event_failures = sorted(set(fact_event_refs) - set(event_ids))
+ duplicate_event_ids = sorted(key for key, count in Counter(event_ids).items() if count > 1)
+ event_pass = not event_failures and not duplicate_event_ids and len(event_ids)==len(event_rows)
+ add_check(
+ "EVENT_REFERENCE_CONSERVATION",
+ event_pass,
+ fact_event_refs,
+ event_ids,
+ issue_code="EVENT_REFERENCE_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "fact_ledger_base"],
+ details={"dangling_refs": event_failures, "duplicate_event_ids": duplicate_event_ids},
+ )
+ # B2 seals evidence-item and event-candidate counts, not a disposition enum.
+ b2_counts=documents.get('b2_event_candidates_gate', {})
+ b2_counts=b2_counts.get('conservation') if isinstance(b2_counts,dict) else None
+ event_document=documents.get('evidence_event_candidates')
+ if isinstance(b2_counts,dict):
+ item_count=len(event_document['items']) if isinstance(event_document,dict) and isinstance(event_document.get('items'),list) else len(event_rows)
+ passed=b2_counts.get('final_candidates')==len(event_rows) and b2_counts.get('final_items')==item_count
+ add_check('B2_EVENT_CANDIDATE_COUNT',passed,[item_count,len(event_rows)],[b2_counts.get('final_items'),b2_counts.get('final_candidates')],issue_code='B2_EVENT_CANDIDATE_COUNT_MISMATCH',impact_scope='EVIDENCE',source_refs=['evidence_event_candidates','b2_event_candidates_gate'])
+ disposition_rows = [row.get("disposition") for row in event_rows if isinstance(row, dict) and "disposition" in row]
+ b2_gate = documents.get("b2_event_candidates_gate")
+ declared_dispositions = None
+ if isinstance(b2_gate, dict):
+ declared_dispositions = b2_gate.get("event_disposition_counts")
+ if declared_dispositions is None and isinstance(b2_gate.get("summary"), dict):
+ declared_dispositions = b2_gate["summary"].get("event_disposition_counts")
+ if isinstance(declared_dispositions, dict):
+ disposition_expected = Counter(
+ {str(key): int(value) for key, value in declared_dispositions.items() if isinstance(value, int)}
+ )
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass: bool | None = disposition_actual == disposition_expected
+ elif disposition_rows:
+ disposition_expected = Counter(str(value) for value in disposition_rows)
+ disposition_actual = Counter(str(value) for value in disposition_rows)
+ disposition_pass = all(isinstance(value, str) and value for value in disposition_rows)
+ else:
+ disposition_expected = Counter()
+ disposition_actual = Counter()
+ disposition_pass = None
+ add_check(
+ "EVENT_DISPOSITION_CONSERVATION",
+ disposition_pass,
+ disposition_actual,
+ disposition_expected,
+ issue_code="EVENT_DISPOSITION_CONSERVATION_FAILED",
+ impact_scope="EVIDENCE",
+ source_refs=["evidence_event_candidates", "b2_event_candidates_gate"],
+ )
+ writer_report = documents.get("fact_ledger_writer_report")
+ if isinstance(writer_report, dict):
+ observed_domain_coverage = Counter(
+ str(domain_id)
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("domain_effects"), dict)
+ for domain_id in row["domain_effects"]
+ )
+ declared_domain_coverage = Counter(
+ {str(key): int(value) for key, value in writer_report.get("domain_effect_coverage", {}).items() if isinstance(value, int)}
+ )
+ observed_readiness = Counter(
+ str(request.get("operand_state"))
+ for row in ledger_rows
+ if isinstance(row, dict) and isinstance(row.get("calculation_requests"), list)
+ for request in row["calculation_requests"]
+ if isinstance(request, dict)
+ )
+ declared_readiness = Counter(
+ {str(key): int(value) for key, value in writer_report.get("calculation_readiness", {}).items() if isinstance(value, int)}
+ )
+ ledger_snapshot = source_snapshots.get("fact_ledger_base")
+ final_hash = writer_report.get("final_sha256")
+ writer_pass = (
+ writer_report.get("row_count") == len(ledger_rows)
+ and declared_domain_coverage == observed_domain_coverage
+ and declared_readiness == observed_readiness
+ and (ledger_snapshot is None or final_hash == ledger_snapshot.raw_sha256)
+ )
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ writer_pass,
+ [len(ledger_rows), observed_domain_coverage, observed_readiness, ledger_snapshot.raw_sha256 if ledger_snapshot else None],
+ [writer_report.get("row_count"), declared_domain_coverage, declared_readiness, final_hash],
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ else:
+ add_check(
+ "FACT_LEDGER_WRITER_REPORT_CONNECTION",
+ None,
+ None,
+ None,
+ issue_code="FACT_LEDGER_WRITER_REPORT_MISMATCH",
+ impact_scope="FACT",
+ source_refs=["fact_ledger_base", "fact_ledger_writer_report"],
+ )
+ if signal_all is not None:
+ file_pass = bool(signal_all.get("file_conservation_pass"))
+ record_pass = bool(signal_all.get("record_conservation_pass"))
+ checks.append({"check_id": "SIGNAL_FILE_ROW_CONSERVATION", "status": "PASS" if file_pass else "FAIL"})
+ checks.append({"check_id": "SIGNAL_RECORD_OCCURRENCE_CONSERVATION", "status": "PASS" if record_pass else "FAIL"})
+ issues.extend(signal_all.get("issues", []))
+ if not file_pass:
+ issues.append(_issue("SIGNAL_FILE_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if not record_pass:
+ issues.append(_issue("SIGNAL_RECORD_CONSERVATION_FAILED", impact_scope="SIGNAL"))
+ if normalized_reviews is not None:
+ review_pass = normalized_reviews.get("conservation_status") == "PASS"
+ checks.append({"check_id": "REVIEW_OCCURRENCE_CONSERVATION", "status": "PASS" if review_pass else "FAIL"})
+ if not review_pass:
+ issues.append(_issue("REVIEW_CONSERVATION_FAILED", impact_scope="REVIEW_ITEM"))
+ issues.extend(normalized_reviews.get("_issues", []))
+ return {"checks": checks, "issues": issues, "passed": not any(check["status"] == "FAIL" for check in checks)}
+
+
+ def _source_ref(
+ logical_id: str,
+ pointer: str,
+ raw_value: Any = _RAW_VALUE_UNSET,
+ *,
+ stage1_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Build a truthful RFC 6901 provenance row without pointer narrowing."""
+
+ row: dict[str, Any] = {
+ "logical_artifact_id": logical_id,
+ "json_pointer": pointer,
+ "raw_value_sha256": canonical_digest(
+ [logical_id, pointer]
+ if raw_value is _RAW_VALUE_UNSET
+ else raw_value
+ ),
+ "source_contract_row_ref": logical_id,
+ }
+ if stage1_id is not None:
+ row["stage1_id"] = stage1_id
+ return row
+
+
+ def _tarjan_scc(nodes: Sequence[str], edges: Sequence[tuple[str, str]]) -> list[list[str]]:
+ adjacency: dict[str, list[str]] = {node: [] for node in nodes}
+ for source, target in edges:
+ adjacency.setdefault(source, []).append(target)
+ adjacency.setdefault(target, [])
+ for value in adjacency.values():
+ value.sort()
+ index = 0
+ stack: list[str] = []
+ on_stack: set[str] = set()
+ indices: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ components: list[list[str]] = []
+
+ def visit(node: str) -> None:
+ nonlocal index
+ indices[node] = index
+ lowlink[node] = index
+ index += 1
+ stack.append(node)
+ on_stack.add(node)
+ for neighbor in adjacency[node]:
+ if neighbor not in indices:
+ visit(neighbor)
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
+ elif neighbor in on_stack:
+ lowlink[node] = min(lowlink[node], indices[neighbor])
+ if lowlink[node] == indices[node]:
+ component: list[str] = []
+ while True:
+ member = stack.pop()
+ on_stack.remove(member)
+ component.append(member)
+ if member == node:
+ break
+ components.append(sorted(component))
+
+ for node in sorted(adjacency):
+ if node not in indices:
+ visit(node)
+ return sorted(components, key=lambda component: component[0])
+
+
+ def _inline_sha256(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
+ raise IngressError(code, "expected one lowercase SHA-256 digest")
+ return value
+
+
+ def _inline_relative_path(value: str, *, code: str) -> str:
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
+ raise IngressError(code, "logical path is empty or malformed")
+ if unicodedata.normalize("NFC", value) != value:
+ raise IngressError(code, "logical path must already be NFC")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
+ raise IngressError(code, "logical path must be a contained relative path")
+ rendered = path.as_posix()
+ if rendered != value:
+ raise IngressError(code, "logical path is not canonical")
+ return rendered
+
+
+ def _inline_parse_mcp_payload(raw: bytes, expected_id: int) -> Mapping[str, Any]:
+ """Parse one JSON or SSE JSON-RPC terminal response with an exact ID."""
+
+ candidates: list[Any]
+ try:
+ candidates = [load_json_strict(raw)]
+ except IngressError:
+ try:
+ text = raw.decode("utf-8", errors="strict")
+ except UnicodeDecodeError as exc:
+ raise IngressError("MCP_RESPONSE_UTF8", "MCP response is not strict UTF-8") from exc
+ events: list[bytes] = []
+ data_lines: list[str] = []
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ if line == "":
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ data_lines = []
+ continue
+ if line.startswith(":") or line.startswith("event:") or line.startswith("id:") or line.startswith("retry:"):
+ continue
+ if not line.startswith("data:"):
+ raise IngressError("MCP_SSE_SHAPE", "unexpected non-data SSE line")
+ payload = line[5:]
+ if payload.startswith(" "):
+ payload = payload[1:]
+ data_lines.append(payload)
+ if data_lines:
+ events.append("\n".join(data_lines).encode("utf-8"))
+ if not events:
+ raise IngressError("MCP_RESPONSE_SHAPE", "MCP response contains no JSON terminal event")
+ candidates = [load_json_strict(event) for event in events]
+ matching = [
+ item
+ for item in candidates
+ if isinstance(item, dict) and item.get("id") == expected_id
+ ]
+ if len(matching) != 1:
+ raise IngressError(
+ "MCP_RESPONSE_ID_MISMATCH",
+ "MCP response must contain exactly one terminal result with the JSON-RPC message ID",
+ )
+ response = matching[0]
+ if response.get("jsonrpc") != "2.0":
+ raise IngressError("MCP_JSONRPC_VERSION", "MCP response jsonrpc must equal 2.0")
+ if response.get("error") is not None:
+ raise IngressError(
+ "MCP_JSONRPC_ERROR",
+ "MCP server returned a JSON-RPC error",
+ details={"rpc_error": response.get("error")},
+ )
+ if "result" not in response or not isinstance(response["result"], dict):
+ raise IngressError("MCP_RESULT_SHAPE", "MCP response result must be an object")
+ return response
+
+
+ def _inline_tool_text(result: Mapping[str, Any], tool_name: str, logical_path: str | None = None) -> str:
+ """Handle both MCP isError and Localdocs' returned plain-text errors."""
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1:
+ raise IngressError("MCP_CONTENT_CARDINALITY", "MCP tool result must contain exactly one content block")
+ block = content[0]
+ if not isinstance(block, dict) or block.get("type") != "text" or not isinstance(block.get("text"), str):
+ raise IngressError("MCP_CONTENT_SHAPE", "MCP tool result must contain one text block")
+ text = block["text"]
+ stripped = text.strip()
+ # Localdocs returns error strings as normal tool results (isError=false).
+ # Recognize only error prefixes; never inspect JSON/source contents for markers.
+ plain_error = re.match(r"^Error(?:\s+[^:\n]+)?:", stripped, re.IGNORECASE) is not None
+ if result.get("isError") is True or plain_error:
+ missing = re.match(r"^Error:\s*(?:Document|File) not found:\s*(.+)$", stripped, re.IGNORECASE)
+ if missing and logical_path is not None and missing.group(1) != logical_path:
+ raise IngressError("LOCALDOCS_ERROR_PATH_MISMATCH", "missing-file response names another path", details={"tool": tool_name, "path": logical_path})
+ flagged_missing = result.get("isError") is True and stripped.lower() in {"not found", "no such file", "does not exist"}
+ code = "LOCALDOCS_NOT_FOUND" if missing or flagged_missing else "MCP_TOOL_ERROR"
+ details = {"tool": tool_name}
+ if logical_path is not None:
+ details["path"] = logical_path
+ raise IngressError(code, f"localdocs {tool_name} reported a tool failure", details=details)
+ if not stripped:
+ raise IngressError("MCP_TOOL_EMPTY", "localdocs returned an empty text result", details={"tool": tool_name, "path": logical_path})
+ return text
+
+
+ def _inline_binary_envelope(text: str, logical_path: str) -> bytes:
+ try:
+ value = load_json_strict(text)
+ except IngressError as exc:
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "read_binary_doc returned an invalid JSON envelope", details={"tool": "read_binary_doc", "path": logical_path, "cause": exc.code}) from exc
+ if isinstance(value, dict) and "results" in value:
+ results = value.get("results")
+ if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
+ raise IngressError("LOCALDOCS_RESULT_CARDINALITY", "binary response must contain one result row")
+ inner: Any = results[0].get("content", results[0].get("text"))
+ value = load_json_strict(inner) if isinstance(inner, str) else inner
+ if not isinstance(value, dict) or not isinstance(value.get("content_base64"), str):
+ raise IngressError("LOCALDOCS_BINARY_ENVELOPE", "binary response lacks content_base64")
+ try:
+ payload = base64.b64decode(value["content_base64"].encode("ascii"), validate=True)
+ except (UnicodeEncodeError, binascii.Error, ValueError) as exc:
+ raise IngressError("LOCALDOCS_BASE64_INVALID", "binary response is not strict base64") from exc
+ declared_size = value.get("byte_length", value.get("size"))
+ if declared_size is not None and (not isinstance(declared_size, int) or declared_size != len(payload)):
+ raise IngressError("LOCALDOCS_BYTE_LENGTH_MISMATCH", f"binary length mismatch: {logical_path}")
+ declared_hash = value.get("sha256")
+ if declared_hash is not None and declared_hash != hashlib.sha256(payload).hexdigest():
+ raise IngressError("LOCALDOCS_HASH_MISMATCH", f"binary hash mismatch: {logical_path}")
+ return payload
+
+
+ class _InlineLocaldocs:
+ """Minimal user/workspace-bound localdocs JSON-RPC client."""
+
+ def __init__(
+ self,
+ user_hash: str,
+ workspace_hash: str,
+ *,
+ client: Any | None = None,
+ timeout_seconds: int = 60,
+ ) -> None:
+ self.user_hash = _context_hash(user_hash, "__user_hash__")
+ self.workspace_hash = _context_hash(workspace_hash, "__workspace_hash__")
+ if client is None:
+ try:
+ import httpx # type: ignore
+ except ImportError as exc:
+ raise IngressError("HTTPX_UNAVAILABLE", "Code Executor must supply httpx==0.28.1") from exc
+ client = httpx.Client(timeout=timeout_seconds)
+ self.client = client
+ self.headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ self._message_ids = itertools.count(10)
+ self._initialized = False
+ self._session_id: str | None = None
+
+ def close(self) -> None:
+ close = getattr(self.client, "close", None)
+ if callable(close):
+ close()
+
+ def _post(self, body: Mapping[str, Any], expected_id: int | None) -> Mapping[str, Any] | None:
+ try:
+ response = self.client.post(LOCALDOCS_URL, json=dict(body), headers=dict(self.headers))
+ response.raise_for_status()
+ except Exception as exc:
+ raise IngressError("MCP_TRANSPORT_ERROR", "localdocs transport failed") from exc
+ session_id = response.headers.get("mcp-session-id")
+ if session_id:
+ if not isinstance(session_id, str) or not session_id.strip():
+ raise IngressError("MCP_SESSION_ID_INVALID", "localdocs returned an invalid session ID")
+ normalized_session_id = session_id.strip()
+ if self._session_id is None:
+ if expected_id != 1:
+ raise IngressError(
+ "MCP_SESSION_ID_OUTSIDE_INITIALIZE",
+ "localdocs first bound a session outside initialize",
+ )
+ self._session_id = normalized_session_id
+ elif normalized_session_id != self._session_id:
+ raise IngressError(
+ "MCP_SESSION_ID_CHANGED",
+ "localdocs changed the initialized session ID",
+ )
+ self.headers["mcp-session-id"] = self._session_id
+ if expected_id is None:
+ return None
+ raw = response.content if isinstance(response.content, bytes) else bytes(response.content)
+ return _inline_parse_mcp_payload(raw, expected_id)
+
+ def initialize(self) -> None:
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {
+ "name": INLINE_CLIENT_NAME,
+ "version": INLINE_CLIENT_VERSION,
+ "user_id": self.user_hash,
+ "workspace_id": self.workspace_hash,
+ },
+ },
+ },
+ 1,
+ )
+ if response is None:
+ raise IngressError("MCP_INITIALIZE_EMPTY", "localdocs initialize returned no result")
+ result = response.get("result")
+ if not isinstance(result, dict) or result.get("protocolVersion") != MCP_PROTOCOL_VERSION:
+ raise IngressError(
+ "MCP_PROTOCOL_VERSION_MISMATCH",
+ "localdocs did not negotiate the requested MCP protocol version",
+ )
+ if self._session_id is None or "mcp-session-id" not in self.headers:
+ raise IngressError("MCP_SESSION_ID_MISSING", "localdocs initialize did not bind a session ID")
+ self._post(
+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
+ None,
+ )
+ self._initialized = True
+
+ def call(self, tool_name: str, arguments: Mapping[str, Any]) -> Mapping[str, Any]:
+ if not self._initialized:
+ raise IngressError("MCP_NOT_INITIALIZED", "localdocs session is not initialized")
+ message_id = next(self._message_ids)
+ response = self._post(
+ {
+ "jsonrpc": "2.0",
+ "id": message_id,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": dict(arguments)},
+ },
+ message_id,
+ )
+ if response is None:
+ raise IngressError("MCP_TOOL_EMPTY", f"localdocs {tool_name} returned no result")
+ return response["result"]
+
+ def read_binary(self, logical_path: str) -> bytes:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_READ_PATH_INVALID")
+ result = self.call("read_binary_doc", {"doc_name": path})
+ return _inline_binary_envelope(_inline_tool_text(result, "read_binary_doc", path), path)
+
+ def read_binary_optional(self, logical_path: str) -> bytes | None:
+ try:
+ return self.read_binary(logical_path)
+ except IngressError as exc:
+ if exc.code == "LOCALDOCS_NOT_FOUND":
+ return None
+ raise
+
+ def write_binary_verified(self, logical_path: str, payload: bytes, *, overwrite: bool = False) -> str:
+ path = _inline_relative_path(logical_path, code="LOCALDOCS_WRITE_PATH_INVALID")
+ encoded = base64.b64encode(payload).decode("ascii")
+ result = self.call(
+ "write_binary_file",
+ {"path": path, "content_base64": encoded, "overwrite": overwrite},
+ )
+ _inline_tool_text(result, "write_binary_file", path)
+ observed = self.read_binary(path)
+ if observed != payload:
+ raise IngressError("LOCALDOCS_WRITE_READBACK_MISMATCH", f"read-back mismatch: {path}")
+ return hashlib.sha256(observed).hexdigest()
+
+
+ SOURCE_POLICY = load_json_strict(r'''{"stage1_sources":[{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","logical_input_id":"evidence_indexed","path":"evidence_indexed.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B1_quality_gate_evidence_indexed","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","logical_input_id":"evidence_event_candidates","path":"evidence_event_candidates.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_quality_gate_event_candidates","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","items"],"requirement_class":"EVIDENCE_EVENT_SCOPE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-CLIENT-GOAL-V8-V1","logical_input_id":"client_goal","path":"client_goal.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A_client_goal","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["primary_goal","constraints","parties"],"requirement_class":"OPTIMIZATION_CONTEXT","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DOMAIN-SCREENING-V1","logical_input_id":"domain_screening","path":"routing/domain_screening.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_A0_domain_screener_02","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_screening"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-DUAL-SG01-V1","logical_input_id":"domain_activation_manifest","path":"routing/domain_activation_manifest.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_D0_domain_activation_gate","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["domain_activation_manifest"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","path":"signals/schemas/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a"},"transaction_identity_pointer":null},{"adapter_id":"S2A-B1-GATE-V1","logical_input_id":"b1_evidence_indexed_gate","path":"quality_gates/B1_evidence_indexed_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-B2-GATE-V1","logical_input_id":"b2_event_candidates_gate","path":"quality_gates/B2_event_candidates_gate.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B12_gate_audit_finalizer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_contract_version","gate_id","overall_severity","hard_gate_findings","review_findings","stage2_auto_progression_allowed"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","logical_input_id":"stage1_part1_soft_gate_handoff","path":"quality_gates/stage1_part1_soft_gate_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_B2_SHA256_soft_gate_handoff_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","handoff_status","review_items","stage2_auto_progression_allowed","hard_gate_summary","review_item_conservation","digest_guard"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-BO-V8-LIST-V1","logical_input_id":"bo","path":"BO.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_manifest","path":"signals/signal_manifest.json","path_rule":null,"producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["files","downstream_read_sets"],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","path":"signals/schemas/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681"},"transaction_identity_pointer":"/transaction_id"},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","logical_input_id":"stage1_part2_review_handoff","path":"quality_gates/stage1_part2_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version","status","review_items"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-LES-CURRENT-V8-V1","logical_input_id":"legal_effect_structures","path":"legal_effect_structures.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"ROUTING_PROFILE_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","path":"platform/schemas/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df"},"transaction_identity_pointer":"/signal_manifest_transaction_id"},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part3_review_handoff","path":"quality_gates/stage1_part3_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_LE_L2_final_structure_index_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part3_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","logical_input_id":"fact_ledger_base","path":"Fact_Ledger_base.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":[],"requirement_class":"IDENTITY_BACKBONE","run_identity_pointer":null,"schema_ref":{"$id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","path":"platform/schemas/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8"},"transaction_identity_pointer":null},{"adapter_id":"S2A-FACT-LEDGER-WRITER-REPORT-V1","logical_input_id":"fact_ledger_writer_report","path":"stage1_tmp/fact_ledger/fact_ledger_writer_report.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["schema_version"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","logical_input_id":"stage1_part4_review_handoff","path":"quality_gates/stage1_part4_review_handoff.json","path_rule":null,"producer_alias_id":null,"producer_id":"Task_C_FL_F2_final_fact_ledger_gate_and_writer","raw_hash_source":"UNAVAILABLE_DEV","required_keys":["stage1_part4_review_handoff"],"requirement_class":"INTEGRITY_CORROBORATOR","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null},{"adapter_id":"S2A-SIGNAL-ALL-V1","logical_input_id":"signal_payload_family","path":null,"path_rule":"signals/","producer_alias_id":"PA-SG-COMPILER-001","producer_id":"Task_C_BO_S0_signal_bundle_writer","raw_hash_source":"MANIFEST_ROW","required_keys":[],"requirement_class":"SIGNAL_PAYLOAD","run_identity_pointer":null,"schema_ref":null,"transaction_identity_pointer":null}],"dependency_locks":{"stage1":{"closure_scope":"REFERENCED_55_ONLY_NOT_FULL_STAGE1_RUNTIME_RELEASE","closure_snapshot_date":"2026-08-29","concrete_paths":[{"binding_status":"BOUND","lock_id":"S1-DEPLOY-001","path":"runtime_manifest.json","schema_id":"stage1_runtime_manifest.v1","sha256":"8964593a64a9b1bc90122054bb09eb3911827a06ed62dab0d6b7c745e7e18f54","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-002","path":"domains/_registry_index.json","schema_id":null,"sha256":"9f177ebf8860e20e05483967a2037f3baa09c2ac92c69ddeb260c04ca31ebf39","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-003","path":"signals/signal_registry.v2.json","schema_id":"signal_registry.v2","sha256":"4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-004","path":"domains/E-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5919f7ea1d7be02666b0c48aa6a66445e6d454fc2fbb21d7fe5154b0a1e68f6f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-005","path":"domains/E-01/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"b557e92cd1b093bf31792dbcf5b62cab8ad064a65c4421e79f141e06b4cc2192","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-006","path":"domains/E-02/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"be407c980c28226a15406f85b5861b04a4e19a13870513ac6626349fc05ac434","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-007","path":"domains/E-03/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7d3814f9b50cd5b33ef65a4eb778693552b3685bd369e765e9ac032734ebe23e","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-008","path":"domains/E-04/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"95a8c600cdce5a687f766788af0f763ee1b6a895e6ed80934afd28fe9a107e25","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-009","path":"domains/E-05/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e50541018f47aa27de2f8b13ec3fa52210cf8456a6feed8356af78c1f1da144a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-010","path":"domains/E-06/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"1e2bee36cb3c24dd37fc3beb3cf70236d531126c4f62ee97b5b42e55f4b0745c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-011","path":"domains/E-07/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"22ac562084b1ce231b7257d099c18b6a4619defa2fc42504d590e0bcc494c5f8","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-012","path":"domains/E-08/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"4d545306d42120e8552dd953d4336ef6de828ea827779944ba73acfda3d3a8bb","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-013","path":"domains/E-09/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7ef7340750094efeb372c397eb3134e21d62dda6988b1f6fa0a197b9963868e0","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-014","path":"domains/E-10/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e8d4f45fa76ea9e09333256dd4ea36cd3dd963bf60c04814a2cb8dc90d152f0a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-015","path":"domains/E-11/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eb78d0188a0a2400307b1c34c8f8703c54cd86dd06b942c1709c44a8630a68e1","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-016","path":"domains/E-12/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"f336accdc6de10cdcc28c1190328054bca402fb77a2a9859d59fbaf5e84dd170","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-017","path":"domains/E-13/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"e27e2e3855b5868a3ec12c7093b872434702f2e465b73c0bfc948b516aa0fc35","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-018","path":"domains/E-14/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"a273148cc17f07d90cda500fa5cb7df30c9cd253f7b86048cf4f63495d36a156","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-019","path":"domains/E-15/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"7f37edddc101a08ed8a0e25f3a2c638e72571edc212ac91d96c1e33c51202a69","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-020","path":"domains/E-16/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"ae9af46ee31b6ef0dafedd35ccd7959a941d67d1a3dcc70e0b13647896873323","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-021","path":"domains/E-17/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"5c61f4486bdc968e4b30734b3c045404f0a711f47ea3abbe6c5c64652fb7f68c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-022","path":"domains/E-18/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"74ff76148d175929bdeeeced77e9a9922d29b51ad3d00ae6711c43c55717692c","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-023","path":"domains/E-19/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"a8578f54a3fead3bbd35c62d7199b0f8aafb77f5d409a87236a55d2550fbfd37","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-024","path":"domains/E-20/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"29ee14cfe7789f004e6b6978d5360cf1bebe33bf88715df0cb47257993a11d00","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-025","path":"domains/E-21/domain_config.json","schema_id":"stage1_domain_config.v2","sha256":"4e1684a843d9e0c5af82f45332ad85abe94eda0c3ff0d578235d892aee39b908","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-026","path":"domains/EC-00/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"fe74de112b73289485dcead7e0fc7d270c794b3cf8a29ee00fab1eb64ba13861","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-027","path":"domains/X1/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"ad2fee7d206018f9a1f66e5fdf40dd67b686f6938099bad1ffc5d538db14ac57","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-028","path":"domains/X2/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"eba7d4671546bd66f1350d144ae0884f8beffb0dffdc147b45b9d5292676d46f","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-029","path":"domains/X3/domain_config.json","schema_id":"stage1_domain_config.v1","sha256":"8b67a638ae4a86aca3a2216974242b11ec39790162c9f366edfa91b02c3d270a","source_manifest":"domains/_registry_index.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-030","path":"platform/schemas/client_goal_domain_profiles.schema.json","schema_id":null,"sha256":"ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-031","path":"platform/schemas/domain_fanout_plan.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_fanout_plan.schema.json","sha256":"3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-032","path":"platform/schemas/domain_seed_output.schema.v3.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_seed_output.schema.v3.json","sha256":"992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-033","path":"platform/schemas/domain_slice.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s1/domain_slice.schema.v2.json","sha256":"212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-034","path":"platform/schemas/fact_exception_pack.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_exception_pack.schema.json","sha256":"4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-035","path":"platform/schemas/fact_ledger_base.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_base.schema.json","sha256":"b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-036","path":"platform/schemas/fact_ledger_candidate_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part4/fact_ledger_candidate_bundle.schema.json","sha256":"4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-037","path":"platform/schemas/legal_effect_structures.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/legal_effect_structures.schema.json","sha256":"fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-038","path":"platform/schemas/structure_seed_bundle.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/part3/structure_seed_bundle.schema.json","sha256":"b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a","source_manifest":"runtime_manifest.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-039","path":"signals/_common/evidence_slot_status.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_slot_status.schema.json","sha256":"292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-040","path":"signals/_common/signal_item.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_item.schema.json","sha256":"de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-041","path":"signals/schemas/domain_activation_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_activation_manifest.schema.json","sha256":"013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-042","path":"signals/schemas/procedural_posture_relief_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/procedural_posture_relief_signals.schema.json","sha256":"fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-043","path":"signals/schemas/party_capacity_standing_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/party_capacity_standing_signals.schema.json","sha256":"66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-044","path":"signals/schemas/governing_law_version_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/governing_law_version_signals.schema.json","sha256":"13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-045","path":"signals/schemas/legal_relation_lifecycle_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_relation_lifecycle_signals.schema.json","sha256":"420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-046","path":"signals/schemas/timeline_notice_condition_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/timeline_notice_condition_signals.schema.json","sha256":"99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-047","path":"signals/schemas/asset_right_state_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/asset_right_state_signals.schema.json","sha256":"fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-048","path":"signals/schemas/liability_causation_damage_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/liability_causation_damage_signals.schema.json","sha256":"34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-049","path":"signals/schemas/defense_exception_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/defense_exception_signals.schema.json","sha256":"010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-050","path":"signals/schemas/evidence_proof_conflict_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/evidence_proof_conflict_signals.schema.json","sha256":"c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-051","path":"signals/schemas/calculation_requirements.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/calculation_requirements.schema.json","sha256":"7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-052","path":"signals/schemas/remedy_enforcement_signals.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/remedy_enforcement_signals.schema.json","sha256":"999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-053","path":"signals/schemas/legal_effect_routes.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/legal_effect_routes.schema.json","sha256":"c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-054","path":"signals/schemas/domain_signal_envelope.schema.v2.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/domain_signal_envelope.schema.v2.json","sha256":"1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc","source_manifest":"signals/signal_registry.v2.json"},{"binding_status":"BOUND","lock_id":"S1-DEPLOY-055","path":"signals/schemas/signal_manifest.schema.json","schema_id":"https://schemas.liti-agent.local/stage1/s5/signal_manifest.schema.json","sha256":"5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681","source_manifest":"signals/signal_registry.v2.json"}],"contract_manifest_ref":{"mode":"CONDITIONAL_RELOCATION_ONLY","path":null,"sha256":null,"status":"NOT_REQUIRED_DEFAULT_PATHS"},"expected_concrete_path_count":55,"full_stage1_runtime_release_status":"STAGE1_NOT_RELEASE_READY"}},"adapter_decisions":[{"adapter_id":"S2A-SIGNAL-ALL-V1","decision":{"file_conservation_equation":"semantic_file_rows + integrity_only_file_rows = Counter(signal_manifest.files[])","global_signal_id_uniqueness_assumed":false,"integrity_only_kinds":["compatibility_view"],"manifest_selector":"/downstream_read_sets/stage2","physical_path_rule":"U/signals/","record_conservation_equation":"used_record_occurrences + unused_record_occurrences + unmapped_record_occurrences = records_from_semantic_files","record_occurrence_key":["manifest_transaction_id","file_path","record_ordinal","signal_id"],"row_order":"PRESERVE_MANIFEST_ORDER","row_source":"/files","semantic_kinds":["canonical","domain_signal"],"sentinel":["ALL"]}},{"adapter_id":"S2A-DUAL-SG01-V1","decision":{"comparison":"PARSED_CANONICAL_PROJECTION_EQUAL","payload_root":"/domain_activation_manifest","projection_json_pointers":["/schema_version","/signal_id","/status","/registry_version","/registry_index_sha256","/screening_sha256","/domain_entries","/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains","/unrouted_material","/conservation_gate","/fail_open_policy","/review_items","/contract_guards"],"raw_hash_policy":"PRESERVE_AND_VERIFY_SEPARATELY","routing_path":"routing/domain_activation_manifest.json","set_semantics_json_pointers":["/active_domain_ids","/supporting_domain_ids","/monitor_domain_ids","/expected_runnable_domain_ids","/required_calculation_domains"],"signal_path":"signals/domain_activation_manifest.json"}},{"adapter_id":"S2A-P1-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P1_REVIEW_HANDOFF","p1_digest_keys":["evidence_indexed_sha256","evidence_event_candidates_sha256","b1_gate_sha256","b2_gate_sha256","screening_sha256","activation_manifest_sha256","registry_index_sha256"],"review_items_json_pointer":"/review_items","schema_version":"stage1_part1_soft_gate_handoff.v1","seal_sources":["routing/domain_screening.json","routing/domain_activation_manifest.json","domains/_registry_index.json"],"source_stage":"P1","status_json_pointer":"/handoff_status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P2-HANDOFF-FLAT-V1","decision":{"count_field_required":false,"logical_input_id":"P2_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part2_review_handoff.v1","seal_sources":["BO.json","signals/signal_manifest.json"],"source_stage":"P2","status_json_pointer":"/status","wrapper_json_pointer":""}},{"adapter_id":"S2A-P3-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P3_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part3_review_handoff.v1","seal_sources":["legal_effect_structures.json","validation_assets/routing/part3_receipt.json"],"source_stage":"P3","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part3_review_handoff"}},{"adapter_id":"S2A-P4-HANDOFF-WRAPPED-V1","decision":{"count_field_required":true,"logical_input_id":"P4_REVIEW_HANDOFF","review_items_json_pointer":"/review_items","schema_version":"stage1_part4_review_handoff.v1","seal_sources":["Fact_Ledger_base.json","validation_assets/routing/part4_receipt.json","stage1_tmp/fact_ledger/fact_ledger_writer_report.json"],"source_stage":"P4","status_json_pointer":"/status","wrapper_json_pointer":"/stage1_part4_review_handoff"}},{"adapter_id":"S2-REVIEW-MAP-V1","decision":{"aggregate_handoff_status_never_resolves_item":true,"handoff_status_mappings":[{"source_stage":"P1","source_value":"READY_NO_REVIEW","technical_disposition":"AVAILABLE"},{"source_stage":"P1","source_value":"READY_WITH_REVIEW","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P1","source_value":"BLOCKED","technical_disposition":"UNAVAILABLE"},{"source_stage":"P2","source_value":"PENDING_FINALIZE","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P2","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P3","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P3","source_value":"FINALIZED","technical_disposition":"AVAILABLE"},{"source_stage":"P4","source_value":"OPEN","technical_disposition":"AVAILABLE_WITH_ISSUES"},{"source_stage":"P4","source_value":"FINALIZED","technical_disposition":"AVAILABLE"}],"mappings":[{"mapping_id":"S2RM-001","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"SUPPORTED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-002","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"CONDITIONAL","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-003","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"UNRESOLVED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-004","normalized_partition":"EXCLUDED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"EXCLUDED","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-005","normalized_partition":"SUPPORTED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"observed","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-006","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"inferred","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-007","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"contested","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-008","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"missing_required","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-009","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-010","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_STATUS","source_stage":"ANY","source_value":"NO_SUPPORT","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-011","normalized_partition":"CONDITIONAL","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"info","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-012","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"review","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-013","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"SOFT_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-014","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"hard_warning","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-015","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"HARD_WARNING","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-016","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"block","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"},{"mapping_id":"S2RM-017","normalized_partition":"UNRESOLVED","resolution_inference_allowed":false,"source_field_kind":"REVIEW_ITEM_SEVERITY","source_stage":"ANY","source_value":"BLOCK","unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}],"normalized_partitions":["SUPPORTED","CONDITIONAL","UNRESOLVED","EXCLUDED","UNMAPPED"],"resolution_inference_allowed":false,"unknown_value_policy":"MAP_TO_UNMAPPED_AND_ISSUE"}},{"adapter_id":"S2A-BO-V8-LIST-V1","decision":{"logical_input_id":"BO","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_C_BO_F0_final_bo_compiler_gate_writer","required_item_fields":["BO_ID","id","BOType","ActionType","JuristicAct","Action","Reason","PriorAct","ReasonRefs","Legal_Keywords","core_field_base","amount","EvidenceTitles","Evidence","source_evidence_indexes","provenance","downstream_seed_refs","extensions"],"required_root_fields":[],"root_shape":"ARRAY","schema_contract_version":null}},{"adapter_id":"S2A-EVIDENCE-V3-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_INDEXED","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B1_quality_gate_evidence_indexed","required_root_fields":["schema_contract_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_indexed.v3"}},{"adapter_id":"S2A-EVENTS-V1-ENVELOPE-V1","decision":{"logical_input_id":"EVIDENCE_EVENT_CANDIDATES","open_source_fields_policy":"PRESERVE_UNMODELED_FIELDS_WITH_RAW_HASH","producer_id":"Task_B2_quality_gate_event_candidates","required_root_fields":["schema_version","items"],"root_shape":"OBJECT_ENVELOPE","schema_contract_version":"evidence_event_candidates.v1"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V1","decision":{"accepted_schema_version":"stage1_domain_config.v1","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-DOMAIN-CONFIG-V2","decision":{"accepted_schema_version":"stage1_domain_config.v2","depends_on_legal_dependency_allowed":false,"rebuttal_slot_synthesis_allowed":false,"required_slot_fields":["element_slots","opposing_fact_slots","defense_map","calculation_bindings","emits_signals"],"undeclared_slot_policy":"PRESERVE_AS_PROPOSED_NEW_SLOT_ISSUE"}},{"adapter_id":"S2A-FACT-LEDGER-CURRENT-V8-V1","decision":{"bo_source_bo_id_multiset_equality_required":true,"fact_id_pattern":"^F-[0-9]{3,}$","legacy_adapter_status":"DISABLED_NO_APPROVED_ADAPTER","producer_generation":"CURRENT_V8","required_row_fields":["fact_id","source_bo_id","domain_effects","calculation_requests"],"root_shape":"ARRAY"}},{"adapter_id":"PA-SG-COMPILER-001","decision":{"bidirectional_match_allowed":true,"global_alias_allowed":false,"orchestration_producer_id":"Task_C_BO_S0_signal_bundle_writer","schema_writer_id":"Task_C_BO_S0_canonical_signal_compiler","scope":"STAGE1_PART2_SIGNAL_TRANSACTION_ONLY"}}],"release_class":"DEV_FIXTURE_RELEASE","limits":{"max_file_bytes":33554432,"max_run_bytes":268435456,"max_json_depth":96,"max_json_items":1000000}}''')
+
+
+
+
+ STATUS_PATH = "ingress/ingress_status.json"
+ NORMAL_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "context/case_context.json", STATUS_PATH})
+ BLOCKED_PATHS = frozenset({"ingress/stage1_input_manifest.json", "ingress/intake_report.json", "review/issue_ledger.base.json", "ingress/technical_diagnostic.json", STATUS_PATH})
+ ROW_KEYS = {
+ "bo": ("business_objects", "BO", "rows", "items"),
+ "fact_ledger_base": ("facts", "fact_ledger", "rows", "items"),
+ "legal_effect_structures": ("structures", "structure_records", "legal_effect_structures", "rows", "items"),
+ "evidence_indexed": ("evidence", "evidence_items", "rows", "items"),
+ "evidence_event_candidates": ("events", "event_candidates", "rows", "items"),
+ }
+ WRAPPER_KEYS = ("payload", "data", "fact_ledger_base", "Fact_Ledger_base", "legal_effect_structures")
+ REVIEW_ARRAY_KEYS = frozenset({"review_items", "review_queue", "blocked_review_items", "unresolved_review_items", "review_findings", "hard_gate_findings"})
+
+
+ def _pointer_token(value: str) -> str:
+ return value.replace("~", "~0").replace("/", "~1")
+
+
+ def _row_locations(document: Any, keys: Sequence[str], pointer: str = "") -> list[tuple[str, Any]]:
+ if isinstance(document, list):
+ return [(f"{pointer}/{i}", row) for i, row in enumerate(document)]
+ if not isinstance(document, dict):
+ raise IngressError("SOURCE_ROWS_SHAPE", "record source must be an array or approved envelope")
+ arrays = [(key, document[key]) for key in keys if isinstance(document.get(key), list)]
+ if len(arrays) > 1:
+ raise IngressError("SOURCE_ROWS_AMBIGUOUS", "multiple record arrays in one source envelope")
+ if arrays:
+ key, rows = arrays[0]
+ return [(f"{pointer}/{_pointer_token(key)}/{i}", row) for i, row in enumerate(rows)]
+ nested = [key for key in WRAPPER_KEYS if isinstance(document.get(key), dict)]
+ if len(nested) != 1:
+ raise IngressError("SOURCE_ROWS_SHAPE", "approved record array is missing or ambiguous")
+ key = nested[0]
+ return _row_locations(document[key], keys, f"{pointer}/{_pointer_token(key)}")
+
+
+ def _source_record_locations(logical: str, document: Any) -> list[tuple[str, Any]]:
+ rows=_row_locations(document,ROW_KEYS[logical])
+ if logical != 'evidence_event_candidates' or not isinstance(document,dict) or document.get('schema_version')!='evidence_event_candidates.v1':return rows
+ events=[]
+ for pointer,item in rows:
+ if not isinstance(item,dict) or not isinstance(item.get('event_candidates'),list):
+ raise IngressError('EVENT_CANDIDATE_ROWS_SHAPE','evidence item event_candidates must be an array')
+ events.extend((f'{pointer}/event_candidates/{i}',v) for i,v in enumerate(item['event_candidates']))
+ return events
+
+ def _array_rows(document: Any, keys: Sequence[str]) -> list[Any]:
+ if document is None:
+ return []
+ return [row for _, row in _row_locations(document, keys)]
+
+
+
+
+ def _root_value(value: Any, field: str, *, workspace_root_allowed: bool) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("DIRECT_ROOT_UNRESOLVED", "pass a concrete workspace-relative root", logical_input_id=field)
+ if value == "." and workspace_root_allowed:
+ return "."
+ try:
+ return _inline_relative_path(value, code="DIRECT_ROOT_INVALID")
+ except IngressError as exc:
+ raise IngressError(exc.code, str(exc), logical_input_id=field) from exc
+
+
+ def _workspace_path(root: str, relative: str) -> str:
+ relative = _inline_relative_path(relative, code="SOURCE_PATH_INVALID")
+ return relative if root == "." else f"{root}/{relative}"
+
+
+ def validate_direct_roots(run_root: Any, deployment_root: Any) -> dict[str, str]:
+ result = {
+ "stage1_run_root_ref": _root_value(run_root, "stage1_run_root_ref", workspace_root_allowed=True),
+ "stage1_deployment_root_ref": _root_value(deployment_root, "stage1_deployment_root_ref", workspace_root_allowed=False),
+ }
+ run = result["stage1_run_root_ref"]
+ output = "stage2_runs/from-stage1/s2_00/v6" if run == "." else f"stage2_runs/from-stage1/{run}/s2_00/v6"
+ out = PurePosixPath(output)
+ for field, value in result.items():
+ # Workspace root contains both original and derived folders; every
+ # actual source read is restricted to the fixed source/manifest paths.
+ if field == "stage1_run_root_ref" and value == ".":
+ continue
+ source = PurePosixPath(value)
+ if out == source or source in out.parents or out in source.parents:
+ raise IngressError("OUTPUT_SOURCE_OVERLAP", "output and source folders must be disjoint", logical_input_id=field)
+ result["output_root"] = output
+ return result
+
+
+ def validate_execution_mode(mode: str, policy: Mapping[str, Any]) -> None:
+ # This YAML is explicitly a workspace execution test, not an authorization
+ # to publish a production release from a DEV policy. All C00-C15 source,
+ # schema, hash, review and conservation checks still apply.
+ if mode != "WORKSPACE_EXECUTION_TEST":
+ code = "DEV_FIXTURE_REAL_RUN_FORBIDDEN" if policy.get("release_class") == "DEV_FIXTURE_RELEASE" else "EXECUTION_MODE_UNAPPROVED"
+ raise IngressError(code, "this standalone YAML admits only workspace execution tests")
+
+
+ def _context_hash(value: Any, field: str) -> str:
+ if isinstance(value, str) and re.search(r"\{\{[^{}]+\}\}", value):
+ raise IngressError("AUTH_CONTEXT_UNRESOLVED", "backend did not bind the authentication context", logical_input_id=field)
+ return _inline_sha256(value, code="AUTH_CONTEXT_HASH_INVALID")
+
+
+
+
+ def _copy_to_temp(root: Path, path: str, raw: bytes) -> None:
+ safe = _safe_relative_path(path)
+ target = root.joinpath(*safe.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+
+
+ def _walk_values(value: Any, pointer: str = "") -> Iterable[tuple[str, Any]]:
+ yield pointer, value
+ if isinstance(value, dict):
+ for key, item in value.items():
+ yield from _walk_values(item, f"{pointer}/{_pointer_token(key)}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ yield from _walk_values(item, f"{pointer}/{index}")
+
+
+ def _schema_dependencies(document: Mapping[str, Any], current_path: str, locks: Mapping[str, Any]) -> set[str]:
+ dependencies = set()
+ for _, item in _walk_values(document):
+ if not isinstance(item, dict) or not isinstance(item.get("$ref"), str):
+ continue
+ ref = item["$ref"].split("#", 1)[0]
+ if not ref:
+ continue
+ candidates = [path for path, row in locks.items() if row.get("schema_id") == ref]
+ if not candidates and "://" not in ref:
+ relative = posixpath.normpath(posixpath.join(posixpath.dirname(current_path), ref))
+ if relative in locks:
+ candidates = [relative]
+ elif ref in locks:
+ candidates = [ref]
+ if not candidates:
+ candidates = [path for path in locks if PurePosixPath(path).name == PurePosixPath(ref).name]
+ if len(candidates) != 1:
+ raise IngressError("SCHEMA_DEPENDENCY_UNBOUND", "schema reference is not uniquely bound to Stage 1 deployment")
+ dependencies.add(candidates[0])
+ return dependencies
+
+
+ def hydrate_stage1(localdocs: _InlineLocaldocs, temp_root: Path, roots: Mapping[str, str], policy: Mapping[str, Any]) -> dict[str, Any]:
+ """Read original Stage 1 bytes at directly supplied roots in this workspace."""
+ stage1_root = temp_root / "stage1"
+ deployment_root = temp_root / "deployment"
+ stage1_root.mkdir(); deployment_root.mkdir()
+ observed: dict[str, bytes] = {}
+ documents: dict[str, Any] = {}
+ source_snapshots: dict[str, Snapshot] = {}
+ issues = []
+ total = 0
+ def remember(path: str, raw: bytes) -> None:
+ nonlocal total
+ if path in observed:
+ if observed[path] != raw:
+ raise IngressError("SOURCE_PATH_CONTENT_CONFLICT", "one source path has conflicting results")
+ return
+ if len(raw) > MAX_FILE_BYTES:
+ raise IngressError("SOURCE_SIZE_LIMIT", "input exceeds per-file byte limit")
+ total += len(raw)
+ if total > MAX_RUN_BYTES:
+ raise IngressError("AGGREGATE_RUN_SIZE_LIMIT", "input set exceeds byte limit")
+ observed[path] = raw
+ for contract in DEFAULT_SOURCE_CONTRACTS:
+ logical = contract["logical_input_id"]
+ relative = contract["path"]
+ logical_path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary_optional(logical_path)
+ if raw is None:
+ issues.append(_issue("SOURCE_MISSING", source_refs=[logical], message=f"required source is absent: {logical_path}"))
+ continue
+ value = load_json_strict(raw)
+ remember(logical_path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ documents[logical] = value
+ source_snapshots[logical] = open_bounded_snapshot(stage1_root, relative, logical_input_id=logical)
+ manifest = documents.get("signal_manifest")
+ if isinstance(manifest, dict):
+ files = manifest.get("files")
+ if not isinstance(files, list):
+ raise IngressError("SIGNAL_FILES_SHAPE", "signal manifest must contain its actual files array")
+ for index, row in enumerate(files):
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
+ raise IngressError("SIGNAL_FILE_ROW_SHAPE", "signal manifest row is malformed")
+ relative = _safe_relative_path(row["path"]).as_posix()
+ if relative.startswith("signals/"):
+ raise IngressError("SIGNAL_PATH_PREFIX_FORBIDDEN", "signal row path must not repeat signals/")
+ relative = f"signals/{relative}"
+ path = _workspace_path(roots["stage1_run_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ remember(path, raw)
+ _copy_to_temp(stage1_root, relative, raw)
+ locks = {row["path"]: row for row in policy["dependency_locks"]["stage1"]["concrete_paths"]}
+ if len(locks) != len(policy["dependency_locks"]["stage1"]["concrete_paths"]):
+ raise IngressError("STAGE1_DEPENDENCY_DUPLICATE_PATH", "upstream dependency table contains duplicate paths")
+ deployment_snapshots: dict[str, Snapshot] = {}
+ deployment_documents: dict[str, Any] = {}
+ needed = {"domains/_registry_index.json", "signals/signal_registry.v2.json"}
+ needed.update(row["schema_ref"]["path"] for row in policy["stage1_sources"] if isinstance(row.get("schema_ref"), dict))
+ activation = documents.get("domain_activation_manifest")
+ payload = _activation_payload(activation) if isinstance(activation, dict) else {}
+ for domain in payload.get("active_domain_ids", []):
+ needed.add(f"domains/{_safe_relative_path(str(domain)).as_posix()}/domain_config.json")
+ while needed:
+ relative = min(needed); needed.remove(relative)
+ if relative in deployment_documents:
+ continue
+ row = locks.get(relative)
+ if row is None:
+ raise IngressError("STAGE1_DEPENDENCY_UNBOUND", "required upstream dependency is not pinned")
+ expected = _inline_sha256(row.get("sha256"), code="STAGE1_DEPENDENCY_UNBOUND")
+ path = _workspace_path(roots["stage1_deployment_root_ref"], relative)
+ raw = localdocs.read_binary(path)
+ if hashlib.sha256(raw).hexdigest() != expected:
+ raise IngressError("STAGE1_DEPENDENCY_HASH_MISMATCH", "upstream deployment file differs from its pin")
+ remember(path, raw)
+ value = load_json_strict(raw)
+ _copy_to_temp(deployment_root, relative, raw)
+ deployment_snapshots[relative] = open_bounded_snapshot(deployment_root, relative, logical_input_id=f"deployment:{relative}")
+ deployment_documents[relative] = value
+ if isinstance(value, dict):
+ needed.update(_schema_dependencies(value, relative, locks) - deployment_documents.keys())
+ if relative == "signals/signal_registry.v2.json" and isinstance(value, dict):
+ for entry in value.get("entries", []):
+ if isinstance(entry, dict) and isinstance(entry.get("schema"), str):
+ schema = entry["schema"]
+ needed.add(schema if schema.startswith("signals/") else f"signals/{schema}")
+ envelope = value.get("domain_envelope")
+ if isinstance(envelope, str):
+ needed.add(envelope if envelope.startswith("signals/") else f"signals/{envelope}")
+ return {"stage1_root": stage1_root, "deployment_root": deployment_root, "snapshots": source_snapshots, "documents": documents, "deployment_snapshots": deployment_snapshots, "deployment_documents": deployment_documents, "observed": observed, "issues": issues}
+
+
+ def verify_remote_stability(localdocs: _InlineLocaldocs, observed: Mapping[str, bytes]) -> None:
+ for path, expected in sorted(observed.items()):
+ if localdocs.read_binary(path) != expected:
+ raise IngressError("HYDRATION_SOURCE_CHANGED", "source differs from the first read/result reference")
+
+
+ def _provenance(logical: str, pointer: str, documents: Mapping[str, Any]) -> dict[str, Any]:
+ found, value = _json_pointer_value(documents[logical], pointer)
+ if not found:
+ raise IngressError("SOURCE_POINTER_INVALID", "projection pointer does not address the original")
+ return _source_ref(logical, pointer, value)
+
+
+ def normalize_review_items(review_documents: Mapping[str, Any], release_lock: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """Preserve every review/gate occurrence, its content, exact pointer, and blocking state."""
+ mapping = _adapter_decision(release_lock or {}, "S2-REVIEW-MAP-V1") or {}
+ table = {(row.get("source_stage", "ANY"), row.get("source_field_kind"), str(row.get("source_value"))): row.get("normalized_partition") for row in mapping.get("mappings", [])}
+ rows = []
+ partitions = Counter()
+ adapter_issues = []
+ for stage_number in range(1, 5):
+ logical = 'stage1_part1_soft_gate_handoff' if stage_number == 1 else f'stage1_part{stage_number}_review_handoff'
+ if logical not in review_documents:
+ continue
+ adapter = f'S2A-P{stage_number}-HANDOFF-' + ('FLAT-V1' if stage_number < 3 else 'WRAPPED-V1')
+ decision = _adapter_decision(release_lock or {}, adapter)
+ if not isinstance(decision, dict):
+ adapter_issues.append(_issue('HANDOFF_ADAPTER_CONTRACT_MISSING', source_refs=[logical]))
+ continue
+ found, wrapper = _json_pointer_value(review_documents[logical], decision.get('wrapper_json_pointer'))
+ if not found or not isinstance(wrapper, dict):
+ adapter_issues.append(_issue(f'P{stage_number}_WRAPPER_MISSING', source_refs=[logical]))
+ continue
+ if wrapper.get('schema_version') != decision.get('schema_version'):
+ adapter_issues.append(_issue(f'P{stage_number}_HANDOFF_SCHEMA_VERSION_MISMATCH', source_refs=[logical]))
+ found, handoff_items = _json_pointer_value(wrapper, decision.get('review_items_json_pointer'))
+ if not found or not isinstance(handoff_items, list):
+ adapter_issues.append(_issue(f'P{stage_number}_REVIEW_ITEMS_SHAPE', source_refs=[logical]))
+ elif decision.get('count_field_required') is True and (wrapper.get('counts', {}).get('review_items') if isinstance(wrapper.get('counts'), dict) else wrapper.get('review_item_count')) != len(handoff_items):
+ adapter_issues.append(_issue('REVIEW_CONSERVATION_FAILED', source_refs=[logical]))
+ for logical, document in sorted(review_documents.items()):
+ stage_match = re.search(r"part([1-4])", logical)
+ stage = f"P{stage_match.group(1)}" if stage_match else "ANY"
+ for pointer, value in _walk_values(document):
+ if not isinstance(value, dict):
+ continue
+ for key in sorted(REVIEW_ARRAY_KEYS):
+ items = value.get(key)
+ if not isinstance(items, list):
+ continue
+ for index, item in enumerate(items):
+ item_pointer = f"{pointer}/{_pointer_token(key)}/{index}"
+ raw_status = item.get("status") if isinstance(item, dict) else None
+ raw_severity = item.get("severity") if isinstance(item, dict) else None
+ kind = "REVIEW_ITEM_STATUS" if raw_status is not None else "REVIEW_ITEM_SEVERITY"
+ raw_value = str(raw_status if raw_status is not None else raw_severity)
+ partition = table.get((stage, kind, raw_value), table.get(("ANY", kind, raw_value), "UNMAPPED"))
+ explicit_block = key == "blocked_review_items" or isinstance(item, dict) and (item.get("blocking") is True or item.get("blocked") is True or str(item.get("status", "")).upper() == "BLOCKED" or str(item.get("severity", "")).upper() in {"BLOCKING", "CRITICAL", "FATAL"})
+ row = {"review_ref": f"{logical}#{item_pointer}", "source_ref": _provenance(logical, item_pointer, review_documents), "source_status_raw": raw_status, "source_severity_raw": raw_severity, "partition": partition, "blocking": bool(explicit_block), "content": item}
+ rows.append(row); partitions[partition] += 1
+ # Count source occurrences independently; duplicates remain distinct by pointer.
+ expected = sum(len(v[k]) for doc in review_documents.values() for _, v in _walk_values(doc) if isinstance(v, dict) for k in REVIEW_ARRAY_KEYS if isinstance(v.get(k), list))
+ return {"normalized_occurrences": rows, "partition_counts": dict(partitions), "conservation_status": "PASS" if expected == len(rows) and len({r['review_ref'] for r in rows}) == expected and not any(x["issue_code"] == "REVIEW_CONSERVATION_FAILED" for x in adapter_issues) else "FAIL", "_issues": adapter_issues}
+
+
+ def _project_content(value: Any) -> Any:
+ if not isinstance(value, dict):
+ return value
+ # Envelope/protocol metadata remains reachable through provenance instead of copying files.
+ return {key: item for key, item in value.items() if key not in {"schema_version", "schema_contract_version", "producer_id", "created_by", "finalized_by", "metadata", "meta"}}
+
+
+ def compile_case_context(documents: Mapping[str, Any], signal_all: Mapping[str, Any], reviews: Mapping[str, Any], deployment_documents: Mapping[str, Any]) -> dict[str, Any]:
+ """Normalize original records once and group only explicit source relationships."""
+ members = []
+ lookup = {}
+ identities = {"bo": ("BO", ("BO_ID",)), "fact_ledger_base": ("FACT", ("fact_id",)), "legal_effect_structures": ("LES", ("structure_id", "legal_effect_structure_id")), "evidence_indexed": ("EVIDENCE", ("evidence_index", "evidence_id", "id")), "evidence_event_candidates": ("EVENT", ("candidate_id", "event_id", "id"))}
+ raw_rows = {}
+ for logical, keys in ROW_KEYS.items():
+ for pointer, value in _source_record_locations(logical, documents[logical]):
+ if not isinstance(value, dict):
+ raise IngressError("SOURCE_RECORD_SHAPE", "original record must be an object")
+ kind, id_keys = identities[logical]
+ identifier = next((str(value[k]) for k in id_keys if value.get(k) is not None), None)
+ ref = f"{logical}#{pointer}"
+ if identifier is not None:
+ if (kind, identifier) in lookup:
+ raise IngressError("SOURCE_RECORD_ID_DUPLICATE", "original record ID occurs more than once")
+ lookup[(kind, identifier)] = ref
+ member = {"member_ref": ref, "kind": kind, "stage1_id": identifier, "source_ref": _provenance(logical, pointer, documents), "field_refs": {key: _provenance(logical, f"{pointer}/{_pointer_token(key)}", documents) for key in value}, "projection": _project_content(value)}
+ members.append(member); raw_rows[ref] = (logical, pointer, value)
+ relationships = []; candidates = []; unresolved = []
+ parent = {m['member_ref']: m['member_ref'] for m in members}
+ def find(ref):
+ while parent[ref] != ref:
+ parent[ref] = parent[parent[ref]]; ref = parent[ref]
+ return ref
+ def join(a,b):
+ a,b=find(a),find(b)
+ if a!=b:parent[max(a,b)]=min(a,b)
+ def edge(source, kind, identifier, relation, pointer, *, hard=True):
+ logical, _, _ = raw_rows[source]
+ target = lookup.get((kind, str(identifier)))
+ row = {"from_ref": source, "to_ref": target, "target_stage1_id": str(identifier), "relation_kind": relation, "source_ref": _provenance(logical, pointer, documents), "hard_join_allowed": hard, "disposition": "OBSERVED" if target else "UNEVALUABLE"}
+ if target is None:
+ unresolved.append(row)
+ elif hard:
+ relationships.append(row); join(source,target)
+ else:
+ candidates.append(row)
+ for member in members:
+ ref=member['member_ref']; logical,pointer,row=raw_rows[ref]
+ if member['kind']=='FACT':
+ if row.get('source_bo_id') is not None:edge(ref,'BO',row['source_bo_id'],'SAME_BO_ID',f"{pointer}/source_bo_id")
+ for keys,kind,relation in [(('evidence_refs','evidence_ids'),'EVIDENCE','SAME_EVIDENCE_REF'),(('event_refs','event_ids'),'EVENT','SAME_EVENT_REF')]:
+ key=next((k for k in keys if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,kind,identifier,relation,f"{pointer}/{key}/{index}")
+ for key in ('relations','explicit_relations','candidate_relations'):
+ for index,item in enumerate(row.get(key,[]) if isinstance(row.get(key),list) else []):
+ if not isinstance(item,dict):continue
+ target=item.get('target_fact_id',item.get('to_fact_id'))
+ relation=str(item.get('relation_kind',item.get('kind','UNCLASSIFIED')))
+ if target is not None:edge(ref,'FACT',target,relation,f"{pointer}/{key}/{index}",hard=relation=='EXPLICIT_CASE_RELATION')
+ elif member['kind']=='LES':
+ for index,identifier in enumerate(row.get('source_bo_ids',[]) if isinstance(row.get('source_bo_ids'),list) else []):edge(ref,'BO',identifier,'SOURCE_BO_ATTACHMENT',f"{pointer}/source_bo_ids/{index}")
+ elif member['kind']=='BO':
+ prov=row.get('provenance',{})
+ if isinstance(prov,dict) and isinstance(prov.get('source_event_candidate_ids'),list):
+ for i,identifier in enumerate(prov['source_event_candidate_ids']):edge(ref,'EVENT',identifier,'SOURCE_EVENT_ATTACHMENT',f'{pointer}/provenance/source_event_candidate_ids/{i}')
+ elif member['kind']=='EVENT':
+ if row.get('source_evidence_index') is not None:edge(ref,'EVIDENCE',row['source_evidence_index'],'SAME_EVIDENCE_REF',f'{pointer}/source_evidence_index')
+ key=next((k for k in ('evidence_refs','evidence_ids') if isinstance(row.get(k),list)),None)
+ if key:
+ for index,identifier in enumerate(row[key]):edge(ref,'EVIDENCE',identifier,'SAME_EVIDENCE_REF',f"{pointer}/{key}/{index}")
+ member_by_ref = {row['member_ref']: row for row in members}
+ grouped=defaultdict(list)
+ for ref in sorted(parent):grouped[find(ref)].append(ref)
+ clusters=[]; membership={}
+ for index,refs in enumerate(sorted(grouped.values(),key=lambda v:v[0]),1):
+ cluster_ref=f"CL-{index:03d}"
+ clusters.append({'cluster_ref':cluster_ref,'member_refs':refs,'source_refs':[member_by_ref[ref]['source_ref'] for ref in refs]})
+ for ref in refs:membership[ref]=cluster_ref
+ cluster_edges=sorted({(membership[r['from_ref']],membership[r['to_ref']]) for r in candidates if r['relation_kind'] in CANDIDATE_RELATION_KINDS and membership[r['from_ref']]!=membership[r['to_ref']]})
+ sccs=_tarjan_scc([c['cluster_ref'] for c in clusters],cluster_edges)
+ component={ref:index for index,group in enumerate(sccs) for ref in group}
+ indegree={i:0 for i in range(len(sccs))}; adjacency=defaultdict(set)
+ for left,right in cluster_edges:
+ a,b=component[left],component[right]
+ if a!=b and b not in adjacency[a]:adjacency[a].add(b); indegree[b]+=1
+ ready=sorted(i for i in indegree if indegree[i]==0); waves=[]
+ while ready:
+ waves.append([sccs[i] for i in ready]); upcoming=[]
+ for i in ready:
+ for j in sorted(adjacency[i]):
+ indegree[j]-=1
+ if indegree[j]==0:upcoming.append(j)
+ ready=sorted(set(upcoming))
+ signal_refs=[]
+ for occurrence in signal_all.get('record_occurrences',[]):
+ logical=f"signal:{occurrence['file_path']}"
+ document=documents[logical]
+ locations=_record_locations_for_signal(document)
+ ordinal=occurrence['record_ordinal']
+ pointer,value=locations[ordinal]
+ signal_refs.append({'source_ref':_provenance(logical,pointer,documents),'signal_id':occurrence['signal_id'],'disposition':occurrence['disposition'],'binding_refs':occurrence.get('binding_refs',[]),'projection':_project_content(value)})
+ for cluster in clusters:
+ member_set=set(cluster['member_refs'])
+ cluster_members = [member_by_ref[ref] for ref in cluster['member_refs']]
+ bound_ids={f"{m['kind']}:{m['stage1_id']}" for m in cluster_members if m['stage1_id'] is not None}
+ selected=[]
+ for index,row in enumerate(signal_refs):
+ tokens={t.replace('fact_id:','FACT:').replace('source_bo_id:','BO:').replace('bo_id:','BO:').replace('evidence_id:','EVIDENCE:').replace('event_id:','EVENT:') for t in row['binding_refs']}
+ if tokens & bound_ids:selected.append(index)
+ cluster['signal_indexes']=selected
+ cluster['review_refs']=[r['review_ref'] for r in reviews['normalized_occurrences'] if any(str(m['stage1_id']) in _collect_values_for_keys(r['content'], {'fact_id','fact_ids','source_fact_ids','BO_ID','bo_id','bo_ids','source_bo_id','source_bo_ids','evidence_index','evidence_id','evidence_ids','evidence_refs','source_evidence_indexes','candidate_id','event_id','event_ids','source_event_candidate_ids'}) for m in cluster_members if m['stage1_id'] is not None)]
+ cluster['bundle']={'member_refs':cluster['member_refs'],'signal_indexes':selected,'review_refs':cluster['review_refs']}
+ slot_links=[]; party_object_refs=[]
+ for logical,document in documents.items():
+ if logical.startswith('deployment:'):continue
+ for pointer,value in _walk_values(document):
+ if not isinstance(value,dict):continue
+ if any(k in value for k in ('slot_id','slot_ref','evidence_slot_id')):
+ slot_links.append({'source_ref':_provenance(logical,pointer,documents),'projection':_project_content(value),'disposition':'OBSERVED'})
+ for key in ('parties','party_refs','object_refs','objects','title_refs'):
+ if isinstance(value.get(key),(list,dict)):
+ party_object_refs.append({'kind':key,'source_ref':_provenance(logical,f"{pointer}/{key}",documents)})
+ return {'source_documents':[_provenance(logical,'',documents) for logical in sorted(documents) if not logical.startswith('deployment:')], 'members':members,'relationships':relationships,'candidate_dependencies':candidates,'unresolved_relationships':unresolved,'clusters':clusters,'scheduling_waves':waves,'client_goal':{'source_ref':_provenance('client_goal','',documents),'projection':_project_content(documents['client_goal'])},'routing':{'source_ref':_provenance('domain_activation_manifest','',documents),'projection':_activation_payload(documents['domain_activation_manifest'])},'signals':signal_refs,'global_review_refs':[r['review_ref'] for r in reviews['normalized_occurrences']],'object_and_party_refs':party_object_refs,'slot_links':slot_links,'slot_link_status':'OBSERVED' if slot_links else 'UNEVALUABLE','active_profiles':[{'path':path,'sha256':canonical_digest(value),'profile':value} for path,value in sorted(deployment_documents.items()) if re.fullmatch(r'domains/[^/]+/domain_config\.json',path)]}
+
+
+ def _record_locations_for_signal(document: Any) -> list[tuple[str, Any]]:
+ if isinstance(document,list):return [(f'/{i}',v) for i,v in enumerate(document)]
+ if not isinstance(document,dict):
+ raise IngressError('SIGNAL_RECORD_SHAPE','signal document must be an array or object')
+ # Match signal_compiler._file_state: SG01 counts domain entries; domain
+ # envelopes count the three candidate arrays, not the envelope itself.
+ if isinstance(document.get('domain_activation_manifest'),dict):
+ inner=document['domain_activation_manifest'];keys=('domain_entries',);prefix='/domain_activation_manifest'
+ elif isinstance(document.get('domain_signal_envelope'),dict):
+ inner=document['domain_signal_envelope'];keys=('element_fact_candidates','opposing_fact_candidates','defense_candidates');prefix='/domain_signal_envelope'
+ else:
+ inner=document;prefix=''
+ keys=tuple(k for k in ('signals','records','items','actio_case_signals','case_liability_signals','bo_legal_effect_routes') if isinstance(inner.get(k),list))
+ if len(keys)>1:raise IngressError('SIGNAL_RECORD_POINTER_AMBIGUOUS','multiple signal record arrays')
+ if not keys:return [('',document)]
+ result=[]
+ for key in keys:
+ if not isinstance(inner.get(key),list):raise IngressError('SIGNAL_RECORD_SHAPE','required signal array is missing: '+key)
+ result.extend((f'{prefix}/{key}/{i}',v) for i,v in enumerate(inner[key]))
+ return result
+
+
+ def _validate_provenance(value: Any, documents: Mapping[str, Any]) -> None:
+ for _,row in _walk_values(value):
+ if not isinstance(row,dict) or not {'logical_artifact_id','json_pointer','raw_value_sha256'}.issubset(row):continue
+ logical=row['logical_artifact_id']
+ if logical not in documents:raise IngressError('SOURCE_REF_UNKNOWN','output refers to an unknown source')
+ found,raw=_json_pointer_value(documents[logical],row['json_pointer'])
+ if not found or canonical_digest(raw)!=row['raw_value_sha256']:
+ raise IngressError('SOURCE_REF_HASH_MISMATCH','output provenance does not match original content')
+
+
+ def _clean_issues(issues: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ rows=[]; seen=set()
+ for row in issues:
+ cleaned={k:row[k] for k in ('issue_code','severity','impact_scope','scope_refs','source_refs','message') if k in row}
+ key=canonical_digest(cleaned)
+ if key not in seen:seen.add(key); rows.append(cleaned)
+ return sorted(rows,key=canonical_digest)
+
+
+ def execute_ingress(hydrated: Mapping[str, Any], roots: Mapping[str, str], *, policy: Mapping[str, Any] = SOURCE_POLICY, execution_mode: str = EXECUTION_MODE) -> dict[str, Any]:
+ """C00-C15 workspace-test core with unchanged source-validation gates."""
+ validate_execution_mode(execution_mode, policy)
+ snapshots=hydrated['snapshots']; deployment=hydrated['deployment_documents']; dep_snapshots=hydrated['deployment_snapshots']
+ contracts=resolve_stage1_sources(hydrated['stage1_root'])
+ ingress=validate_ingress_contracts(snapshots,contracts,policy,deployment_snapshots=dep_snapshots,deployment_documents=deployment)
+ documents=ingress['documents']; issues=list(hydrated['issues'])+ingress['issues']; checks=[]
+ signal_all={}; reviews={'normalized_occurrences':[],'partition_counts':{},'conservation_status':'PASS','_issues':[]}
+ try:
+ if set(documents)!={r['logical_input_id'] for r in DEFAULT_SOURCE_CONTRACTS}:
+ raise IngressError('SOURCE_SET_INCOMPLETE','required Stage 1 sources are unavailable')
+ signal_all=expand_stage2_signal_all(hydrated['stage1_root'],documents['signal_manifest'],signal_registry=deployment.get('signals/signal_registry.v2.json'))
+ signal_all=bind_signal_occurrences(signal_all,documents)
+ issues.extend(signal_all['issues'])
+ for row in signal_all['ordered_file_rows']:
+ logical=f"signal:{row['file_path']}"
+ document=signal_all['_parsed_documents_by_path'][row['file_path']]
+ documents[logical]=document
+ manifest_row=documents['signal_manifest']['files'][row['manifest_index']]
+ schema_path=manifest_row.get('schema',manifest_row.get('schema_path'))
+ if isinstance(schema_path,str):
+ if not schema_path.startswith('signals/'):schema_path=f'signals/{schema_path}'
+ schema=deployment.get(schema_path)
+ if not isinstance(schema,dict):raise IngressError('SIGNAL_SCHEMA_UNBOUND','signal schema is not in the selected upstream closure')
+ try:_validate_schema_node(document,schema,root_schema=schema,schema_documents=_schema_document_index(deployment),instance_path=logical)
+ except _SchemaViolation as exc:raise IngressError('SIGNAL_SCHEMA_VALIDATION_FAILED',str(exc)) from exc
+ activation=signal_all['_parsed_documents_by_path'].get('domain_activation_manifest.json')
+ if activation is None:raise IngressError('SG01_SIGNAL_ARTIFACT_MISSING','signal ALL lacks domain activation')
+ verify_activation_projection(documents['domain_activation_manifest'],activation)
+ seals=verify_cross_artifact_seals(documents,snapshots,{'stage1_domain_registry_index':dep_snapshots['domains/_registry_index.json']} if 'domains/_registry_index.json' in dep_snapshots else {})
+ checks.extend(seals['checks']); issues.extend(seals['issues'])
+ reviews=normalize_review_items(documents,policy)
+ conserved=check_conservation(documents,signal_all=signal_all,normalized_reviews=reviews,source_snapshots=snapshots)
+ checks.extend(conserved['checks']); issues.extend(conserved['issues'])
+ for logical,doc in documents.items():
+ if logical.startswith('signal:'):continue
+ for pointer,value in _walk_values(doc):
+ if not isinstance(value,dict):continue
+ if value.get('stage2_auto_progression_allowed') is False or value.get('blocking') is True or value.get('blocked') is True or str(value.get('status',value.get('handoff_status',''))).upper()=='BLOCKED':
+ issues.append(_issue('UPSTREAM_BLOCKING_GATE',source_refs=[f'{logical}#{pointer}']))
+ if any(r['blocking'] for r in reviews['normalized_occurrences']):issues.append(_issue('UPSTREAM_BLOCKING_REVIEW'))
+ except (IngressError,_SchemaViolation) as exc:
+ code=exc.code if isinstance(exc,IngressError) else 'SOURCE_SCHEMA_VALIDATION_FAILED'
+ issues.append(_issue(code,message=str(exc)))
+ issues=_clean_issues(issues)
+ serious=any(row.get('severity')=='ERROR' and row.get('issue_code') not in {'PRODUCER_ID_UNEVALUABLE','UNMAPPED_REVIEW_STATUS'} for row in issues)
+ if any(row.get('parse_status')!='PASS' or row.get('schema_status')=='FAIL' or row.get('seal_status')=='FAIL' for row in ingress['source_contract_rows']):serious=True
+ if any(c.get('status')=='FAIL' for c in checks):serious=True
+ status='BLOCKED' if serious else 'READY_WITH_ISSUES' if issues or any(r['partition'] in {'UNRESOLVED','CONDITIONAL','UNMAPPED'} for r in reviews['normalized_occurrences']) or any(r.get('seal_status')=='UNEVALUABLE' for r in ingress['source_contract_rows']) else 'READY'
+ context=None
+ if status!='BLOCKED':
+ try:
+ context=compile_case_context(documents,signal_all,reviews,deployment)
+ if not context['clusters']:
+ raise IngressError('NO_COHERENT_CLUSTER', 'no source records form a usable case context')
+ if context['unresolved_relationships']:
+ issues=_clean_issues(issues+[_issue('RELATION_TARGET_UNEVALUABLE',severity='WARNING')]); status='READY_WITH_ISSUES'
+ _validate_provenance(context,documents)
+ except IngressError as exc:
+ issues=_clean_issues(issues+[_issue(exc.code,message=str(exc))]); status='BLOCKED'; context=None
+ _validate_provenance(reviews['normalized_occurrences'],documents)
+ header={'execution_mode':execution_mode,'source_policy_release_class':policy['release_class'],'schema_version':'stage2_s2_00_direct.v4','algorithm_version':ALGORITHM_VERSION,'stage1_run_root_ref':roots['stage1_run_root_ref'],'stage1_deployment_root_ref':roots['stage1_deployment_root_ref']}
+ manifest_rows=[{'logical_input_id':row['logical_input_id'],'path':snapshots[row['logical_input_id']].relative_path if row['logical_input_id'] in snapshots else row.get('expected_path'),'raw_sha256':row.get('raw_sha256'),'byte_length':row.get('byte_length'),'parse_status':row.get('parse_status'),'schema_status':row.get('schema_status'),'seal_status':row.get('seal_status'),'run_identity_ref':row.get('run_identity_ref'),'transaction_identity_ref':row.get('transaction_identity_ref')} for row in ingress['source_contract_rows']]
+ for row in signal_all.get('ordered_file_rows',[]):manifest_rows.append({'logical_input_id':f"signal:{row['file_path']}",'path':row['physical_path'],'raw_sha256':row['raw_sha256'],'byte_length':row['byte_length'],'hash_status':row['hash_status'],'record_count_status':row['record_count_status']})
+ deployment_rows=[{'path':path,'raw_sha256':snap.raw_sha256,'byte_length':snap.byte_length} for path,snap in sorted(dep_snapshots.items())]
+ source_hashes={path:hashlib.sha256(raw).hexdigest() for path,raw in sorted(hydrated['observed'].items())}
+ files={
+ 'ingress/stage1_input_manifest.json':{**header,'sources':manifest_rows,'deployment_sources':deployment_rows},
+ 'ingress/intake_report.json':{**header,'checks':checks,'issues':issues,'source_contract_rows':[{k:v for k,v in row.items() if k!='downstream_allowed_actions'} for row in ingress['source_contract_rows']]},
+ 'review/issue_ledger.base.json':{**header,'review_items':reviews['normalized_occurrences'],'partition_counts':reviews['partition_counts'],'conservation_status':reviews['conservation_status'],'issues':issues},
+ }
+ if status=='BLOCKED':files['ingress/technical_diagnostic.json']={**header,'status':status,'issues':issues,'checks':checks}
+ else:files['context/case_context.json']={**header,**context}
+ serialized={path:canonical_json_bytes(value)+b'\n' for path,value in files.items()}
+ artifact_rows=[{'path':path,'raw_sha256':hashlib.sha256(raw).hexdigest(),'byte_length':len(raw)} for path,raw in sorted(serialized.items())]
+ files[STATUS_PATH]={**header,'status':status,'output_root':roots['output_root'],'source_hashes':source_hashes,'artifacts':artifact_rows,'written_last':True,'publication_semantics':'STATUS_LAST_LOGICAL_COMMIT'}
+ serialized[STATUS_PATH]=canonical_json_bytes(files[STATUS_PATH])+b'\n'
+ validate_output_files(serialized,roots)
+ return {'status':status,'files':serialized,'documents':documents}
+
+
+ def validate_output_files(files: Mapping[str, bytes], roots: Mapping[str, str]) -> dict[str, Any]:
+ status=load_json_strict(files.get(STATUS_PATH,b''))
+ allowed=NORMAL_PATHS if status.get('status') in {'READY','READY_WITH_ISSUES'} else BLOCKED_PATHS if status.get('status')=='BLOCKED' else frozenset()
+ if set(files)!=allowed:raise IngressError('OUTPUT_ARTIFACT_SET_INVALID','output set differs from its processing state')
+ common={'schema_version','algorithm_version','stage1_run_root_ref','stage1_deployment_root_ref','execution_mode','source_policy_release_class'}
+ fields={
+ 'ingress/stage1_input_manifest.json':{'sources','deployment_sources'},
+ 'ingress/intake_report.json':{'checks','issues','source_contract_rows'},
+ 'review/issue_ledger.base.json':{'review_items','partition_counts','conservation_status','issues'},
+ 'context/case_context.json':{'source_documents','members','relationships','candidate_dependencies','unresolved_relationships','clusters','scheduling_waves','client_goal','routing','signals','global_review_refs','object_and_party_refs','slot_links','slot_link_status','active_profiles'},
+ 'ingress/technical_diagnostic.json':{'status','issues','checks'},
+ STATUS_PATH:{'status','output_root','source_hashes','artifacts','written_last','publication_semantics'},
+ }
+ for path,raw in files.items():
+ value=load_json_strict(raw)
+ if not isinstance(value,dict) or set(value)!=common|fields[path]:raise IngressError('OUTPUT_CLOSED_SCHEMA_INVALID','output fields do not match the inline contract')
+ validate_execution_mode(value['execution_mode'], SOURCE_POLICY)
+ if value['source_policy_release_class'] != SOURCE_POLICY['release_class']:raise IngressError('OUTPUT_POLICY_BINDING_INVALID', 'output policy classification differs')
+ if value['algorithm_version']!=ALGORITHM_VERSION or value['schema_version']!='stage2_s2_00_direct.v4':raise IngressError('OUTPUT_VERSION_INVALID','output algorithm/schema version differs')
+ if any(value[key]!=roots[key] for key in ('stage1_run_root_ref','stage1_deployment_root_ref')):raise IngressError('OUTPUT_SOURCE_BINDING_INVALID','output roots differ from inputs')
+ if status['output_root']!=roots['output_root'] or status['written_last'] is not True or status['publication_semantics']!='STATUS_LAST_LOGICAL_COMMIT':raise IngressError('OUTPUT_STATUS_INVALID','status does not identify the logical completion boundary')
+ rows=status['artifacts']
+ if not isinstance(rows,list) or len(rows)!=len(files)-1 or {r.get('path') for r in rows}!=set(files)-{STATUS_PATH}:raise IngressError('OUTPUT_STATUS_SET_INVALID','status inventory differs from actual outputs')
+ for row in rows:
+ raw=files[row['path']]
+ if set(row)!={'path','raw_sha256','byte_length'} or row['raw_sha256']!=hashlib.sha256(raw).hexdigest() or row['byte_length']!=len(raw):raise IngressError('OUTPUT_STATUS_HASH_INVALID','status inventory does not match output bytes')
+ return status
+
+
+ def publish_result(localdocs: _InlineLocaldocs, roots: Mapping[str,str], files: Mapping[str,bytes]) -> dict[str,Any]:
+ """No overwrite, exact completed-result reuse, and status-last publication."""
+ status=validate_output_files(files,roots); output=roots['output_root']
+ existing=localdocs.read_binary_optional(f'{output}/{STATUS_PATH}')
+ if existing is not None:
+ if existing!=files[STATUS_PATH]:raise IngressError('EXISTING_OUTPUT_CONFLICT','existing completed output differs in source, version, status, or inventory')
+ for relative,raw in sorted(files.items()):
+ if localdocs.read_binary(f'{output}/{relative}')!=raw:raise IngressError('EXISTING_OUTPUT_CORRUPT','existing artifact differs from completed status')
+ publication='REUSED_COMPLETED_OUTPUT'
+ else:
+ for relative in sorted(NORMAL_PATHS|BLOCKED_PATHS):
+ if relative!=STATUS_PATH and localdocs.read_binary_optional(f'{output}/{relative}') is not None:raise IngressError('PARTIAL_OUTPUT_CONFLICT','unfinished output requires explicit recovery; no overwrite')
+ for relative in sorted(set(files)-{STATUS_PATH}):localdocs.write_binary_verified(f'{output}/{relative}',files[relative],overwrite=False)
+ localdocs.write_binary_verified(f'{output}/{STATUS_PATH}',files[STATUS_PATH],overwrite=False)
+ publication='PUBLISHED_STATUS_LAST'
+ return {'ok':status['status']!='BLOCKED','status':status['status'],'execution_mode':status['execution_mode'],'source_policy_release_class':status['source_policy_release_class'],'output_root':output,'publication':publication,'ingress_status_sha256':hashlib.sha256(files[STATUS_PATH]).hexdigest()}
+
+
+ def run_inline_mcp(run_root: Any = STAGE1_RUN_ROOT, deployment_root: Any = STAGE1_DEPLOYMENT_ROOT, *, execution_mode: str = EXECUTION_MODE, client: Any | None = None) -> int:
+ localdocs = None
+ try:
+ roots = validate_direct_roots(run_root, deployment_root)
+ validate_execution_mode(execution_mode, SOURCE_POLICY)
+ localdocs = _InlineLocaldocs(INLINE_USER_HASH, INLINE_WORKSPACE_HASH, client=client)
+ localdocs.initialize()
+ with tempfile.TemporaryDirectory(prefix="liti-s2-00-") as directory:
+ hydrated = hydrate_stage1(localdocs, Path(directory), roots, SOURCE_POLICY)
+ result = execute_ingress(hydrated, roots, policy=SOURCE_POLICY, execution_mode=execution_mode)
+ verify_remote_stability(localdocs, hydrated["observed"])
+ receipt = publish_result(localdocs, roots, result["files"])
+ print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
+ return 0 if receipt["ok"] else 2
+ except Exception as exc:
+ error = exc.as_dict() if isinstance(exc, IngressError) else {"code":"S2_00_RUNTIME_ERROR", "message":str(exc)}
+ # A remote status may already exist if its read-back failed.
+ print(json.dumps({"ok":False,"status":"FAILED","error":error}, ensure_ascii=False, separators=(",", ":")))
+ return 2
+ finally:
+ if localdocs is not None:
+ localdocs.close()
+
+
+ if __name__ == '__main__':
+ raise SystemExit(run_inline_mcp())
+ task_procedure:
+ IN:
+ nexts:
+ - Task_S2_00_deterministic_ingress
+ wait_until: []
+ Task_S2_00_deterministic_ingress:
+ nexts:
+ - OUT
+ wait_until:
+ - IN
+ OUT:
+ nexts: []
+ wait_until:
+ - Task_S2_00_deterministic_ingress