From 6da9492ce5aed1d3f340ae5353bc1cf5ce32fa65 Mon Sep 17 00:00:00 2001 From: jhogyu Date: Thu, 5 Nov 2026 19:29:20 +0900 Subject: [PATCH] feat(stage1): apply Part 4 consistency fixes P4-01..08 and record Nov 5 live runs - Part 4 YAML: party links from value_facts, recommender label scoped by (domain, attached_type, bo), unique calculation request counts, BO input seal against Part 3 receipt, gate-without-rows review code with blocks_final_drafting, SG-06/SG-10 reads removed - Part 2 YAML: projection-note handoff items use source_field; manifest pin updated to 9d2df172 - Runtime assets: fact_ledger_compiler, fact_ledger_policy, signal_compiler and resealed runtime_manifest - Live run reports (Nov 5): Part 2 run 1, Part 3 run 5, Part 4 runs 1-2, all succeeded; consistency report and solutions document; backups Co-Authored-By: Claude Opus 5.5 --- .../Default_Agent/runtime_manifest.json | 10 +- .../signals/compiler/signal_compiler.py | 2 +- .../signals/compiler/signal_compiler.txt | 2 +- .../stage1_runtime/fact_ledger_compiler.py | 53 +- .../stage1_runtime/fact_ledger_compiler.txt | 53 +- .../stage1_runtime/fact_ledger_policy.v1.json | 3 +- .../Testrun/Nov_05/실행결과보고서_1_part_2.md | 140 + .../Testrun/Nov_05/실행결과보고서_1_part_4.md | 163 + .../Testrun/Nov_05/실행결과보고서_2_part_4.md | 110 + .../Testrun/Nov_05/실행결과보고서_5_part_3.md | 112 + .../fact_ledger_compiler_11_05_5_22pm.py.bak | 945 +++ .../fact_ledger_policy_11_05_5_22pm.json.bak | 405 ++ .../runtime_manifest_11_05_5_22pm.json.bak | 1867 ++++++ .../v.8/signal_compiler_11_05_5_22pm.py.bak | 183 + .../1. Stage_1/v.8/stage_1_part_2_v.8.yml | 12 +- .../v.8/stage_1_part_2_v.8_11_05_5_22pm.yml | 5769 +++++++++++++++++ .../v.8/stage_1_part_3_v.8_11_05_5_22pm.yml | 2589 ++++++++ .../1. Stage_1/v.8/stage_1_part_4_v.8.yml | 99 +- .../v.8/stage_1_part_4_v.8_11_05_5_22pm.yml | 1265 ++++ ...업간일치성보고서_part_4_on_part_1_to_3.md | 254 + ...치성보고서_해결법_part_4_on_part_1_to_3.md | 190 + .../agent_scripts/작업_히스토리_11_04_밤.txt | 447 +- .../YAML_Prompts/2. Stage_2/MEMORY.md | 141 + 23 files changed, 14765 insertions(+), 49 deletions(-) create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_compiler_11_05_5_22pm.py.bak create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_policy_11_05_5_22pm.json.bak create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/runtime_manifest_11_05_5_22pm.json.bak create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/signal_compiler_11_05_5_22pm.py.bak create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8_11_05_5_22pm.yml create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_3_v.8_11_05_5_22pm.yml create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8_11_05_5_22pm.yml create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md create mode 100644 Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json index 71f3d99c..812aa449 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json @@ -1522,11 +1522,11 @@ }, { "path": "signals/compiler/signal_compiler.py", - "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b" + "sha256": "3a997bab70fe54c2815d776edabcc5115caf703c29756bc2919aad578bc2c013" }, { "path": "signals/compiler/signal_compiler.txt", - "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b" + "sha256": "3a997bab70fe54c2815d776edabcc5115caf703c29756bc2919aad578bc2c013" }, { "path": "signals/compiler/signal_gate.py", @@ -1758,15 +1758,15 @@ }, { "path": "stage1_runtime/fact_ledger_compiler.py", - "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64" + "sha256": "533dcee7302a0b9a238660091ab6cb607748144db53239b20a7425992aa4fcb8" }, { "path": "stage1_runtime/fact_ledger_compiler.txt", - "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64" + "sha256": "533dcee7302a0b9a238660091ab6cb607748144db53239b20a7425992aa4fcb8" }, { "path": "stage1_runtime/fact_ledger_policy.v1.json", - "sha256": "08fad0b20e299063b502fd2a0ae1877b9a7074bdce5391110ea5d632c53787f9" + "sha256": "57a97715f1890ac24b8d75de97d733d136ffe603ffa29d8b69b38f08ea744975" }, { "path": "stage1_runtime/prompt_compiler.py", diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py index 8f289b2d..1377bed1 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py @@ -166,7 +166,7 @@ def compile_transaction(inputs: dict[str, Any], output_dir: Path) -> dict[str, A }, "downstream_read_sets": { "part3_L0": ["SG-02", "SG-05", "SG-07", "SG-11", "SG-13"], - "part4_F0": ["SG-04", "SG-06", "SG-07", "SG-10", "SG-11"], + "part4_F0": ["SG-04", "SG-07", "SG-11"], # 11-05 P4-04: SG-06·SG-10 은 stage2(ALL)가 직접 읽는다 "stage2": ["ALL"], }, "writer": WRITER_ID, diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt index 8f289b2d..1377bed1 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt @@ -166,7 +166,7 @@ def compile_transaction(inputs: dict[str, Any], output_dir: Path) -> dict[str, A }, "downstream_read_sets": { "part3_L0": ["SG-02", "SG-05", "SG-07", "SG-11", "SG-13"], - "part4_F0": ["SG-04", "SG-06", "SG-07", "SG-10", "SG-11"], + "part4_F0": ["SG-04", "SG-07", "SG-11"], # 11-05 P4-04: SG-06·SG-10 은 stage2(ALL)가 직접 읽는다 "stage2": ["ALL"], }, "writer": WRITER_ID, diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py index 84112c74..48e2a28c 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py @@ -361,7 +361,12 @@ def compile_fact_ledger_candidates( structure_type_sidecars: dict, activation_document: Any, alias_declarations: Any, - policy: dict) -> dict: + policy: dict, + party_links_document: Any = None, + bo_scoped_review_codes: dict | None = None) -> dict: + # party_links_document — Part 1 value_facts_party_links.json(P4-01). 없으면 parties 는 빈 배열. + # bo_scoped_review_codes — {LES 코드: 그 코드가 실제로 가리키는 (domain_id, type_id, BO id) 집합}(P4-02). + # 구조 레코드에 달린 코드를 집합 안의 BO 행에만 옮긴다. None 이면 구조 단위 그대로. reviews: list[dict] = [] audit: dict[str, Any] = {} @@ -473,6 +478,18 @@ def compile_fact_ledger_candidates( gate_input_counts["operand_states"] += 1 audit["gate_input_counts"] = gate_input_counts + # ---- P4-01 — 금액 연결 당사자(client_goal 정규명) ------------------- + links_root = _dict(party_links_document) + party_by_value: dict[str, list[tuple[str, str]]] = {} + if links_root.get("status") in ("READY", "READY_WITH_REVIEW"): + for link in _list(links_root.get("links")): + link = _dict(link) + path = str(link.get("path") or "") + if (link.get("status") == "RESOLVED" and path.startswith("parties[") + and _nonblank(link.get("party_ref"))): + party_by_value.setdefault(str(link.get("value_id")), []).append( + (str(link["party_ref"]), path)) + # ---- F0-1 ~ F0-6b — 행 생성 ---------------------------------------- bo_records = [b for b in _list(bo_document) if isinstance(b, dict)] bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or "")) @@ -490,14 +507,16 @@ def compile_fact_ledger_candidates( fact_id = "F-%03d" % idx bo_id = str(bo.get("BO_ID") or "") # (가) 9필드 + # parties — BO value_refs 의 금액 연결 당사자만 싣는다. Performer·Subject 는 Part 2 정책이 + # 채우지 않는 칸이다(bo_surface_projection_policy not_projected). 빈 배열 = 금액 연결 당사자 없음. parties = [] - if _nonblank(core.get("Performer")): - parties.append({"role": "actor", "value": _text(core.get("Performer"), 160), - "source": "BO.core_field_base"}) - if _nonblank(core.get("Subject")): - parties.append({"role": "counterparty", - "value": _text(core.get("Subject"), 160), - "source": "BO.core_field_base"}) + seen_party: set[str] = set() + for value_id in _strings(bo.get("value_refs")): + for party_ref, path in party_by_value.get(value_id, []): + if party_ref not in seen_party: + seen_party.add(party_ref) + parties.append({"role": "value_party", "value": party_ref, + "source": "value_facts_party_links:%s/%s" % (value_id, path)}) provenance = _dict(bo.get("provenance")) alternatives = _list(provenance.get("amount_alternatives")) related = _list(provenance.get("amount_related_values")) @@ -534,7 +553,9 @@ def compile_fact_ledger_candidates( if isinstance(record.get("type_id"), str): slot["type_ids"].add(record["type_id"]) slot["review_codes"].update( - c for c in _strings(record.get("review_codes")) if _CODE_RE.match(c)) + c for c in _strings(record.get("review_codes")) if _CODE_RE.match(c) + and (domain_id, record.get("type_id"), bo_id) + in _dict(bo_scoped_review_codes).get(c, {(domain_id, record.get("type_id"), bo_id)})) domain_effects = {d: {k: sorted(v) for k, v in slot.items()} for d, slot in sorted(domain_effects.items())} modules = sorted({m for slot in domain_effects.values() for m in slot["module"]}) @@ -756,10 +777,16 @@ def compile_fact_ledger_candidates( projection_rows = [r["fact_id"] for r in rows if domain_id in r["domain_effects"]] entry["projected_row_count"] = len(projection_rows) - reviews.append({"review_code": "GATE_FIRED_REVIEW", + # 투영 행 0 — 사실 행 근거 없는 발화는 코드로 구분한다. 심각도는 유지한다(P4-08). + reviews.append({"review_code": ("GATE_FIRED_REVIEW" if projection_rows + else "GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW"), "severity": ("HARD_WARNING" if entry["blocks_final_drafting"] else "SOFT_WARNING"), - "gate_id": gate_id, "detail": ",".join(emitted)[:160]}) + "gate_id": gate_id, "domain_id": domain_id, + "projected_row_count": len(projection_rows), + # S2_20 은 코드 대신 이 표지로도 차단 게이트를 센다 — 새 코드에서도 등급이 유지된다. + "blocks_final_drafting": entry["blocks_final_drafting"], + "detail": ",".join(emitted)[:160]}) fired_by_domain.setdefault(domain_id, []).append({ "gate_id": gate_id, "codes": emitted, "row_must_consider": rule["row_must_consider"], @@ -818,9 +845,9 @@ def compile_fact_ledger_candidates( "action": row["action"], "legal_calculation_object": row["legal_calculation_object"], "object_spec": row["object_spec"], - "calculation_request_ids": sorted( + "calculation_request_ids": sorted(set( str(c.get("calculation_id")) for c in - row["calculation_requests"] if c.get("calculation_id"))} + row["calculation_requests"] if c.get("calculation_id")))} item = {"exception_id": "FX-%03d" % (len(exceptions) + 1), "exception_type": "legal_calculation_required", "fact_id": row["fact_id"], diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt index 84112c74..48e2a28c 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt @@ -361,7 +361,12 @@ def compile_fact_ledger_candidates( structure_type_sidecars: dict, activation_document: Any, alias_declarations: Any, - policy: dict) -> dict: + policy: dict, + party_links_document: Any = None, + bo_scoped_review_codes: dict | None = None) -> dict: + # party_links_document — Part 1 value_facts_party_links.json(P4-01). 없으면 parties 는 빈 배열. + # bo_scoped_review_codes — {LES 코드: 그 코드가 실제로 가리키는 (domain_id, type_id, BO id) 집합}(P4-02). + # 구조 레코드에 달린 코드를 집합 안의 BO 행에만 옮긴다. None 이면 구조 단위 그대로. reviews: list[dict] = [] audit: dict[str, Any] = {} @@ -473,6 +478,18 @@ def compile_fact_ledger_candidates( gate_input_counts["operand_states"] += 1 audit["gate_input_counts"] = gate_input_counts + # ---- P4-01 — 금액 연결 당사자(client_goal 정규명) ------------------- + links_root = _dict(party_links_document) + party_by_value: dict[str, list[tuple[str, str]]] = {} + if links_root.get("status") in ("READY", "READY_WITH_REVIEW"): + for link in _list(links_root.get("links")): + link = _dict(link) + path = str(link.get("path") or "") + if (link.get("status") == "RESOLVED" and path.startswith("parties[") + and _nonblank(link.get("party_ref"))): + party_by_value.setdefault(str(link.get("value_id")), []).append( + (str(link["party_ref"]), path)) + # ---- F0-1 ~ F0-6b — 행 생성 ---------------------------------------- bo_records = [b for b in _list(bo_document) if isinstance(b, dict)] bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or "")) @@ -490,14 +507,16 @@ def compile_fact_ledger_candidates( fact_id = "F-%03d" % idx bo_id = str(bo.get("BO_ID") or "") # (가) 9필드 + # parties — BO value_refs 의 금액 연결 당사자만 싣는다. Performer·Subject 는 Part 2 정책이 + # 채우지 않는 칸이다(bo_surface_projection_policy not_projected). 빈 배열 = 금액 연결 당사자 없음. parties = [] - if _nonblank(core.get("Performer")): - parties.append({"role": "actor", "value": _text(core.get("Performer"), 160), - "source": "BO.core_field_base"}) - if _nonblank(core.get("Subject")): - parties.append({"role": "counterparty", - "value": _text(core.get("Subject"), 160), - "source": "BO.core_field_base"}) + seen_party: set[str] = set() + for value_id in _strings(bo.get("value_refs")): + for party_ref, path in party_by_value.get(value_id, []): + if party_ref not in seen_party: + seen_party.add(party_ref) + parties.append({"role": "value_party", "value": party_ref, + "source": "value_facts_party_links:%s/%s" % (value_id, path)}) provenance = _dict(bo.get("provenance")) alternatives = _list(provenance.get("amount_alternatives")) related = _list(provenance.get("amount_related_values")) @@ -534,7 +553,9 @@ def compile_fact_ledger_candidates( if isinstance(record.get("type_id"), str): slot["type_ids"].add(record["type_id"]) slot["review_codes"].update( - c for c in _strings(record.get("review_codes")) if _CODE_RE.match(c)) + c for c in _strings(record.get("review_codes")) if _CODE_RE.match(c) + and (domain_id, record.get("type_id"), bo_id) + in _dict(bo_scoped_review_codes).get(c, {(domain_id, record.get("type_id"), bo_id)})) domain_effects = {d: {k: sorted(v) for k, v in slot.items()} for d, slot in sorted(domain_effects.items())} modules = sorted({m for slot in domain_effects.values() for m in slot["module"]}) @@ -756,10 +777,16 @@ def compile_fact_ledger_candidates( projection_rows = [r["fact_id"] for r in rows if domain_id in r["domain_effects"]] entry["projected_row_count"] = len(projection_rows) - reviews.append({"review_code": "GATE_FIRED_REVIEW", + # 투영 행 0 — 사실 행 근거 없는 발화는 코드로 구분한다. 심각도는 유지한다(P4-08). + reviews.append({"review_code": ("GATE_FIRED_REVIEW" if projection_rows + else "GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW"), "severity": ("HARD_WARNING" if entry["blocks_final_drafting"] else "SOFT_WARNING"), - "gate_id": gate_id, "detail": ",".join(emitted)[:160]}) + "gate_id": gate_id, "domain_id": domain_id, + "projected_row_count": len(projection_rows), + # S2_20 은 코드 대신 이 표지로도 차단 게이트를 센다 — 새 코드에서도 등급이 유지된다. + "blocks_final_drafting": entry["blocks_final_drafting"], + "detail": ",".join(emitted)[:160]}) fired_by_domain.setdefault(domain_id, []).append({ "gate_id": gate_id, "codes": emitted, "row_must_consider": rule["row_must_consider"], @@ -818,9 +845,9 @@ def compile_fact_ledger_candidates( "action": row["action"], "legal_calculation_object": row["legal_calculation_object"], "object_spec": row["object_spec"], - "calculation_request_ids": sorted( + "calculation_request_ids": sorted(set( str(c.get("calculation_id")) for c in - row["calculation_requests"] if c.get("calculation_id"))} + row["calculation_requests"] if c.get("calculation_id")))} item = {"exception_id": "FX-%03d" % (len(exceptions) + 1), "exception_type": "legal_calculation_required", "fact_id": row["fact_id"], diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json index bfd5aedb..3cf2b324 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json @@ -68,7 +68,7 @@ "source_bo_id": "BO_ID 그대로", "type": "compact.bo_type 단독 (LES types[0] 폴백 금지)", "date": "first_value(core_field_base.BehaviorTime, bo.date) — bo.date 는 BO 18키에 없어 항상 None. 골든은 BehaviorTime 0/59 라 전건 null", - "parties": "core_field_base 단독 — Performer -> role: actor · Subject -> role: counterparty · 값은 text(party, 160) · source: 'BO.core_field_base'. 구 signal 경로 폐지", + "parties": "BO value_refs 의 금액 연결 당사자 단독(11-05 P4-01) — value_facts_party_links.json 의 RESOLVED parties[i] 연결만, 값은 party_ref(client_goal 정규명) · role: value_party · source: 'value_facts_party_links:/'. 연결표의 value_facts_sha256 이 P2 handoff value_facts_binding(BOUND)과 같을 때만 쓴다. 빈 배열 = 금액 연결 당사자 없음. Performer·Subject 는 Part 2 가 채우지 않는 칸이라 쓰지 않는다", "amount": "value_id 있는 금액: json.dumps(ensure_ascii=False, sort_keys=True) 그대로. 절단·공백 정규화 없음. BO provenance.amount_alternatives 가 있으면 JSON 에 conflict{status, note, candidates[, selected_value_id]} 를 더한다. 그 밖의 값: text(first_value(bo.amount, core_field_base.Amount), 240). provenance.amount_related_values 가 있으면 related_values·note 를 더한다. 금액 본체는 언제나 BO 값이다", "action": "first_value(compact.action, core_field_base.Action) — 정규화 계층 통과 후의 소문자 키", "evidence_refs": "BO source_evidence_indexes 단독 — LES 증거는 합집합하지 않는다(합집합하면 v.8 에서 깨진다). LES 증거는 domain_effects 쪽에만 싣는다", @@ -263,6 +263,7 @@ "calculation_join": { "join_key": "signal_id (details.request_id 는 보장되지 않는 키)", "operand_state": "Part 2 산출을 재산정 없이 승계한다(D-P4-6). deferred 는 registry 선언값이다.", + "calculation_request_key": "request_id 가 계산 요청의 유일 키다(11-05 P4-03). 행의 calculation_requests 는 관련성 표시라 같은 요청이 여러 행에 있다. 계산·합산은 request_id 고유 기준으로 한다(writer report calculation_request_unique_count·calculation_readiness_unique).", "calculation_id_missing": "signal_id 로 대체하고 CALCULATION_ID_SUBSTITUTED_REVIEW 계수 — 버리지 않는다", "dangling_ref": "calculation_id 없는 stub 항목으로 적재(버리면 등식 ④가 정상 실행에서 발화) · CALCULATION_REF_DANGLING_REVIEW 계수", "law_version_refs": "SG-11 레코드 law_version_refs ∪ details.law_version_refs ∪ 해당 도메인 SG-04 레코드 signal_id — 버전 확정 판단 금지(SG-04 는 참조만)" diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md new file mode 100644 index 00000000..c9df70e2 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md @@ -0,0 +1,140 @@ +# Stage 1 Part 2 실행결과보고서 1 (2026-11-05, Part 4 일치성 개정 반영판) + +- **대상:** `stage_1_part_2_v.8.yml`(`a212b744…`)이다. Part 4 일치성 해결법에 따라 두 곳을 고친 판이다. + - **P4-06:** projection-note와 F0 정규화 handoff 항목을 `"source_review_code": None, "source_field": …`로 바꿨다. + - **manifest 고정값:** `EXPECTED_RUNTIME_MANIFEST_SHA256`을 `9d2df172…`로 갱신했다. +- **실행:** + - workspace `11월_1일_구성`, 세션 `1fb26ede`. + - YAML 업로드 09:55:40·09:55:54(2회). 실행 2026-11-05 09:56:57.87 ~ 10:01:12.01 UTC(**4분 14초**). +- **근거(모두 읽기 전용):** `agent-backend` 로그(타임스탬프 포함)만 썼다. + - task 이벤트, 코드 task 결과 JSON, `[USAGE]`·`usage:` 토큰 기록. + - R1 사전 읽기 원문, `write_file` 결과, 실행 코드 본문. + - localdocs 파일은 암호화돼 저장되므로 내용을 직접 읽지 않았다(Part 4 보고서 1 참고). + +## 1. 판정 — **성공** (BO `PASS` 88건, signal `READY_WITH_REVIEW`) + +| 기준 | 결과 | +|---|---| +| 백엔드 | task 37개 모두 `task_complete`. `task_error`·`task_retry`·`stage_error` 0건. `stage_complete`·`execution_complete` 각 1건 | +| A0 배포 게이트 | `READY`. 모듈 8종 반입, 도메인 15개, value_facts `BOUND`. 경고 1건(`PREFLIGHT_FILE_NEAR_LIMIT`, 공유 우주 254,830자 / 한도 260,000) | +| worker·capture | worker 15개 모두 LLM 1회로 끝났다. capture 15개 모두 `CAPTURED`, `echo_mismatch` 0 | +| R0 | `READY`. 후보 88 → ledger 88(정확 중복 흡수 0), 근접 중복 군집 16, 예외 13, review 382, salvage 0 | +| R1 | Gemini 3.5 Flash-Lite 9.69초. 결정 파일 4,406자 기록 | +| F0 | **`PASS`. BO 88건.** 게이트 7개 모두 PASS. 금액 결속 46, 하향 0, 사람 판정 0 | +| S0 | `READY_WITH_REVIEW`. 정본 signal 거래 1건(`S5TX-92952e6df623cb1f439f`), 파일 32종. signal gate PASS, 오류 0 | +| 비용 | **$1.99**(로그 기록 합계 $1.988904) | + +### 1.1 개정판이 실행됐는지 + +- 로그에 남은 실행 코드에 `"source_review_code": None`과 `"source_field"`가 각 2회 나온다(P4-06). +- 새 manifest sha `9d2df172…`가 1회 나오고, 옛 값 `a828e962`는 0회다. +- A0가 `READY`를 냈으므로 서버 `runtime_manifest.json`의 sha가 이 고정값과 맞았다. 11-05 9:36에 올린 새 manifest가 Part 2 배포 게이트도 통과한 것이다. + +### 1.2 로그의 오류 기록 (실행에 영향 없음) + +- `read_docs` 호출 12건이 3회 재시도 끝에 실패했다. 원인은 `MCPError: SSE stream ended without a response`다. + - task가 확인된 것은 11건이다: worker 0·1·2·3·6·7·8·9·10·12·13. 나머지 1건은 바로 뒤 줄에 task 표시가 없어 특정하지 못했다. + - 실패 시각: 09:57:14~17, 15개 worker가 동시에 사전 읽기를 하던 때다. +- **영향 없음.** 이 호출은 사전 읽기를 마친 뒤의 부수 `read_docs`다. + - 15개 worker 모두 그 전에 `Pre-read loaded 6 file(s)`를 기록했다. + - 모두 `Injected no-tools preflight (2 dynamic + 4 shared)`로 입력 6개를 주입받고 정상 응답했다. +- localdocs의 동시 SSE 연결이 몰릴 때 생기는 백엔드 쪽 일시 오류로 본다. YAML 수정은 필요 없다. + +## 2. IO 구조 (실측 시각) + +``` +A0 (코드, 09:57:02 완료, 4.42s) ─ 봉인 대조(manifest 9d2df172) · slice 15 · 한도 검사 + └▶ runtime/{domain_slices, compiled_prompts, worker_inputs}/ ×15 · runtime/shared/* +prewarm (Sol, 4.53s, 캐시 기록 114,055) ─▶ load_fanout (코드 3.35s, PREPARED 15) + ▼ 15개 동시 (09:57:14~18 요청) +worker_* ×15 (Sol, 10.2~137.0s) ─▶ capture_* ×15 (각 약 3.2s) ─▶ runtime/domain_seed_outputs/.json + ▼ 마지막 worker 10:00:47 +R0 (코드 3.94s) ─▶ postb_seed_ledger.json(88) · exception_pack(13) · review_handoff(382) +R1 (Flash-Lite 9.69s, 10:01:04) ─▶ postb_adjudication_decisions.json +F0 (코드 3.29s) ─▶ BO.json(88) · postb_compiled_bundle_compact.json · handoff FINALIZED +S0 (코드 4.00s, 10:01:12) ─▶ signals/signal_manifest.json + 31파일 +``` + +## 3. 산출물 + +### 3.1 worker 15개 (GPT-6.1 Sol, `responses` 엔드포인트, 도구 미노출) + +| 도메인 | worker | 소요(초) | 입력 토큰 | 캐시 적중 | 출력 토큰 | seed 크기(자) | +|---|---|---:|---:|---:|---:|---:| +| E-01 | 0 | 43.99 | 122,684 | 114,055 | 4,248 | 15,521 | +| E-02 | 1 | 105.33 | 126,462 | 114,055 | 11,255 | 49,625 | +| E-03 | 2 | 34.10 | 123,795 | 114,055 | 2,996 | 10,029 | +| E-04 | 3 | 74.63 | 128,425 | 114,055 | 7,510 | 30,873 | +| E-07 | 4 | 25.34 | 121,548 | 114,055 | 2,260 | 7,824 | +| E-08 | 5 | 64.37 | 125,071 | 114,055 | 5,814 | 21,425 | +| E-09 | 6 | 136.99 | 132,535 | 114,055 | 14,358 | 61,216 | +| E-10 | 7 | 116.88 | 132,412 | 114,055 | 13,060 | 52,019 | +| E-11 | 8 | 77.96 | 135,867 | 114,055 | 7,779 | 28,736 | +| E-12 | 9 | 26.66 | 122,795 | 114,055 | 1,424 | 3,924 | +| E-13 | 10 | 102.96 | 131,548 | 114,055 | 10,668 | 39,840 | +| E-15 | 11 | 32.07 | 120,666 | 114,055 | 2,923 | 10,478 | +| X1 | 12 | 110.00 | 126,585 | 114,055 | 13,233 | 56,823 | +| X2 | 13 | 131.05 | 135,633 | 114,055 | 13,864 | 55,837 | +| X3 | 14 | 10.22 | 117,845 | 114,055 | 550 | 1,196 | + +- 15개 모두 공유 접두부 114,055토큰이 캐시에 적중했다(입력의 84~97%). prewarm이 캐시를 기록한 덕분이다. +- `thoughts` 토큰은 0으로 기록됐다. + +### 3.2 R0·R1·F0 + +- **R0:** 후보 88건이 모두 ledger에 들어갔다. + - 예외 13건은 모두 `field_conflict`다. 같은 출처의 후보끼리 `BehaviorTime`이나 금액이 갈린 경우다. + - 13건 모두 `escalation_flag: true`다. +- **R1:** 13건을 판정해 `postb_adjudication_decisions.json`(4,406자)에 기록했다. +- **F0:** `r1_decision_state: READ`. `human_review_count` 0이므로 `BLOCK_REVIEW` 판정은 0건이다. + - 게이트 7개 결과: `r1_decision_presence`, `candidate_conservation`(BO 88 + 흡수 0 = ledger 88), `bo_items_array_non_empty`, `bo_schema_and_reference_validation`, `extension_payload_key_declaration_check`(BO 유형 5, 선언 키 175, 미선언 확장 키 88건), `value_ref_check`(BOUND, 하향 0, 금액 BO 46), `post_write_json_parse`. 모두 PASS. + +### 3.3 S0 signal + +- `active_domains`는 13개다(E-08·E-13 제외). 4차와 같다. +- 미배정 operand는 47개다. +- 입력: seed 15, BO id 88, evidence 30, event 100, meeting 41, fact_id 117. +- 호환 뷰 `case_liability_signals.json`·`legal_effect_signals.json`이 비어 있다는 `COMPATIBILITY_VIEW_EMPTY` 알림이 나왔다(이전과 같은 알려진 알림). + - 알림에 실린 `downstream_read_sets.part4_F0`가 `["SG-04","SG-07","SG-11"]`이다. P4-04로 고친 `signal_compiler`가 서버에서 쓰였다는 뜻이다. + +## 4. LLM API 비용 + +| 호출 | 모델 | 횟수 | 입력(비캐시) | 캐시 적중 | 캐시 기록 | 출력 | 비용 | +|---|---|---:|---:|---:|---:|---:|---:| +| prewarm | GPT-6.1 Sol | 1 | — | — | 114,055 | 0 | $0.2851 | +| worker | GPT-6.1 Sol | 15 | 193,046 | 1,710,825 | 0 | 111,942 | $1.6766 | +| R1 | Gemini 3.5 Flash-Lite | 1 | 74,736 | 4,780 | 0 | 1,841 | $0.0272 | +| **합계** | | **17** | | | | | **$1.9889** | + +- 로그 `[USAGE]` 17건 합계는 $1.988904이고, 위 분해와 같다. +- 로그 비용에서 역산한 단가(100만 토큰당)는 다음과 같다. 15개 worker에서 오차 $0.000001 이내로 맞는다. + - GPT-6.1 Sol: 입력 $2.00, 캐시 적중 $0.10, 캐시 기록 $2.50, 출력 $10.00. + - Flash-Lite: 입력 $0.30, 캐시 적중 $0.03, 출력 $2.50. +- worker 비용의 67%($1.12)가 출력 토큰이다. +- 캐시가 없었다면 worker 비용은 약 $4.93였을 것이다. prewarm 비용($0.29)을 더해도 약 $2.97를 아꼈다. + +## 5. 회차 비교 + +| 지표 | 11-04 4차(`5d47278e`) | **11-05 1차(`1fb26ede`)** | +|---|---:|---:| +| 결과 | 전부 성공 | **전부 성공** | +| 후보·BO | 78 / 78 | **88 / 88** | +| R0 예외 | 8 | **13** | +| R1 BLOCK / F0 사람 판정 | 2 / 2 | **0 / 0** | +| review handoff | 451 | **382** (R0 기준) | +| 금액 결속 BO | 42 | **46** | +| active_domains | 13 | 13 | +| 런타임 · 비용 | 4분 35초 · $1.96 | **4분 14초 · $1.99** | + +- 이번 개정은 worker 프롬프트를 바꾸지 않았다. 후보 수가 바뀐 것(78 → 88)은 LLM을 다시 실행해서 생긴 차이다. + +## 6. 남은 일 + +1. **Part 3·Part 4를 다시 실행해야 한다.** BO가 88건으로 바뀌었고 signal 거래 id도 새로 바뀌었다(`S5TX-89d9…` → `S5TX-9295…`). + - 지금 서버의 Part 3·4 산출(BO 78 기준)은 낡았다. + - Part 4 F0는 BO 봉인(`bo_input_seal`)을 Part 3 영수증과 대조한다. 그래서 Part 3를 건너뛰고 Part 4만 돌리면 `PART4_BO_SEAL_MISMATCH`로 멈춘다. + - 순서: Part 3 → Part 4. +2. **P4-06 효과는 Part 4를 다시 실행해야 확인된다.** Part 4 review 중 `P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW`(이전 55건)가 0건이 되는지 본다. +3. **F1 위치 편향:** Part 4 보고서 1에서 지적한 문제다. 다음 Part 4 실행에서 다시 관찰한다. +4. **커밋은 아직 하지 않았다.** Part 2·4 YAML과 자산 6종이 로컬 작업 트리에만 있다. +5. **검증 범위:** 형식, 흐름, 계약 준수, 비용만 보았다. BO와 signal의 법률적 타당성은 판단하지 않았다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md new file mode 100644 index 00000000..f5913bbf --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md @@ -0,0 +1,163 @@ +# Stage 1 Part 4 실행결과보고서 1 (2026-11-05, 일치성 해결법 7건 적용판 첫 실행) + +- **대상:** `stage_1_part_4_v.8.yml`(`c53a0120…`, 1,348행)이다. P4-01~08 가운데 7건을 적용한 판이다. + - 적용 순서: P4-06 → 07 → 08 → 02 → 03 → 04 → 01. + - 보존본: `_11_05_5_22pm`. +- **함께 배포한 정적 자산 6종:** workspace `Default_Agent/` 아래에 올라간 시각(UTC)은 다음과 같다. + - 09:33 `stage1_runtime/fact_ledger_compiler.py`·`.txt` + - 09:34 `stage1_runtime/fact_ledger_policy.v1.json` + - 09:35 `signals/compiler/signal_compiler.py`·`.txt` + - 09:36 `runtime_manifest.json` +- **실행:** + - workspace `11월_1일_구성`, 세션 `13825502`. + - YAML 업로드 09:39:29, 실행 2026-11-05 09:40:32.35 ~ 09:40:46.90 UTC(**14.6초**). +- **입력:** Part 2 4차 산출(BO 78건)과 Part 3 4차 산출(세션 `6ed2a14b`, 부착 68/미부착 10)이다. **Part 2는 다시 실행하지 않았다.** +- **근거(모두 읽기 전용):** + - `agent-backend` 로그(타임스탬프 포함): task 결과 JSON, F1 사전 읽기 원문, F1 `write_file` 결과, 실행 코드 본문. + - localdocs 파일 목록과 크기. + - 같은 YAML·자산·입력으로 돌린 로컬 재생 하네스(`scratchpad/p4run/replay_sel`). + +> **localdocs는 파일을 암호화해서 저장한다.** 서버 파일은 평문보다 28바이트(nonce 12 + tag 16) 크고, sha256으로 로컬 파일과 비교할 수 없다. +> 평문은 백엔드 API로만 받을 수 있는데, 그 경로는 관리자 토큰이 필요해 이번에는 쓰지 않았다. +> 대신 아래 §1.2의 세 가지 대조로 서버 산출이 로컬 재생본과 같은지 확인했다. + +## 1. 판정 — **성공** + +| 기준 | 결과 | +|---|---| +| 백엔드 | task 3개 모두 `task_complete`. `task_error`·`task_retry`·Traceback 0건. `stage_complete`·`execution_complete` 각 1건 | +| F0 (code) | 3.81초. `READY_WITH_REVIEW`. 모듈 5종 반입, 행 78, 게이트 선언 82·구현 10·발화 5, 예외 7, review 200. `errors`·`warnings` 비어 있음 | +| F1 (LLM) | `gemini-3.5-flash-lite`, 1회 6.89초, 15,139토큰. `write_file` 1회로 `fact_adjudication.json` 2,020자 기록 | +| F2 (code) | 3.52초. `READY_WITH_REVIEW`. 행 78, **선택 7·미해결 0**, 보존 등식 통과. `final_sha256` **`0780f4f0af7f…`** | +| 배포 게이트 | 통과. 새 컴파일러 시그니처(`party_links_document`·`bo_scoped_review_codes`)로 호출해 정상 반환했다 → 서버에 개정 자산이 올라가 있고 manifest 봉인도 맞았다 | + +### 1.1 실행된 코드가 개정판인지 + +로그의 F0·F2 코드 본문에서 개정 표지를 셌다. + +| 표지 | 개수 | 해당 수정 | +|---|---|---| +| `PARTY_LINKS_PATH`, `party_links_document` | 4, 1 | P4-01 | +| `BO_SCOPED_P3_CODES`, `bo_scoped_review_codes`, `P3_HANDOFF_ABSENT_REVIEW` | 2, 1, 2 | P4-02 | +| `calculation_request_unique_count` | 1 | P4-03 | +| `SG06`, `SG10` | **0** | P4-04 (읽기 제거) | +| `P3_RECEIPT_PATH`, `PART4_BO_SEAL_MISMATCH` | 4, 1 | P4-07 | +| `VALUE_FACTS_PARTY_LINKS_STALE_REVIEW` | 2 | P4-01 신선도 검사 | + +### 1.2 서버 산출 = 로컬 재생 산출 + +1. **F0 결과 JSON이 같다.** 로컬 재생 F0 결과와 서버 F0 결과가 필드 단위로 같다(`row_count` 78, `gates` 82/10/5, `exception_count` 7, `review_item_count` 200, `warnings` []). +2. **F1 입력 pack이 바이트 단위로 같다.** 로그에 남은 F1 사전 읽기 원문과 로컬 pack이 sha `6e560dacdfbd…`, 10,874바이트로 같다. +3. **F2 최종 sha가 같다.** 로컬에서 F1 판정을 "각 예외의 첫 후보 선택(`SELECT_AMOUNT`)"으로 두고 F2를 돌렸다. 그 결과 `final_sha256`이 서버 값 `0780f4f0…`과 **같다.** + - 따라서 F1 LLM은 7건 모두 첫 후보를 골랐다. + - 서버 `Fact_Ledger_base.json`은 로컬 모사본과 바이트 단위로 같다. +4. **나머지 파일은 크기가 같다.** 서버 크기에서 28을 뺀 값이 로컬 모사본 크기와 6개 파일 모두 같다. + +| 파일 | 서버(암호문) | −28 | 로컬 모사 | +|---|---|---|---| +| `Fact_Ledger_base.json` | 227,498 | 227,470 | 227,470 | +| `stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json` | 251,475 | 251,447 | 251,447 | +| `stage1_tmp/fact_ledger/fact_exception_pack.json` | 10,902 | 10,874 | 10,874 | +| `stage1_tmp/fact_ledger/fact_ledger_writer_report.json` | 2,750 | 2,722 | 2,722 | +| `quality_gates/stage1_part4_review_handoff.json` | 32,247 | 32,219 | 32,219 | +| `validation_assets/routing/part4_receipt.json` | 1,702 | 1,674 | 1,674 | +| 자산: compiler `.py`·`.txt` / policy / signal_compiler / manifest | 49,823 / 23,648 / 9,016 / 72,189 | 49,795 / 23,620 / 8,988 / 72,161 | 로컬 개정판과 같음 | + +- `fact_adjudication.json`(2,048 → 2,020)은 LLM 문장이 들어 있어 모사하지 않았다. + +이하 §2~§4의 수치는 서버 산출과 같은 로컬 모사본에서 읽었다. + +## 2. IO 구조 (실측 시각) + +``` +F0 (09:40:32.39 → 36.20, 3.81s) + ─▶ fact_ledger_candidate_bundle.json · fact_exception_pack.json(7) + fact_adjudication.json(PENDING) · stage1_part4_review_handoff.json(OPEN, 200) + part4_receipt.json +F1 (→ 43.36, Gemini 6.89s) ─▶ fact_adjudication.json (READY, 결정 7) +F2 (→ 46.90, 3.52s) ─▶ Fact_Ledger_base.json · fact_ledger_writer_report.json + handoff FINALIZED(200) +``` + +## 3. 수정별 효과 (개정 전 재생과 비교) + +| 수정 | 개정 전 | 이번 실행 | +|---|---|---| +| **P4-01** 당사자 | `parties`가 있는 행 0 | **42행**, `value_party` 74개. 출처 예: `value_facts_party_links:E-003-VF-001/parties[0]` = 오국한 | +| **P4-02** 추천기 표지 | `PART3_BO_ATTACHED_BY_RECOMMENDER`가 12행에 퍼짐 | **5행**(bh3·bh7·bh31·bh40·bh42). Part 3 4차에서 실제로 붙은 BO 5건과 같다 | +| **P4-03** 계산 요청 | 행 단위 합계만 있음(blocked 67 / deferred 10 / partial 323 = 400) | 같은 값에 더해 `request_id` 기준 **고유 46건**(blocked 8 / deferred 2 / partial 36). 보존 등식 `calc_row` 400 = 400 | +| **P4-04** 신호 읽기 | SG-06·SG-10 읽음 | 읽지 않음. `signal_compiler`의 Part 4 집합은 SG-04·SG-07·SG-11 | +| **P4-06** Part 2 비코드 항목 | `P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW` 55건 | **그대로 55건.** Part 2를 다시 돌리지 않아 handoff가 예전 것이기 때문이다(§5) | +| **P4-07** BO 봉인 | 확인 없음 | `entry_seals.bo_input_seal` = **MATCHED**. LES 봉인 MATCHED, 신호 31파일, config 체인 15 | +| **P4-08** 행 없는 게이트 | E-15 게이트가 `GATE_FIRED_REVIEW`(행 0) | E-15 세 개는 **`GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW`**, X1 두 개는 `GATE_FIRED_REVIEW`(행 5). 다섯 개 모두 `blocks_final_drafting`이 있다 | + +### 3.1 게이트 발화 5건 + +| 영역 | gate | review_code | 심각도 | 투영 행 | blocks_final_drafting | +|---|---|---|---|---|---| +| E-15 | E15-G01 | GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW | HARD | 0 | true | +| E-15 | E15-G02 | GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW | SOFT | 0 | false | +| E-15 | E15-G03 | GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW | HARD | 0 | true | +| X1 | X1-G01 | GATE_FIRED_REVIEW | HARD | 5 | true | +| X1 | X1-G02 | GATE_FIRED_REVIEW | SOFT | 5 | false | + +- HARD 3건은 모두 `blocks_final_drafting: true`다. 그래서 S2_20이 `review_code` 문자열만 보지 않고 이 키도 보면 HARD 경보가 낮아지지 않는다. +- E15-G02(SOFT, 행 0)는 S2_20 등급이 3에서 4로 내려간다. YAML 머리말에 적어 둔, 받아들인 차이다. + +### 3.2 handoff review 200건 (FINALIZED) + +| review_code | 건수 | +|---|---| +| GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW | 72 | +| P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW | 55 | +| STRUCTURE_UNATTACHED_REVIEW | 28 | +| CALCULATION_BASIS_INCOMPLETE_REVIEW | 26 | +| FACT_ROW_UNATTACHED_REVIEW | 10 | +| GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW | 3 | +| LEGACY_ALIAS_SELF_MISMATCH_REVIEW | 2 | +| GATE_FIRED_REVIEW | 2 | +| LEGACY_ALIAS_DECLARATION_INCOMPLETE_REVIEW | 1 | +| CALCULATION_REQUEST_UNATTACHED_REVIEW | 1 | + +- 심각도: SOFT 197, HARD 3. +- `CALCULATION_BASIS_CONFLICT_REVIEW`는 0건이다. F1이 7건을 모두 판정해 F2가 갈림 항목을 하나도 덧붙이지 않았다. F1을 BLOCK으로 둔 재생에서는 7건이 붙어 207건이었다. +- 입력이 빠졌을 때 남기는 review(`P3_HANDOFF_ABSENT_REVIEW`, `VALUE_FACTS_PARTY_LINKS_STALE_REVIEW`, BO 봉인 미확인)는 하나도 나오지 않았다. 세 입력이 모두 있었고 신선했다. + +### 3.3 보존 등식 (F0 영수증·F2 보고서 모두 통과) + +| 등식 | 값 | +|---|---| +| row | BO 78 = 행 78 | +| attachment | 부착 68 + 미부착 10 = 78 (Part 3 4차와 같음) | +| effect | 68 = 68 | +| calc_row | 400 = 400 | +| calc_source | SG-11 47개 중 부착 46, 미부착 1 | + +- 영역별 효과 수: E-01 3, E-02 12, E-03 2, E-04 7, E-07 1, E-08 2, E-09 6, E-10 13, E-11 4, E-13 4, X1 5, X2 9. + +## 4. F1 금액 판정 7건 (모두 `SELECT_AMOUNT`, 첫 후보) + +| 예외 | fact | 선택 value_id | 후보 수 | 내용 | +|---|---|---|---|---| +| FX-001 | F-002 | E-014-VF-003 | 3 | 신림동 상가의 등기상 명의·담보 설정·말소 계보 | +| FX-002 | F-007 | E-004-VF-002 | 3 | 신림동 상가의 연도별 시가 평가 | +| FX-003 | F-008 | E-004-VF-006 | 2 | 포천시 임야의 연도별 평가구간 | +| FX-004 | F-011 | E-004-VF-002 | 4 | 신림동 상가와 포천시 임야의 기간별 시가 평가 | +| FX-005 | F-032 | E-013-VF-006 | 3 | 성수동 대지의 지분별 담보·명의 계보 | +| FX-006 | F-044 | E-014-VF-003 | 3 | 신림동 상가 매매등기와 피보전채권·담보·명의신탁 항변 | +| FX-007 | F-054 | E-006-VF-003 | 2 | 이문호의 상가 매매대금 수령(보증금과 구별) | + +- 일곱 예외의 사유는 모두 `legal_calculation_required`다. +- F2는 BO 금액을 바꾸지 않는다. `amount.conflict`만 `SELECTED`와 `selected_value_id`로 표시한다. 그래서 잘못 골랐더라도 원 금액과 후보는 남는다. + +## 5. 관찰과 남은 일 + +1. **F1이 7건 모두 첫 후보를 골랐다.** 위치 편향일 수 있다. + - 특히 FX-004는 두 목적물(신림동·포천)에 걸친 평가인데 신림동 값 하나(VF-002)를 골랐다. FX-002도 같은 값을 골랐다. + - `legal_calculation_required` 예외는 하나를 고르기보다 `BLOCK_REVIEW`로 두는 편이 맞을 수 있다. + - 확인 방법: `fact_adjudication.json`의 `rationale`을 읽는다(암호화돼 있어 이번에는 못 읽음). 필요하면 F1 프롬프트에 "계산이 필요한 예외는 후보 하나를 고르지 않는다" 규칙을 두는 것을 검토한다. +2. **P4-06 효과는 아직 확인되지 않았다.** Part 2 YAML(`a212b744…`)을 다시 돌려야 비코드 항목 55건이 사라진다. + - 로컬 모사에서는 review가 207건에서 152건으로 줄었다. + - 서버 manifest가 이미 새 판(크기 72,161 = 로컬 `9d2df172…`)이라, Part 2의 `EXPECTED_RUNTIME_MANIFEST_SHA256` 검사도 통과할 것으로 본다. +3. **`GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW` 72건이 review의 36%다.** 게이트 선언 82개 중 10개만 구현돼 생기는 기존 소음이다. 이번 개정 범위 밖이다. +4. **커밋은 아직 하지 않았다.** 개정 YAML 2개와 자산 6종이 로컬 작업 트리에만 있다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md new file mode 100644 index 00000000..b7ef1e68 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md @@ -0,0 +1,110 @@ +# Stage 1 Part 4 실행결과보고서 2 (2026-11-05, Part 2·3 재실행 산출 위 재실행) + +- **대상:** `stage_1_part_4_v.8.yml`(`c53a0120…`). 1차와 같은 판이다(이 구간 로그에 `upload-agent` 없음). +- **실행:** workspace `11월_1일_구성`, 세션 `b4fc2158`, 2026-11-05 10:20:48.84 ~ 10:21:03.63 UTC(**14.8초**). +- **입력이 1차와 다르다.** + - Part 2 개정판 첫 실행 산출(세션 `1fb26ede`, BO 88, signal `S5TX-92952e6df623cb1f439f`). + - Part 3 5차 산출(세션 `88ee7816`, 부착 82 / 미부착 6, 추천기 부착 0). +- **근거(모두 읽기 전용):** + - `agent-backend` 로그: task 이벤트, F0·F2 결과 JSON, F1 사전 읽기 원문, `[USAGE]`. + - localdocs 파일 목록과 크기. + +> **이번에는 서버 산출을 바이트 단위로 대조하지 못했다.** +> 1차에서는 같은 입력으로 로컬 재생을 돌려 F2 최종 sha를 맞췄다. 이번에는 Part 2·3 입력이 새로 바뀌었고, 그 평문이 로컬에 없다(localdocs는 파일을 암호화해 저장한다). +> F1 판정 원문도 로그에 앞부분만 남아, 어느 예외에서 어떤 값을 골랐는지 알 수 없다. +> 아래 내용은 로그에 남은 결과 JSON과 F1 입력 원문만으로 판단했다. + +## 1. 판정 — **성공** + +| 기준 | 결과 | +|---|---| +| 백엔드 | task 3개 모두 완료. 오류·재시도·Traceback 0건. `stage_complete`·`execution_complete` 각 1건 | +| F0 (code, 3.68초) | `READY_WITH_REVIEW`. 모듈 5종, **행 88**, 게이트 82/10/5, 예외 7, **review 133**. `errors`·`warnings` 비어 있음 | +| F1 (Gemini 3.5 Flash-Lite, 7.44초) | `fact_adjudication.json` 2,095자 기록 | +| F2 (code, 3.34초) | `READY_WITH_REVIEW`. 행 88, **선택 3·미해결 4**, 보존 등식 통과. `final_sha256` `701a65e1ad60…` | +| 비용 | **$0.0114** | + +### 1.1 로그로 확인한 것과 확인하지 못한 것 + +| 수정 | 확인 결과 | +|---|---| +| P4-07 BO 봉인 | **통과.** BO가 Part 3 영수증과 어긋나면 F0가 `PART4_BO_SEAL_MISMATCH`로 멈추고, 영수증이 없거나 비면 경고를 남긴다. 둘 다 없었다(`warnings: []`). 새 BO 88건이 Part 3 5차 영수증과 일치했다 | +| P4-06 Part 2 비코드 항목 | **간접 확인.** review가 200에서 133으로 67건 줄었다. 1차의 비코드 항목 55건이 빠진 것과 방향이 맞다. 다만 입력도 바뀌어 항목별 분해는 하지 못했다 | +| 행·보존 | 행 88 = BO 88. F2 보존 등식 통과 | +| P4-01 당사자, P4-02 추천기 표지, P4-03 고유 계산 요청, P4-08 게이트 코드 | **미확인.** 결과가 암호화된 산출 파일 안에만 있다. 1차 실행에서 같은 코드가 정상 동작한 것은 확인했다(보고서 1) | + +## 2. IO 구조 (실측 시각) + +``` +F0 (10:20:48.9 → 52.6, 3.68s) ─▶ bundle(272,799) · pack(7) · handoff(OPEN, 133) · receipt +F1 (→ 10:21:00.3, Gemini 7.44s, 호출 2회) ─▶ fact_adjudication.json (2,095자) +F2 (→ 10:21:03.6, 3.34s) ─▶ Fact_Ledger_base.json(248,553) · writer_report · handoff FINALIZED +``` + +- 괄호 안 숫자는 평문 크기다(서버 크기 − 28바이트). + +## 3. 결과물 + +### 3.1 1차와 비교 + +| 지표 | 1차 (`13825502`, BO 78) | **2차 (`b4fc2158`, BO 88)** | +|---|---:|---:| +| 행 | 78 | **88** | +| 게이트 선언 / 구현 / 발화 | 82 / 10 / 5 | 82 / 10 / 5 | +| 금액 예외 | 7 | 7 | +| F0 review | 200 | **133** | +| F1 선택 / 미해결 | 7 / 0 (모두 첫 후보) | **3 / 4** | +| `Fact_Ledger_base.json` 평문 | 227,470 | 248,553 | +| 실행 시간 · 비용 | 14.6초 · $0.0115 | 14.8초 · $0.0114 | + +- 1차 비용은 이번에 로그 `[USAGE]`에서 다시 확인했다(09:40:43, $0.011500). 1차 보고서에는 적지 않았던 값이다. + +- **F1이 이번에는 3건만 골랐다.** 나머지 4건은 미해결로 남았고, F2가 이 4건을 `CALCULATION_BASIS_CONFLICT_REVIEW`로 handoff에 덧붙였다(최종 133 + 4 = 137건 예상). + - 1차에서 걱정한 "모든 예외에 첫 후보 선택"은 이번에 나타나지 않았다. + - 다만 판정 원문이 로그에서 잘려, 어느 3건을 골랐는지는 확인하지 못했다. + +### 3.2 F1 금액 예외 7건 (입력 원문) + +| 예외 | fact | 후보 value_id | 내용 | +|---|---|---|---| +| FX-001 | F-023 | E-014-VF-003·004·005 | 신림동 상가의 주소 동일성·소유 계보·담보 존속·말소·실질 귀속 다툼 | +| FX-002 | F-036 | E-013-VF-006·008·009 | 성수동 대지의 표시·공유지분 변동·경매 전후 등기 계보 | +| FX-003 | F-047 | E-004-VF-002·003·004·006·007 | 신림동 상가와 포천 임야의 기간별 시가 평가(반환가액 검토용) | +| FX-004 | F-049 | E-004-VF-002·003·004 | 신림동 상가의 기간별 시가 평가와 건물 표시 결합 | +| FX-005 | F-050 | E-004-VF-006·007, E-008-VF-002 | 포천 임야의 기간별 감정 시가와 담보가치에 관한 상반된 자료 | +| FX-006 | F-054 | E-003-VF-001, E-014-VF-003 | 신림동 상가의 오민한 명의 이전(채권자취소 대상 처분 후보) | +| FX-007 | F-087 | E-006-VF-003·006 | 박성희의 성수동 대지·상가 관리·사용 약정(사용이익 귀속) | + +- 1차와 같은 대상(신림동·포천·성수동)이 다시 예외로 나왔다. 다만 fact id와 후보 묶음이 바뀌었다(BO가 새로 만들어졌기 때문). +- FX-003처럼 두 목적물에 걸친 기간별 평가는 값 하나를 고르는 것이 맞지 않다. 이런 항목은 미해결로 남는 편이 옳다. + +## 4. LLM API 비용 + +| 호출 | 모델 | 입력(비캐시) | 캐시 적중 | 출력 | 비용 | +|---|---|---:|---:|---:|---:| +| F1 1차 응답(`write_file`) | Gemini 3.5 Flash-Lite | 13,538 | 2,390 | 1,081 | | +| F1 2차 응답(종료) | Gemini 3.5 Flash-Lite | 14,671 | 2,390 | 46 | | +| **합계** | | 28,209 | 4,780 | 1,127 | **$0.011424** | + +- 로그 `[USAGE]` 기록은 $0.011424 한 건이다. +- 단가(100만 토큰당: 입력 $0.30, 캐시 적중 $0.03, 출력 $2.50)로 다시 계산해도 같은 값이 나온다. +- F0·F2는 코드 task라 LLM 비용이 없다. + +## 5. Stage 1 전체 재실행 결과 (11-05) + +| Part | 세션 | 결과 | 시간 | 비용 | +|---|---|---|---:|---:| +| Part 2 | `1fb26ede` | BO `PASS` 88, signal `READY_WITH_REVIEW` | 4분 14초 | $1.989 | +| Part 3 | `88ee7816` | L2 `READY_WITH_REVIEW`, 부착 82 / 88 | 48.5초 | $0.023 | +| Part 4 | `b4fc2158` | `READY_WITH_REVIEW`, 행 88, 선택 3 / 미해결 4 | 14.8초 | $0.011 | +| **합계** | | **세 Part 모두 성공** | 약 5분 17초 | **약 $2.02** | + +## 6. 남은 일 + +1. **산출 상세 확인(선택).** 다음 항목은 암호화된 산출 파일을 읽어야 확인된다. + - handoff 항목 구성: 비코드 항목 0건, 금액 갈림 4건. + - 당사자 행 수와 추천기 표지 0행. + - F1이 어느 3건을 골랐는지. + - 읽는 방법은 두 가지다. 관리자 토큰으로 백엔드 파일 API를 쓰도록 허용하거나, 사용자가 해당 파일을 받아 로컬에 두면 된다. +2. **커밋.** Part 2·4 YAML과 정적 자산 6종을 함께 커밋해야 한다. 서버에는 이미 같은 판이 올라가 있다. +3. **Stage 2 연결.** 새 `Fact_Ledger_base.json`(행 88)과 Part 4 handoff를 S2_00 입력으로 다시 바인딩할지 정한다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md new file mode 100644 index 00000000..afc5a4f9 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md @@ -0,0 +1,112 @@ +# Stage 1 Part 3 실행결과보고서 5 (2026-11-05, Part 2 재실행 산출 위 재실행) + +- **대상:** `stage_1_part_3_v.8.yml`. 4차와 같은 판으로, 이번에는 다시 올리지 않았다(이 구간 로그에 `upload-agent` 없음). +- **실행:** workspace `11월_1일_구성`, 세션 `88ee7816`, 2026-11-05 10:15:46.65 ~ 10:16:35.18 UTC(**48.5초**). +- **입력:** Part 2 개정판의 첫 실행 산출이다(세션 `1fb26ede`). BO 88건, signal 거래 `S5TX-92952e6df623cb1f439f`. +- **근거(모두 읽기 전용):** `agent-backend` 로그(타임스탬프 포함)만 썼다. + - task 이벤트, 코드 task 결과 JSON, `[USAGE]`, JEV 호출 기록. + - capture 코드에 실린 JEV 확률 분포. + - localdocs 파일은 암호화돼 저장되므로 내용을 직접 읽지 않았다. + +## 1. 판정 — **성공** (L2 `READY_WITH_REVIEW`) + +| 기준 | 결과 | +|---|---| +| 백엔드 | task 37개 모두 `task_complete`. `task_error`·`task_retry`·Traceback 0건. `stage_complete`·`execution_complete` 각 1건 | +| L0 | `READY_WITH_REVIEW`(3.99초). 구조 50, theta 34, review 14. **BO 88 중 부착 82, 미부착 6.** route 91 중 부착 83, 미부착 8. SG-11 47개 모두 연결 | +| glossary | Gemini 3.8 Flash 1회, 24.8초. `glossary_status: OK`, 수용 40, 정의 없는 쌍 유형 0 | +| planner | `PLANNED`. 후보 유형 6개, 쌍 16개 | +| JEV | 16회 모두 응답(`jev-1.14.0`, 각 0.23~0.27초). capture 16개 모두 `ANSWERED` | +| apply | `APPLIED`. **UNDECIDED 6, ACCEPT 0, 부착 0.** 번들은 다시 쓰지 않았고 handoff만 다시 썼다 | +| L2 | `READY_WITH_REVIEW`(3.49초). 구조 50, 품질 게이트 셋(declaration·route·bo) 통과. 색인 by_domain 15·by_module 22·by_bo_id 82. review_queue 3 | +| 비용 | **약 $0.023** | + +## 2. IO 구조 (실측 시각) + +``` +L0 (코드, →10:15:50, 3.99s) ─▶ structure_seed_bundle · handoff(OPEN, 14) + ├▶ glossary (Gemini 3.8 Flash 24.8s, →10:16:15) ─▶ type_glossary.json (수용 40) + └▶ planner (코드 3.30s) ─▶ recommender_requests (후보 6 / 쌍 16) + ├▶ recommender_0..15 (JEV, 10:16:19, 각 0.23~0.27s) + │ └▶ capture_0..15 ─▶ recommender_answers/pair_0000~0015.json + └▶ apply (코드 3.20s) ─▶ handoff 재기록 · 영수증 + L2 (코드 3.49s, →10:16:35) ─▶ legal_effect_structures.json (READY_WITH_REVIEW) · handoff FINALIZED +``` + +## 3. 결과물 + +### 3.1 L0 부착이 크게 늘었다 + +| 지표 | 4차 (BO 78 입력) | **5차 (BO 88 입력)** | +|---|---:|---:| +| L0 부착 / 미부착 | 63 / 15 | **82 / 6** | +| 최종 부착 / 미부착 | 68 / 10 (추천기로 5건 추가) | **82 / 6** (추천기 추가 0) | +| route 부착 / 미부착 | 66 / 18 | **83 / 8** | +| 추천기 후보 / 쌍 | 13 / 17 | **6 / 16** | +| JEV 결과 | ACCEPT 4 · UNDECIDED 9 | **ACCEPT 0 · UNDECIDED 6** | + +- Part 3 YAML은 바뀌지 않았다. 부착이 늘어난 것은 입력 BO가 바뀌었기 때문이다. + - 4차에서 추천기가 E-02 `money_claim`에 붙였던 유형(부분 변제·최고 등)은 이번 BO에서 L0가 규칙만으로 붙였다. +- 미부착 BO 6건의 후보 유형은 다음 6개다. + - E-10 `auction_sale_transfer`, E-10 `security_enforcement_auction_commencement` + - E-11 `possession_transfer` + - E-12 `title_trust_ownership_assertion` + - E-15 `succession_opening_and_heir_scope`, E-15 `succession_renunciation_acceptance` + +### 3.2 JEV 판정 16쌍 (적용 임계값: 수용 0.80, 마진 0.20) + +| 쌍 | 도메인 | 후보 유형 → 선언 유형 | 선택 | part_of | unrelated | independent | +|---|---|---|---|---:|---:|---:| +| 0 | E-10 | auction_sale_transfer → registry_invalidity | unrelated | 0.22 | 0.57 | 0.21 | +| 1 | E-10 | auction_sale_transfer → secured_debt | unrelated | 0.11 | 0.81 | 0.08 | +| 2 | E-10 | auction_sale_transfer → succession_notice_lien_asset_defense | unrelated | 0.10 | 0.77 | 0.13 | +| 3 | E-10 | security_enforcement_auction_commencement → registry_invalidity | unrelated | 0.03 | 0.92 | 0.05 | +| 4 | E-10 | security_enforcement_auction_commencement → secured_debt | **part_of** | **0.75** | 0.07 | 0.18 | +| 5 | E-10 | security_enforcement_auction_commencement → succession_notice_lien_asset_defense | unrelated | 0.13 | 0.66 | 0.21 | +| 6 | E-11 | possession_transfer → land_use_gain | unrelated | 0.28 | 0.60 | 0.12 | +| 7 | E-11 | possession_transfer → possession_vindication | **part_of** | **0.44** | 0.27 | 0.28 | +| 8 | E-11 | possession_transfer → succession_notice_lien_asset_defense | unrelated | 0.07 | 0.78 | 0.15 | +| 9 | E-12 | title_trust_ownership_assertion → aggregate_building_management | unrelated | 0.01 | 0.92 | 0.07 | +| 10 | E-12 | title_trust_ownership_assertion → boundary_determination | unrelated | 0.00 | 0.83 | 0.17 | +| 11 | E-12 | title_trust_ownership_assertion → coownership_governance | unrelated | 0.01 | 0.79 | 0.20 | +| 12 | E-12 | title_trust_ownership_assertion → coownership_partition | unrelated | 0.01 | 0.68 | 0.31 | +| 13 | E-12 | title_trust_ownership_assertion → exclusive_use_settlement | unrelated | 0.01 | 0.85 | 0.14 | +| 14 | E-15 | succession_opening_and_heir_scope → succession_notice_lien_asset_defense | **part_of** | **0.43** | 0.38 | 0.19 | +| 15 | E-15 | succession_renunciation_acceptance → succession_notice_lien_asset_defense | **part_of** | **0.66** | 0.16 | 0.18 | + +- `wording_variant`는 모든 쌍에서 0.00~0.01이다. +- **6건 모두 UNDECIDED인 이유:** part_of를 고른 4쌍의 확률이 0.75·0.66·0.44·0.43이다. 모두 수용 임계값 0.80에 못 미친다. 나머지 12쌍은 unrelated를 골랐다. +- **경매개시결정 → 피담보채권(쌍 4, 0.75)이 가장 가깝다.** 담보권 실행 경매는 피담보채권 행사의 한 과정이므로 방향은 맞다. 하지만 임계값 미달이라 사람 검토로 남았다. +- E-12 명의신탁 소유 주장은 선언 유형 5개 모두와 unrelated였다(0.68~0.92). 이 영역에 맞는 선언 유형이 registry에 없을 수 있다. +- 쌍 상태의 `glossary_source: "llm_unverified"`는 YAML이 정한 정상 표시다. glossary가 LLM으로 만든 정의임을 JEV에 알린다. + +### 3.3 L2 + +- 구조 50, theta 34. by_bo_id 색인 82개는 부착 BO 수와 같다. +- review_queue는 3건이다. +- L0 handoff review는 14건이다. 4차는 33건이었고, 그중 `PART3_BO_UNATTACHED`(HARD)가 15건이었다. 미부착이 6건으로 줄어든 영향이다. +- apply가 다시 쓴 handoff의 최종 건수는 로그에 없다. 파일이 암호화돼 있어 직접 확인하지도 못했다. + - 추정: 두 후보 유형은 모든 쌍에서 unrelated를 골랐다(E-10 `auction_sale_transfer`, E-12 `title_trust_ownership_assertion`). 이들에 SOFT `PART3_RECOMMENDER_TARGET_UNRELATED`가 붙었을 것이다. + +## 4. LLM API 비용 + +| 호출 | 모델 | 횟수 | 입력 | 출력 | 비용(로그) | +|---|---|---:|---:|---:|---:| +| glossary | Gemini 3.8 Flash | 1 | 15,387 | 3,018 | $0.022858 | +| recommender | JEV `jev-1.14.0` | 16 | 13,675 (JEV 기록 합) | — | $0.000538 (`[USAGE]` 15건) | +| **합계** | | **17** | | | **약 $0.0234** | + +- `[USAGE]` 기록은 16건이다(glossary 1 + JEV 15). JEV 한 건은 같은 시각에 끝나 기록이 빠진 것으로 보인다. 빠진 1건은 약 $0.00004로, 합계에 영향이 없다. +- glossary 캐시 적중은 0이다(`cached_tokens=None`). 입력이 1만 5천 토큰이라 비용 영향은 작다. + +## 5. 남은 일 + +1. **Part 4를 다시 실행해야 한다.** Part 3 산출(BO 88, 부착 82)과 영수증이 새로 바뀌었다. + - Part 4 F0는 BO 봉인을 이 영수증과 대조하므로 이제 통과할 조건이 갖춰졌다. + - 확인할 것: + - P4-06: `P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW` 55건 → 0건. + - P4-02: 추천기 표지 0행. 이번에 추천기가 붙인 BO가 없기 때문이다. + - F1 위치 편향. +2. **임계값 0.80 재검토(선택):** part_of 0.75(경매개시결정 → 피담보채권)처럼 맞는 방향의 판정이 수용되지 않았다. 다만 4차의 수용 4건은 0.99였다. 지금 임계값을 유지하고 사람 검토로 넘기는 것이 보수적인 선택이다. +3. **커밋은 아직 하지 않았다.** Part 2·4 YAML과 자산 6종이 로컬 작업 트리에만 있다. +4. **검증 범위:** 형식, 흐름, 계약 준수, 비용만 보았다. 법률효과 구조의 타당성은 표본 판단(§3.2)만 했다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_compiler_11_05_5_22pm.py.bak b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_compiler_11_05_5_22pm.py.bak new file mode 100644 index 00000000..84112c74 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_compiler_11_05_5_22pm.py.bak @@ -0,0 +1,945 @@ +#!/usr/bin/env python3 +"""Compile v.8 Fact Ledger candidate rows from BO, LES, signals, envelopes, and gate sidecars. + +순수 함수 모듈 — I/O·시각·난수 없음. 규칙 선언은 fact_ledger_policy.v1.json 이 유일 정본이며 +이 모듈은 그것을 읽어 dispatch 만 한다. gate_id·27필드·registry type_id 리터럴을 코드에 두지 +않는다(정적 검사 11·12). 사건 종류 이름을 어디에도 두지 않는다(137종 원칙). + +공개 API + normalize_gate_rules(sidecar_doc, policy) 17축 방언 정규화 리더 + resolve_alias_table(alias_declarations, sidecars, policy) + compile_fact_ledger_candidates(...) 조립 본체 (아래 시그니처) +""" +from __future__ import annotations + +import json +import re +from typing import Any + +_WS_RE = re.compile(r"\s+") +_CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") +_DOMAIN_RE = re.compile(r"^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$") + + +# --------------------------------------------------------------------------- +# 공용 헬퍼 +# --------------------------------------------------------------------------- + +def _dict(value: Any) -> dict: + return value if isinstance(value, dict) else {} + + +def _list(value: Any) -> list: + return value if isinstance(value, list) else [] + + +def _strings(value: Any) -> list[str]: + return [item for item in _list(value) if isinstance(item, str)] + + +def _nonblank(value: Any) -> bool: + return value not in (None, "", [], {}) + + +def _text(value: Any, limit: int) -> str | None: + """키 오름차순 JSON -> 공백열 단일 공백 -> limit 절단 -> 빈 문자열이면 None.""" + if value is None: + return None + if isinstance(value, str): + rendered = value + else: + rendered = json.dumps(value, ensure_ascii=False, sort_keys=True) + rendered = _WS_RE.sub(" ", rendered).strip() + if not rendered: + return None + return rendered[:limit] + + +def _first_value(*values: Any) -> Any: + for value in values: + if _nonblank(value): + return value + return None + + +def _first_key(record: dict, keys: list[str]) -> Any: + for key in keys: + if _nonblank(record.get(key)): + return record[key] + return None + + +def _dedupe_keep_order(items: list[str]) -> list[str]: + seen: set[str] = set() + out: list[str] = [] + for item in items: + if item not in seen: + seen.add(item) + out.append(item) + return out + + +# --------------------------------------------------------------------------- +# F0-0c — BO 압축·정규화 (구본 _compact_bo 등가 계층. (가) 9필드 전부의 전제) +# --------------------------------------------------------------------------- + +def compact_bo(bo: dict, policy: dict) -> dict: + norm = _dict(policy.get("bo_normalization")) + key_map = _dict(norm.get("key_map")) + keep = _strings(norm.get("domain_payload_keep_keys")) + out: dict[str, Any] = {} + for key, value in bo.items(): + out[key_map.get(key, key)] = value + payload = _dict(_dict(bo.get("extensions")).get("domain_payload")) + out["domain_payload"] = {k: payload[k] for k in keep + if k in payload and _nonblank(payload[k])} + out["core"] = _dict(bo.get("core_field_base")) + return out + + +# --------------------------------------------------------------------------- +# 금액 — Part 2 가 BO 에 고른 정본을 옮긴다. 값이 갈렸으면 표시만 더한다. 숫자를 만들지 않는다. +# --------------------------------------------------------------------------- + +def amount_text(value: Any, alternatives: list, related: list, notes: dict) -> str | None: + """정본 금액은 자르지도 공백을 접지도 않는다. S2_10 에 닿는 행 칸이 이 문자열이라 표시도 여기 싣는다.""" + body = value if isinstance(value, dict) else ({"value_text": value} if value else {}) + marks: dict = {} + if alternatives: + marks["conflict"] = {"status": "UNRESOLVED", "note": notes.get("conflict_note"), "candidates": alternatives} + if related: + marks.update(related_values=related, note=notes.get("related_values_note")) + if marks or _dict(value).get("value_id"): + return json.dumps(dict(body, **marks), ensure_ascii=False, sort_keys=True) + return _text(value, 240) + + +# --------------------------------------------------------------------------- +# (다) — 증거력 산정 (정책 evidence_scoring_da_2 의 5갈래 · 순서 그대로) +# --------------------------------------------------------------------------- + +def _flatten_evidence(document: Any, depth: int = 3) -> list[dict]: + rows: list[dict] = [] + + def visit(node: Any, level: int) -> None: + if level > depth: + return + if isinstance(node, dict): + if any(k in node for k in ("evidence_index", "id", "evidence_id", + "eid", "index", "doc_id")): + rows.append(node) + return + for value in node.values(): + visit(value, level + 1) + elif isinstance(node, list): + for item in node: + visit(item, level + 1) + + visit(document, 0) + return rows + + +def _evidence_id(record: dict) -> str | None: + value = _first_key(record, ["evidence_index", "id", "evidence_id", + "eid", "index", "doc_id"]) + return value if isinstance(value, str) else None + + +def _excerpt_from_indexed(record: dict) -> str: + facts = _strings(record.get("key_facts")) + if facts: + return " ".join(facts) + parts = _strings(record.get("key_dates")) + _strings(record.get("key_amounts")) + if parts: + return " ".join(parts) + for value in record.values(): + if isinstance(value, str) and value.strip(): + return value + return "" + + +def build_evidence_authority(evidence_document: Any) -> dict[str, dict]: + authority: dict[str, dict] = {} + for record in _flatten_evidence(evidence_document): + eid = _evidence_id(record) + if not eid: + continue + authority[eid] = { + "evidence_index": eid, + "title": _first_key(record, ["title", "Title", "name", "doc_title"]), + "excerpt": _excerpt_from_indexed(record), + "priority": _first_key(record, ["priority", "Priority", "weight"]), + "authentication": _first_key(record, ["authentication", "auth", + "source_authentication"]), + "source": "evidence_indexed.json", + } + return authority + + +def score_evidence(evidence_refs: list[str], authority: dict[str, dict], + policy: dict, reviews: list[dict], + fact_id: str) -> tuple[str, str, int]: + """(credibility, proof_strength, 절단여유 최소값) — 정책 5갈래 순서 그대로.""" + scoring = _dict(policy.get("evidence_scoring_da_2")) + markers = _strings(scoring.get("markers_documentary")) + rows: list[dict] = [] + for ref in evidence_refs: + row = authority.get(ref) + if row is None: + # 우주 밖 참조 — stub 도 비어 있지 않은 증거 행으로 계수된다(정책 승계). + reviews.append({"review_code": "EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + row = {"evidence_index": ref, "missing": True} + rows.append(row) + if not rows: + return "low", "low", -1 + pieces: list[str] = [] + slack = 10 ** 9 + for row in rows: + rendered = _WS_RE.sub(" ", json.dumps(row, ensure_ascii=False, + sort_keys=True)).strip() + slack = min(slack, 300 - len(rendered)) + pieces.append(rendered[:300]) + text = " ".join(pieces) + if any(marker in text for marker in markers): + return "high", "documentary", slack + if len(rows) >= 2: + return "high", "high", slack + if ("meeting" in text) or ("회의" in text) or ("면담" in text): + return "medium", "meeting_only_core", slack + return "medium", "medium", slack + + +# --------------------------------------------------------------------------- +# F0-0 — 17축 사이드카 방언 정규화 리더 +# --------------------------------------------------------------------------- + +def normalize_gate_rules(sidecar_doc: Any, policy: dict) -> dict: + """사이드카 한 파일을 정규화한다. {rules: {gate_id: norm}, file_meta, warnings}.""" + axes = _dict(_dict(policy.get("gate_execution")).get("normalization_axes_17")) + array_keys = _strings(axes.get("rule_array_keys")) or ["rules", "gates"] + code_keys = _strings(axes.get("emitted_code_keys")) + doc = _dict(sidecar_doc) + raw_rules: list[dict] = [] + array_key = None + for key in array_keys: + if isinstance(doc.get(key), list): + array_key = key + raw_rules = [r for r in doc[key] if isinstance(r, dict)] + break + warnings: list[dict] = [] + norm_rules: dict[str, dict] = {} + for rule in raw_rules: + gate_id = rule.get("gate_id") + if not isinstance(gate_id, str): + warnings.append({"code": "GATE_RULE_WITHOUT_ID", "detail": str(rule)[:120]}) + continue + writer = _dict(rule.get("writer_effect")) + row_eff = _dict(rule.get("row_effect")) + on_true = _dict(rule.get("on_true")) + condition = rule.get("condition") + cond_kind = "dict" if isinstance(condition, dict) else "str" + cond_key = next(iter(condition), None) if cond_kind == "dict" else None + cond_value = condition.get(cond_key) if cond_kind == "dict" else condition + emitted: list[str] = [] + for key in code_keys: + value = rule.get(key) + if isinstance(value, str): + emitted.append(value) + else: + emitted.extend(_strings(value)) + blocks = None + for container, key in (("writer_effect", "final_drafting_block"), + ("writer_effect", "blocks_final_drafting"), + ("on_true", "blocks_final_drafting")): + holder = writer if container == "writer_effect" else on_true + if key in holder: + blocks = bool(holder[key]) + break + status_fire = (writer.get("status_when_triggered") + or writer.get("status_on_fire") + or on_true.get("writer_status")) + evaluation = (rule.get("evaluation_mode") or rule.get("implementation_type") + or rule.get("evaluation")) + norm_rules[gate_id] = { + "gate_id": gate_id, + "condition_kind": cond_kind, + "condition_key": cond_key, + "condition_value": cond_value, + "emitted_codes": _dedupe_keep_order(emitted), + "blocks_final_drafting": blocks, + "status_when_triggered": status_fire, + "row_must_consider": bool(row_eff.get("must_consider")), + "preserve_seed": bool(on_true.get("preserve_seed")), + "unknown_or_missing_policy": rule.get("unknown_or_missing_policy"), + "evaluation": evaluation, + "writes_fact_ledger": writer.get("writes_fact_ledger"), + "silent_repair_forbidden": rule.get("silent_repair_forbidden"), + "source_membership_required": rule.get("source_membership_required"), + "input_declaration": rule.get("input_fields") or rule.get("input_contracts"), + } + if doc.get("global_status_rule") is not None: + warnings.append({"code": "SIDECAR_GLOBAL_STATUS_RULE_IGNORED", + "detail": str(doc.get("global_status_rule"))[:120]}) + return {"rules": norm_rules, + "file_meta": {"array_key": array_key, + "schema_version": doc.get("schema_version"), + "status_key": ("closure_status" if "closure_status" in doc + else ("status" if "status" in doc else None))}, + "warnings": warnings} + + +# --------------------------------------------------------------------------- +# F0-0b — 별칭 해소 (D-P4-7 — 전수 자기선언 대조 · 침묵 탈락 금지) +# --------------------------------------------------------------------------- + +def resolve_alias_table(alias_declarations: Any, structure_type_sidecars: dict, + policy: dict) -> dict: + root = _dict(alias_declarations) + root = _dict(root.get("extension_payload_key_declarations", root)) + table = {k: _strings(v) for k, v in _dict(root.get("legacy_alias_targets")).items()} + derived_mismatches = _list(root.get("legacy_declaration_mismatches")) + abbrev = _dict(_dict(policy.get("legacy_alias")).get("abbreviation_map")) + self_decl: dict[str, set] = {} + for domain_id, doc in sorted(_dict(structure_type_sidecars).items()): + doc = _dict(doc) + rows = None + for key in ("types", "structure_types", "records", "entries"): + if isinstance(doc.get(key), list): + rows = doc[key] + break + for row in rows or []: + if not isinstance(row, dict): + continue + value = row.get("legacy_source") or row.get("legacy_source_domain") + if not isinstance(value, str): + continue + head = value.split("_")[0] + if head not in abbrev: + continue # 'Part3 fallback' 등 비 B* 값은 선언이 아니다 + self_decl.setdefault(abbrev[head], set()).add(domain_id) + reviews: list[dict] = [] + mismatch_map: dict[str, dict] = {} + for legacy in sorted(set(table) | set(self_decl)): + declared = self_decl.get(legacy, set()) + aliased = set(table.get(legacy, [])) + missing = sorted(declared - aliased) + excess = sorted(aliased - declared) + if missing: + mismatch_map[legacy] = {"missing": missing, "excess": excess} + reviews.append({"review_code": "LEGACY_ALIAS_SELF_MISMATCH_REVIEW", + "severity": "SOFT_WARNING", "legacy": legacy, + "missing_domain_ids": missing, + "excess_domain_ids": excess}) + derived_missing = sorted({str(_dict(m).get("domain_id")) + for m in derived_mismatches if _dict(m).get("domain_id")}) + actual_missing = sorted({d for m in mismatch_map.values() for d in m["missing"]}) + if derived_missing != actual_missing: + reviews.append({"review_code": "LEGACY_ALIAS_DECLARATION_INCOMPLETE_REVIEW", + "severity": "SOFT_WARNING", + "derived_list": derived_missing, + "actual_missing": actual_missing}) + return {"table": table, "self_declarations": {k: sorted(v) for k, v in self_decl.items()}, + "mismatches": mismatch_map, "reviews": reviews} + + +# --------------------------------------------------------------------------- +# 조립 본체 +# --------------------------------------------------------------------------- + +def compile_fact_ledger_candidates( + bo_document: Any, + les_document: Any, + signal_documents: dict, + domain_envelopes: dict, + p2_handoff_document: Any, + evidence_document: Any, + registry_index: Any, + domain_configs: dict, + gate_sidecars: dict, + structure_type_sidecars: dict, + activation_document: Any, + alias_declarations: Any, + policy: dict) -> dict: + reviews: list[dict] = [] + audit: dict[str, Any] = {} + + activation_root = _dict(activation_document) + activation_root = _dict(activation_root.get("domain_activation_manifest", + activation_root)) + expected_runnable = _strings(activation_root.get("expected_runnable_domain_ids")) + + # ---- F0-0 리더 · F0-0b 별칭 ---------------------------------------- + normalized: dict[str, dict] = {} + dialect_counts: dict[str, Any] = {"array_key": {}, "files": 0} + reader_warnings: list[dict] = [] + for domain_id, sidecar in sorted(_dict(gate_sidecars).items()): + result = normalize_gate_rules(sidecar, policy) + normalized[domain_id] = result + dialect_counts["files"] += 1 + ak = result["file_meta"]["array_key"] + dialect_counts["array_key"][ak] = dialect_counts["array_key"].get(ak, 0) + 1 + reader_warnings.extend(result["warnings"]) + audit["sidecar_dialects"] = dialect_counts + audit["reader_warnings"] = reader_warnings + + alias = resolve_alias_table(alias_declarations, structure_type_sidecars, policy) + reviews.extend(alias["reviews"]) + + # ---- LES 적재 ------------------------------------------------------- + les_root = _dict(les_document) + structure_records = [r for r in _list(les_root.get("structure_records")) + if isinstance(r, dict)] + record_by_id = {r.get("structure_id"): r for r in structure_records + if isinstance(r.get("structure_id"), str)} + index = _dict(les_root.get("structure_index")) + by_bo_id = {k: _strings(v) for k, v in _dict(index.get("by_bo_id")).items()} + + # ---- SG 적재 -------------------------------------------------------- + def signal_records(sg: str) -> list[dict]: + doc = _dict(_dict(signal_documents).get(sg)) + return [r for r in _list(doc.get("records")) if isinstance(r, dict)] + + sg11_records = signal_records("SG-11") + sg11_by_signal_id = {r.get("signal_id"): r for r in sg11_records + if isinstance(r.get("signal_id"), str)} + sg04_by_domain: dict[str, list[str]] = {} + for record in signal_records("SG-04"): + for domain_id in _strings(record.get("domain_ids")): + if isinstance(record.get("signal_id"), str): + sg04_by_domain.setdefault(domain_id, []).append(record["signal_id"]) + + # ---- F0-7b — 게이트 입력 정규화 ------------------------------------ + handoff_root = _dict(p2_handoff_document) + handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root)) + handoff_items = [r for r in _list(handoff_root.get("review_items")) + if isinstance(r, dict)] + code_pool: dict[str, list[str]] = {} + gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0, + "handoff_not_a_code": 0, "handoff_domain_unresolved": 0, + "slot_entries": 0, "operand_states": 0} + for domain_id in expected_runnable: + env = _dict(_dict(domain_envelopes).get(domain_id)) + env = _dict(env.get("domain_signal_envelope", env)) + for item in _list(env.get("review_items")): + code = _dict(item).get("review_code") or _dict(item).get("code") + if isinstance(code, str) and _CODE_RE.match(code): + code_pool.setdefault(domain_id, []).append(code) + gate_input_counts["envelope_review_items"] += 1 + for item in handoff_items: + raw_code = item.get("source_review_code") + if not (isinstance(raw_code, str) and _CODE_RE.match(raw_code)): + if raw_code is not None: + gate_input_counts["handoff_not_a_code"] += 1 + reviews.append({"review_code": "P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW", + "severity": "SOFT_WARNING", + "detail": str(raw_code)[:80]}) + continue + source_domain = item.get("source_domain") + targets: list[str] = [] + if isinstance(source_domain, str): + if _DOMAIN_RE.match(source_domain): + targets = [source_domain] + elif source_domain in alias["table"]: + targets = alias["table"][source_domain] + if not targets: + gate_input_counts["handoff_domain_unresolved"] += 1 + reviews.append({"review_code": "P2_HANDOFF_DOMAIN_UNRESOLVED_REVIEW", + "severity": "SOFT_WARNING", + "detail": str(source_domain)[:80]}) + continue + for domain_id in targets: + code_pool.setdefault(domain_id, []).append(raw_code) + gate_input_counts["handoff_codes"] += 1 + slot_status: dict[str, list[dict]] = {} + for domain_id in expected_runnable: + env = _dict(_dict(domain_envelopes).get(domain_id)) + env = _dict(env.get("domain_signal_envelope", env)) + entries = [e for e in _list(env.get("evidence_slot_status")) + if isinstance(e, dict)] + if entries: + slot_status[domain_id] = entries + gate_input_counts["slot_entries"] += len(entries) + operand_by_domain: dict[str, list[str]] = {} + for record in sg11_records: + details = _dict(record.get("details")) + state = record.get("operand_state") or details.get("operand_state") + if not isinstance(state, str): + continue + for domain_id in (_strings(record.get("domain_ids")) + or _strings(details.get("domain_ids"))): + operand_by_domain.setdefault(domain_id, []).append(state) + gate_input_counts["operand_states"] += 1 + audit["gate_input_counts"] = gate_input_counts + + # ---- F0-1 ~ F0-6b — 행 생성 ---------------------------------------- + bo_records = [b for b in _list(bo_document) if isinstance(b, dict)] + bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or "")) + authority = build_evidence_authority(evidence_document) + calc_types = set(_strings(policy.get("legal_calculation_object_types"))) + rows: list[dict] = [] + attach_stats = {"attached_bo": 0, "unattached_bo": 0} + used_structure_ids: set[str] = set() + used_sg11: set[str] = set() + slack_min = 10 ** 9 + pack_policy = _dict(policy.get("exception_pack")) + for idx, bo in enumerate(bo_sorted, 1): + compact = compact_bo(bo, policy) + core = compact["core"] + fact_id = "F-%03d" % idx + bo_id = str(bo.get("BO_ID") or "") + # (가) 9필드 + parties = [] + if _nonblank(core.get("Performer")): + parties.append({"role": "actor", "value": _text(core.get("Performer"), 160), + "source": "BO.core_field_base"}) + if _nonblank(core.get("Subject")): + parties.append({"role": "counterparty", + "value": _text(core.get("Subject"), 160), + "source": "BO.core_field_base"}) + provenance = _dict(bo.get("provenance")) + alternatives = _list(provenance.get("amount_alternatives")) + related = _list(provenance.get("amount_related_values")) + amount = amount_text(_first_value(compact.get("amount"), core.get("Amount")), alternatives, + related, pack_policy) + action = _first_value(compact.get("action"), core.get("Action")) + evidence_refs = _strings(bo.get("source_evidence_indexes")) + # F0-3 — LES 조인 + structure_ids = sorted(set(by_bo_id.get(bo_id, []))) + attached = [record_by_id[s] for s in structure_ids if s in record_by_id] + if attached: + attach_stats["attached_bo"] += 1 + else: + attach_stats["unattached_bo"] += 1 + reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": "%s source_domain=%s" % ( + bo_id, provenance.get("source_domain"))}) + used_structure_ids.update(s for s in structure_ids if s in record_by_id) + domain_effects: dict[str, dict] = {} + for record in attached: + domain_id = record.get("domain_id") + if not isinstance(domain_id, str): + continue + slot = domain_effects.setdefault(domain_id, { + "module": set(), "role_projection": set(), "structure_ids": set(), + "type_ids": set(), "review_codes": set()}) + if isinstance(record.get("module"), str): + slot["module"].add(record["module"]) + if isinstance(record.get("role_projection"), str): + slot["role_projection"].add(record["role_projection"]) + if isinstance(record.get("structure_id"), str): + slot["structure_ids"].add(record["structure_id"]) + if isinstance(record.get("type_id"), str): + slot["type_ids"].add(record["type_id"]) + slot["review_codes"].update( + c for c in _strings(record.get("review_codes")) if _CODE_RE.match(c)) + domain_effects = {d: {k: sorted(v) for k, v in slot.items()} + for d, slot in sorted(domain_effects.items())} + modules = sorted({m for slot in domain_effects.values() for m in slot["module"]}) + roles = sorted({r for slot in domain_effects.values() + for r in slot["role_projection"]}) + type_ids = sorted({t for slot in domain_effects.values() + for t in slot["type_ids"]}) + # F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지) + calculation_requests: list[dict] = [] + route_refs: list[str] = [] + # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다. + for ref in sorted({ref for record in attached + for ref in _strings(record.get("calculation_request_refs"))}): + route_refs.append(ref) + sg = sg11_by_signal_id.get(ref) + if sg is None: + calculation_requests.append({"calculation_id": None, + "request_id": ref, + "provenance": {"signal_id": ref, + "dangling": True}}) + reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + continue + used_sg11.add(ref) + details = _dict(sg.get("details")) + calc_id = details.get("calculation_id") + if not isinstance(calc_id, str) or not calc_id: + calc_id = ref + reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + law_refs = sorted(set( + _strings(sg.get("law_version_refs")) + + _strings(details.get("law_version_refs")) + + [ref2 for d in _strings(sg.get("domain_ids")) + for ref2 in sg04_by_domain.get(d, [])])) + calculation_requests.append({ + "calculation_id": calc_id, + "request_id": ref, + "operand_state": (sg.get("operand_state") + or details.get("operand_state")), + "missing_operands": _strings(details.get("missing_operands")), + "law_version_refs": law_refs, + "provenance": {"signal_id": ref, + "structure_ids": sorted( + s for s in structure_ids + if ref in _strings( + _dict(record_by_id.get(s)).get( + "calculation_request_refs")))}, + }) + # (다) 증거력 + credibility, proof_strength, slack = score_evidence( + evidence_refs, authority, policy, reviews, fact_id) + slack_min = min(slack_min, slack) + # (나) 15필드 + object_spec = _text(core.get("Object"), 160) + calc_obj_candidates = sorted(calc_types & set(type_ids)) + legal_calculation_object = calc_obj_candidates[0] if calc_obj_candidates else None + alias_vocab = _dict(policy.get("alias_module_vocabulary")) + mod_actio = alias_vocab.get("actio_fields") + mod_money = alias_vocab.get("money_claim_effect") + mod_successor = alias_vocab.get("commercial_successor_effect") + actio_ids = sorted({s for slot in domain_effects.values() + for s in slot["structure_ids"] + if mod_actio in slot["module"]}) + actio_roles = sorted({r for slot in domain_effects.values() + if mod_actio in slot["module"] + for r in slot["role_projection"]}) + money_ids = sorted({s for slot in domain_effects.values() + if mod_money in slot["module"] + for s in slot["structure_ids"]}) + successor_ids = sorted({s for slot in domain_effects.values() + if mod_successor in slot["module"] + for s in slot["structure_ids"]}) + row = { + "fact_id": fact_id, + "source_bo_id": bo_id, + "type": compact.get("bo_type") if isinstance(compact.get("bo_type"), str) else None, + "date": _first_value(core.get("BehaviorTime"), compact.get("date")), + "parties": parties, + "object_spec": object_spec, + "amount": amount, + "action": action if isinstance(action, str) else _text(action, 240), + "evidence_refs": evidence_refs, + "credibility": credibility, + "legal_centrality": "high" if attached else "medium", + "proof_strength": proof_strength, + "legal_effect_roles": roles, + "claim_chain_ref": {"claim_group_ids": [], "liability_group_ids": [], + "signal_count": len(route_refs)}, + "linked_structures": {"structure_ids": structure_ids}, + "must_not_drop_in_claim_types": modules, + "must_consider": bool(attached), + "state_context": {"bo_type": compact.get("bo_type") + if isinstance(compact.get("bo_type"), str) else None, + # 금액 표시는 FACT 에만 있다. 미부착이어도 도메인 맥락에 닿게 한다. + "domain_ids": sorted(domain_effects) or ( + [str(provenance.get("source_domain"))] + if alternatives or related else [])}, + "money_claim_effect": {"enabled": bool(money_ids), + "structure_ids": money_ids}, + "commercial_successor_effect": {"enabled": bool(successor_ids), + "structure_ids": successor_ids}, + "actio_roles": actio_roles, + "linked_actio_structures": actio_ids, + "downstream_module_candidates": modules, + "skeleton_validation_codes": [], + "derived_fact": action if isinstance(action, str) else _text(action, 240), + "derivation_basis": ("structure_ids=" + ",".join(structure_ids) + if structure_ids else "bo_only"), + "legal_calculation_object": legal_calculation_object, + "domain_effects": domain_effects, + "calculation_requests": calculation_requests, + } + rows.append(row) + audit["evidence_truncation_slack_min"] = (None if slack_min == 10 ** 9 else slack_min) + + # ---- F0-8 — 게이트 합집합 실행 (§4.4 그대로) ------------------------ + gate_exec = _dict(policy.get("gate_execution")) + implemented = set(_strings(gate_exec.get("implemented_condition_keys"))) + default_missing_policy = str(gate_exec.get("unknown_or_missing_policy_default") + or "fail_open_to_review") + declared_gates: dict[str, dict] = {} + for domain_id in expected_runnable: + config = _dict(_dict(domain_configs).get(domain_id)) + config_root = _dict(config.get("domain_config", config)) + for gate in _list(config_root.get("gates")): + gate = _dict(gate) + gate_id = gate.get("gate_id") + if isinstance(gate_id, str): + declared_gates[gate_id] = {"domain_id": domain_id, "declared": gate} + all_rules: dict[str, dict] = {} + for domain_id, result in normalized.items(): + for gate_id, rule in result["rules"].items(): + all_rules[gate_id] = {"domain_id": domain_id, "rule": rule} + gate_report: list[dict] = [] + fired_by_domain: dict[str, list[dict]] = {} + for gate_id in sorted(declared_gates): + info = declared_gates[gate_id] + domain_id = info["domain_id"] + declared = info["declared"] + registry_codes = [c for c in _strings(declared.get("review_codes")) + if _CODE_RE.match(c)] + entry: dict[str, Any] = {"gate_id": gate_id, "domain_id": domain_id, + "fired": False, "input_state": "n/a"} + rule_info = all_rules.get(gate_id) + if rule_info is None: + entry["disposition"] = "GATE_SPEC_NOT_DEPLOYED_REVIEW" + reviews.append({"review_code": "GATE_SPEC_NOT_DEPLOYED_REVIEW", + "severity": "SOFT_WARNING", "gate_id": gate_id}) + gate_report.append(entry) + continue + rule = rule_info["rule"] + fired = False + if rule["condition_kind"] == "dict": + key = rule["condition_key"] + if key in implemented: + entry["disposition"] = "implemented" + value = rule["condition_value"] + if key == "any_review_code_present": + pool = code_pool.get(domain_id) + if pool is None and domain_id not in _dict(domain_envelopes): + entry["input_state"] = "input_missing" + entry["missing_policy"] = ( + rule["unknown_or_missing_policy"] or default_missing_policy) + else: + entry["input_state"] = "supplied" + fired = bool(set(_strings(value)) & set(pool or [])) + elif key == "required_slots_missing_or_conflicting": + entries = slot_status.get(domain_id) + if entries is None and domain_id not in _dict(domain_envelopes): + entry["input_state"] = "input_missing" + entry["missing_policy"] = ( + rule["unknown_or_missing_policy"] or default_missing_policy) + else: + entry["input_state"] = "supplied" + wanted = set(_strings(value)) + fired = any( + (e.get("slot_id") in wanted) + and (e.get("status") in ("missing", "conflicted")) + for e in entries or []) + elif key == "calculation_operand_state_in": + states = operand_by_domain.get(domain_id) + entry["input_state"] = ("supplied" if states else "input_missing") + fired = bool(set(_strings(value)) & set(states or [])) + else: + entry["disposition"] = "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW" + entry["condition_key"] = key + reviews.append({"review_code": "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW", + "severity": "SOFT_WARNING", "gate_id": gate_id, + "detail": str(key)}) + else: + entry["disposition"] = "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW" + entry["predicate_spec"] = _text(rule["condition_value"], 200) + reviews.append({"review_code": "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW", + "severity": "SOFT_WARNING", "gate_id": gate_id, + "detail": _text(rule["condition_value"], 160)}) + # 차단 표지 대조 — registry ↔ 정규화된 사이드카. + declared_blocks = declared.get("blocks_final_drafting") + if (rule["blocks_final_drafting"] is not None + and declared_blocks is not None + and bool(declared_blocks) != rule["blocks_final_drafting"]): + reviews.append({"review_code": "GATE_BLOCK_FLAG_MISMATCH_REVIEW", + "severity": "SOFT_WARNING", "gate_id": gate_id}) + entry["block_flag_mismatch"] = True + emitted = _dedupe_keep_order(rule["emitted_codes"] + registry_codes) + excess = [c for c in rule["emitted_codes"] if c not in registry_codes] + if excess: + entry["codes_not_in_registry"] = excess + reviews.append({"review_code": "GATE_EMITTED_CODE_NOT_IN_REGISTRY", + "severity": "SOFT_WARNING", "gate_id": gate_id, + "detail": ",".join(excess)[:160]}) + entry["fired"] = fired + entry["blocks_final_drafting"] = (rule["blocks_final_drafting"] + if rule["blocks_final_drafting"] is not None + else bool(declared_blocks)) + if fired: + projection_rows = [r["fact_id"] for r in rows + if domain_id in r["domain_effects"]] + entry["projected_row_count"] = len(projection_rows) + reviews.append({"review_code": "GATE_FIRED_REVIEW", + "severity": ("HARD_WARNING" if entry["blocks_final_drafting"] + else "SOFT_WARNING"), + "gate_id": gate_id, "detail": ",".join(emitted)[:160]}) + fired_by_domain.setdefault(domain_id, []).append({ + "gate_id": gate_id, "codes": emitted, + "row_must_consider": rule["row_must_consider"], + "preserve_seed": rule["preserve_seed"], + "blocks_final_drafting": entry["blocks_final_drafting"], + "status_when_triggered": rule["status_when_triggered"], + "projected_rows": projection_rows, + }) + gate_report.append(entry) + orphan_rules = sorted(set(all_rules) - set(declared_gates)) + for gate_id in orphan_rules: + reviews.append({"review_code": "GATE_RULE_NOT_IN_REGISTRY", + "severity": "SOFT_WARNING", "gate_id": gate_id}) + + # ---- 행 투영 3분기 + F0-8b 스켈레톤 -------------------------------- + skeleton_order = _strings(_dict(policy.get("skeleton_checks")).get("order")) + for row in rows: + codes: list[str] = [] + if not _nonblank(row["derived_fact"]): + codes.append(skeleton_order[0]) + if not row["evidence_refs"]: + codes.append(skeleton_order[1]) + if not row["linked_structures"]["structure_ids"]: + codes.append(skeleton_order[2]) + gate_codes: list[str] = [] + for domain_id in sorted(row["domain_effects"]): + for firing in sorted(fired_by_domain.get(domain_id, []), + key=lambda f: f["gate_id"]): + gate_codes.extend(firing["codes"]) + if firing["row_must_consider"]: + row["must_consider"] = row["must_consider"] or True + row["skeleton_validation_codes"] = _dedupe_keep_order(codes + gate_codes) + + # ---- 어느 행에도 닿지 못한 계산 요청 -------------------------------- + for ref in sorted(set(sg11_by_signal_id) - used_sg11): + reviews.append({"review_code": "CALCULATION_REQUEST_UNATTACHED_REVIEW", + "severity": "SOFT_WARNING", "detail": ref}) + + # ---- STRUCTURE_UNATTACHED_REVIEW ----------------------------------- + unattached_structures = sorted(set(record_by_id) - used_structure_ids) + for structure_id in unattached_structures: + reviews.append({"review_code": "STRUCTURE_UNATTACHED_REVIEW", + "severity": "SOFT_WARNING", "detail": structure_id}) + + # ---- F0-9 — 예외 pack ---------------------------------------------- + char_limit = int(pack_policy.get("pack_item_char_limit") or 2000) + exceptions: list[dict] = [] + for row, bo in zip(rows, bo_sorted): + provenance = _dict(bo.get("provenance")) + alternatives = _list(provenance.get("amount_alternatives")) + # 칸은 차 있어도 BO 금액은 없다 + unbodied = 0 if bo.get("amount") else len(_list(provenance.get("amount_related_values"))) + if alternatives: + payload = {"amount_candidates": alternatives, + "current_value_id": _dict(bo.get("amount")).get("value_id"), + "action": row["action"], + "legal_calculation_object": row["legal_calculation_object"], + "object_spec": row["object_spec"], + "calculation_request_ids": sorted( + str(c.get("calculation_id")) for c in + row["calculation_requests"] if c.get("calculation_id"))} + item = {"exception_id": "FX-%03d" % (len(exceptions) + 1), + "exception_type": "legal_calculation_required", + "fact_id": row["fact_id"], + "source_bo_id": row["source_bo_id"], + "conflict_flags": ["CALCULATION_BASIS_CONFLICT"], + "compact_payload": payload} + rendered = json.dumps(item, ensure_ascii=False) + if len(rendered) > char_limit: + item["oversize_review"] = True + reviews.append({"review_code": "CALCULATION_PACK_OVERSIZE_REVIEW", + "severity": "SOFT_WARNING", + "fact_id": row["fact_id"], + "detail": "pack item oversize %d>%d" % (len(rendered), + char_limit)}) + exceptions.append(item) + elif (row["legal_calculation_object"] is not None + and (unbodied or (not _nonblank(row["amount"])) + or (not _nonblank(row["object_spec"])))): + reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW", + "severity": "SOFT_WARNING", "fact_id": row["fact_id"], + "detail": "amount_or_object_spec_blank" + + (" related_values=%d" % unbodied if unbodied else "")}) + unreachable = {name for name, meta in + _dict(policy.get("f1_exception_types")).items() + if _dict(meta).get("unreachable_in_v8")} + for item in exceptions: + if item["exception_type"] in unreachable: + raise ValueError(json.dumps({ + "reason_code": "PART4_UNREACHABLE_EXCEPTION_TYPE", + "exception_type": item["exception_type"]}, ensure_ascii=False)) + + # ---- F0-10 — 보존 등식 계수 ---------------------------------------- + effect_left = sum(len(r["domain_effects"]) for r in rows) + effect_right = 0 + calc_right = 0 + for bo in bo_sorted: + bo_id = str(bo.get("BO_ID") or "") + attached = [record_by_id[s] for s in by_bo_id.get(bo_id, []) + if s in record_by_id] + effect_right += len({r.get("domain_id") for r in attached + if isinstance(r.get("domain_id"), str)}) + calc_right += len({ref for r in attached + for ref in _strings(r.get("calculation_request_refs"))}) + calc_left = sum(len(r["calculation_requests"]) for r in rows) + sg11_total = len(sg11_records) + sg11_unused = sg11_total - len(used_sg11) + equations = { + "row": {"left": len(rows), "right": len(bo_sorted), + "holds": len(rows) == len(bo_sorted)}, + "attachment_coverage": { + "attached": attach_stats["attached_bo"], + "unattached": attach_stats["unattached_bo"], + "total": len(bo_sorted), + "holds": (attach_stats["attached_bo"] + attach_stats["unattached_bo"] + == len(bo_sorted))}, + "effect": {"left": effect_left, "right": effect_right, + "holds": effect_left == effect_right}, + "calc_row": {"left": calc_left, "right": calc_right, + "holds": calc_left == calc_right}, + "calc_source": {"attached_distinct": len(used_sg11), + "unattached_distinct": sg11_unused, + "total": sg11_total, + "holds": len(used_sg11) + sg11_unused == sg11_total}, + } + + # ---- 상태·집계 ------------------------------------------------------ + les_review_codes = set(_strings(policy.get("les_inherited_review_codes"))) + les_review_present = any( + (set(slot["review_codes"]) & les_review_codes) + for row in rows for slot in row["domain_effects"].values()) or any( + _dict(r).get("review_required") for r in structure_records) + status = ("READY_WITH_REVIEW" + if (reviews or exceptions or les_review_present) + else "READY") + counts = { + "rows": len(rows), + "bo_records": len(bo_sorted), + "structure_records": len(structure_records), + "gates_declared": len(declared_gates), + "gates_implemented": sum(1 for e in gate_report + if e.get("disposition") == "implemented"), + "gates_visualized_str": sum( + 1 for e in gate_report + if e.get("disposition") == "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW"), + "gates_visualized_unsupported": sum( + 1 for e in gate_report + if e.get("disposition") == "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW"), + "gates_fired": sum(1 for e in gate_report if e.get("fired")), + "orphan_rules": len(orphan_rules), + "review_items": len(reviews), + "exceptions": len(exceptions), + "conservation": equations, + } + bundle = { + "schema_version": "stage1_fact_ledger_candidate_bundle.v1", + "status": status, + "rows": rows, + "gate_report": {"gates": gate_report, + "fired_by_domain": {d: f for d, f in + sorted(fired_by_domain.items())}, + "orphan_rule_ids": orphan_rules}, + "counts": counts, + "signal_manifest_transaction_id": None, + "expected_runnable_domain_ids": expected_runnable, + "alias_resolution": {"table": alias["table"], + "self_declarations": alias["self_declarations"], + "mismatches": alias["mismatches"]}, + "created_by": "fact_ledger_compiler", + } + pack = { + "schema_version": "stage1_fact_exception_pack.v1", + "has_exceptions": bool(exceptions), + "exception_count": len(exceptions), + "exceptions": exceptions, + "budget": {"pack_item_char_limit": char_limit}, + } + audit["unattached_structure_ids"] = unattached_structures + audit["equations"] = equations + return {"fact_ledger_candidate_bundle": bundle, + "fact_exception_pack": pack, + "review_items": reviews, + "audit": audit} diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_policy_11_05_5_22pm.json.bak b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_policy_11_05_5_22pm.json.bak new file mode 100644 index 00000000..bfd5aedb --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/fact_ledger_policy_11_05_5_22pm.json.bak @@ -0,0 +1,405 @@ +{ + "schema_version": "stage1_fact_ledger_policy.v1", + "status": "ACTIVE", + "purpose": "Part 4 Fact Ledger 의 규칙 선언 정본. 27필드 목록·순서·합성 규칙, 증거력 산정, 게이트 방언 정규화와 구현 범위, 별칭 파생, 보존 등식, 루트 래핑을 코드 밖에 둔다. 코드는 이 선언을 읽어 dispatch 만 한다. registry 가 말하지 않는 값은 만들지 않는다 — 137종 사건 이름을 어디에도 두지 않는다.", + "authority": { + "strategy": "stage_1_part_4_개정전략서.md", + "row_baseline": "선행구축/S_2_GPT_v2/fixtures/legacy_equivalence/run_{1,2}/fact_ledger/Fact_Ledger_base.json (59행 x 27키 실측)", + "gate_sidecars": "domains//gates.json x25 (조립본 바이트 동일 복사 · 127규칙 · registry 121 전건 커버)", + "case_kind_names_forbidden": true + }, + "final_fields_27": [ + "fact_id", + "source_bo_id", + "type", + "date", + "parties", + "object_spec", + "amount", + "action", + "evidence_refs", + "credibility", + "legal_centrality", + "proof_strength", + "legal_effect_roles", + "claim_chain_ref", + "linked_structures", + "must_not_drop_in_claim_types", + "must_consider", + "state_context", + "money_claim_effect", + "commercial_successor_effect", + "actio_roles", + "linked_actio_structures", + "downstream_module_candidates", + "skeleton_validation_codes", + "derived_fact", + "derivation_basis", + "legal_calculation_object" + ], + "new_fields_2": [ + "domain_effects", + "calculation_requests" + ], + "new_fields_note": "29키 = 구 27 + 신규 2. 신규 2키는 required 로 올리지 않는다(D-P4-4 · Stage 2 호환). domain_effects 의 module·role_projection 은 정렬된 배열이다 — 한 도메인이 복수 module 을 선언할 수 있어 스칼라로 두면 정보가 소실된다(D-P4-e).", + "fact_id_format": "F-{idx:03d}", + "fact_id_rule": "BO_ID 사전순 1-기반 연속. 연속성은 F2 가 경성 단언한다.", + "row_cardinality": "BO 1건 = 1행", + "bo_normalization": { + "key_map": { + "BOType": "bo_type", + "Action": "action", + "BO_ID": "bo_id" + }, + "domain_payload_keep_keys": [ + "money_claim_details", + "possession_state", + "lien_state", + "notice_lifecycle", + "asset_alias", + "fractional_effect_events" + ], + "nonblank_only": true, + "note": "구본 _compact_bo(369-374행) 등가 계층. 정규화 없이 원본 대문자 키를 소문자로 찾으면 전건 None 이 된다 — (가) 9필드 전부의 전제." + }, + "field_synthesis_ga_9": { + "note": "(가) BO 유래 9필드 — 골든 59행 전건 값등가 요구. 우변을 바꾸면 정상 구현에서 G-r 이 깨진다.", + "fact_id": "F-{idx:03d} (BO_ID 사전순 1-기반)", + "source_bo_id": "BO_ID 그대로", + "type": "compact.bo_type 단독 (LES types[0] 폴백 금지)", + "date": "first_value(core_field_base.BehaviorTime, bo.date) — bo.date 는 BO 18키에 없어 항상 None. 골든은 BehaviorTime 0/59 라 전건 null", + "parties": "core_field_base 단독 — Performer -> role: actor · Subject -> role: counterparty · 값은 text(party, 160) · source: 'BO.core_field_base'. 구 signal 경로 폐지", + "amount": "value_id 있는 금액: json.dumps(ensure_ascii=False, sort_keys=True) 그대로. 절단·공백 정규화 없음. BO provenance.amount_alternatives 가 있으면 JSON 에 conflict{status, note, candidates[, selected_value_id]} 를 더한다. 그 밖의 값: text(first_value(bo.amount, core_field_base.Amount), 240). provenance.amount_related_values 가 있으면 related_values·note 를 더한다. 금액 본체는 언제나 BO 값이다", + "action": "first_value(compact.action, core_field_base.Action) — 정규화 계층 통과 후의 소문자 키", + "evidence_refs": "BO source_evidence_indexes 단독 — LES 증거는 합집합하지 않는다(합집합하면 v.8 에서 깨진다). LES 증거는 domain_effects 쪽에만 싣는다", + "derived_fact": "action 복제 단독 — 구본 4항 서술 분기는 삭제 확정(deprecation 절)" + }, + "field_synthesis_na_15": { + "note": "(나) LES 유래 15필드 — 골든 등가를 요구하지 않는다(EXPECTED_DELTA-04). v.8 LES 부착에서 결정론으로 재산출한다. 부착 0 이면 아래 기본값이 그대로 남는다.", + "object_spec": { + "rule": "core_field_base.Object 단독 · 없으면 null · 폴백 없음", + "decision": "D-P4-d=(가) — LES 폴백 대상(asset_cluster_ids)이 Part 3 v.8 에서 소멸했으므로 BO 단독 원천으로 확정한다" + }, + "legal_centrality": "부착 있으면 high · 없으면 medium", + "legal_effect_roles": "부착 레코드 role_projection 정렬 합집합 · 기본 []", + "claim_chain_ref": "{claim_group_ids: [], liability_group_ids: [], signal_count: 부착 계산 요청 ref 수} — 구 그룹 ID 는 v.8 에 존재하지 않으므로 상시 빈 배열", + "linked_structures": "{structure_ids: 정렬 합집합} · 기본 {structure_ids: []}", + "must_not_drop_in_claim_types": "부착 레코드 module 정렬 합집합 · 기본 []", + "must_consider": "1차 = 부착 존재 여부(bool) · 게이트 행 투영이 OR 로 갱신한다 — (나)∩(라) 겸용 필드", + "state_context": "{bo_type, domain_ids: domain_effects 키 정렬} · 미부착이면 [] · 단 amount_alternatives 나 amount_related_values 가 있는 행은 BO source_domain", + "money_claim_effect": "{enabled: module 'money_claim' 부착 여부, structure_ids: 해당 정렬 목록}", + "commercial_successor_effect": "{enabled: module 'commercial_successor' 부착 여부, structure_ids: 해당 정렬 목록}", + "actio_roles": "module 'actio' 부착 레코드의 role_projection 정렬 합집합 · 기본 []", + "linked_actio_structures": "module 'actio' 부착 레코드의 structure_id 정렬 목록 · 기본 []", + "downstream_module_candidates": "must_not_drop_in_claim_types 와 같은 파생(골든 59/59 동일값 실측 승계)", + "derivation_basis": "부착 있으면 'structure_ids=' + 콤마결합 · 없으면 'bo_only'", + "legal_calculation_object": "부착 type_id ∩ legal_calculation_object_types 의 사전순 최소 · 없으면 null" + }, + "legal_calculation_object_types": [ + "fraudulent_transfer", + "land_use_gain", + "money_claim", + "secured_debt", + "valuation" + ], + "legal_calculation_object_note": "구본 677행 5-원소 집합 승계(D-P4-1 값 이관). calculation_bindings 비공백 도메인으로 대체하면 항등식으로 퇴화한다(라운드 12 실측 — 25도메인 x type_id 56종 전건).", + "evidence_scoring_da_2": { + "note": "(다) credibility·proof_strength — 골든 59행 전건 값등가 요구. 갈래 순서를 바꾸면 재현이 깨진다(문서 초안 4갈래 = 29/59 실측).", + "authority_row_keys": { + "evidence_index": "id 키 6종(evidence_index·id·evidence_id·eid·index·doc_id) 첫 적중", + "title": "first_key(title, Title, name, doc_title)", + "excerpt": "key_facts -> key_dates/key_amounts -> 대표 문자열 폴백", + "priority": "first_key(priority, Priority, weight)", + "authentication": "first_key(authentication, auth, source_authentication)", + "source": "고정 문자열 'evidence_indexed.json'" + }, + "flatten_depth": 3, + "universe_missing_stub": "{evidence_index: eid, missing: true} — stub 도 비어 있지 않은 증거 행으로 계수한다(구본 1136행 승계)", + "text_rule": "행마다 json.dumps(sort_keys=True, ensure_ascii=False) -> 공백열 단일 공백 -> 300자 절단 -> ' '.join 으로 합쳐 1회 대조(합친 뒤 절단이 아니다). sort_keys 에서 title 이 최후미라 절단이 마커를 먼저 지운다 — 절단 여유를 영수증에 적는다", + "markers_documentary": [ + "등기", + "계약", + "판결", + "공문", + "금융", + "송금", + "계좌", + "registry", + "contract", + "judgment" + ], + "branches_in_order": [ + { + "order": 1, + "condition": "증거 행 0건", + "credibility": "low", + "proof_strength": "low" + }, + { + "order": 2, + "condition": "마커 10종 중 하나라도 text 에 존재", + "credibility": "high", + "proof_strength": "documentary" + }, + { + "order": 3, + "condition": "증거 행 2건 이상", + "credibility": "high", + "proof_strength": "high" + }, + { + "order": 4, + "condition": "text 에 meeting 또는 회의 또는 면담", + "credibility": "medium", + "proof_strength": "meeting_only_core" + }, + { + "order": 5, + "condition": "그 외 전부", + "credibility": "medium", + "proof_strength": "medium" + } + ] + }, + "skeleton_checks": { + "order": [ + "EMPTY_DERIVED_FACT", + "NO_EVIDENCE_REFS", + "NO_LINKED_LEGAL_EFFECT_STRUCTURE" + ], + "note": "스켈레톤 3코드를 이 고정 순서로 먼저, 그 뒤 게이트 코드를 gate_id 오름차순으로 append, 중복은 첫 출현 위치 보존 dedupe. G-n(바이트 동일)·G-r 이 순서에 의존한다." + }, + "gate_execution": { + "implemented_condition_keys": [ + "any_review_code_present", + "required_slots_missing_or_conflicting", + "calculation_operand_state_in" + ], + "visualized_condition_keys": { + "boundary_or_overlap_detected": "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW — 정의처(domain_extension.schema · Stage2_handoff_contract)가 배포 트리에 없다(D-P4-c=(가) · source_refs 배포 선언 0회 실측)" + }, + "str_condition_disposition": "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW — 술어 명세를 코드로 옮기는 것은 판정식 창작이다(D-P4-b=(가))", + "orphan_rule_disposition": "GATE_RULE_NOT_IN_REGISTRY", + "unknown_or_missing_policy_default": "fail_open_to_review", + "block_semantics": "blocks_final_drafting: true 는 Stage 1 기록을 막지 않는다. 행은 기록되고 final_writer_status 가 READY_WITH_REVIEW 가 되며 발화는 handoff GATE_FIRED_REVIEW(HARD_WARNING)로 남는다. S2_00 은 이를 건수로만 넘긴다.", + "row_projection": { + "target_rows": "발화 게이트의 도메인 d 에 대해 R(d) = { row | d ∈ row.domain_effects 키 }", + "codes": "R(d) 전 행의 skeleton_validation_codes 에 합집합 부착(순서 규칙은 skeleton_checks)", + "must_consider": "row_effect.must_consider 보유 규칙 발화 시 R(d) 전 행 OR 갱신(기존 True 미소실)", + "preserve_seed": "on_true.preserve_seed 는 행 필드가 아니라 writer report 게이트별 발화 목록에만 기록", + "empty_target": "R(d) 공집합이면 행에 닿지 않고 writer report 와 handoff GATE_FIRED_REVIEW 에 계수(침묵 아님)" + }, + "normalization_axes_17": { + "rule_array_keys": [ + "rules", + "gates" + ], + "emitted_code_keys": [ + "emitted_codes", + "emitted_review_codes", + "review_code" + ], + "effect_containers": [ + "writer_effect", + "row_effect", + "on_true" + ], + "block_flag_paths": [ + "writer_effect.final_drafting_block", + "writer_effect.blocks_final_drafting", + "on_true.blocks_final_drafting" + ], + "status_when_triggered_paths": [ + "writer_effect.status_when_triggered", + "writer_effect.status_on_fire", + "on_true.writer_status" + ], + "evaluation_keys": [ + "evaluation_mode", + "implementation_type", + "evaluation" + ], + "row_effect_keys": [ + "row_effect.must_consider", + "on_true.preserve_seed" + ], + "file_status_keys": [ + "closure_status", + "status" + ], + "input_declaration_keys": [ + "input_fields", + "input_contracts" + ], + "optional_flags": [ + "writes_fact_ledger", + "unknown_or_missing_policy", + "silent_repair_forbidden", + "source_membership_required" + ], + "global_status_rule_note": "사이드카 global_status_rule 3방언은 채택하지 않는다 — 경고로만 기록하고 전역 규칙은 아래 global_status_rule 하나를 쓴다" + }, + "emitted_code_registry_check_surface": "gates[].review_codes (게이트 단위) — 도메인 어휘 면을 쓰면 실측 초과 2건(E18-G03·E20-G03)이 사라진다" + }, + "legacy_alias": { + "source": "routing/extension_payload_key_declarations.v1.json legacy_alias_targets", + "self_declaration_scan": "배포 domains//structure_types.json 전수 — 배열 키 방언(types·structure_types·entries) 정규화 · legacy_source 약칭(B1~B5)을 완전명으로 정규화 · B* 형이 아닌 값(예: 'Part3 fallback')은 선언이 아니다", + "mismatch_disposition": "누락 도메인은 해소 결과에 추가하지 않고 LEGACY_ALIAS_SELF_MISMATCH_REVIEW 로 누락 도메인 ID·영향 항목 수를 계수한다. 자산의 legacy_declaration_mismatches 는 파생 목록이므로 대조용으로만 쓰고 불일치 시 LEGACY_ALIAS_DECLARATION_INCOMPLETE_REVIEW 를 계수한다.", + "abbreviation_map": { + "B1": "B1_Money_Successor", + "B2": "B2_Secured_Registry", + "B3": "B3_Land_Valuation", + "B4": "B4_Actio", + "B5": "B5_Succession_Notice_Lien_Asset_Defense" + } + }, + "p2_handoff_rules": { + "code_key": "source_review_code — issue_type 은 enum 밖 값을 뭉갠다", + "code_pattern": "^[A-Z][A-Z0-9_]{2,127}$", + "not_a_code_disposition": "P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW", + "domain_attribution": "source_domain 을 별칭 해소표로 registry 도메인 ID 로 옮긴 뒤 해당 도메인 게이트에만 공급한다(전역 병합 금지 — 교차 오발화)", + "domain_unresolved_disposition": "P2_HANDOFF_DOMAIN_UNRESOLVED_REVIEW — 어느 게이트에도 공급하지 않는다" + }, + "calculation_join": { + "join_key": "signal_id (details.request_id 는 보장되지 않는 키)", + "operand_state": "Part 2 산출을 재산정 없이 승계한다(D-P4-6). deferred 는 registry 선언값이다.", + "calculation_id_missing": "signal_id 로 대체하고 CALCULATION_ID_SUBSTITUTED_REVIEW 계수 — 버리지 않는다", + "dangling_ref": "calculation_id 없는 stub 항목으로 적재(버리면 등식 ④가 정상 실행에서 발화) · CALCULATION_REF_DANGLING_REVIEW 계수", + "law_version_refs": "SG-11 레코드 law_version_refs ∪ details.law_version_refs ∪ 해당 도메인 SG-04 레코드 signal_id — 버전 확정 판단 금지(SG-04 는 참조만)" + }, + "conservation_equations_5": { + "row": "len(rows) == len(BO.json) -> PART4_ROW_CONSERVATION_BROKEN", + "attachment_coverage": "부착 BO 수 + 미부착 BO 수 == len(BO.json) -> PART4_BO_ATTACHMENT_COVERAGE_BROKEN", + "effect": "Σ_bo |domain_effects 키| == Σ_bo |by_bo_id 레코드 distinct domain_id| -> PART4_EFFECT_CONSERVATION_BROKEN", + "calc_row": "Σ_bo |calculation_requests| == Σ_bo |by_bo_id 레코드 distinct calculation_request_refs| -> PART4_CALC_CONSERVATION_BROKEN", + "calc_source": "부착 distinct SG-11 + 미부착 distinct == SG-11 레코드 총수 -> PART4_CALC_SOURCE_CONSERVATION_BROKEN", + "note": "④와 ⑤는 차원이 다르다 — 컴파일러가 SG-11 signal_id 를 도메인 전 레코드에 복사하므로 행 항목 수 ≠ 원천 레코드 수. by_bo_id == {} 는 정상 입력이다(골든 경로 부착 0/59)." + }, + "unattached_review": { + "bo": "FACT_ROW_UNATTACHED_REVIEW", + "structure": "STRUCTURE_UNATTACHED_REVIEW", + "note": "보존 등식은 손실을 세지 흡수를 세지 않는다 — 침묵 금지를 등식 위에 따로 건다" + }, + "exception_pack": { + "surviving_type": "legal_calculation_required", + "review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW", + "trigger": "BO provenance.amount_alternatives 가 있는 행(값이 갈린 금액 정본)은 pack 적재 + conflict_flags [CALCULATION_BASIS_CONFLICT]. 계산 대상 유형 여부와 무관하다 · 그 밖에 legal_calculation_object 가 있고 amount 또는 object_spec 공백이거나 BO 금액 없이 provenance.amount_related_values 만 있으면 pack 미적재 + CALCULATION_BASIS_INCOMPLETE_REVIEW 검토(이 경우 detail 에 related_values 건수)", + "exception_id_format": "FX-{n:03d}", + "pack_item_char_limit": 2000, + "oversize_disposition": "자동 차단이 아니라 exception_id 유지한 채 CALCULATION_PACK_OVERSIZE_REVIEW", + "unreachable_in_v8": { + "unresolved_asset_cluster_projection": "asset_cluster 계열이 Part 3 v.8 에서 소멸(P2·P3·LES 스키마·컴파일러 0회)", + "unresolved_structure_role_projection": "registry structure_types 73/73 이 module·role_projection 전건 선언(결손 0)" + }, + "unreachable_disposition": "pack 에 실리면 PART4_UNREACHABLE_EXCEPTION_TYPE 경성 실패", + "conflict_note": "값이 다른 금액 정본이 함께 있다. BO 금액이 있으면 그것이 금액 본체이고 확정된 값이 아니다. selected_value_id 는 계산 근거 판정이며 금액을 바꾸지 않는다. 별개 사실일 수 있으므로 소장 금액은 변호사가 확인한다.", + "related_values_note": "related_values 는 이 BO 와 연결된 값 표시이고 BO 금액이 아니다. BO 금액이 있으면 그것이 금액 본체이고 related_values 는 월세처럼 per 가 있는 별도 금액이다. BO 금액이 없으면 이율 같은 비금액과 요건사실에 언급만 된 금액도 들어 있을 수 있다. 소장 금액은 변호사가 확인한다." + }, + "adjudication": { + "accepted_status": [ + "READY", + "READY_NO_EXCEPTIONS", + "READY_WITH_BLOCKS" + ], + "note": "F1 은 행 금액을 바꾸지 않는다. 계산 근거 판정은 amount JSON 의 conflict.selected_value_id 에만 남는다. Part 2 R1 과 같은 원칙이다 — 값이 다른 정본은 별개 사실일 수 있다. LLM 출력 이상은 멈추지 않고 UNRESOLVED 표시와 CALCULATION_BASIS_CONFLICT_REVIEW 로 내린다." + }, + "global_status_rule": "금액 예외(SELECTED 포함) · deterministic review · LES 승계 검토(review_codes 2종 ∪ review_required 플래그) · gate review code 중 하나라도 있으면 READY_WITH_REVIEW, 아니면 READY (동결 계약 승계 — 사이드카 3방언 값은 경고로만 기록)", + "les_inherited_review_codes": [ + "UNREGISTERED_EFFECT_TYPE_REVIEW", + "PART3_REGISTRY_SIDECAR_MISMATCH" + ], + "root_wrapping_table": { + "signals/signal_manifest.json": null, + "routing/domain_activation_manifest.json": "domain_activation_manifest", + "BO.json": "(array)", + "legal_effect_structures.json": null, + "signals/domain_signals/.json": "domain_signal_envelope", + "quality_gates/stage1_part2_review_handoff.json": null, + "evidence_indexed.json": null, + "stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json": "fact_ledger_candidate_bundle", + "stage1_tmp/fact_ledger/fact_exception_pack.json": "fact_exception_pack", + "stage1_tmp/fact_ledger/fact_adjudication.json": "fact_exception_adjudication", + "Fact_Ledger_base.json": "(array)", + "stage1_tmp/fact_ledger/fact_ledger_writer_report.json": null, + "quality_gates/stage1_part4_review_handoff.json": "stage1_part4_review_handoff", + "validation_assets/routing/part4_receipt.json": null, + "signals/governing_law_version_signals.json": null, + "signals/timeline_notice_condition_signals.json": null, + "signals/asset_right_state_signals.json": null, + "signals/evidence_proof_conflict_signals.json": null, + "signals/calculation_requirements.json": null + }, + "review_codes_soft": [ + "GATE_SPEC_NOT_DEPLOYED_REVIEW", + "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW", + "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW", + "GATE_RULE_NOT_IN_REGISTRY", + "GATE_EMITTED_CODE_NOT_IN_REGISTRY", + "GATE_BLOCK_FLAG_MISMATCH_REVIEW", + "FACT_ROW_UNATTACHED_REVIEW", + "STRUCTURE_UNATTACHED_REVIEW", + "CALCULATION_REF_DANGLING_REVIEW", + "CALCULATION_ID_SUBSTITUTED_REVIEW", + "CALCULATION_BASIS_INCOMPLETE_REVIEW", + "LEGACY_ALIAS_SELF_MISMATCH_REVIEW", + "LEGACY_ALIAS_DECLARATION_INCOMPLETE_REVIEW", + "P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW", + "P2_HANDOFF_DOMAIN_UNRESOLVED_REVIEW", + "EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE", + "EMPTY_DERIVED_FACT", + "NO_EVIDENCE_REFS", + "NO_LINKED_LEGAL_EFFECT_STRUCTURE", + "CALCULATION_REQUEST_UNATTACHED_REVIEW", + "CALCULATION_PACK_OVERSIZE_REVIEW" + ], + "hard_failure_codes": [ + "PART4_ASSET_DEPLOYMENT_INCOMPLETE", + "PART4_RUNTIME_MANIFEST_INVALID", + "MODULE_MIRROR_UNREGISTERED", + "MODULE_MIRROR_HASH_MISMATCH", + "PART4_POLICY_INVALID", + "PART4_LEDGER_SCHEMA_STALE", + "PART4_COMPILER_STALE", + "PART4_SIGNAL_SEAL_FAILED", + "PART4_REGISTRY_INDEX_SEAL_FAILED", + "PART4_LES_TRANSACTION_MISMATCH", + "PART4_ROW_CONSERVATION_BROKEN", + "PART4_BO_ATTACHMENT_COVERAGE_BROKEN", + "PART4_EFFECT_CONSERVATION_BROKEN", + "PART4_CALC_CONSERVATION_BROKEN", + "PART4_CALC_SOURCE_CONSERVATION_BROKEN", + "PART4_BO_CONSERVATION_BROKEN", + "PART4_FACT_ID_SEQUENCE_BROKEN", + "PART4_DOMAIN_EFFECT_NOT_ACTIVE", + "PART4_LEDGER_SCHEMA_INVALID", + "PART4_UNREACHABLE_EXCEPTION_TYPE", + "PART4_WRITE_REREAD_MISMATCH" + ], + "deprecation": { + "old_4_fields_alias": "money_claim_effect·commercial_successor_effect·actio_roles·linked_actio_structures 는 v.8 한 버전 동안 domain_effects 로부터의 결정론 별칭이다. v.9 에서 제거 예정(D-P4-a=(가)).", + "derived_fact_4part_branch": "구본의 date·actor·obj·action 4항 서술 분기는 삭제 확정 — object_spec 참조가 끊겨 조건이 영구 거짓이 되는 사문이다.", + "old_signal_3_root_names": "actio_case_signals·case_liability_signals·legal_effect_signals 뿌리 이름을 읽지 않는다(C-7 폐쇄)." + }, + "f1_exception_types": { + "legal_calculation_required": { + "unreachable_in_v8": false + }, + "unresolved_asset_cluster_projection": { + "unreachable_in_v8": true + }, + "unresolved_structure_role_projection": { + "unreachable_in_v8": true + } + }, + "alias_module_vocabulary": { + "money_claim_effect": "money_claim", + "commercial_successor_effect": "commercial_successor", + "actio_fields": "actio", + "note": "구 4필드 별칭이 참조하는 module 어휘. 코드에 리터럴을 두지 않는다(정적 검사 11) — registry structure_types[].module 이 원천이고 이 선언은 그중 별칭 파생이 쓰는 세 값을 고정한다." + }, + "review_codes_hard_warning": [ + "CALCULATION_BASIS_CONFLICT_REVIEW", + "GATE_FIRED_REVIEW" + ], + "review_codes_note": "GATE_FIRED_REVIEW 는 blocks_final_drafting 게이트만 HARD_WARNING, 나머지는 SOFT_WARNING 이다." +} diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/runtime_manifest_11_05_5_22pm.json.bak b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/runtime_manifest_11_05_5_22pm.json.bak new file mode 100644 index 00000000..71f3d99c --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/runtime_manifest_11_05_5_22pm.json.bak @@ -0,0 +1,1867 @@ +{ + "entries": [ + { + "path": "computations/CE-01/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-01/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-01/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-01/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-01/calculation_config.json", + "sha256": "3203d7794e560fadea0fdef3185d778c4e008035faa48073aa031bd1af1c4cf9" + }, + { + "path": "computations/CE-01/input.schema.json", + "sha256": "4b38fc245443c122964cd991b625e10dcd1c8197322fb4be6b67ce6d25dab2e3" + }, + { + "path": "computations/CE-01/legal_sources.json", + "sha256": "36b2c2b59f7d779045da04afe628993187db1f898c765caa6f6ef7124869e0e5" + }, + { + "path": "computations/CE-01/result.schema.json", + "sha256": "6b59729f53471e597b0f69c2dc2d9ad8699edbb14d7eb734f3bc1edac1acb157" + }, + { + "path": "computations/CE-01/rule_bindings.json", + "sha256": "c45cea648e1e31b3b6e3bc5a855f162146d95ffb64914cdc51321cb39bcc9086" + }, + { + "path": "computations/CE-01/runtime.py", + "sha256": "ae4c5dd04251be4fc5d95ac87f940a76c86efd174538de7e36fcad064d26c685" + }, + { + "path": "computations/CE-01/runtime.txt", + "sha256": "ae4c5dd04251be4fc5d95ac87f940a76c86efd174538de7e36fcad064d26c685" + }, + { + "path": "computations/CE-01/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-01/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-02/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-02/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-02/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-02/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-02/calculation_config.json", + "sha256": "8c3ca126253713b8d0ab7b2fc7b642744a11da6e1289fb058cd26700376830d7" + }, + { + "path": "computations/CE-02/input.schema.json", + "sha256": "c793bf6ee703ff74949c3f6c6bd601043c353a5f2270d33cf1179c495d49f409" + }, + { + "path": "computations/CE-02/legal_sources.json", + "sha256": "516d1df3c30bca72ddca5ad553365b51428734d7d889737eced278df4b2a28d2" + }, + { + "path": "computations/CE-02/result.schema.json", + "sha256": "040e9b835292a22b7189f322a77326e884104fdd5eca1e6735ac8032b2d3e110" + }, + { + "path": "computations/CE-02/rule_bindings.json", + "sha256": "ef13267fe8a9d1465bc4e8d9cb17113e8bc8f5c67fa8d593057364e9b9ef5c41" + }, + { + "path": "computations/CE-02/runtime.py", + "sha256": "d3c137e3ddbab07e53fec3d8f0653e01c8b00c4db3c5cd0edf964aaa9cdae3c6" + }, + { + "path": "computations/CE-02/runtime.txt", + "sha256": "d3c137e3ddbab07e53fec3d8f0653e01c8b00c4db3c5cd0edf964aaa9cdae3c6" + }, + { + "path": "computations/CE-02/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-02/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-03/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-03/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-03/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-03/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-03/calculation_config.json", + "sha256": "58c373598b08b6cc589684f6f6665882c9678f608eb95bc0f5b5b9f9a064e86a" + }, + { + "path": "computations/CE-03/input.schema.json", + "sha256": "11d587b3ca72fc6f09b13b4e032943d4111f9f07c13cbfd28b08ec292820f1f8" + }, + { + "path": "computations/CE-03/legal_sources.json", + "sha256": "fa5a8d24bf34e898637cb0928498e0930853a6e302c443725c98e7978ef7c866" + }, + { + "path": "computations/CE-03/result.schema.json", + "sha256": "584c593086729508bdc7dcf77f41165e087bee080b6f5eee4752e1a176f0d747" + }, + { + "path": "computations/CE-03/rule_bindings.json", + "sha256": "03903645939d2a24103c6e2ec38f406c58087e5be1c8e3ba2868beaf23a22884" + }, + { + "path": "computations/CE-03/runtime.py", + "sha256": "345259ad0e6642617465f5bece4070b7c869af4c95398992185166873851e7ce" + }, + { + "path": "computations/CE-03/runtime.txt", + "sha256": "345259ad0e6642617465f5bece4070b7c869af4c95398992185166873851e7ce" + }, + { + "path": "computations/CE-03/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-03/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-04/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-04/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-04/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-04/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-04/calculation_config.json", + "sha256": "715362e80a35b578cd70a3ca6ea6a3081d777c4dfe65076097172d7090a43505" + }, + { + "path": "computations/CE-04/input.schema.json", + "sha256": "297f4f3909cdfff92b99af02d68eb05f3615138e7012e3480b18c50f4018955f" + }, + { + "path": "computations/CE-04/legal_sources.json", + "sha256": "abe56ff1f1c61cf033a4382c9f1522cc5c9ab396fb4afd2b1736388e2f35c1f0" + }, + { + "path": "computations/CE-04/result.schema.json", + "sha256": "acbd26ff73ff673ff77cb98a3cf888f8b0b11e0418ec7b794589dad78f544008" + }, + { + "path": "computations/CE-04/rule_bindings.json", + "sha256": "27da494fba541247ad6dd5608f82fcdf36cf6532d887790fc57a437bbafeb959" + }, + { + "path": "computations/CE-04/runtime.py", + "sha256": "db82038e271c68a4265412b052df9a142078621e798c812d7253849e5b3e73ac" + }, + { + "path": "computations/CE-04/runtime.txt", + "sha256": "db82038e271c68a4265412b052df9a142078621e798c812d7253849e5b3e73ac" + }, + { + "path": "computations/CE-04/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-04/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-05/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-05/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-05/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-05/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-05/calculation_config.json", + "sha256": "b9fdd5c29cb3236860dc235c615cc3d9de76df1b83a913c539fdd1ed08525593" + }, + { + "path": "computations/CE-05/input.schema.json", + "sha256": "0a6a5685d8b371d21879d9471e4836170b556566748e59ab0bf8e92093551f65" + }, + { + "path": "computations/CE-05/legal_sources.json", + "sha256": "705f076994c0aac833fd693c262fffe9272654ae8e5119db9909229ab1f0526f" + }, + { + "path": "computations/CE-05/result.schema.json", + "sha256": "090a3d412d4dd3c73484a104566372be477d646cd489f32f2142a7bc80076966" + }, + { + "path": "computations/CE-05/rule_bindings.json", + "sha256": "7a7c80890e1f1dc7d31e791aedd6ff3cbf758808890b659817a6a9b24524dde1" + }, + { + "path": "computations/CE-05/runtime.py", + "sha256": "539c97da9a9e6efe5236a2f83de1b93ea0f29820abb8e9d85d75abad0a7fa066" + }, + { + "path": "computations/CE-05/runtime.txt", + "sha256": "539c97da9a9e6efe5236a2f83de1b93ea0f29820abb8e9d85d75abad0a7fa066" + }, + { + "path": "computations/CE-05/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-05/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-06/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-06/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-06/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-06/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-06/calculation_config.json", + "sha256": "af6698a82611c6b433ab0325c85e023af8e03ed3243c0df93ad0d79a242e5453" + }, + { + "path": "computations/CE-06/input.schema.json", + "sha256": "e0d17b241b10a2100468502f9f603c58f286bf88334dd87a9092ddfd16d9c03f" + }, + { + "path": "computations/CE-06/legal_sources.json", + "sha256": "68226ef6ac76dfaf5c190bd18b2d14135c275aefaa9ce641661e864e1f0f47a4" + }, + { + "path": "computations/CE-06/result.schema.json", + "sha256": "fd75007c1efdadf38532ca8b472dce2141059a2a262e1afb6a4b112f8469607e" + }, + { + "path": "computations/CE-06/rule_bindings.json", + "sha256": "05e3929ff879676220e17d3692adda9e4291f8931d9a08dd55c0a89e6952211d" + }, + { + "path": "computations/CE-06/runtime.py", + "sha256": "ca4793e19e8584c02b8ca539f0a3ddf97e98bc3915c3f0f6c507a495b704fe22" + }, + { + "path": "computations/CE-06/runtime.txt", + "sha256": "ca4793e19e8584c02b8ca539f0a3ddf97e98bc3915c3f0f6c507a495b704fe22" + }, + { + "path": "computations/CE-06/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-06/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-07/build_scenarios.py", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-07/build_scenarios.txt", + "sha256": "6ea1e4d6aaf320bcff54357f1e6cfed0b6db4cbdcf33dc5a3dd69a865ba0b4e4" + }, + { + "path": "computations/CE-07/calculate_preview.py", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-07/calculate_preview.txt", + "sha256": "d891d55e2b19838e882267aaab9f45414c0af308b0ea0453d87363757afc0fec" + }, + { + "path": "computations/CE-07/calculation_config.json", + "sha256": "9d8fbc73d1e258d6f07ea0752e5a41f1f3cab6ed263420bffe39bf78ee1a9732" + }, + { + "path": "computations/CE-07/input.schema.json", + "sha256": "5b746de91963c1acc7e91141a94c0e6a234220f40efaae019ff60d5aabda024b" + }, + { + "path": "computations/CE-07/legal_sources.json", + "sha256": "31b7e72fb91ece1cd8b7e910235951c23d2a9c3962c7eb247b0611a6e61a7634" + }, + { + "path": "computations/CE-07/result.schema.json", + "sha256": "0e68e5748eb7954457102c0a9fd145cab6e66dfd67295dab32aac322c4843c89" + }, + { + "path": "computations/CE-07/rule_bindings.json", + "sha256": "9c5dfbca715415fdd70006e3d9238293162d6cf24c89077c316fb5911657da24" + }, + { + "path": "computations/CE-07/runtime.py", + "sha256": "aa6b3064ca7a32cb06f8d86592ebc045b5a7c4761c65cce4ce810c0943754911" + }, + { + "path": "computations/CE-07/runtime.txt", + "sha256": "aa6b3064ca7a32cb06f8d86592ebc045b5a7c4761c65cce4ce810c0943754911" + }, + { + "path": "computations/CE-07/validate_operands.py", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-07/validate_operands.txt", + "sha256": "bb0e1f4a0229201889ec2ad3636a4a0d0f2940c7368fe28a6ae0da25ddbb6fe7" + }, + { + "path": "computations/CE-08/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-08/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-08/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-08/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-08/calculation_config.json", + "sha256": "af76ca7365a2ff67cfcfe5a98bcdad381dd069d98a7a50c995bf8a4e022ea4f4" + }, + { + "path": "computations/CE-08/input.schema.json", + "sha256": "5173c015bb2d3d546cc6fb06f4c9a7228e13e02ab20c5930224de6ac835ea688" + }, + { + "path": "computations/CE-08/legal_sources.json", + "sha256": "a5914a15751ed248e2cec995fcbfe9a623b2f213b8dd1e02f5cf2f777b214d3f" + }, + { + "path": "computations/CE-08/result.schema.json", + "sha256": "87606d3cb13fe880eb73f3d43128d006c9d8956310de24fd48a1037a00613eba" + }, + { + "path": "computations/CE-08/rule_bindings.json", + "sha256": "12bf2326c39fa0d044a66b9f7bb9129221f2d168e8a02834893c8800f1672df0" + }, + { + "path": "computations/CE-08/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-08/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-09/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-09/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-09/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-09/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-09/calculation_config.json", + "sha256": "06e42c61676f1f0d2cd3bcfe25a4257f6b541f630652510568b66f979ff01294" + }, + { + "path": "computations/CE-09/input.schema.json", + "sha256": "aaff89593e8ad63f21d1cb08c22ca3cf604f8b45d991e5e0be6abbe4125773d0" + }, + { + "path": "computations/CE-09/legal_sources.json", + "sha256": "9153f64b23ec2770452c21e58da58626aa7d5adb55d2af33d15bc82834c02c2e" + }, + { + "path": "computations/CE-09/result.schema.json", + "sha256": "f13cfd422622a9b5f5b561ebe33b3ea3f873c5f7a116b551128ba54d6119093c" + }, + { + "path": "computations/CE-09/rule_bindings.json", + "sha256": "3eed1546d7d546eda76797a3e3f7f845bd54cb00213b6d266c9a370163d10401" + }, + { + "path": "computations/CE-09/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-09/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-10/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-10/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-10/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-10/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-10/calculation_config.json", + "sha256": "fb2cbb42cbee14327696d958b28cbc56ace3e658a603ce9ab4495a573bf30868" + }, + { + "path": "computations/CE-10/input.schema.json", + "sha256": "2614a0105da34d1cb92c6bea41939782e06911e6ade1084ab46089748daf93c0" + }, + { + "path": "computations/CE-10/legal_sources.json", + "sha256": "79405a0ef65ad1c68eed0a7858451e13a0611056b66f627402c7ab1eadbaa260" + }, + { + "path": "computations/CE-10/result.schema.json", + "sha256": "3f0f882ec80d917a9467d6ad103913689f19d76dd928be4b41c4e5148093145b" + }, + { + "path": "computations/CE-10/rule_bindings.json", + "sha256": "40c97d91bea995d115c87273275eb431713bc2765ea7282fe3ea4379c1ea42df" + }, + { + "path": "computations/CE-10/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-10/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-11/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-11/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-11/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-11/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-11/calculation_config.json", + "sha256": "c8227234e8be3c0070d6f227fba793fe07c32fa9f66b0448eb56090ccdf6a8b5" + }, + { + "path": "computations/CE-11/input.schema.json", + "sha256": "27abe619222ffba678fa5c79581c58018055cb4cc52822808fe9f67998e6d233" + }, + { + "path": "computations/CE-11/legal_sources.json", + "sha256": "d410993f1f1c539d9648f575b904e8cf44cc8a884a3de515f7dd9141c5fbf2b7" + }, + { + "path": "computations/CE-11/result.schema.json", + "sha256": "158d2cbe5512f321539e5ec15b3a7a0dd2bd7cee5e7696b5da614f0eb146c301" + }, + { + "path": "computations/CE-11/rule_bindings.json", + "sha256": "85633f8db119854985bd5977112f60b9a95ca372e1984435cc45b9c1906b4122" + }, + { + "path": "computations/CE-11/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-11/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-12/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-12/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-12/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-12/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-12/calculation_config.json", + "sha256": "37b3f54711741e7904470edd27edd73252941cfa9676795d7cf3d094b0e50e5f" + }, + { + "path": "computations/CE-12/input.schema.json", + "sha256": "dc0bf45b7b2cb025d8499db3018414d53e869b5f124d73b8a19568b6b6ea1da6" + }, + { + "path": "computations/CE-12/legal_sources.json", + "sha256": "c5f24a0d78643a318eaeb7d415542b7f229c9f883461e93716bbd5da67245670" + }, + { + "path": "computations/CE-12/result.schema.json", + "sha256": "bc23734a58e301ffe5fc14cdb5e856fd4ca19e797c2b744795f5ad27f7fe9a9e" + }, + { + "path": "computations/CE-12/rule_bindings.json", + "sha256": "e1eb7a94032bdd61f236f93fe40790cb7ba936b7516ed699ac039c4afb888c7d" + }, + { + "path": "computations/CE-12/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-12/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-13/build_scenarios.py", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-13/build_scenarios.txt", + "sha256": "3e8a6566877a1ed0db0b2ecf44a9d0c2a155b298111a1febfa41e2c887da3b31" + }, + { + "path": "computations/CE-13/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-13/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-13/calculation_config.json", + "sha256": "0777b8d75002f503fe947cba412dd78c4f665974249f04d00ea510ba736e3669" + }, + { + "path": "computations/CE-13/input.schema.json", + "sha256": "c4fdb99ed30ad0527e337d3d5f93d783e3df4487b8ab976d0d522c8a8e9c633a" + }, + { + "path": "computations/CE-13/legal_sources.json", + "sha256": "9251de924bc65f1f1ccf112408333b774769fb4f8c578be5f46afa3dd250381a" + }, + { + "path": "computations/CE-13/result.schema.json", + "sha256": "9eba9125f2d9c740aad40674e46cbc999985e2f2845bb178f90d9b0ffc956c3d" + }, + { + "path": "computations/CE-13/rule_bindings.json", + "sha256": "4ffca8e7c9f7d6318ed476521a039455ca1be0c3c15e78633595dd27edf6ff70" + }, + { + "path": "computations/CE-13/validate_operands.py", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-13/validate_operands.txt", + "sha256": "7e59236c0a04581a63e89d33a0afa252b1fa2b4fcd8d82d8c6c6265b2161db8f" + }, + { + "path": "computations/CE-R1/build_scenarios.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R1/build_scenarios.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R1/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R1/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R1/calculation_config.json", + "sha256": "9f8b365ff6e2f530886bf6ec3d3cb0ad1bc0c4ab1f971b22789085e4c5d0d482" + }, + { + "path": "computations/CE-R1/input.schema.json", + "sha256": "128e2f1f9255d3a71db061aa8b7e0a63d0cbcdbf145f05077dd77e85fa0f92d7" + }, + { + "path": "computations/CE-R1/legal_sources.json", + "sha256": "e5b3fa59bb7c2abd0ab503f48dbca62323056a85dedb8ef87e1850b5e4e9bc1a" + }, + { + "path": "computations/CE-R1/result.schema.json", + "sha256": "8500fa2d64469705fb5b90fcd75ffdeea8a14ad343471436f29935bc9b306679" + }, + { + "path": "computations/CE-R1/rule_bindings.json", + "sha256": "6d91a467a0e8b70a119cc022ad9a0a7826a4c890dbb2a33b35de0e063c5c6e35" + }, + { + "path": "computations/CE-R1/validate_operands.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R1/validate_operands.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/build_scenarios.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/build_scenarios.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/calculation_config.json", + "sha256": "bd880eea154c8f7b14ee0fad1c30275eb94ab7a16261991e19c89a963ba17f07" + }, + { + "path": "computations/CE-R2/input.schema.json", + "sha256": "604862070ca05071d33035f056b06addf07eb95628093e5d78c8b969728dc44b" + }, + { + "path": "computations/CE-R2/legal_sources.json", + "sha256": "d7dfe4f134bfcbad54159d1dea0c58abcd3e39035766d1bcdeed3b26161974e0" + }, + { + "path": "computations/CE-R2/result.schema.json", + "sha256": "3b89d09e2166d31b48c413de038fb92f6e58d64713bf828ccb8a36c7ecc0f266" + }, + { + "path": "computations/CE-R2/rule_bindings.json", + "sha256": "22725fe7f52e3ab28dbb9b538e886115e7abb064c4b5e6d053832d58e2e3a45e" + }, + { + "path": "computations/CE-R2/validate_operands.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R2/validate_operands.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/build_scenarios.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/build_scenarios.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/calculation_config.json", + "sha256": "89c4cf1264ca3fb63624b1df6fd9bd3990d7c320d776fde5d88ad0f351c8880e" + }, + { + "path": "computations/CE-R3/input.schema.json", + "sha256": "eb8c3219a8e117ad8eb73ef974663638ab7f239a817d0462acc79f142dab2ba6" + }, + { + "path": "computations/CE-R3/legal_sources.json", + "sha256": "f5d6d3dab2c3654ed2a1186a67bfe165ee3a9cd41b2be58a88ac140ae53195a1" + }, + { + "path": "computations/CE-R3/result.schema.json", + "sha256": "0d5dd5a296da5f6afe469075c28d93e51d9c32de7ca882b575194a7b719a27bd" + }, + { + "path": "computations/CE-R3/rule_bindings.json", + "sha256": "1a7206f5f77e24bd200dca86286daaf80c00679744e37b31fbc429869f371582" + }, + { + "path": "computations/CE-R3/validate_operands.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R3/validate_operands.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/build_scenarios.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/build_scenarios.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/calculate_preview.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/calculate_preview.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/calculation_config.json", + "sha256": "aaa58513348b2f65a2da30753f94d4bd7ffec71568b59ed9607025006a970bef" + }, + { + "path": "computations/CE-R4/input.schema.json", + "sha256": "a9f1052844261ea32b0c40f2dda594681218fce6eead25d130fd3b1ab217028c" + }, + { + "path": "computations/CE-R4/legal_sources.json", + "sha256": "974ebfc8bd488d4105fb83637b1d3aed32ee631530ae1daaf7d653da104a21c6" + }, + { + "path": "computations/CE-R4/result.schema.json", + "sha256": "d71aa181f66e5b9bf96385e47b4302bc469f6517d09981b781938d658ff2cef2" + }, + { + "path": "computations/CE-R4/rule_bindings.json", + "sha256": "230cbc7c6785695dad0334a27d7da735b10b7198007b42134db4ba31be0acac7" + }, + { + "path": "computations/CE-R4/validate_operands.py", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/CE-R4/validate_operands.txt", + "sha256": "ba28e4c4f5a7cea416cd37a91b9ba68ca0e1c2f3156a13f69bee3dbf9ac58cfc" + }, + { + "path": "computations/_shared/numeric_guards.py", + "sha256": "498280d6f8080aafd5c1c46e70747514e4685a19f2a87f6bf254a6856b26d365" + }, + { + "path": "computations/_shared/numeric_guards.txt", + "sha256": "498280d6f8080aafd5c1c46e70747514e4685a19f2a87f6bf254a6856b26d365" + }, + { + "path": "computations/calculation_registry.json", + "sha256": "7ec7200acf2b6f31923edadf368e62784ea322b46862fd57e990b97d131b9da5" + }, + { + "path": "computations/calculation_registry_manifest.json", + "sha256": "2298d5b6fb8a1a977fce08079a78b18fefa675d32fc041640c083ce2cf8fe270" + }, + { + "path": "contracts/signals/s5_execution_contract.v2.json", + "sha256": "311ac8721ec297bc86e54c83f0866d61629bd99f15746f86bbbff32914d35e02" + }, + { + "path": "domains/E-00/gates.json", + "sha256": "665499a6eaa2466846633e26c3736379091b52ca7514c8ffc14c742728c84057" + }, + { + "path": "domains/E-00/module_role_projection.json", + "sha256": "278ecdd4ac6c004f9994d6357ef439d089456a5e65bed0f74f49170ba3315932" + }, + { + "path": "domains/E-00/structure_types.json", + "sha256": "ae4a94fdbb0e2a8e0273a259e38c28774a3f2f24985878286f18a9ae05cbabaa" + }, + { + "path": "domains/E-01/gates.json", + "sha256": "d3b5acefeaf2fd42cffabad18e1caa82dc5930c4d9638ac9f9caca20e58c7194" + }, + { + "path": "domains/E-01/module_role_projection.json", + "sha256": "cb263ca339f7b749a51b57fa12d915fda3644f09e648d15a84202651a23a84fb" + }, + { + "path": "domains/E-01/structure_types.json", + "sha256": "f2c423a0346a347292b3ca33d3a9f33a82d540e83cbb5f79bb8dae7161c68b26" + }, + { + "path": "domains/E-02/gates.json", + "sha256": "fe1bbd285fd0d6fd6116ea8cd4ff9196514be84a64e8891a30fa063d0283eff7" + }, + { + "path": "domains/E-02/module_role_projection.json", + "sha256": "e21465cf806fb080d75f89526f9c142010c392ee87454a5a19248b9a80eb7c28" + }, + { + "path": "domains/E-02/structure_types.json", + "sha256": "e470dd3c96f2f9b8bfa6c2c97b05259281005a84b6eea24c38d322abdf16ad8e" + }, + { + "path": "domains/E-03/gates.json", + "sha256": "c1c7fb4b8685592a1bf1e09e78050944ccbafe25ec04164f6f1685b2a2e67820" + }, + { + "path": "domains/E-03/module_role_projection.json", + "sha256": "f693146dfb3ba2ac5fa6a6221c6b2dc7e32084acb06823b1f46f423a56546704" + }, + { + "path": "domains/E-03/structure_types.json", + "sha256": "70c579a03c41226e6383fe7b4aa5e60f4b0f5a723db30f6292dd2a0bde4d17bb" + }, + { + "path": "domains/E-04/gates.json", + "sha256": "190bd66c8d1df9d547879fb302b104fddca309f9983ee512932b9668cca9afaa" + }, + { + "path": "domains/E-04/module_role_projection.json", + "sha256": "4c4bd473a12ad1dfcc8c9392503cd057017385a21287a89cb7ea147f3cf7d2d6" + }, + { + "path": "domains/E-04/structure_types.json", + "sha256": "e8b15e9e5a39a488bf9ef660d69c7bc2db832248eb33788ba2ae54a9b5200e73" + }, + { + "path": "domains/E-05/gates.json", + "sha256": "118d3b69eeb89b961a8a0bcdb1e011addbec8d24d5279faf0edfe39c907617f8" + }, + { + "path": "domains/E-05/module_role_projection.json", + "sha256": "7fabfa3893a138dccb4e5bc797444f5f999c0e51ec6b0c8fbe0211eff3f03a6c" + }, + { + "path": "domains/E-05/structure_types.json", + "sha256": "22707fbce849991c099a08885cac929d1ba842aa896945f9921c3214e4c701d0" + }, + { + "path": "domains/E-06/gates.json", + "sha256": "1f847a976bbcc37e37ed0daf5d141f7d611ed10823b7874e6ad7e6c7ce746926" + }, + { + "path": "domains/E-06/module_role_projection.json", + "sha256": "805b73b2b15cb720b62cd83455de85a67bda434255b69d588eb98f2527f88b71" + }, + { + "path": "domains/E-06/structure_types.json", + "sha256": "a6520f72813caeaf72d62fd63eca10a1f46fd4fb3ffd97f97f222f37c53e8663" + }, + { + "path": "domains/E-07/gates.json", + "sha256": "9d6ed4dba2cf63de8688b4c047d01771bbb2d8cdab1674b9ea584ed3d570df32" + }, + { + "path": "domains/E-07/module_role_projection.json", + "sha256": "9920ed415f9768beb517100e97fa7d2eb862ca90ca83f802ea460f8f6bbf2445" + }, + { + "path": "domains/E-07/structure_types.json", + "sha256": "fd4946e24cacc3bcc74c7fee5ce7fca99d3e5f2339fe3a9d698c54e2626a6c01" + }, + { + "path": "domains/E-08/gates.json", + "sha256": "b567e5a1862adbce09420dca71ee7cc32f8771f3efb8f2428f6110d3d396b488" + }, + { + "path": "domains/E-08/module_role_projection.json", + "sha256": "4a8c284b5d3bbf8ca224e9f08398e6f563b00cec6de72f5128acc4cd8425eced" + }, + { + "path": "domains/E-08/structure_types.json", + "sha256": "a7ee6782c6541d0c6f6f6107a1d3615c2e7003a979741f2afc9d5d686a59e51d" + }, + { + "path": "domains/E-09/gates.json", + "sha256": "8570e2704bdb75225bdb8391a89525a0d121b828d7fecafdc8ebb72c7754e6bf" + }, + { + "path": "domains/E-09/module_role_projection.json", + "sha256": "ab93656808a832cfd73a6d75ed28d75e50e6cc66c67d59d765fcb8bbf638205f" + }, + { + "path": "domains/E-09/structure_types.json", + "sha256": "c374b8b912679cc765b152c58ecd8320898f947b799e44ca509aa622669d7f4c" + }, + { + "path": "domains/E-10/gates.json", + "sha256": "31bf82ccc8b543a6e0a4a17275f18a42900bec6161cce41dbdf88100659773cf" + }, + { + "path": "domains/E-10/module_role_projection.json", + "sha256": "80f760d9d8516cc81ebe503a2967418c43e11f8b8410231081111483dfa6477d" + }, + { + "path": "domains/E-10/structure_types.json", + "sha256": "07be97d40e422e14e570574c4e1da875307fe487c39e2ba9862ffd4b1623b748" + }, + { + "path": "domains/E-11/gates.json", + "sha256": "a63a84e674e8b0f5919304000dde92f4786fe2fc3eab1214cc4f1b9fbc93fc09" + }, + { + "path": "domains/E-11/module_role_projection.json", + "sha256": "0a55ce91b1845d64d085710110aec22bfcea66967ab5fce3a4acf5179faf65f1" + }, + { + "path": "domains/E-11/structure_types.json", + "sha256": "6e565bab389f59866a0eafa8b7b7ff89f90ef2363ced3d9a4240100d3b3c3b90" + }, + { + "path": "domains/E-12/gates.json", + "sha256": "b3013940aa8d496272378f76ddab7f3695f1bbc68a9773dfebf7a567ba693c42" + }, + { + "path": "domains/E-12/module_role_projection.json", + "sha256": "207ef7d4a1300c12aa54cb1defa1110a6a9d18850d0fc4e144baebe6ff2b3c27" + }, + { + "path": "domains/E-12/structure_types.json", + "sha256": "ef97f4b0ed05637165bfb211fc9be0cb3bcf0523e6b5a645c007e8dc2825bea9" + }, + { + "path": "domains/E-13/gates.json", + "sha256": "3a9d36fe9c8de15853c6b9ff8d342f6e3d3b30431a4e5fdddb3bf34b13cd9aa9" + }, + { + "path": "domains/E-13/module_role_projection.json", + "sha256": "412df6800be576d7f789bc7fc2045091eb9c49fd346e442ba42d6f29300f7313" + }, + { + "path": "domains/E-13/structure_types.json", + "sha256": "cc18073ca443e98a34e139c08d11121ceb7d4ecd366ad3b3d5cb65ddb53e36f7" + }, + { + "path": "domains/E-14/gates.json", + "sha256": "36a08d9c88a6878fe0474b59411e8496a4b9a5674edcaf5e5f290cf75c047934" + }, + { + "path": "domains/E-14/module_role_projection.json", + "sha256": "cead5634615b6b417390b37a948a050ea89cba37485bb79617bd1296c06829a5" + }, + { + "path": "domains/E-14/structure_types.json", + "sha256": "5b0025a720a7b9f1ad7c74ce8d79f0969b282690abc0e3171e28dbf41933153b" + }, + { + "path": "domains/E-15/gates.json", + "sha256": "059c800b75b7afa8836a9eeb1352fe99116d216f858374eb1cc847ec0c298eae" + }, + { + "path": "domains/E-15/module_role_projection.json", + "sha256": "873f921bbbc86fc07a0c1ecfcbcacee67b1d9592b2efd7319290a10e8c1ba018" + }, + { + "path": "domains/E-15/structure_types.json", + "sha256": "784ceabd17c6de6d95a30f52dd5fd4036946fbedc556f2bad536225057a0f5fe" + }, + { + "path": "domains/E-16/gates.json", + "sha256": "eba2368cb418aa574b84b6e088ff73e60869802385505996b731cdeaeb4bc7bc" + }, + { + "path": "domains/E-16/module_role_projection.json", + "sha256": "24ad172b32d4942be6f4031c582f928d3c6feb6e442027e3ee02700519744b11" + }, + { + "path": "domains/E-16/structure_types.json", + "sha256": "b0bb30602ec424d35359c1a676ccca2bb2eda4a676997753da44d1dbbcc1f0b3" + }, + { + "path": "domains/E-17/gates.json", + "sha256": "b517109ee6df850682ada51c16a3c686680b72e50fe3e30b98486c84ca0cae8d" + }, + { + "path": "domains/E-17/module_role_projection.json", + "sha256": "498e2320ad04a907680b8588ee1b1b9ee7487e131bece96a601979d60796f5a4" + }, + { + "path": "domains/E-17/structure_types.json", + "sha256": "d306dbdf583453d51f643eb8398920efb1bb5bfa82b3a600caa79f45f790b2eb" + }, + { + "path": "domains/E-18/gates.json", + "sha256": "c28bd022f7a873f2c48c679ff005749f8128f0eae69a41bbfa320f8b474b6742" + }, + { + "path": "domains/E-18/module_role_projection.json", + "sha256": "b0699a793cdc52e6f74e9df3254f403858e83080be9e402bf3c7dae3cd8ffd0e" + }, + { + "path": "domains/E-18/structure_types.json", + "sha256": "ce4eae3a54bfe7ac31f16b657cc0a891580e025f7bfecb1812c015e7fd0c2500" + }, + { + "path": "domains/E-19/gates.json", + "sha256": "24b6ebcdf38678663890cc960877bf86124582531ede6ae751741fd3002c3704" + }, + { + "path": "domains/E-19/module_role_projection.json", + "sha256": "00950a8c76d4367ccd6dc000476c810df33e49b07fce124545e350530b008b99" + }, + { + "path": "domains/E-19/structure_types.json", + "sha256": "58b9503558bcab3fb7ae76532659d54694208d813197e97bac148d50795feb22" + }, + { + "path": "domains/E-20/gates.json", + "sha256": "40314fa600094cb73634d7bef81804df35e6e713b5b11bd5e300a84add75a00f" + }, + { + "path": "domains/E-20/module_role_projection.json", + "sha256": "7aef9706b50161693005ee61fc576a1562929fdf20830a3187fdda2a94fae8e3" + }, + { + "path": "domains/E-20/structure_types.json", + "sha256": "6766546fd61d3f46f0d0b71bc3c41d5c63a525954b2568d8003c9f5e90234074" + }, + { + "path": "domains/E-21/gates.json", + "sha256": "c3fc58291924b41cb7a22b97ffa5f4f573fab9ff39d3ffddd49587469f51cdd3" + }, + { + "path": "domains/E-21/module_role_projection.json", + "sha256": "de6b0f29ad8100744a1a4fe8393a44a8a921d604b5244f832256450cb547722a" + }, + { + "path": "domains/E-21/structure_types.json", + "sha256": "b027ff04f21cc4a86c8285e2cde6f8fd23e0ff3a3aeb3fa61a9bd10142814e36" + }, + { + "path": "domains/X1/gates.json", + "sha256": "cd68a09a8e1c99fd2c0ee236bd7754664161d4cab5385cf83df347eaefea13ee" + }, + { + "path": "domains/X1/module_role_projection.json", + "sha256": "1bceacd99f408384fec9547262017d8c857dbdb58ae906446c45ce8f1e322920" + }, + { + "path": "domains/X1/structure_types.json", + "sha256": "3344a27beb548c7d0b083b6e442a8f70ca89ce02d22614fda83203d3ff53e7e9" + }, + { + "path": "domains/X2/gates.json", + "sha256": "bf9d6fff3c80e0eb31359387bfd231137587a21f5429e5fc5e0e863ebe34c89e" + }, + { + "path": "domains/X2/module_role_projection.json", + "sha256": "9282422d06035a78b592c110c197c1afa58e78294566eecd2666f0c61820cd5f" + }, + { + "path": "domains/X2/structure_types.json", + "sha256": "f51c0404bab1c5f4506012460ba02faf2cee6c958d49ee353095366defacd2ec" + }, + { + "path": "domains/X3/gates.json", + "sha256": "a3319e942736e35f399c25fdf8b00ef4ee35a44fcb669f7c1e350a2856eaeb98" + }, + { + "path": "domains/X3/module_role_projection.json", + "sha256": "93d3709c7d01132b82f0445d18eab7e666ea8d7fe2afe9b308bf87af5477be10" + }, + { + "path": "domains/X3/structure_types.json", + "sha256": "91f7ef0a971b519bd7fea8fb2efc61770afeb83b3a6ee774f153aea28a9de913" + }, + { + "path": "domains/_common/common_worker_contract.md", + "sha256": "4dd1bfcb12fef1a2077d670d1d87ffa67f2258b272fa7a0744ddd0692dd7367d" + }, + { + "path": "law_versions/_law_source_index.json", + "sha256": "b979f53d7062fb0594aeb193b759dff6b56b4797f58a0fd07598902a7d84c3fb" + }, + { + "path": "law_versions/calculator_runtime.py", + "sha256": "3d90b2af3a7bd1e743dfb654cc529b0044c867fd343ea9931c1bb1f3797e86ca" + }, + { + "path": "law_versions/calculator_runtime.txt", + "sha256": "3d90b2af3a7bd1e743dfb654cc529b0044c867fd343ea9931c1bb1f3797e86ca" + }, + { + "path": "law_versions/current_version_pin.json", + "sha256": "ab1d6cb8ad9b5257ec7e96b064ceb8395ff1709e042f478e713c0bdaf5459a0b" + }, + { + "path": "law_versions/forbidden_literal_dictionary.json", + "sha256": "7b0ca421eddc3b6a1913b62af2e419436eebe1899a09da203c32f47c65d738ca" + }, + { + "path": "law_versions/index.json", + "sha256": "44f746f4ec656d05d11f85cab7d39ba507a49a944bdcab2f46afce2a0b235b87" + }, + { + "path": "law_versions/law_source.schema.json", + "sha256": "70c786833aa7876f2e1babefea780f5b57fd1b69271e60e0673df76f18d7ed43" + }, + { + "path": "law_versions/law_version_registry.schema.json", + "sha256": "8c443ca46f50a60dedda3d7f52e4968ae26d82ebab2f7ac33a1685f6532fa250" + }, + { + "path": "law_versions/records/accelerated_litigation_interest.json", + "sha256": "3ffe86f04c6815955dedb6d377087116c96f25723a44adfcabc960cd13fd3d49" + }, + { + "path": "law_versions/records/ce13_attorney_fee_cost_inclusion.json", + "sha256": "9967d8ab167e17a41eb4d97618b4a4b21e31a4798c1d4c9d5f727613c1f1268c" + }, + { + "path": "law_versions/records/ce13_claim_value_rules.json", + "sha256": "43b22c0aa31ba80dd04b941c95f50084f07ae927b93f8a50eae4da3a080ed467" + }, + { + "path": "law_versions/records/ce13_stamp_fee_schedule.json", + "sha256": "f1f9899528050fee53b62e08edbb287b0910ed873f02695ecc259851e7aff241" + }, + { + "path": "law_versions/records/civil_commercial_statutory_interest.json", + "sha256": "7ae7dbba23221accd42c9d55270d09c9a0443a024eb3c78a07d3792aa1ea4b9a" + }, + { + "path": "law_versions/records/commercial_lease_major_versions.json", + "sha256": "108b5f23743aa6dff853c3c148881b6c3f1855284e6ef7d31c6feb720d3c52b7" + }, + { + "path": "law_versions/records/housing_lease_major_versions.json", + "sha256": "cd8bc45d6f19f7c43aae7bf3c61920129b03b23c07377bf1312008a80d8ee8bd" + }, + { + "path": "law_versions/records/interest_limitation_cap.json", + "sha256": "bd7a59ac226a8fc2168f1734b74c33a872c77a9e139fcc1dd3d7e7ea8d1f2d4a" + }, + { + "path": "law_versions/records/labor_delay_interest.json", + "sha256": "45a8992ea73c6ca519c61ed77f9c5189e555117efc63bc39648f561b396dcb86" + }, + { + "path": "law_versions/records/major_limitation_exclusion_periods.json", + "sha256": "64fbaa6e30a5a49d81a413a313b1c8d9f3b9f63c2077df3d7c28b58552d5eda3" + }, + { + "path": "law_versions/resolve_rule.py", + "sha256": "a96929c5960e431717fe4f2803fcabadc867d32430ed4b4213c8ce035be2efeb" + }, + { + "path": "law_versions/resolve_rule.txt", + "sha256": "a96929c5960e431717fe4f2803fcabadc867d32430ed4b4213c8ce035be2efeb" + }, + { + "path": "law_versions/rules/LR-ACCELERATED-JUDGMENT-INTEREST/2003-06-01.json", + "sha256": "20e168cfed8b02f7ac88e079812e138cc846c1d867e3fc417f87a7c146dc20a6" + }, + { + "path": "law_versions/rules/LR-ACCELERATED-JUDGMENT-INTEREST/2015-10-01.json", + "sha256": "758ccbe4422dd7d4e95d37ef34c673e48ddfb0dd7cf7ffd1257244041f18f4b3" + }, + { + "path": "law_versions/rules/LR-ACCELERATED-JUDGMENT-INTEREST/2019-06-01.json", + "sha256": "b2c0a43a1f96eb6f84779c7d0db296b800eeeebbea76a78ddf59488a7cbd73e3" + }, + { + "path": "law_versions/rules/LR-CE13-ATTORNEY-FEE-COST-INCLUSION/2018-04-01-current.json", + "sha256": "eb1424f3f619cafe1857f40ffb4e19243837b8686dfa8089960fb2a6453721f7" + }, + { + "path": "law_versions/rules/LR-CE13-CLAIM-VALUE-TABLE/2023-10-19-current.json", + "sha256": "bf9d3b9a11fb30240215d4c63108de958917a6d856c73eb5c063bcecd4e3688e" + }, + { + "path": "law_versions/rules/LR-CE13-FIRST-INSTANCE-STAMP/2023-10-19-current.json", + "sha256": "c39692cd45996fbeeda82e4380ae36efc509e06ee56cbc7f60ecbf7b2f12df47" + }, + { + "path": "law_versions/rules/LR-CIVIL-STATUTORY-INTEREST/civil-act-379-current.json", + "sha256": "89d87d5c2fd6fce98f9dd0eb1248ff3977a67d72ce8e8cb02567969da42ecbd5" + }, + { + "path": "law_versions/rules/LR-COMMERCIAL-LEASE-PANDEMIC/2020-09-29.json", + "sha256": "3af7daef66b399430f06797f3cc2d8c40abf54edcdea69348eaad45270bc571d" + }, + { + "path": "law_versions/rules/LR-COMMERCIAL-LEASE-PREMIUM/2015-05-13.json", + "sha256": "55aed9928928fb0a9d8f2351de7d82e8f2af59581067d9e8c5f8a3ffb607f266" + }, + { + "path": "law_versions/rules/LR-COMMERCIAL-LEASE-RENEWAL/2018-10-16.json", + "sha256": "0b2cf82d0bb1337e454f89e68055aac6051201f294f633b0ae06717adc289012" + }, + { + "path": "law_versions/rules/LR-COMMERCIAL-STATUTORY-INTEREST/commercial-act-54-current.json", + "sha256": "6922e051be8292c0f2330de4e8793137d9e43e2a25b47d83ed7eaa66f66fbd64" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CANCELLATION-ACT/CivilAct-146-juridical-act.json", + "sha256": "a69b16e6169468c0e6e1e2cb3510c6fb17a3c90928529f9239ee4b11deba714f" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CANCELLATION-RATIFICATION-POSSIBLE/CivilAct-146-ratification-possible.json", + "sha256": "c0deade3d1b4d18cd8d9737d915b8f7c8ca7ef176d2c5462651eb6983ffefbd0" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CONTRACTOR-DEFECT/CivilAct-670.json", + "sha256": "b6533f2950549c41c65f9809bb43ae4990f21acb39f121a0081d97298609558a" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CONTRACTOR-STRUCTURE-DESTRUCTION/CivilAct-671-destruction-damage.json", + "sha256": "479fe40fccfd01db22005adc50e3a7604520045a24e2b674e766dbdaaadf354f" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CONTRACTOR-STRUCTURE-DURABLE/CivilAct-671-durable.json", + "sha256": "577fbc6c2c380f0763ac24e50853121b0bdeca87b319a0f2d10a4ba9ca94e620" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-CONTRACTOR-STRUCTURE-ORDINARY/CivilAct-671-ordinary.json", + "sha256": "8f35fe02575257a12018fae5b444c7406a80f89c53686adb6e24e50d255e0fa2" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-FRAUDULENT-ACT-ACT/CivilAct-406-2-act.json", + "sha256": "5fd1a86d29fa2a3511a996419415f2a91ed8e07554eecda21137ceb4e3c56f5f" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-FRAUDULENT-ACT-KNOWLEDGE/CivilAct-406-2-knowledge.json", + "sha256": "68fc66a41cf4070d1c24d91fb349043fdef0c6a1ae53385458a741969a32b360" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-INHERITANCE-RECOVERY-KNOWLEDGE/CivilAct-999-knowledge-current-line.json", + "sha256": "c9a9a44e37a0aa364c70c82354d0bf954b2ac403c6b7a1311de3d28fce7dc22f" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-INHERITANCE-RECOVERY-LONG/CivilAct-999-infringement-act.json", + "sha256": "2d0b9e77ef535918b9c0695290734a36b2605cbc3204670253535df84c3ef698" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-INHERITANCE-RECOVERY-LONG/CivilAct-999-inheritance-opening-pre-2002.json", + "sha256": "1e613701767916a0819be51cae8c23bde2b6cae769896b33f57736f11f271cf0" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-RESERVED-PORTION-KNOWLEDGE/CivilAct-1117-knowledge.json", + "sha256": "e0b511c2eb128edbaaa3cb04b7a86b469923d9e61c0c66a03be3480d4601aece" + }, + { + "path": "law_versions/rules/LR-EXCLUSION-RESERVED-PORTION-OPENING/CivilAct-1117-opening.json", + "sha256": "19700b5472b44b6905254b86d42901f0c878bc3eb1df9a9406390d366c5c24df" + }, + { + "path": "law_versions/rules/LR-HOUSING-LEASE-INFORMATION/2023-04-18.json", + "sha256": "eb72f4d629938f3ea173efa42459f01a0bdd98b0167cb9c6fa5bcd52909ed6c4" + }, + { + "path": "law_versions/rules/LR-HOUSING-LEASE-NOTICE-WINDOW/2020-12-10.json", + "sha256": "92c222923e86a47c1aaa605e3faba43a9359c1b2ccd29e4abea34618ebeef529" + }, + { + "path": "law_versions/rules/LR-HOUSING-LEASE-RENEWAL/2020-07-31.json", + "sha256": "a5808931cfbd30fda9e74dd398eae5ebc209e2d44aa4681816e6e83bb55b527a" + }, + { + "path": "law_versions/rules/LR-INTEREST-LIMITATION-CAP/2007-06-30.json", + "sha256": "7e408e9d54ce9645d9bbef0c94ef4e9afd7bb2e80bede91527920562cdf07e38" + }, + { + "path": "law_versions/rules/LR-INTEREST-LIMITATION-CAP/2014-07-15.json", + "sha256": "97a0e6bc47565fbd22f1abd88813cdff330656644d567ecaf2c2bcb1a540c702" + }, + { + "path": "law_versions/rules/LR-INTEREST-LIMITATION-CAP/2018-02-08.json", + "sha256": "ef0121da5eaa0755cc89f19f8514b20405403ae8f79abcf1f80d588d728d038a" + }, + { + "path": "law_versions/rules/LR-INTEREST-LIMITATION-CAP/2021-07-07.json", + "sha256": "d812a1183145084176b12d7359522d557667ddfcf62557d1922b4cf27eed577f" + }, + { + "path": "law_versions/rules/LR-LABOR-DELAY-INTEREST/2025-10-23.json", + "sha256": "58e66fb2850c1b93d8ed1469f6a8f256660911a9a09c38d044a241a3485a47bf" + }, + { + "path": "law_versions/rules/LR-LABOR-DELAY-INTEREST/pre-2025-10-23.json", + "sha256": "d6c1d43cc3e37764025dc15f17b50cf7516e17e3fa2f9639e9efa6e08dd939de" + }, + { + "path": "law_versions/rules/LR-LIMITATION-COMMERCIAL-CLAIM/CommercialAct-64.json", + "sha256": "db0970f4ace14329de4da7ba1dd8f8554bbbcab0a2e2f5ab3b4829b4b3522994" + }, + { + "path": "law_versions/rules/LR-LIMITATION-GENERAL-CLAIM/CivilAct-162-1.json", + "sha256": "2db0f112943535b6b47c8ec97872a212b27f99fa6607663e8e45b329ccf4964f" + }, + { + "path": "law_versions/rules/LR-LIMITATION-LABOR-WAGE-CLAIM/LaborStandardsAct-49-current-codification.json", + "sha256": "3518b0a00aac0633508bfcf9b2bdc49c6c3b3d35b0857e800e5522f324e42cb5" + }, + { + "path": "law_versions/rules/LR-LIMITATION-PROPERTY-RIGHT/CivilAct-162-2.json", + "sha256": "0cc9f43c4bc75dd1dc390d4c86446ae16e5a6e779742238562a3cf1e353d645b" + }, + { + "path": "law_versions/rules/LR-LIMITATION-SHORT-ONE-YEAR/CivilAct-164.json", + "sha256": "418ed935dc515c3d27270b2883991c173c9a6d5a4ebcb5c46e5345b11090fdd4" + }, + { + "path": "law_versions/rules/LR-LIMITATION-SHORT-THREE-YEAR/CivilAct-163.json", + "sha256": "50ec20bb0bf38788750b9bba1353349583f67dd71595f42764701d88da893000" + }, + { + "path": "law_versions/rules/LR-LIMITATION-TORT-ACT/CivilAct-766-2.json", + "sha256": "bd4c050039a94f623987800427b8e8c82d41fd59142c2ce0e993d90d8f6b3aab" + }, + { + "path": "law_versions/rules/LR-LIMITATION-TORT-KNOWLEDGE/CivilAct-766-1.json", + "sha256": "f272737f2f703ac7d21801d8a3b25a29e098ebdb2b3f98dd3852b539c55c2190" + }, + { + "path": "law_versions/source_status/source_occurrence_inventory.json", + "sha256": "2d2a2647dd0964eebfd9beadec753821e6ec158af8ab43b0561ae0ed88a2cb43" + }, + { + "path": "law_versions/source_status/source_repin_status.json", + "sha256": "f44e21988306748bfdde5d629d1e955f592d669c2af280eefb88f01c9ae74228" + }, + { + "path": "platform/contracts/determinism_scope_contract.json", + "sha256": "8734102d9e2e9b695a3b12e91e7ab1b7208e1c1403729c082d708ee2c4a70532" + }, + { + "path": "platform/reference_catalogs/calculation_ids.json", + "sha256": "fb14965b8315e01d47d694a10a674eda5db606ab9c7bbb6345de98495ba233b8" + }, + { + "path": "platform/reference_catalogs/domain_ids.json", + "sha256": "4740d98e6a31bd0e7d9f792189712a8af1d0a87ec0bbd181deba1e34edb08355" + }, + { + "path": "platform/reference_catalogs/profile_ids.json", + "sha256": "84f3538229df73e2d7ca58eb32da3d9b38ab1037edb67d4ac43e31e51c20aea3" + }, + { + "path": "platform/router/s3_sg01_router_config.json", + "sha256": "4913b119f5ee08f96b52e10bd1f8376326564f1ab4742909fd2d0f07ded4efc6" + }, + { + "path": "platform/router/s3_sg01_router_input.schema.json", + "sha256": "9895accee6271e7fb4637ee303be858cea4af7b461015db2d7f1c47dc019c7e2" + }, + { + "path": "platform/router/s3_sg01_router_output.schema.json", + "sha256": "4af85d52a60254149a3506cd5aa36cce1360e275b3c195d08307876379114b51" + }, + { + "path": "platform/schemas/client_goal_domain_profiles.schema.json", + "sha256": "ae2bfe0d754a09cbae16b2c15bf1518fc23f9e1bda8fa1f5f949606c8e42c010" + }, + { + "path": "platform/schemas/domain_fanout_plan.schema.json", + "sha256": "3b0948613a5996028b9c030a99f0b51d682f6035e019557756b1a15d43971113" + }, + { + "path": "platform/schemas/domain_seed_output.schema.v3.json", + "sha256": "992acf05dbccb34c65ead4e8c592f424e3b91672dc109cbd1bfa76a0a71a13c9" + }, + { + "path": "platform/schemas/domain_slice.schema.v2.json", + "sha256": "212a405088e7cf7ba2c65528a1c716938c946df7fe3bae3256b613051ed31aa3" + }, + { + "path": "platform/schemas/fact_exception_pack.schema.json", + "sha256": "4eba7e51ed46a99e3704bc2333169749f4a16935de26a8c8027c1cac98ea58cf" + }, + { + "path": "platform/schemas/fact_ledger_base.schema.json", + "sha256": "b3f0e79ecb4c2f720f3e07e89154aadbd2327e4129cc703569fb5635240d2fe8" + }, + { + "path": "platform/schemas/fact_ledger_candidate_bundle.schema.json", + "sha256": "4e481504fb795b2be510680a8fa88124f5763a8124462f7870be4125ed9a7730" + }, + { + "path": "platform/schemas/legal_effect_structures.schema.json", + "sha256": "fc962e8ae39f9bede64ba017297eded6413689204a065e00c3b3bdca8f1854df" + }, + { + "path": "platform/schemas/structure_seed_bundle.schema.json", + "sha256": "b7af9e422b6ac3876cffea39ec4f617eea76a631a57dfdfcd57d3785a83c667a" + }, + { + "path": "routing/activation_cue_digest.md", + "sha256": "7e98885a50e1880b5ee7e2f459ab47010f90387e5c463a484a152054c2321e97" + }, + { + "path": "routing/evidence_component_union.md", + "sha256": "ecd6e1877f476139012b79fdc04380c067b8e81af86707bcc5c2b311b3fabf79" + }, + { + "path": "routing/extension_payload_key_declarations.v1.json", + "sha256": "1684e13896bc9dfd0e7aa1a3b01354f58b2fa6ed00908bec6f861bce4b47235c" + }, + { + "path": "signals/_common/evidence_slot_status.schema.json", + "sha256": "292b03960b187cef668b8635a8d7539fde7c31f0c20d01af52c4f6ff8519d7b1" + }, + { + "path": "signals/_common/signal_item.schema.json", + "sha256": "de8695f98041c06cf50c0d8d2ebc31e7b3c518ca9d39a27da940438704c58bb1" + }, + { + "path": "signals/adapters/s3_domain_seed_adapter.py", + "sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5" + }, + { + "path": "signals/adapters/s3_domain_seed_adapter.txt", + "sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5" + }, + { + "path": "signals/adapters/s3_envelope_migration_adapter.py", + "sha256": "c87262a3a04b6da08e035bfb25abdc66b497381f67f12ca4c82494dde36700d6" + }, + { + "path": "signals/adapters/s3_envelope_migration_adapter.txt", + "sha256": "c87262a3a04b6da08e035bfb25abdc66b497381f67f12ca4c82494dde36700d6" + }, + { + "path": "signals/adapters/s4_calculation_adapter.py", + "sha256": "5fbec03c551cababd019f4022544553ee91f29fb1ba39f2113fad46af6c9315b" + }, + { + "path": "signals/adapters/s4_calculation_adapter.txt", + "sha256": "5fbec03c551cababd019f4022544553ee91f29fb1ba39f2113fad46af6c9315b" + }, + { + "path": "signals/adapters/sg01_activation_adapter.py", + "sha256": "b194eda84a781dda5c95999349b73cfd34a92573d3abae9aac655408663dd5ca" + }, + { + "path": "signals/adapters/sg01_activation_adapter.txt", + "sha256": "b194eda84a781dda5c95999349b73cfd34a92573d3abae9aac655408663dd5ca" + }, + { + "path": "signals/compiler/common.py", + "sha256": "3f5f0d133aac8f2086cd9beda4dee62309c57322d5005ba263880d0048c62ab5" + }, + { + "path": "signals/compiler/common.txt", + "sha256": "3f5f0d133aac8f2086cd9beda4dee62309c57322d5005ba263880d0048c62ab5" + }, + { + "path": "signals/compiler/projections.py", + "sha256": "b65c12ce7cb57dc77cfc5bac9ccd7fa55093f14a9432d309b1603da96fa259a7" + }, + { + "path": "signals/compiler/projections.txt", + "sha256": "b65c12ce7cb57dc77cfc5bac9ccd7fa55093f14a9432d309b1603da96fa259a7" + }, + { + "path": "signals/compiler/schema_validator.py", + "sha256": "374bb3eeb2b58aa51f2816a7950c846f658cc704b15fb9bdd260cad48eb1515b" + }, + { + "path": "signals/compiler/schema_validator.txt", + "sha256": "374bb3eeb2b58aa51f2816a7950c846f658cc704b15fb9bdd260cad48eb1515b" + }, + { + "path": "signals/compiler/signal_compiler.py", + "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b" + }, + { + "path": "signals/compiler/signal_compiler.txt", + "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b" + }, + { + "path": "signals/compiler/signal_gate.py", + "sha256": "8b16197c8a6fbc2806a31de009f0b17cf0fa0a20d745b49fbe21b88ff768a37c" + }, + { + "path": "signals/compiler/signal_gate.txt", + "sha256": "8b16197c8a6fbc2806a31de009f0b17cf0fa0a20d745b49fbe21b88ff768a37c" + }, + { + "path": "signals/compiler/transaction_writer.py", + "sha256": "33a1f61d23f76a95204b1c2ff324d39dd04fd88f3a80e5e82764c21dab6c52ac" + }, + { + "path": "signals/compiler/transaction_writer.txt", + "sha256": "33a1f61d23f76a95204b1c2ff324d39dd04fd88f3a80e5e82764c21dab6c52ac" + }, + { + "path": "signals/compiler/writer_boundary.py", + "sha256": "901a4d4636adf56c74c3c912af7dfbddebc92f33a62376346dfa6d9fda39d51a" + }, + { + "path": "signals/compiler/writer_boundary.txt", + "sha256": "901a4d4636adf56c74c3c912af7dfbddebc92f33a62376346dfa6d9fda39d51a" + }, + { + "path": "signals/contracts/admission_runtime_contract.json", + "sha256": "471915fdced832c15aed158e60b35503dd638dd6e1ec4be98b6e68ad8d8f12fc" + }, + { + "path": "signals/emitters/emit_sg02.py", + "sha256": "d988c900453b8518cdd53c67b5acbd120ee76563db7b20f57d67eaff90514a86" + }, + { + "path": "signals/emitters/emit_sg02.txt", + "sha256": "d988c900453b8518cdd53c67b5acbd120ee76563db7b20f57d67eaff90514a86" + }, + { + "path": "signals/emitters/emit_sg03.py", + "sha256": "63b880aea4e0b13307948e692f50fa2d144ccd0862cedffc861bed5a812c5cdf" + }, + { + "path": "signals/emitters/emit_sg03.txt", + "sha256": "63b880aea4e0b13307948e692f50fa2d144ccd0862cedffc861bed5a812c5cdf" + }, + { + "path": "signals/emitters/emit_sg04.py", + "sha256": "ea8799469f61f4b5a241751c91c6d2ac967529febfba1a88b543e807ecf334ae" + }, + { + "path": "signals/emitters/emit_sg04.txt", + "sha256": "ea8799469f61f4b5a241751c91c6d2ac967529febfba1a88b543e807ecf334ae" + }, + { + "path": "signals/emitters/emit_sg05.py", + "sha256": "d653ad284b0d90e6bca4af8010fd0ad47a74b4f0c76acc529b8b57c195823d40" + }, + { + "path": "signals/emitters/emit_sg05.txt", + "sha256": "d653ad284b0d90e6bca4af8010fd0ad47a74b4f0c76acc529b8b57c195823d40" + }, + { + "path": "signals/emitters/emit_sg06.py", + "sha256": "f7b2fd78672e5d8b16ac8c1221617ebc63949fbbdda44c28546a07772775658b" + }, + { + "path": "signals/emitters/emit_sg06.txt", + "sha256": "f7b2fd78672e5d8b16ac8c1221617ebc63949fbbdda44c28546a07772775658b" + }, + { + "path": "signals/emitters/emit_sg07.py", + "sha256": "adca1822d8b2cbded2875dde2226b0e669229febb9e02e187b0362478d423cba" + }, + { + "path": "signals/emitters/emit_sg07.txt", + "sha256": "adca1822d8b2cbded2875dde2226b0e669229febb9e02e187b0362478d423cba" + }, + { + "path": "signals/emitters/emit_sg08.py", + "sha256": "04878c1881a5ee96ef493ad7bf0d46f49a2a18a2e0c00dbf293d71929c7c83d4" + }, + { + "path": "signals/emitters/emit_sg08.txt", + "sha256": "04878c1881a5ee96ef493ad7bf0d46f49a2a18a2e0c00dbf293d71929c7c83d4" + }, + { + "path": "signals/emitters/emit_sg09.py", + "sha256": "c832e0b4bef81549fda1f0c11535256e80caa8933734fbfb3cd2f3cea4397b21" + }, + { + "path": "signals/emitters/emit_sg09.txt", + "sha256": "c832e0b4bef81549fda1f0c11535256e80caa8933734fbfb3cd2f3cea4397b21" + }, + { + "path": "signals/emitters/emit_sg10.py", + "sha256": "309b608ce02c1bb1cfe5eadddfa8824fd7a711bfd3d9b34a99a5b30e203674d8" + }, + { + "path": "signals/emitters/emit_sg10.txt", + "sha256": "309b608ce02c1bb1cfe5eadddfa8824fd7a711bfd3d9b34a99a5b30e203674d8" + }, + { + "path": "signals/emitters/emit_sg11.py", + "sha256": "ba5611d76827b2fde9b35458b675a0e364057dce5dedd697218032b6039d15d0" + }, + { + "path": "signals/emitters/emit_sg11.txt", + "sha256": "ba5611d76827b2fde9b35458b675a0e364057dce5dedd697218032b6039d15d0" + }, + { + "path": "signals/emitters/emit_sg12.py", + "sha256": "1ca89e3c375f045e298e2b489f1cc08aefbd8f8d592beef37da99cd841065431" + }, + { + "path": "signals/emitters/emit_sg12.txt", + "sha256": "1ca89e3c375f045e298e2b489f1cc08aefbd8f8d592beef37da99cd841065431" + }, + { + "path": "signals/emitters/emit_sg13.py", + "sha256": "2392ab26906c42f741402a9b867a2d57ad7af04fbe85700a65aeb08331095b04" + }, + { + "path": "signals/emitters/emit_sg13.txt", + "sha256": "2392ab26906c42f741402a9b867a2d57ad7af04fbe85700a65aeb08331095b04" + }, + { + "path": "signals/emitters/emitter_runtime.py", + "sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7" + }, + { + "path": "signals/emitters/emitter_runtime.txt", + "sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7" + }, + { + "path": "signals/schemas/asset_right_state_signals.schema.json", + "sha256": "fc34fbb3d33a284c3d57f3c278cbda8b3555ef26ee2f06b803fd2410ebce38b6" + }, + { + "path": "signals/schemas/calculation_requirements.schema.json", + "sha256": "7fdb5ef0f50d7af22ac417abc4022cd238f5ab0dc942866420616729a9e3571f" + }, + { + "path": "signals/schemas/defense_exception_signals.schema.json", + "sha256": "010148c15e60e4d112b142f80b1723c06e34ba22b3edefae9e4371f2353b053e" + }, + { + "path": "signals/schemas/domain_activation_manifest.schema.json", + "sha256": "013a6ebd230ebe46dda665af9f6c4448b267444b44e7b8f701f2fae80a2ee92a" + }, + { + "path": "signals/schemas/domain_signal_envelope.schema.v2.json", + "sha256": "1483d6c5f98083f59172feff9b7c15b44d3ed789db5b6172d0de05f06e9d3fbc" + }, + { + "path": "signals/schemas/evidence_proof_conflict_signals.schema.json", + "sha256": "c419f568e28c06c629bc715aff7b0737b77e9c4871c91d4fae8f6ecf04196390" + }, + { + "path": "signals/schemas/governing_law_version_signals.schema.json", + "sha256": "13a3f62f03356090d2cb24de2da0ba217928dfe8eb3c111d0f5e87c7df3119ee" + }, + { + "path": "signals/schemas/legal_effect_routes.schema.json", + "sha256": "c24cb740c370aa2477199a0225be8291164ef5c787601fd962a370c642cc3cc0" + }, + { + "path": "signals/schemas/legal_relation_lifecycle_signals.schema.json", + "sha256": "420613a5900c4360487b89b978efedde58f5ddc61644130e4b9e63ef8ab33d8b" + }, + { + "path": "signals/schemas/liability_causation_damage_signals.schema.json", + "sha256": "34102cb8eeda80773eb62a5ee61e3d714bf90424ed5350dcac4b7bf873a72c5a" + }, + { + "path": "signals/schemas/party_capacity_standing_signals.schema.json", + "sha256": "66de89ac53964166f6caabd50cbc03eb82dede0acf702d5e6d825c1d82ef81d0" + }, + { + "path": "signals/schemas/procedural_posture_relief_signals.schema.json", + "sha256": "fefb4317ad63088919b61777c71fe75ee6aa507b9f599dcf455d2af63dfc5e0d" + }, + { + "path": "signals/schemas/remedy_enforcement_signals.schema.json", + "sha256": "999e1969b983748f209e9b5239f7edd0ec43bc642d9ea8fd7edbf34f9ce653f3" + }, + { + "path": "signals/schemas/signal_manifest.schema.json", + "sha256": "5e72084780b82b29582c9ffcf48f3e4894d7c0b152e5ce8df394583c07dde681" + }, + { + "path": "signals/schemas/timeline_notice_condition_signals.schema.json", + "sha256": "99c66208524155cea6bbd5e24fd26998cc9b653c89b24b569c793e36f1623d35" + }, + { + "path": "signals/signal_registry.v2.json", + "sha256": "4392b40da458102f8dd11b40b40ae3f694b7b5911849b050e2e4118c569e5ab0" + }, + { + "path": "stage1_runtime/_asset_bundle.txt", + "sha256": "8237a5d2e19a3eab4b25d09e11142b5fdf41ee99949b2482eac6c92e34d7bb8d" + }, + { + "path": "stage1_runtime/activation_gate.py", + "sha256": "62c54e4165e876e688bbbdbfb3b089fcbdb3ce0ee0973af6b82b9cd9ce5d1a5b" + }, + { + "path": "stage1_runtime/activation_gate.txt", + "sha256": "62c54e4165e876e688bbbdbfb3b089fcbdb3ce0ee0973af6b82b9cd9ce5d1a5b" + }, + { + "path": "stage1_runtime/bo_surface_projection_policy.v1.json", + "sha256": "d96e96d2178060e935c9309f0dfb59c5567d47ebbb9774d76335358724dab3c2" + }, + { + "path": "stage1_runtime/domain_fanout_planner.py", + "sha256": "0ff8ec40b81cc7afb257195562a13a7020b8e9e043f4f95620f159ff611265d9" + }, + { + "path": "stage1_runtime/domain_fanout_planner.txt", + "sha256": "0ff8ec40b81cc7afb257195562a13a7020b8e9e043f4f95620f159ff611265d9" + }, + { + "path": "stage1_runtime/domain_slice_compiler.py", + "sha256": "68451f7ded3e597ca4da592d68595b58ed06919f9f48ffe20249328ad5402610" + }, + { + "path": "stage1_runtime/domain_slice_compiler.txt", + "sha256": "68451f7ded3e597ca4da592d68595b58ed06919f9f48ffe20249328ad5402610" + }, + { + "path": "stage1_runtime/fact_ledger_compiler.py", + "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64" + }, + { + "path": "stage1_runtime/fact_ledger_compiler.txt", + "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64" + }, + { + "path": "stage1_runtime/fact_ledger_policy.v1.json", + "sha256": "08fad0b20e299063b502fd2a0ae1877b9a7074bdce5391110ea5d632c53787f9" + }, + { + "path": "stage1_runtime/prompt_compiler.py", + "sha256": "bfd80e90577d1f8be715cd581f8280f422dd8ba7cb526030cd9eaf7cb8151e30" + }, + { + "path": "stage1_runtime/prompt_compiler.txt", + "sha256": "bfd80e90577d1f8be715cd581f8280f422dd8ba7cb526030cd9eaf7cb8151e30" + }, + { + "path": "stage1_runtime/prompt_composition_policy.json", + "sha256": "8d3f003ecc5e53eb7112115126e325b77292a27b0a542a10c8cecfe6c6bbfdea" + }, + { + "path": "stage1_runtime/registry_loader.py", + "sha256": "b90e3a1ad6c26a1dca4d49635b8a97c8153d36147f2f1b1672429b2f7a0f02dc" + }, + { + "path": "stage1_runtime/registry_loader.txt", + "sha256": "b90e3a1ad6c26a1dca4d49635b8a97c8153d36147f2f1b1672429b2f7a0f02dc" + }, + { + "path": "stage1_runtime/registry_validator.py", + "sha256": "a8eff67f69433430efae9fa5292cba597e52dbb2e67d156ca18cb7055886538e" + }, + { + "path": "stage1_runtime/registry_validator.txt", + "sha256": "a8eff67f69433430efae9fa5292cba597e52dbb2e67d156ca18cb7055886538e" + }, + { + "path": "stage1_runtime/runtime_common.py", + "sha256": "5a76c488f15e54d7d143f2e18bbd3f104b3b32e5c13a84f0a98e276049bb9145" + }, + { + "path": "stage1_runtime/runtime_common.txt", + "sha256": "5a76c488f15e54d7d143f2e18bbd3f104b3b32e5c13a84f0a98e276049bb9145" + }, + { + "path": "stage1_runtime/schema_subset_validator.py", + "sha256": "18d470ff8dc775ce4b7da490e1f503913b821f7d95ad3d22ad0b8061d18aa377" + }, + { + "path": "stage1_runtime/schema_subset_validator.txt", + "sha256": "18d470ff8dc775ce4b7da490e1f503913b821f7d95ad3d22ad0b8061d18aa377" + }, + { + "path": "stage1_runtime/seed_admission_policy.v1.json", + "sha256": "b41c7a4b51a0859104d7a2a5edb3b9c3db41d3f1481338fb1a0526d746f77522" + }, + { + "path": "stage1_runtime/stage_a_context_builder.py", + "sha256": "1943493e09d674fc8b8168967087ef831c578607cfb1d6aa77e33771a0bc9f4c" + }, + { + "path": "stage1_runtime/stage_a_context_builder.txt", + "sha256": "1943493e09d674fc8b8168967087ef831c578607cfb1d6aa77e33771a0bc9f4c" + }, + { + "path": "stage1_runtime/structure_index_compiler.py", + "sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb" + }, + { + "path": "stage1_runtime/structure_index_compiler.txt", + "sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb" + }, + { + "path": "stage1_runtime/structure_index_policy.v1.json", + "sha256": "8eeedbcae6f3e4f648aa485b8620b23f4fdc16f43e0b678f224a403e915b1689" + }, + { + "path": "stage1_runtime/worker_output_validator.py", + "sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7" + }, + { + "path": "stage1_runtime/worker_output_validator.txt", + "sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7" + }, + { + "path": "tools/s3_router_v2.py", + "sha256": "bb3b163f8489e387befa1c4553ed125a12ea47b0f3a83013a5d2689daf32efd9" + }, + { + "path": "tools/s3_router_v2.txt", + "sha256": "bb3b163f8489e387befa1c4553ed125a12ea47b0f3a83013a5d2689daf32efd9" + }, + { + "path": "tools/s6_sg01_router.py", + "sha256": "7d958d73a1f04edc2ab3d89aa4c1b000d2bc8bb02b3fc22694b58a3021cd8be0" + }, + { + "path": "tools/s6_sg01_router.txt", + "sha256": "7d958d73a1f04edc2ab3d89aa4c1b000d2bc8bb02b3fc22694b58a3021cd8be0" + } + ], + "program_release_status": "STAGE1_NOT_RELEASE_READY", + "runtime_artifact_count": 465, + "schema_version": "stage1_runtime_manifest.v1" +} diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/signal_compiler_11_05_5_22pm.py.bak b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/signal_compiler_11_05_5_22pm.py.bak new file mode 100644 index 00000000..8f289b2d --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/signal_compiler_11_05_5_22pm.py.bak @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Canonical Stage 1 signal compiler with a single transactional writer.""" + +from __future__ import annotations + +import hashlib +import importlib +import json +from copy import deepcopy +from pathlib import Path +from typing import Any + +from adapters.sg01_activation_adapter import adapt_and_validate +from adapters.s3_domain_seed_adapter import adapt as adapt_s3_domain_seeds +from compiler.projections import project_actio, project_case_liability, project_legal_effect +from compiler.transaction_writer import WRITER_ID, write_transaction + + +_SIGNALS_ROOT = Path(__file__).resolve().parents[1] + + +def _load_contracts() -> tuple[dict[str, Any], dict[str, Any]]: + registry = json.loads((_SIGNALS_ROOT / "signal_registry.v2.json").read_text(encoding="utf-8")) + execution = json.loads((_SIGNALS_ROOT.parents[1] / "contracts" / "s5_execution_contract.v2.json").read_text(encoding="utf-8")) + return registry, execution + + +_REGISTRY, _EXECUTION = _load_contracts() +SIGNAL_FILES = {item["signal_id"]: item["file"] for item in _REGISTRY["entries"]} +COMPATIBILITY_FILES = { + "actio": "compatibility_views/actio_case_signals.json", + "liability": "compatibility_views/case_liability_signals.json", + "effect": "compatibility_views/legal_effect_signals.json", +} + + +def _json_bytes(value: Any) -> bytes: + return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8") + + +def _compatibility_json_bytes(value: Any) -> bytes: + """Preserve legacy insertion order so frozen compatibility bytes also replay.""" + return (json.dumps(value, ensure_ascii=False, sort_keys=False, indent=2) + "\n").encode("utf-8") + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _domain_envelopes(inputs: dict[str, Any], sg01: dict[str, Any]) -> dict[str, dict[str, Any]]: + manifest = sg01["domain_activation_manifest"] + # Every runnable domain has a worker, so its calculation_refs must reach Part 3 and Part 4. + runnable = sorted(set(manifest.get("expected_runnable_domain_ids", []))) + supplied = inputs.get("domain_signal_envelopes", {}) + legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {}) + out: dict[str, dict[str, Any]] = {} + registry_sha = str(manifest.get("registry_index_sha256") or "0" * 64) + extension_domains = {item["domain_id"]: item["extension_key"] for item in _EXECUTION["e13_extension_domains"]} + for domain_id in runnable: + provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None + if isinstance(provided, dict): + envelope = provided + else: + extensions: dict[str, Any] = {} + if domain_id in extension_domains and isinstance(legacy_actio, dict): + extensions[extension_domains[domain_id]] = { + "legacy_status": legacy_actio.get("status", "EMPTY"), + "records": deepcopy(legacy_actio.get("actio_case_signals", [])), + } + envelope = { + "domain_signal_envelope": { + "schema_version": "stage1_domain_signals.v2", + "domain_id": domain_id, + "domain_registry_version": manifest.get("registry_version", "UNKNOWN"), + "registry_index_sha256": registry_sha, + "status": "READY" if extensions else "NO_SUPPORT", + "element_fact_candidates": [], + "opposing_fact_candidates": [], + "defense_candidates": [], + "evidence_slot_status": [], + "calculation_refs": [], + "dependency_refs": [], + "review_items": [], + "extensions": extensions, + } + } + out[domain_id] = envelope + return out + + +def _file_state(payload: Any, *, signal_code: str | None = None) -> tuple[str, int, str]: + if signal_code == "SG-01": + inner = payload["domain_activation_manifest"] + return ("review" if inner.get("status") == "READY_WITH_REVIEW" else "ready", len(inner.get("domain_entries", [])), inner["schema_version"]) + if signal_code: + status = payload.get("status", "EMPTY") + state = "blocked" if status == "BLOCKED" else ("review" if status == "READY_WITH_REVIEW" else ("empty" if status == "EMPTY" else "ready")) + return state, len(payload.get("records", [])), payload["schema_version"] + if "domain_signal_envelope" in payload: + inner = payload["domain_signal_envelope"] + state = "review" if inner.get("status") == "READY_WITH_REVIEW" else ("empty" if inner.get("status") == "NO_SUPPORT" else "ready") + count = sum(len(inner.get(key, [])) for key in ("element_fact_candidates", "opposing_fact_candidates", "defense_candidates")) + return state, count, inner["schema_version"] + list_keys = [key for key, value in payload.items() if isinstance(value, list)] + count = len(payload[list_keys[0]]) if list_keys else 0 + status = payload.get("status", "EMPTY") + state = "review" if status == "READY_WITH_REVIEW" else ("empty" if status == "EMPTY" else "ready") + return state, count, payload["schema_version"] + + +def compile_transaction(inputs: dict[str, Any], output_dir: Path) -> dict[str, Any]: + inputs = adapt_s3_domain_seeds(inputs) + sg01 = adapt_and_validate(inputs) + canonical: dict[str, Any] = {"SG-01": sg01} + for number in range(2, 14): + code = f"SG-{number:02d}" + module = importlib.import_module(f"emitters.emit_sg{number:02d}") + canonical[code] = module.emit(inputs) + domains = _domain_envelopes(inputs, sg01) + views = { + "actio": project_actio(domains), + "liability": project_case_liability(canonical["SG-05"], canonical["SG-08"]), + "effect": project_legal_effect(canonical["SG-13"]), + } + objects: dict[str, Any] = {SIGNAL_FILES[code]: value for code, value in canonical.items()} + objects.update({f"domain_signals/{domain_id}.json": value for domain_id, value in domains.items()}) + objects.update({COMPATIBILITY_FILES[key]: value for key, value in views.items()}) + compatibility_paths = set(COMPATIBILITY_FILES.values()) + encoded = { + path: (_compatibility_json_bytes(value) if path in compatibility_paths else _json_bytes(value)) + for path, value in objects.items() + } + files = [] + for path in sorted(encoded): + signal_code = next((code for code, filename in SIGNAL_FILES.items() if filename == path), None) + state, count, schema_version = _file_state(objects[path], signal_code=signal_code) + kind = "canonical" if signal_code else ("domain_signal" if path.startswith("domain_signals/") else "compatibility_view") + files.append({ + "path": path, + "schema_version": schema_version, + "record_count": count, + "file_sha256": _sha(encoded[path]), + "hash_kind": "raw_file_sha256", + "writer": WRITER_ID, + "kind": kind, + "state": state, + "lifecycle": "active", + }) + sg01_manifest = sg01["domain_activation_manifest"] + states = {entry["state"] for entry in files} + overall = "BLOCKED" if "blocked" in states else ("READY_WITH_REVIEW" if "review" in states else "READY") + source_universe = inputs.get("source_universe", {}) + manifest = { + "schema_version": "signal_manifest.v2", + "transaction_id": "S5TX-" + _sha(_json_bytes(files))[:20], + "status": overall, + "files": files, + "domain_signal_files": sorted(path for path in objects if path.startswith("domain_signals/")), + "compatibility_views": sorted(COMPATIBILITY_FILES.values()), + "active_domains": sorted(sg01_manifest.get("active_domain_ids", [])), + "active_calculations": sorted(sg01_manifest.get("required_calculation_domains", [])), + "unrouted_counts": { + "issues": len(sg01_manifest.get("unrouted_material", [])), + "evidence": int(source_universe.get("unrouted_evidence_count", 0)), + "operands": sum(1 for item in canonical["SG-11"].get("records", []) if item.get("status") in {"missing_required", "review"}), + }, + "downstream_read_sets": { + "part3_L0": ["SG-02", "SG-05", "SG-07", "SG-11", "SG-13"], + "part4_F0": ["SG-04", "SG-06", "SG-07", "SG-10", "SG-11"], + "stage2": ["ALL"], + }, + "writer": WRITER_ID, + "transaction_guards": { + "canonical_writer_count": 1, + "compatibility_views_are_projections": True, + "source_membership_required": True, + "meeting_only_evidence_promotion_forbidden": True, + "negative_conflict_preservation_required": True, + }, + } + encoded["signal_manifest.json"] = _json_bytes(manifest) + write_transaction(output_dir, encoded) + return manifest diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8.yml index 0a62d8af..2553d9f5 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8.yml +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8.yml @@ -126,6 +126,9 @@ # worker H-3 : 사건 후보에서 나온 후보는 EVT id 를 source_refs 에 함께 적는다(prewarm·worker 두 블록 동일). # R0 H-4 근접 중복 키 = 사건 id 있으면 (event, 사건 id, BOType, ActionType), 없으면 (document, 증거 index, …). # H-5 field_conflict 주석의 "단일 값" 전제 정정. 온라인 미실행. +# 2026-11-05 Part 4 일치성 해결법 (작업간일치성보고서_해결법_part_4_on_part_1_to_3.md) +# P4-06 투영 메모·F0 정규화 노트 handoff 항목의 source_review_code 를 null 로, 칸 이름은 source_field 로 옮겼다(Part 4 잡음 55건). +# 자산 signal_compiler part4_F0 = SG-04·SG-07·SG-11(P4-04)·fact_ledger_compiler·fact_ledger_policy 개정 → runtime_manifest a828e962… → 9d2df172…. 온라인 미실행. # # 삭제 — Task_C_BO_Stage_B_B1~B5 다섯 (v3 1502~2826행, 1,325행) # §6.7 규율대로 즉시 삭제하지 않는다. 템플릿으로 승계 5도메인을 돌려 같은 BO 가 나오는 @@ -371,7 +374,7 @@ Agent: RUNTIME_MANIFEST_SCHEMA = "stage1_runtime_manifest.v1" # 옛 묶음이 서버에 그대로면 아래 파일 대조는 통과한다. 이 YAML 이 기대하는 묶음을 고정한다. # 배포 자산을 바꿀 때마다 함께 갱신한다. - EXPECTED_RUNTIME_MANIFEST_SHA256 = "a828e962d1f6dbb8607cab16479c55b2ced96ad55305c6f25873ce25194b8084" + EXPECTED_RUNTIME_MANIFEST_SHA256 = "9d2df172844b960b96a92f2226d5ebf5c1138a6044f741c8e97944e11ec40989" # registry_validator 는 overlay 오류를 모으기만 한다. 네 코드는 배포 문제이므로 경성으로 올린다. OVERLAY_ERROR_CODES = ("PROMPT_OVERLAY_HASH_MISMATCH", "PROMPT_OVERLAY_NOT_FOUND", "PROMPT_OVERLAY_PATH_INVALID", "PROMPT_OVERLAY_REFERENCE_DIVERGENCE") @@ -3593,7 +3596,9 @@ Agent: "source_domain": domain_id, "severity": "SOFT_WARNING", "issue_type": note_item["issue_type"], - "source_review_code": note_item.get("field"), + # 투영 메모에는 원본 review_code 가 없다. 칸 이름은 source_field 로 둔다(P4-06). + "source_review_code": None, + "source_field": note_item.get("field"), "source_event_candidate_ids": [], "source_evidence_indexes": [], "source_meeting_clause_ids": [], @@ -5032,7 +5037,8 @@ Agent: "source_domain": str(note.get("candidate_ref") or "").split(":")[0] or None, "severity": "SOFT_WARNING", "issue_type": "schema_field_fallback", - "source_review_code": note.get("field"), + "source_review_code": None, + "source_field": note.get("field"), # P4-06 — 칸 이름은 코드가 아니다 "source_event_candidate_ids": [], "source_evidence_indexes": [], "source_meeting_clause_ids": [], diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8_11_05_5_22pm.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8_11_05_5_22pm.yml new file mode 100644 index 00000000..0a62d8af --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_2_v.8_11_05_5_22pm.yml @@ -0,0 +1,5769 @@ +# ============================================================================= +# Liti-agent Stage 1 Part 2 v.8 — BO 컴파일 (동적 도메인 fan-out) · 통합 실행본 +# +# 정본 근거 +# 전체 DAG : stage_1_update_strategy.md §1 Part 2 블록 · §3 세부 워크플로우 +# 개정 전략 : stage_1_part_2_optimal_update_strategy_v.2.md +# 선결작업 : part_2_우선작업_report.md · part_2_우선작업_2_report.md +# 패치 : part_2_prerequisite/patches/C1_C2_registry_component_ids.patch.md +# +# 구성 — task 9종 (2026-11-03: prewarm · load_fanout · capture 추가) +# [개정] Task_C_BO_A0_context_and_domain_slice_compiler 상수 3덩어리 -> 모듈 5개 호출 +# (v.8 handoff guard, 2026-10-10, 실패분석 §4 F-2) Part 1 handoff 가 BLOCKED 면 PART1_HANDOFF_BLOCKED 로 즉시 중단 +# [신설] Task_C_B_domain_worker_* 정적 worker 5개 대체 템플릿 +# [개정] Task_C_BO_R0_seed_reducer_and_exception_planner fan-out 기대집합 + validator + C-2 +# [개정] Task_C_BO_R1_exception_adjudicator 가액금액 금액 상충 규칙 · drop_candidate_refs 명시 +# [개정] Task_C_BO_F0_final_bo_compiler_gate_writer BOType 어휘 registry 합집합 +# [개정] Task_C_BO_S0_signal_bundle_writer 인라인 모듈 -> 조립본 모듈 반입 +# +# 2026-10-30 가액금액 정본 결속 (가액금액_반영후_part_2_개정계획서.md) +# 금액의 출처를 하나로 모은다. worker 는 숫자를 쓰지 않고 value_id 만 고르며, 숫자는 코드가 정본에서 채운다. +# A0 정본 결속 판정(BOUND·ABSENT·MISMATCH) · 회차 카탈로그 stage1_tmp/task_c_bo/value_facts_catalog.json · +# rank-50 실행 가드(금액 기재 규칙) · source_universe_manifest.value_fact_ids +# worker 카탈로그를 정적 preflight 로 읽고 amount_facts[].source_refs 에 value_id 하나만 적는다 +# R0 수용 검증 전 value_id 정규화 · 정본 숫자 채움 · BO amount 단계표 선택 · value_refs · 중복 키에 value_refs +# R1 프롬프트 한 줄(정본 사본은 기재 완전성으로 고르지 않는다) +# F0 amount.value_id · value_refs · value_ref_check(불일치는 그 BO 의 amount 만 null, 실패로 세지 않음) +# S0 source_universe.fact_ids · all_source_refs 에 value_fact_ids(매니페스트에서 읽는다) +# 자산 bo_surface_projection_policy.v1.json 에 amount_selection 추가(추가형, 도메인별 덮어쓰기) · +# runtime_manifest sha 갱신 후 배포. overlay 의 폐기 키 domain_review_queue 정리는 이번 범위 밖이다 +# (common_worker_contract 가 이미 금지하고, 고치려면 registry overlay 해시를 함께 바꿔야 한다). +# 전제 Part 1(V0~V3 포함)이 OUT 에 도달한 뒤에 시작한다. V 가 도는 중에 시작하면 ABSENT 로 진행한다. +# 남는 비정본 금액 경로: Action 자유문. Part 4 행 amount 는 BO 값 + 표시이고 F1 판정은 금액을 바꾸지 않는다 +# +# 2026-10-30 Part 3 정합 (가액금액반영후_part_3_개정전략서_v.2.md) +# 정합은 삭제나 중단이 아니라 표시로 맞춘다. 보존의 기준은 S2_10 입력이다. +# worker 효과 유형 규칙은 common_worker_contract.md 에 둔다(overlay 보다 우선). 미등록 효과는 registered:false 로 남긴다. +# R0 Action 마지막 대체값 :effect_unspecified · 처분이 review 인 검증기 경고를 handoff 로 올린다 +# R1 DROP 은 drop_candidate_refs 를 명시한다 +# F0 안전하지 않은 DROP 은 버리지 않고 review · candidate_ref_to_bo_id 병합 사슬 해소 · 흡수된 seed 의 Legal_Keywords 합집합 +# S0 seed 에 candidate_ref · bo_absent 를 메모리에서 표시한다(효과 후보를 비우지 않는다) +# 자산 s3_domain_seed_adapter(계산 요청 id·도메인 · route 표시 · 봉투 행의 범위 밖 ref 제거) · +# emitter_runtime(worker 유래 blocked 는 review) · signal_compiler(실행 도메인 전체 봉투, 보조 도메인도 signal gate 를 받는다) · +# worker_output_validator(R-4 유형 대조) · 정책·공통 계약 갱신 +# +# 2026-10-31 추가 개정 (추가개정전략서_stage_1_part2_3_자산포함_v2.md) +# 법령 명단은 잇지 않는다. Stage 1 은 판본을 추적하지 않고 Stage 2 가 확정한다. +# A0 rank-50 가드에 법령 인용 규칙 · 기대 runtime_manifest sha 대조(PART2_RUNTIME_MANIFEST_STALE) +# R0 수용본을 admitted_seeds/.json 에 쓴다 · _sink_for 자기 참조 수정 · 사전 검증기 호출 가드 · +# 미등재 슬롯 status 보존 · slot_id 소문자 정규화 · root status 동의어 선적용 +# S0 수용본을 읽되 행 배열 6종과 뿌리 review 는 worker 원본을 쓴다 · 원본 해시 대조(S0_ADMITTED_SEED_DRIFT) +# 자산 s3_domain_seed_adapter(SG-01 값 사용 · 입력 null 방어 · 계산 행 게이트 키 제거 · extensions.unverified_refs) · +# seed_admission_policy(enum_unmapped_fallback · 슬롯 status 파생) · runtime_manifest sha 갱신 +# +# 2026-10-31 Part 3 정합 추가 개정 (개정전략서_part2_추가개정_for_part3.md) +# R0 행 제거는 값 처분 뒤 내림차순으로 행마다 한 번만 한다 · 격리한 후보의 오류는 다시 처분하지 않는다 · +# 같은 값을 다시 쓰는 파생은 복구로 치지 않는다 +# F0 도메인을 건너 병합된 BO 에 provenance.source_keywords · absorbed_sources 를 남긴다 +# S0 수용 전 worker 가 쓴 후보 수준 bo_absent 를 지운다 +# 자산 s3_domain_seed_adapter(스키마 밖 키는 worker_extra 문자열로 접는다) · structure_index_compiler(유형을 낸 도메인에 BO 부착) · +# fact_ledger_compiler(계산 ref distinct) · structure_index_policy · runtime_manifest sha 갱신 +# +# 2026-11-03 worker 캐시 최적화 (캐시최적화_part_2_앙상블_Fable.md §3, GPT-6.1 Sol) +# worker 는 llm_endpoint: responses 가 필수다. 없으면 chat.completions 로 가고 SDK 3.40.0 Completions.create 에 +# text 인자가 없어 llm_verbosity 가 TypeError 를 낸다(호출 전 실패). Sol 도구 호출도 Responses 전용. +# worker 도구 없는 1회 호출(expose_tools false · max_iterations 1 · llm_result_envelope true). 첫 user 메시지에는 +# {{item.*}} 가 없고(호출 불변 = OpenAI prefix breakpoint 구간), 둘째 user 메시지 가 +# 인스턴스 값 4개를 준다. cache_control {explicit, 30m, [prefix]}. ttl 15m 은 백엔드가 30m 으로 바꿔 보내므로 실제 값을 쓴다. +# 태그는 OpenAI 경로에서 경계를 만들지 않는다(bridge 는 메시지 인덱스에 찍는다). +# prewarm Task_C_B_domain_prewarm — worker 첫 user 프롬프트·정적 preflight 3종과 바이트 동일, prewarm: true, 무출력. +# load_fanout Task_C_B_domain_load_fanout — A0 성공·계획 sha 를 대조한 뒤 dynamic_fanout 을 낸다. 실패해도 raise 하지 않고 +# 빈 fan-out + stage1_tmp/task_c_bo/fanout_blocked.json 을 남긴다(fan-out 부모가 raise 하면 all X_* 가 영원히 기다린다). +# capture Task_C_B_domain_capture_* — 응답 봉투의 JSON 을 expected_output_path 에 그대로 쓴다. 값을 고치지 않는다 +# (R0 의 SEED_ECHO_* 판정은 worker 가 어느 자료로 작업했는지를 echo 값으로 가린다). 실패는 비JSON 표식. +# A0 공유 정적 파일 2종을 더 낸다 — runtime/shared/source_universe.json(전 도메인 공통 evidence·event 레코드), +# runtime/shared/vocabulary.md(어휘 사전, 조립 프롬프트에서는 뺀다). 도메인별 runtime/worker_inputs/.json 은 +# slice 에서 공통 우주를 뺀 나머지다. slice 파일과 그 sha 는 불변. 분할본을 합치면 원 slice 와 같은지 fail-closed 로 검사하고, +# preflight 한도(파일 260,000자 · 합계 500,000자)를 대조한다. 조립 프롬프트 sha 는 새 본문으로 재계산한다. +# R0 fanout_blocked.json 이 CLEARED 가 아니면 PART2_FANOUT_BLOCKED_UPSTREAM 으로 멈춘다(_init 직후). seed 가 비JSON 표식이면 +# PART2_SEED_CAPTURE_FAILED. R0 는 all capture_* 를 기다린다. 정적 preflight 4종 = evidence_component_union.md(도구 없는 호출이라 +# 직접 실어야 한다) · 공유 우주 · 어휘 · 카탈로그. +# 프롬프트 본문은 재배치됐다(내용 그대로 조건 해제). 하류 3종(validator·R0·S0)은 slice 의 payload·excerpt 를 읽지 않는다. +# 온라인 미실행. 첫 실주행 판정: prewarm 행 cache_write≈P·cached≈0, worker 행 cached≈P·write≈0·도메인당 1행, 로그 prefix boundary 2/N. +# +# 2026-11-01 Part 4 금액 표시 정합 (개정전략서_part_4_v.3.md M1) +# BO amount 선택 규칙은 그대로 두고, 값이 갈린 금액과 per 금액, 금액을 정하지 못한 BO 의 관련 값을 provenance 에 실어 Part 4 로 넘긴다. +# R0 select_amount 둘째 반환값을 같은 단계 value_id 목록으로 바꾼다 · 한 금액 항목의 다중 id 를 후보와 value_refs 에 남긴다 +# F0 흡수 후보 금액 승계(값이 하나일 때만) · provenance.amount_alternatives · provenance.amount_related_values(amount null 이고 값 갈림 없는 BO 는 +# value_refs 전부, 그 밖의 BO 는 per 금액만) · R1 MERGE 를 뿌리끼리 이어 순환 소실을 막고 원장에 없는 target 은 R1_MERGE_REJECTED 로 남긴다 +# 두 표시 키는 Part 4 가 행 amount 로 옮겨 S2_10 에 닿는다(stage_1_part_4_v.8.yml M2). +# 금액 승계는 현행 Part 4 행 amount 를 바꾸고, 다중 id 의 value_refs 는 중복 판정을 바꿔 BO·행 수를 늘리거나 줄일 수 있다 +# R1 MERGE 수정은 사라지던 후보를 BO 로 남겨 BO·행 수를 늘리고 뒤 bh 번호를 민다 +# +# 2026-11-04 일치성 기반 개정 (개정전략서_일치성기반_part_2.md) +# C-07 prewarm·worker SOURCE_MEMBERSHIP_RULES 에 상담 조항 id 인용 금지 불릿(두 블록 바이트 동일). +# 조항 내용은 review_items[].reason 에 적는다(전략서의 "해당 원소의 reason"은 seed 스키마상 review_items 에만 있다). +# C-05 A0 verify_content_seal — evidence_indexed·evidence_event_candidates 원문을 digest_guard 와 대조, 이후 digest·컴파일은 같은 원문. +# C-01 domain_slice_compiler._adapt_entry — D0 의 primary_positive_refs·screening_confidence 를 읽는다(meeting_positive_refs 제외). +# positive_refs 가 채워져 selected_sources 가 생기고 review_only_refs 가 준다. worker 입력이 커진다(11-04 실측 X2 3,925 → 50,505자, +# 도메인별 합계 추정 약 45.8만 자로 한도 50만 자 안, 90% 경고선 위). 첫 실행에서 preflight_report.per_domain_total 과 +# E-04·E-11·E-13·X2 overlay 동작(C-17)을 확인한다. +# C-03 stage_a_context_builder 사건 record 에 obligation_direction·support_locators[{directness}]만 싣는다(비었으면 키 생략). +# 전략서의 다섯 키 그대로 싣기는 11-04 실측 공유 출처 우주 284,973자로 한도 260,000자를 넘어 줄였다(254,818자). +# legal_keywords·location·source_fact_candidate 는 의도적으로 뺐다. 되살리지 않는다. +# worker prewarm·worker (두 블록 바이트 동일)에 참조 형식 명시(결과보고서_1_part_2.md §5-2). +# dependency_refs 는 도메인 id 문자열, party_refs·object_refs 는 영문 식별자만. 11-04 실행의 R0 보정 532건 대응. +# 당사자·목적물 전용 영문 id 가 입력에 없어 두 배열은 대개 비고(빈 배열에 review 를 만들지 않음) BO Object 는 계속 null 이다 +# (채우려면 id 체계가 따로 필요). 온라인 미실행. +# 자산 runtime_manifest sha ca806ca9… → a828e962… (두 모듈 .py·.txt). 서버 사본 교체 후 실행한다. 온라인 미실행. +# 2026-11-04 오후 F0·S0 실패 대응 (Testrun/Nov_04/실패결과보고서_1_part_2.md §3). prewarm·worker reasoning medium 판(_medium.yml 기반). +# F0 F-1 blocked 항목은, 같은 exception 에 canonical·field 판정이 하나 이상 있고 어떤 판정(link·semantic 포함)에도 +# BLOCK_REVIEW 가 없을 때만 HARD_WARNING review(F0:r1_blocked:*)로 낮춘다. 그 밖에는 지금처럼 멈춘다. +# Part 2 handoff 는 blocks_final_drafting 키를 쓰지 않아 넣지 않았다. +# R1 F-2 blocked_review_items 에는 BLOCK_REVIEW 로 판정한 exception 만 넣는다. +# S0 S-1 all_source_refs 에 routing/domain_screening.json source_document_refs(MTG.*) 추가 — SG-01 conflict_refs 대조용. +# 부작용: seed 행의 MTG.* ref 가 extensions.unverified_refs 로 빠지지 않고 signal 에 남는다(C-07 로 worker 인용은 0건). +# S-2 build_inputs 첫머리에서 review handoff 가 FINALIZED 이고 bo_item_count == len(BO.json) 인지 확인한다. +# 남은 틈: R0 가 handoff 를 쓰기 전에 실패하면 지난 회차 FINALIZED 가 남는다. SG-01 positive 검사는 D0 가 +# primary_positive_refs 를 써서 여전히 빈 검사다(모듈 범위). +# 온라인 미실행. +# 2026-11-04 4pm 개정 (개정전략서_part_2_11_04_4pm.md H-1~H-5). 위 F-1 은 폐기·대체했다. +# F0 H-1 R1 의 BLOCK_REVIEW(blocked 목록 — id 문자열·객체 — 또는 판정 값)로 멈추지 않는다. 그 exception 의 canonical +# 판정(MERGE·DROP 포함)과 field 값 선택은 적용하지 않아 후보를 따로 보존하고 F0:human_review: +# (HARD_WARNING, issue_type human_judgment_required, code R1_BLOCK_REVIEW)로 넘긴다. link BLOCK 은 prior 판정에서 NO_LINK 와 같다. +# stdout·compact 에 human_review_count. +# R1 H-2 서로 다른 행위는 KEEP_SEPARATE, BLOCK_REVIEW 는 같은 행위의 값 상충만. 기준 첫 항의 "단일 값 선택" 전제도 정정. +# worker H-3 : 사건 후보에서 나온 후보는 EVT id 를 source_refs 에 함께 적는다(prewarm·worker 두 블록 동일). +# R0 H-4 근접 중복 키 = 사건 id 있으면 (event, 사건 id, BOType, ActionType), 없으면 (document, 증거 index, …). +# H-5 field_conflict 주석의 "단일 값" 전제 정정. 온라인 미실행. +# +# 삭제 — Task_C_BO_Stage_B_B1~B5 다섯 (v3 1502~2826행, 1,325행) +# §6.7 규율대로 즉시 삭제하지 않는다. 템플릿으로 승계 5도메인을 돌려 같은 BO 가 나오는 +# 것을 확인한 뒤(Q-4) 삭제한다(Q-5). 이 파일은 그 확인이 끝난 상태를 전제한다. +# +# 확정 계약 (stage_1_update_strategy.md §0.3) +# slice runtime/domain_slices/.json task_c_bo_stage_b_domain_slice.v2 +# worker 산출 runtime/domain_seed_outputs/.json task_c_bo_stage_b_domain_bo_seed.v3 +# fan-out fanout/domain_fanout_plan.json domain_fanout_plan.v1 +# worker 이름 Task_C_B_domain_worker_* · 인스턴스 DOMAIN-<도메인ID> +# 실행 인자 --asset-root · --execution-root · --logical-root +# 구 slice/seed 경로(stage1_tmp/task_c_bo/domain_slices|domain_seed_outputs)는 쓰지 않는다 +# (legacy_paths_forbidden). stage_a_context·source_universe_manifest(P-1 복귀)와 +# postb_* 3종은 stage1_tmp/task_c_bo/ 를 정본 경로로 유지한다. R0 수용본도 그 아래 admitted_seeds/ 에 둔다. +# +# 모듈 반입 — Part 1 D0 규약 R-1~R-5 승계 +# .txt 미러를 read_raw 로 읽고 runtime_manifest.json 의 sha256 과 대조한 뒤 +# /tmp/s1/_rt 에 .py 로 기록하고 sys.path 에 넣는다. 미러는 정본 .py 옆에 있다. +# +# 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. +# 들여쓰기는 Part 2 v3 관례(Stages 2 · tasks 4 · task_name 4)를 유지한다. +# ============================================================================= +--- +Agent: + name: Liti-agent_Civil_Suit_Plaintiff_Stage_1_Part_2 + description: 민사소송 원고 송무 초지능 AI변호사 - Stage 1 Part 2 + version: v.2 + Stages: + - name: stage1_BO_시그널_생성 + description: BO 생성, 시그널 생성 + llm_provider: openai + llm_model: gpt-4o-2024-08-06 + tools: + mcpServers: + localdocs: + type: streamable-http + url: http://mcp-localdocs:8012/mcp + description: Get the content of local documents + code-executor: + type: streamable-http + url: https://code-executor.mcp.eroomai.com/mcp + description: Run scripts of programming languages + headers: + Authorization: Bearer rR8OXqWrVZA1gFEo8oWfBkw2XgpWoGrrspw5ObsxTCM= + tasks: + - task_name: Task_C_BO_A0_context_and_domain_slice_compiler + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 300 + code: | + #!/usr/bin/env python3 + # Task_C_BO_A0_context_and_domain_slice_compiler (v4) + # 1) 자산 반입 -> 2) 봉인 검증 -> 3) registry 로드·검증 -> + # 4) 프롬프트 조립 -> 5) slice 컴파일 -> 6) fan-out 계획 -> 7) 기록 + # 도메인 상수를 두지 않는다. 라우팅 판정은 모듈 안에서만 일어난다. + import contextlib + import datetime + import hashlib + import io + import itertools + import json + import os + import posixpath + import pathlib + import sys + import unicodedata + + import httpx + + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # 빠지면 localdocs 가 루트 경로를 보므로 사용자 파일을 찾지 못한다. + # Task_A0_domain_screener_02.yml 의 검증 완료본을 그대로 복사했다. + # ------------------------------------------------------------------ + TASK_NAME = "Task_C_BO_A0_context_and_domain_slice_compiler" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 파일 내용을 재직렬화 없이 원문 그대로 돌려준다. + # registry_index_sha256 과 screening_sha256 은 원문 바이트의 해시여야 + # 하므로 재직렬화를 절대 허용하지 않는다. + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + if s.startswith("```"): + for part in s.split("```"): + part = part.strip() + if part.startswith("json"): + part = part[4:].strip() + if part.startswith("{") or part.startswith("["): + s = part + break + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + # ------------------------------------------------------------------ + # 실행 뿌리 세 개 — D-5 §2.4 0-c-2 확정값. 모듈에는 argv 로만 넘긴다. + # ------------------------------------------------------------------ + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + LOGICAL_ROOT = "/tmp/s1" + + WORK = pathlib.Path(EXECUTION_ROOT) + RT = WORK / "_rt" + + # 미러는 정본 .py 옆에 놓인다. 이름이 아니라 논리 경로로 지목한다. + MODULE_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "registry_loader": "Default_Agent/stage1_runtime/registry_loader.txt", + "registry_validator": "Default_Agent/stage1_runtime/registry_validator.txt", + "prompt_compiler": "Default_Agent/stage1_runtime/prompt_compiler.txt", + "domain_slice_compiler": "Default_Agent/stage1_runtime/domain_slice_compiler.txt", + "domain_fanout_planner": "Default_Agent/stage1_runtime/domain_fanout_planner.txt", + "stage_a_context_builder": "Default_Agent/stage1_runtime/stage_a_context_builder.txt", + } + MODULES = ["runtime_common", "schema_subset_validator", "registry_loader", + "registry_validator", "prompt_compiler", "domain_slice_compiler", + "domain_fanout_planner", "stage_a_context_builder"] + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + + # 사건 산출물. Part 1 이 낸 것만 읽는다. + HANDOFF = "quality_gates/stage1_part1_soft_gate_handoff.json" + ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" + SCREENING = "routing/domain_screening.json" + EVIDENCE = "evidence_indexed.json" + EVENTS = "evidence_event_candidates.json" + # meeting_clause_ids 는 evidence·event 문서에 없다. 실측으로 확인했다 + # (구 매니페스트 41개 중 두 문서에서 발견되는 것 0개). 원문을 읽어야 나온다. + MEETING = "client_meeting.md" + # R-3 — Part 1 screener 03 이 낸 어휘 사전. 여덟 갈래 중 여섯을 E|O|V|D|R| 줄로 담는다. + # 네 번째 digest 생성기를 만들지 않는다 — 이미 있는 것을 프롬프트 조각으로 붙인다. + VOCABULARY = "routing/candidate_profile_vocabulary.md" + + # 정적 자산. + REGISTRY_INDEX = "Default_Agent/domains/_registry_index.json" + COMMON_CONTRACT = "Default_Agent/domains/_common/common_worker_contract.md" + POLICY = "Default_Agent/stage1_runtime/prompt_composition_policy.json" + SLICE_SCHEMA = "Default_Agent/platform/schemas/domain_slice.schema.v2.json" + FANOUT_SCHEMA = "Default_Agent/platform/schemas/domain_fanout_plan.schema.json" + SPECIAL_LAW_INDEX = "Default_Agent/special_law_profiles/_registry_index.json" + + # F-2 — Part 2 가 조립본에서 읽는 정적 자산 중 경로가 고정된 것. 이 목록이 곧 배포 요구 선언이다. + # S0 의 signal 스키마 폐포 17종과 미러 24종은 런타임에 계산되거나 S0 가 이미 경성으로 대조하므로 + # 여기 넣지 않는다. 그 경계는 의도한 것이다. + PART2_REQUIRED_ASSETS = ( + SLICE_SCHEMA, + FANOUT_SCHEMA, + COMMON_CONTRACT, + POLICY, + "Default_Agent/platform/schemas/domain_seed_output.schema.v3.json", # R0 + "Default_Agent/signals/signal_registry.v2.json", # S0 + "Default_Agent/contracts/signals/s5_execution_contract.v2.json", # S0 + "Default_Agent/routing/extension_payload_key_declarations.v1.json", # F0 + "Default_Agent/stage1_runtime/worker_output_validator.txt", # R0 전용 미러 + "Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json", # R0·F0 — BO 투영 정책 + "Default_Agent/stage1_runtime/seed_admission_policy.v1.json", # R0 — 시드 수용 정책 + ) + RUNTIME_MANIFEST_SCHEMA = "stage1_runtime_manifest.v1" + # 옛 묶음이 서버에 그대로면 아래 파일 대조는 통과한다. 이 YAML 이 기대하는 묶음을 고정한다. + # 배포 자산을 바꿀 때마다 함께 갱신한다. + EXPECTED_RUNTIME_MANIFEST_SHA256 = "a828e962d1f6dbb8607cab16479c55b2ced96ad55305c6f25873ce25194b8084" + # registry_validator 는 overlay 오류를 모으기만 한다. 네 코드는 배포 문제이므로 경성으로 올린다. + OVERLAY_ERROR_CODES = ("PROMPT_OVERLAY_HASH_MISMATCH", "PROMPT_OVERLAY_NOT_FOUND", + "PROMPT_OVERLAY_PATH_INVALID", "PROMPT_OVERLAY_REFERENCE_DIVERGENCE") + PART2_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + + # 산출 경로 — 새 계약만 쓴다. + SLICE_DIR = "runtime/domain_slices" + SLICE_ROOT_KEY = "stage_b_domain_slice" + PROMPT_DIR = "runtime/compiled_prompts" + SEED_DIR = "runtime/domain_seed_outputs" + FANOUT_PATH = "fanout/domain_fanout_plan.json" + # P-1 — v4 개정에서 구 slice 경로를 걷어내며 이 둘의 접두까지 벗겼던 것을 되돌린다. + # 이 둘은 slice 가 아니며 R0·F0·S0 가 여기서 읽는다(v3 1104·1105행). + STAGE_A_PATH = "stage1_tmp/task_c_bo/stage_a_context.json" + SOURCE_MANIFEST_PATH = "stage1_tmp/task_c_bo/source_universe_manifest.json" + RECEIPT_PATH = "validation_assets/routing/stage_receipt.json" + + # 가액금액 정본 결속(2026-10-30, 개정계획서 §3.1). Part 1 V2·V3 산출을 읽어 회차 카탈로그 한 파일로 묶는다. + # slice 에는 싣지 않는다 — v2 slice 는 이미 약 200k자라 도메인마다 중복하면 preflight 파일 한도를 넘는다. + VALUE_FACTS = "value_facts.json" + VALUE_FACTS_GATE = "quality_gates/value_facts_gate.json" + VALUE_FACTS_LINKS = "value_facts_party_links.json" + CATALOG_PATH = "stage1_tmp/task_c_bo/value_facts_catalog.json" + CATALOG_SOFT_LIMIT_CHARS = 80000 + # 2026-11-03 캐시 — worker 전용 입력. slice·조립 프롬프트 파일은 그대로 두고 사본만 더 낸다. + # 공유 2종은 정적 preflight(첫 user 메시지에 inline, prefix breakpoint 앞), worker_inputs 는 동적 preflight. + SHARED_UNIVERSE_PATH = "runtime/shared/source_universe.json" + SHARED_VOCAB_PATH = "runtime/shared/vocabulary.md" + WORKER_INPUT_DIR = "runtime/worker_inputs" + COMPONENT_UNION = "Default_Agent/routing/evidence_component_union.md" + SHARED_UNIVERSE_KINDS = ("evidence", "event_candidate") + # 배포 백엔드 한도(2026-11-03 컨테이너 env). 넘으면 백엔드가 경고만 남기고 파일을 건너뛴다 — + # 공유 파일이 빠지면 prefix 경계가 마지막 메시지로 밀려 도메인 꼬리 전체가 1.25배로 쓰인다. 여기서 막는다. + PREFLIGHT_FILE_LIMIT_CHARS = 260000 + PREFLIGHT_TOTAL_LIMIT_CHARS = 500000 + # rank-50 실행 가드. 도메인 overlay(rank 30)가 payload 에 금액·operand 를 쓰라고 해도 이 조각이 뒤에 붙어 우선한다. + VALUE_GUARD_PATH = "runtime/value_facts_guard.md" + VALUE_GUARD_TEXT = ( + "## 금액 기재 규칙 (실행 가드, rank 50)\n" + "- amount_facts·payload·action_summary 에 금액·가액 숫자를 적지 않는다(증거 excerpt 원문 인용은 그대로 둔다). 금액은 `stage1_tmp/task_c_bo/value_facts_catalog.json` 의 `value_id` 로만 가리킨다.\n" + "- `amount_facts[]` 원소는 {\"amount_type\": \"<역할>\", \"decimal_value\": null, \"currency\": null, " + "\"source_refs\": [\"\"]} 로 쓴다. 숫자와 통화는 코드가 정본에서 채운다.\n" + "- 앞의 조각이 payload 에 금액·operand 를 적으라고 해도 숫자 대신 `payload.value_id` 로 가리킨다. " + "`action_summary` 에도 숫자를 옮기지 않는다.\n" + "- 카탈로그에 맞는 레코드가 없으면 금액 칸을 비우고 `review_items` 에 `AMOUNT_NOT_IN_VALUE_FACTS` 를 남긴다.\n" + "\n## 법령 인용 규칙 (실행 가드, rank 50)\n" + "- slice 에는 법령 출처가 없다. 앞의 조각이 SG-04 주입이나 version pin 을 말해도 법령 id 를 적으라는 뜻이 아니다.\n" + "- `source_id`·`source_refs` 에 조문·규칙·버전 id 를 적지 않는다. `calculation_requests` 에도 `law_version_refs` 를 쓰지 않는다. " + "`source_kind` 에 `law_version`·`registry` 를 쓰지 않는다. 기억으로 조문을 인용하지 않는다.\n" + "- 기준일은 slice 출처에서 그대로 보존한다. 적용 법령 판본이 쟁점이면 `review_items` 에 `LAW_VERSION_BASIS_REVIEW` 를 남긴다.\n" + "- slice 출처가 인용한 조문은 그 출처의 `excerpt` 에 그대로 둔다.\n") + CATALOG_RECORD_KEYS = ("value_id", "value_kind", "value_type", "item_label", "amount_text", + "amount_value", "currency", "per", "value_basis", "dates", "object_label_text") + + ERRORS = [] + WARNINGS = [] + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def utc_now(): + # stage_a_context 의 created_at_utc 전용이다. + # 조립 프롬프트 해시에는 들어가지 않으므로 결정성(판정 2)에 영향이 없다. + return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + def stage_text(logical_name, body): + # 논리 이름을 그대로 실행 뿌리 아래 상대경로로 쓴다. + target = WORK / logical_name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(body.encode("utf-8")) + return len(body.encode("utf-8")) + + + # ------------------------------------------------------------------ + # 0) 배포 완전성 — F-2. 모듈 반입보다 앞이고 봉인 검증보다도 앞이다. + # 봉인은 사건 산출물의 문제이고 이것은 조립본의 문제라 원인이 다르다. + # 첫 실패에서 멈추지 않고 전부 모은다 — 배포는 한 번에 고쳐야 한다. + # ------------------------------------------------------------------ + def assert_deployment(): + """조립본이 Part 2 개정 델타를 한 벌로 받았는지 본다. 읽기만 한다.""" + manifest_raw = read_raw(RUNTIME_MANIFEST) + if sha_text(manifest_raw) != EXPECTED_RUNTIME_MANIFEST_SHA256: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_RUNTIME_MANIFEST_STALE", + "expected": EXPECTED_RUNTIME_MANIFEST_SHA256, "actual": sha_text(manifest_raw), + "remedy": PART2_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + manifest = json.loads(manifest_raw) + if manifest.get("schema_version") != RUNTIME_MANIFEST_SCHEMA: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_RUNTIME_MANIFEST_INVALID", "detail": "schema_version", + "expected": RUNTIME_MANIFEST_SCHEMA, "actual": manifest.get("schema_version"), + }, ensure_ascii=False)) + rows = [row for row in (manifest.get("entries") or []) if isinstance(row, dict)] + paths = [row.get("path") for row in rows] + duplicates = sorted({p for p in paths if paths.count(p) > 1}) + if manifest.get("runtime_artifact_count") != len(rows) or duplicates: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_RUNTIME_MANIFEST_INVALID", "detail": "count_or_duplicate", + "declared_count": manifest.get("runtime_artifact_count"), "actual_count": len(rows), + "duplicate_paths": duplicates, + }, ensure_ascii=False)) + expected = {row["path"]: row["sha256"] for row in rows} + unregistered, mismatch, unreadable = [], [], [] + for logical in sorted(set(list(MODULE_MIRRORS.values()) + list(PART2_REQUIRED_ASSETS))): + rel = logical[len(ASSET_ROOT):] + want = expected.get(rel) + if want is None: + unregistered.append(rel) + try: + body = read_raw(logical) + except Exception: + unreadable.append(rel) + continue + if want is not None and want != sha_text(body): + mismatch.append({"path": rel, "expected": want, "actual": sha_text(body)}) + if unregistered or mismatch or unreadable: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_ASSET_DEPLOYMENT_INCOMPLETE", + "message": "조립본에 Part 2 개정 자산이 한 벌로 반영되지 않았다.", + "unregistered": unregistered, "hash_mismatch": mismatch, "unreadable": unreadable, + "remedy": PART2_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + return manifest + + + # ------------------------------------------------------------------ + # 1) 모듈 반입 — R-1~R-5. 해시가 어긋나면 실행하지 않는다. + # ------------------------------------------------------------------ + def materialize_modules(): + RT.mkdir(parents=True, exist_ok=True) + manifest_doc = json.loads(read_raw(RUNTIME_MANIFEST)) + expected = {row["path"]: row["sha256"] + for row in manifest_doc.get("entries") or []} + staged = [] + for name in MODULES: + logical = MODULE_MIRRORS[name] + raw = read_raw(logical).encode("utf-8") + want = expected.get(logical[len("Default_Agent/"):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (RT / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(RT) not in sys.path: + sys.path.insert(0, str(RT)) + return staged + + + # ------------------------------------------------------------------ + # 2) 봉인 검증 — 세 해시는 read_raw 원문에서 계산한다 (§6.1-3). + # ------------------------------------------------------------------ + def verify_seal(handoff, screening_raw, manifest_raw, index_raw): + root = handoff.get("stage1_part1_soft_gate_handoff", handoff) + guard = root.get("digest_guard") or {} + pairs = [("screening_sha256", sha_text(screening_raw)), + ("activation_manifest_sha256", sha_text(manifest_raw)), + ("registry_index_sha256", sha_text(index_raw))] + for key, actual in pairs: + declared = guard.get(key) + if declared is None: + raise RuntimeError("SEAL_KEY_MISSING:%s" % key) + if declared != actual: + raise RuntimeError("SEAL_FAILED:%s" % key) + return {key: value for key, value in pairs} + + + def verify_content_seal(handoff, evidence_raw, events_raw): + # C-05 — verify_seal 과 같은 형식. 반환값은 seal 에 합치지 않는다(seal 은 stage_a digest_guard 로 넘어간다). + root = handoff.get("stage1_part1_soft_gate_handoff", handoff) + guard = root.get("digest_guard") or {} + pairs = [("evidence_indexed_sha256", sha_text(evidence_raw)), + ("evidence_event_candidates_sha256", sha_text(events_raw))] + for key, actual in pairs: + declared = guard.get(key) + if declared is None: + raise RuntimeError("SEAL_KEY_MISSING:%s" % key) + if declared != actual: + raise RuntimeError("SEAL_FAILED:%s" % key) + return {key: value for key, value in pairs} + + + # ------------------------------------------------------------------ + # 3) C-1 — evidence authority map 에 registry_component_ids 통과 (P0 판정 B) + # component_keys(문서 추출 구조 이름)와 계층이 다르므로 섞지 않는다. + # ------------------------------------------------------------------ + def evidence_authority_map(evidence_document): + root = evidence_document.get("evidence_indexed", evidence_document) + items = root.get("items") if isinstance(root, dict) else evidence_document + out = {} + for item in items if isinstance(items, list) else []: + if not isinstance(item, dict): + continue + index = item.get("evidence_index") or item.get("evidence_index_proposed") + if not isinstance(index, str) or not index: + continue + out[index] = { + "evidence_index": index, + "doc_uid": item.get("doc_uid"), + "doc_type": item.get("doc_type"), + "source_pointer": item.get("source_pointer") or {}, + "registry_component_ids": [ + str(value) for value in (item.get("registry_component_ids") or []) + if isinstance(value, str) and value + ], + } + return out + + + # ------------------------------------------------------------------ + # 3-b) 가액금액 정본 결속 — 개정계획서 §3.1 + # BOUND 일 때만 정본 레코드를 카탈로그에 싣는다. ABSENT·MISMATCH 이면 빈 카탈로그를 쓰고 + # Part 2 는 그대로 진행한다(Part 1 에서 사건 사슬이 V 를 기다리지 않는 것과 같은 원칙). + # run_id 는 대조하지 않는다 — V2 가 같은 변수로 두 파일에 쓰는 값이라 대조해도 의미가 없다. + # ------------------------------------------------------------------ + def _read_optional(name): + # 파일 없음만 None 이다. MCP 오류는 그대로 올려 A0 를 멈춘다(조용히 ABSENT 로 넘기지 않는다). + try: + return read_raw(name) + except RuntimeError as exc: + if str(exc).startswith(("EMPTY_RESPONSE:", "EMPTY_CONTENT:")): + return None + raise + + + def value_facts_binding(handoff_root, evidence_raw, facts_raw, gate_raw): + """(status, reason) 를 돌려준다. 지문은 T9 봉인값·V2 gate 지문·A0 가 읽은 원문 셋이 같아야 한다.""" + if facts_raw is None and gate_raw is None: + return "ABSENT", "VALUE_FACTS_FILES_ABSENT" + if gate_raw is None: + return "MISMATCH", "VALUE_FACTS_GATE_ABSENT" + try: + gate = json.loads(gate_raw) + except Exception: + return "MISMATCH", "VALUE_FACTS_GATE_UNPARSABLE" + if gate.get("status") not in ("READY", "READY_WITH_REVIEW"): + # V2 가 BLOCKED 이면 records 를 비워 쓴다. 정본이 없는 회차다. + return "ABSENT", "VALUE_FACTS_GATE_%s" % gate.get("status") + if facts_raw is None: + return "MISMATCH", "VALUE_FACTS_ABSENT_WITH_GATE" + if gate.get("value_facts_sha256") != sha_text(facts_raw): + return "MISMATCH", "VALUE_FACTS_SHA_MISMATCH" + sealed = (handoff_root.get("digest_guard") or {}).get("evidence_indexed_sha256") + fingerprint = (gate.get("source_fingerprint") or {}).get("evidence_indexed_sha256") + if not sealed or fingerprint != sealed or sealed != sha_text(evidence_raw): + return "MISMATCH", "EVIDENCE_INDEXED_FINGERPRINT_MISMATCH" + return "BOUND", None + + + def build_value_facts_catalog(handoff_root, evidence_raw): + facts_raw = _read_optional(VALUE_FACTS) + gate_raw = _read_optional(VALUE_FACTS_GATE) + status, reason = value_facts_binding(handoff_root, evidence_raw, facts_raw, gate_raw) + binding = {"status": status, "reason": reason, + "value_facts_sha256": sha_text(facts_raw) if facts_raw else None, + "gate_sha256": sha_text(gate_raw) if gate_raw else None, + "record_count": 0} + records = [] + if status == "BOUND": + facts = json.loads(facts_raw) + # V3 연결은 같은 value_facts 를 본 것일 때만 쓴다. 낡은 연결은 버린다. + party_refs = {} + links_raw = _read_optional(VALUE_FACTS_LINKS) + links = json.loads(links_raw) if links_raw else {} + if (links.get("value_facts_sha256") == binding["value_facts_sha256"] + and links.get("status") in ("READY", "READY_WITH_REVIEW")): + for link in links.get("links") or []: + if link.get("status") == "RESOLVED": + party_refs[(link.get("value_id"), link.get("path"))] = link.get("party_ref") + for rec in facts.get("records") or []: + if not isinstance(rec, dict) or not isinstance(rec.get("value_id"), str): + continue + row = {key: rec[key] for key in CATALOG_RECORD_KEYS if rec.get(key) not in (None, "", [])} + row["evidence_index"] = (rec.get("source_ref") or {}).get("evidence_index") + if not row["evidence_index"]: + # R0 가 value_id 자리를 증거 index 로 바꾸지 못하면 후보 전체가 격리된다. 싣지 않는다. + warn("VALUE_FACT_WITHOUT_EVIDENCE_INDEX", rec["value_id"]) + continue + parties = [] + for i, party in enumerate(rec.get("parties") or []): + if isinstance(party, dict) and party.get("party_label"): + entry = {"party_label": party["party_label"]} + ref = party_refs.get((rec["value_id"], "parties[%d]" % i)) + if ref: + entry["party_ref"] = ref + parties.append(entry) + if parties: + row["parties"] = parties + relations = [{"type": rel.get("type"), "target_value_ids": rel.get("target_value_ids") or []} + for rel in rec.get("relations") or [] if isinstance(rel, dict)] + if relations: + row["relations"] = relations + records.append(row) + binding["record_count"] = len(records) + catalog = {"schema_version": "stage1_part2_value_facts_catalog.v1", + "binding": binding, "records": records} + binding["catalog_chars"] = len(canonical(catalog)) + if status == "ABSENT": + warn("VALUE_FACTS_ABSENT", str(reason)) + elif status == "MISMATCH": + warn("VALUE_FACTS_INTEGRITY_MISMATCH", str(reason)) + if binding["catalog_chars"] > CATALOG_SOFT_LIMIT_CHARS: + warn("VALUE_FACTS_CATALOG_LARGE", "%d chars > %d" % (binding["catalog_chars"], CATALOG_SOFT_LIMIT_CHARS)) + return catalog + + + # ------------------------------------------------------------------ + # 4) 본체 + # ------------------------------------------------------------------ + def main(): + # F-2 — 게이트가 먼저다. 반입도 봉인도 그 뒤다. + gate_manifest = assert_deployment() + staged_modules = materialize_modules() + import registry_loader + import registry_validator + import prompt_compiler + import domain_slice_compiler + import domain_fanout_planner + import stage_a_context_builder + + handoff = read_json(HANDOFF) + # v.8 handoff guard(2026-10-10, 실패분석_stage_1_part_2_v.8.md §4 F-2) — Part 1 이 BLOCKED 를 선언했으면 여기서 멈춘다. + # handoff writer 는 handoff_status == "BLOCKED" iff stage2_auto_progression_allowed is False 로 쓴다. 둘은 이중 방어다. + root = handoff.get("stage1_part1_soft_gate_handoff", handoff) + if root.get("handoff_status") == "BLOCKED" or root.get("stage2_auto_progression_allowed") is False: + raise RuntimeError(json.dumps({ + "reason_code": "PART1_HANDOFF_BLOCKED", + "handoff_status": root.get("handoff_status"), + "hard_gate_ids": (root.get("hard_gate_summary") or {}).get("hard_gate_ids"), + "remedy": "Part 1 hard gate 를 해소한 뒤(해당 mapper 재실행 또는 B2 정규화) Part 2 를 재실행한다."}, ensure_ascii=False)) + screening_raw = read_raw(SCREENING) + manifest_raw = read_raw(ACTIVATION_MANIFEST) + index_raw = read_raw(REGISTRY_INDEX) + seal = verify_seal(handoff, screening_raw, manifest_raw, index_raw) + + stage_text(REGISTRY_INDEX, index_raw) + index_doc = json.loads(index_raw) + index = index_doc.get("domain_registry_index", index_doc) + for entry in index.get("entries") or []: + config_path = entry.get("config_path") + if not isinstance(config_path, str) or not config_path: + raise RuntimeError("REGISTRY_CONFIG_PATH_MISSING:%s" % entry.get("domain_id")) + logical = unicodedata.normalize("NFC", "Default_Agent/domains/" + config_path + if not config_path.startswith("Default_Agent/") + else config_path) + config_text = read_raw(logical) + stage_text(logical, config_text) + # 프롬프트 조각도 함께 반입한다. prompt_compiler 가 도메인별 + # seed_prompt_overlay 를 읽으므로 config 만 실으면 fragment not found 로 멈춘다. + # 파일 이름을 짓지 않는다 — config 가 선언한 prompt_overlay_ref 를 따라간다. + overlay_ref = json.loads(config_text).get("prompt_overlay_ref") + if isinstance(overlay_ref, str) and overlay_ref: + overlay_logical = unicodedata.normalize( + "NFC", overlay_ref if overlay_ref.startswith("Default_Agent/") + else posixpath.join(posixpath.dirname(logical), overlay_ref)) + try: + stage_text(overlay_logical, read_raw(overlay_logical)) + except Exception as exc: + warn("PROMPT_OVERLAY_STAGE_SKIPPED", "%s: %s" % (overlay_logical, exc)) + # 특별법 profile 조각 반입 — prompt_compiler.collect_domain_fragments 는 + # domain_config.special_law_profiles 가 선언한 profile_id 를 profile_paths 인자에서 + # 찾는다. 그 인자를 넘기지 않으면 파일이 배포돼 있어도 + # PROMPT_REQUIRED_FRAGMENT_MISSING 으로 멈춘다(디스크를 보지 않는 검사다). + # 파일 이름을 짓지 않는다 — profile registry 가 선언한 prompt_overlay_path 를 따라간다. + profile_paths = {} + try: + slp_index_raw = read_raw(SPECIAL_LAW_INDEX) + except Exception as exc: + warn("SPECIAL_LAW_INDEX_ABSENT", "%s: %s" % (SPECIAL_LAW_INDEX, exc)) + else: + stage_text(SPECIAL_LAW_INDEX, slp_index_raw) + slp_doc = json.loads(slp_index_raw) + slp_index = slp_doc.get("special_law_profile_registry_index", slp_doc) + slp_base = posixpath.dirname(SPECIAL_LAW_INDEX) + for entry in slp_index.get("entries") or []: + profile_id = entry.get("profile_id") + overlay_path = entry.get("prompt_overlay_path") + if not isinstance(profile_id, str) or not profile_id: + continue + if not isinstance(overlay_path, str) or not overlay_path: + warn("SPECIAL_LAW_OVERLAY_PATH_MISSING", str(profile_id)) + continue + overlay_logical = unicodedata.normalize( + "NFC", overlay_path if overlay_path.startswith("Default_Agent/") + else posixpath.join(slp_base, overlay_path)) + try: + stage_text(overlay_logical, read_raw(overlay_logical)) + except Exception as exc: + warn("SPECIAL_LAW_OVERLAY_STAGE_SKIPPED", "%s: %s" % (overlay_logical, exc)) + continue + profile_paths[profile_id] = overlay_logical + + stage_text(COMMON_CONTRACT, read_raw(COMMON_CONTRACT)) + stage_text(POLICY, read_raw(POLICY)) + + slice_schema = json.loads(read_raw(SLICE_SCHEMA)) + fanout_schema = json.loads(read_raw(FANOUT_SCHEMA)) + + # F-3 — 입력 능력 검사. 장부(F-2)가 아니라 의미를 본다. + # 매니페스트와 스키마를 함께 옛 판본으로 되돌리면 장부는 자기들끼리 맞아 통과한다. + # 그 자리에서 유일하게 남는 검사가 이것이다. + _sb = (slice_schema.get("properties") or {}).get("stage_b_domain_slice") or {} + _props = _sb.get("properties") or {} + _missing = [k for k in ("domain_declarations",) if k not in _props] + if "hash_kind" not in ((_props.get("compiled_prompt") or {}).get("properties") or {}): + _missing.append("compiled_prompt.hash_kind") + if _missing: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SLICE_SCHEMA_STALE", + "message": "슬라이스 스키마가 컴파일러가 내는 키를 선언하지 않는다. 조립본의 스키마가 개정 전 판본이다.", + "path": SLICE_SCHEMA, "missing_declarations": _missing, + "remedy": "domain_slice.schema.v2.json 을 후보 오버레이 판본으로 덮어쓴다.", + }, ensure_ascii=False)) + + os.chdir(EXECUTION_ROOT) + registry = registry_loader.load_registry(REGISTRY_INDEX) + validation = registry_validator.validate_registry(REGISTRY_INDEX) + # F-4d — overlay 계열 네 코드만 경성으로 올린다. validate_registry 전체를 올리면 + # 지금 통과 중인 다른 review 항목까지 막힌다. 부분 복사에서 흔한 것은 훼손이 아니라 + # 누락이고, 누락은 PROMPT_OVERLAY_NOT_FOUND 로 나온다. + _ovl = [e for e in (validation.get("errors") or []) + if isinstance(e, dict) and e.get("code") in OVERLAY_ERROR_CODES] + if _ovl: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_ASSET_DEPLOYMENT_INCOMPLETE", "detail": "prompt_overlay", + "codes": sorted({str(e.get("code")) for e in _ovl}), + "domains": sorted({str(e.get("domain_id")) for e in _ovl}), + "remedy": PART2_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + if validation.get("status") not in ("PASS", "READY", "OK"): + warn("REGISTRY_VALIDATION_NOT_PASS", str(validation.get("status"))) + + manifest = json.loads(manifest_raw) + manifest_root = manifest.get("domain_activation_manifest", manifest) + # D-3 넓은 정의 — execution_eligible 이 유일한 결정 필드다. + eligible = sorted({row.get("domain_id") + for row in manifest_root.get("domain_entries") or [] + if row.get("execution_eligible") is True}) + expected_runnable = sorted(set(manifest_root.get("expected_runnable_domain_ids") or [])) + if eligible != expected_runnable: + raise RuntimeError("A0_EXPECTED_RUNNABLE_SET_MISMATCH") + + evidence_raw = read_raw(EVIDENCE) + evidence_document = json.loads(evidence_raw) + events_raw = read_raw(EVENTS) + events_document = json.loads(events_raw) + # C-05 — 증거·사건 파일을 Part 1 봉인과 대조한다. 이후 digest·컴파일은 같은 원문을 쓴다(결과는 seal 에 합치지 않는다). + verify_content_seal(handoff, evidence_raw, events_raw) + authority = evidence_authority_map(evidence_document) + # 3-b — 카탈로그는 worker 의 정적 preflight 이므로 fan-out 보다 먼저 쓴다. + catalog = build_value_facts_catalog(root, evidence_raw) + catalog_text = canonical(catalog) + write_doc(CATALOG_PATH, catalog_text) + value_fact_ids = [row["value_id"] for row in catalog["records"]] + + # 프롬프트 조립 — rank 10 -> 20 -> 30 -> 40 -> 50. 상한 96,000 B / 24,000 자. + policy = json.loads(read_raw(POLICY)) + # R-3 — 어휘 사전을 실행 뿌리에 실어 조각으로 붙인다. 부재는 경고로 남기고 진행한다 + # (Part 1 이 아직 그 파일을 내지 않은 배포에서도 조립은 되어야 한다). + # 2026-11-03 캐시 — 어휘 사전은 전 도메인 공통이라 조립 프롬프트에 끼우지 않고 공유 정적 파일로 낸다 + # (앙상블 §3.5 · Q6). extra_specs 는 비운다. 정책 required_categories 는 common_contract·domain 뿐이라 + # 조립은 그대로 통과한다. 부재면 표식 한 줄을 써서 prewarm·worker 의 정적 파일 집합이 같게 한다. + vocabulary_specs = [] + try: + vocabulary_text = read_raw(VOCABULARY) + except Exception as exc: + warn("VOCABULARY_FRAGMENT_ABSENT", "%s: %s" % (VOCABULARY, exc)) + vocabulary_text = "VOCABULARY_ABSENT\n" + write_doc(SHARED_VOCAB_PATH, vocabulary_text) + # rank-50 실행 가드 — 실행 뿌리 아래에 두어야 compile_fragments 의 release root 검사를 통과한다. + stage_text(VALUE_GUARD_PATH, VALUE_GUARD_TEXT) + prompt_manifests = {} + for domain_id in expected_runnable: + specs = prompt_compiler.collect_domain_fragments( + domain_id, registry, common_contract_path=COMMON_CONTRACT, + profile_paths=profile_paths, extra_specs=vocabulary_specs, + runtime_guard_path=str(pathlib.Path(EXECUTION_ROOT) / VALUE_GUARD_PATH)) + text, manifest_row = prompt_compiler.compile_fragments(specs, policy) + rel = "%s/%s.md" % (PROMPT_DIR, domain_id) + stage_text(rel, text) + write_doc(rel, text) + row = dict(manifest_row) + row["compiled_prompt_path"] = rel + row["compiled_prompt_sha256"] = sha_text(text) + row.setdefault("composition_policy_sha256", sha_text(read_raw(POLICY))) + row["_manifest_dir"] = EXECUTION_ROOT + row["_chars"] = len(text) + prompt_manifests[domain_id] = row + + # R-2 — Part 1 screener 02 가 CALC_NOT_IN_BINDINGS 로 이미 검증해 낸 + # requested_calculation_domains 를 통과시킨다. 새 registry 를 적재하지 않는다. + # 봉인용 원문 바이트(screening_raw)는 손대지 않고 파싱만 따로 한다. + # 파싱 실패와 계약 위반을 갈라 둔다. try 로 함께 감싸면 계약 위반이 경고로 + # 강등되어 조용히 통과한다 — 애초에 고치려던 것이 그 조용함이다. + screening_calc = {} + try: + screening_doc = json.loads(screening_raw) + except Exception as exc: + screening_doc = None + warn("SCREENING_CALC_PARSE_SKIPPED", str(exc)) + if screening_doc is not None: + # 루트 래핑을 벗긴다. Part 1 은 {"domain_screening": {...}} 로 쓰고 + # 스키마가 그 키를 required 로 못박는다. 벗기지 않으면 candidates 가 + # 늘 None 이 되어 예외도 없이 아무 일도 일어나지 않는다. + screening_root = screening_doc.get("domain_screening", screening_doc) \ + if isinstance(screening_doc, dict) else None + if not isinstance(screening_root, dict): + raise RuntimeError("SCREENING_ROOT_INVALID") + candidate_rows = screening_root.get("candidates") + if not isinstance(candidate_rows, list) or not candidate_rows: + raise RuntimeError("SCREENING_CANDIDATES_EMPTY") + for row in candidate_rows: + if not isinstance(row, dict): + raise RuntimeError("SCREENING_CANDIDATE_INVALID") + domain_id = row.get("domain_id") + codes = [str(v) for v in (row.get("requested_calculation_domains") or []) + if isinstance(v, str) and v] + if isinstance(domain_id, str) and domain_id and codes: + screening_calc[domain_id] = sorted(set(codes)) + + # P-2a — stage_a_context 를 slice 컴파일보다 먼저 만든다. slice 의 source_universe 가 + # 인용할 event 식별자의 정본이 event_candidate_map 이기 때문이다. 순서가 뒤였을 때 + # A0 는 원시 evidence_event_candidates 문서를 넘겼고, domain_slice_compiler._records 가 + # 그 문서-단위 items(30건)를 후보로 오인해 candidate_id 를 못 찾아 + # event:unidentified:NNNN 로 대체했다. 그 값은 source_universe_manifest 의 + # event_candidate_ids(EVT-...-NN, 84건)와 교집합이 0 이라, 워커가 규율을 지켜 + # slice 안의 것만 인용해도 R0 가 "source_refs outside Stage A universe" 로 차단했다. + meeting_raw = read_raw(MEETING) + created_at_utc = utc_now() + input_digests = { + MEETING: sha_text(meeting_raw), + EVIDENCE: sha_text(evidence_raw), + EVENTS: sha_text(events_raw), + SCREENING: seal["screening_sha256"], + ACTIVATION_MANIFEST: seal["activation_manifest_sha256"], + REGISTRY_INDEX: seal["registry_index_sha256"], + } + stage_a = stage_a_context_builder.build_stage_a_context( + meeting_text=meeting_raw, + evidence_obj=evidence_document, + event_obj=events_document, + input_digests_sha256=input_digests, + created_at_utc=created_at_utc, + digest_guard=seal, + expected_runnable_domain_ids=expected_runnable) + source_manifest = stage_a_context_builder.build_source_universe_manifest( + stage_a, input_digests_sha256=input_digests, + registry_index_sha256=seal["registry_index_sha256"]) + # 3-b — 덧붙이기 키. R0·F0·S0 는 키를 골라 읽고 이 매니페스트는 봉인 해시가 없다. + source_manifest["value_fact_ids"] = sorted(value_fact_ids) + # 맵을 통째로 넘기지 않는다 — domain_slice_compiler._records 는 dict 를 받으면 + # by_evidence_index(값이 id 리스트)에 먼저 걸려 빈 목록을 돌려준다. 후보 레코드 + # 목록으로 평탄화해 넘겨야 _record_id 가 candidate_id 를 찾아 EVT-...-NN 을 쓴다. + event_candidate_records = [ + row for row in ((stage_a.get("event_candidate_map") or {}).get("by_candidate_id") or {}).values() + if isinstance(row, dict)] + if not event_candidate_records: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_EVENT_CANDIDATE_MAP_EMPTY", + "message": "stage_a event_candidate_map.by_candidate_id 가 비었다. slice 의 event 식별자를 정본으로 실을 수 없다.", + }, ensure_ascii=False)) + try: + result = domain_slice_compiler.compile_domain_slices( + manifest, registry, evidence_document, event_candidate_records, + manifest_sha256=seal["activation_manifest_sha256"], + evidence_sha256=sha_text(evidence_raw), + events_sha256=sha_text(events_raw), + slice_schema=slice_schema, + compiled_prompt_manifests=prompt_manifests, + expected_output_dir=SEED_DIR, + screening_calculation_domains=screening_calc) + except TypeError as exc: + # F-3b 앞단 — 옛 컴파일러는 screening_calculation_domains 를 받지 않는다. 그대로 두면 + # 배포 원인을 말하지 않는 TypeError 로 끝난다. 이름을 붙여 같은 코드로 내보낸다. + raise RuntimeError(json.dumps({ + "reason_code": "PART2_COMPILER_STALE", + "message": "컴파일러가 새 인자를 받지 않는다. 조립본의 domain_slice_compiler 가 개정 전 판본이다.", + "detail": "signature_mismatch", "signature_error": str(exc)[:200], + "remedy": "domain_slice_compiler.py|.txt 를 후보 오버레이 판본으로 덮어쓴다.", + }, ensure_ascii=False)) + + # F-3b — 출력 능력 검사. 기록 루프 앞이다. 여기서 멈추면 슬라이스가 한 벌도 나가지 않는다. + # 새 스키마가 domain_declarations 를 required 로 올리지 않으므로(P0 판정 C) 옛 컴파일러의 + # 산출도 스키마 검증은 26/26 통과한다. 장부가 볼 수 없는 그 자리를 이 검사가 막는다. + _bad = [] + for _did, _obj in sorted((result.get("slices") or {}).items()): + _root = (_obj or {}).get(SLICE_ROOT_KEY) or _obj or {} + if ("domain_declarations" not in _root + or "hash_kind" not in (_root.get("compiled_prompt") or {})): + _bad.append(_did) + if _bad: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_COMPILER_STALE", + "message": "컴파일러가 registry 선언 블록을 싣지 않았다. 조립본의 domain_slice_compiler 가 개정 전 판본이다.", + "domains_without_declarations": _bad, + "remedy": "domain_slice_compiler.py|.txt 를 후보 오버레이 판본으로 덮어쓴다.", + }, ensure_ascii=False)) + + slice_hashes = {} + for domain_id, slice_obj in (result.get("slices") or {}).items(): + rel = "%s/%s.json" % (SLICE_DIR, domain_id) + text = canonical(slice_obj) + stage_text(rel, text) + write_doc(rel, text) + slice_hashes[domain_id] = sha_text(text) + + # 2026-11-03 캐시 — worker 전용 입력(앙상블 §3.5). slice 의 source_universe 는 evidence·event 레코드가 + # 전 도메인 공통이고(domain_slice_compiler 가 전체 레코드로 만든다) 도메인 고유 항목(meeting_clause·other)이 + # 뒤에 붙는다. 공통부를 한 파일로 떼어 내고, 도메인 파일에는 나머지를 둔다. 하류(validator·R0·S0)는 + # slice 의 payload·excerpt 를 읽지 않으므로 slice 파일은 그대로 둔다. 분할본을 합치면 원본과 같은지 + # 정규 JSON 해시로 검사한다 — 어긋나면 worker 가 돌기 전에 멈춘다. + shared_universe = None + shared_universe_sha = None + worker_input_sizes = {} + for domain_id, slice_obj in sorted((result.get("slices") or {}).items()): + s_root = (slice_obj or {}).get(SLICE_ROOT_KEY) or {} + universe = list(s_root.get("source_universe") or []) + common = [x for x in universe + if isinstance(x, dict) and x.get("source_kind") in SHARED_UNIVERSE_KINDS] + extra = [x for x in universe + if not (isinstance(x, dict) and x.get("source_kind") in SHARED_UNIVERSE_KINDS)] + if universe != common + extra: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SHARED_UNIVERSE_ORDER", + "message": "source_universe 가 공통부(evidence·event) 뒤에 도메인 고유부가 오는 순서가 아니다. 분할하면 순서가 바뀐다.", + "domain_id": domain_id}, ensure_ascii=False)) + common_sha = sha_text(canonical(common)) + if shared_universe is None: + shared_universe = common + shared_universe_sha = common_sha + elif common_sha != shared_universe_sha: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SHARED_UNIVERSE_DIVERGENT", + "message": "도메인 간 공통 source_universe 가 다르다. 공유 파일로 떼어 낼 수 없다.", + "domain_id": domain_id, "expected": shared_universe_sha, "actual": common_sha}, ensure_ascii=False)) + # 동치 검사 — 공유 파일(첫 도메인의 공통부) + 이 도메인의 고유부 = 원 slice 의 source_universe. + if canonical(dict(s_root, source_universe=shared_universe + extra)) != canonical(s_root): + raise RuntimeError(json.dumps({ + "reason_code": "PART2_WORKER_INPUT_NOT_EQUIVALENT", + "message": "공유 우주 + 도메인 고유부가 원 slice 와 같지 않다.", + "domain_id": domain_id}, ensure_ascii=False)) + worker_input = {k: v for k, v in s_root.items() if k != "source_universe"} + worker_input["schema_version"] = "task_c_bo_stage_b_domain_worker_input.v1" + worker_input["slice_schema_version"] = s_root.get("schema_version") + worker_input["slice_path"] = "%s/%s.json" % (SLICE_DIR, domain_id) + worker_input["slice_sha256"] = slice_hashes.get(domain_id) + worker_input["shared_source_universe"] = { + "path": SHARED_UNIVERSE_PATH, "sha256": shared_universe_sha, "count": len(shared_universe), + "note": "출처 우주 = 공유 파일 source_universe ∪ 아래 source_universe_domain_extra. 순서는 공유 → 고유."} + worker_input["source_universe_domain_extra"] = extra + wi_text = canonical({"stage_b_domain_worker_input": worker_input}) + write_doc("%s/%s.json" % (WORKER_INPUT_DIR, domain_id), wi_text) + worker_input_sizes[domain_id] = len(wi_text) + shared_universe_text = canonical({ + "schema_version": "task_c_bo_shared_source_universe.v1", + "source_kinds": list(SHARED_UNIVERSE_KINDS), + "count": len(shared_universe or []), + "source_universe": shared_universe or []}) + write_doc(SHARED_UNIVERSE_PATH, shared_universe_text) + # preflight 한도 대조. 정적 3종(공유 우주·어휘·카탈로그) + 동적 2종(조립 프롬프트·worker 입력)의 도메인별 합계. + static_sizes = {SHARED_UNIVERSE_PATH: len(shared_universe_text), + SHARED_VOCAB_PATH: len(vocabulary_text), + CATALOG_PATH: len(catalog_text)} + # worker 가 component_id 어휘로 쓰는 배포 자산. 도구 없는 호출이라 정적 preflight 로 실어야 한다(검증 지적). + try: + static_sizes[COMPONENT_UNION] = len(read_raw(COMPONENT_UNION)) + except Exception as exc: + warn("COMPONENT_UNION_ABSENT", "%s: %s" % (COMPONENT_UNION, exc)) + preflight_report = {"static": static_sizes, "per_domain_total": {}, "limit_file": PREFLIGHT_FILE_LIMIT_CHARS, + "limit_total": PREFLIGHT_TOTAL_LIMIT_CHARS} + _over = [] + for _p, _n in static_sizes.items(): + if _n > PREFLIGHT_FILE_LIMIT_CHARS: + _over.append({"path": _p, "chars": _n}) + elif _n > PREFLIGHT_FILE_LIMIT_CHARS * 0.9: + warn("PREFLIGHT_FILE_NEAR_LIMIT", "%s: %d" % (_p, _n)) + for domain_id, _wi in worker_input_sizes.items(): + _cp = int((prompt_manifests.get(domain_id) or {}).get("_chars") or 0) + for _p, _n in (("%s/%s.json" % (WORKER_INPUT_DIR, domain_id), _wi), + ("%s/%s.md" % (PROMPT_DIR, domain_id), _cp)): + if _n > PREFLIGHT_FILE_LIMIT_CHARS: + _over.append({"path": _p, "chars": _n}) + elif _n > PREFLIGHT_FILE_LIMIT_CHARS * 0.9: + warn("PREFLIGHT_FILE_NEAR_LIMIT", "%s: %d" % (_p, _n)) + _total = sum(static_sizes.values()) + _wi + _cp + preflight_report["per_domain_total"][domain_id] = _total + if _total > PREFLIGHT_TOTAL_LIMIT_CHARS: + _over.append({"path": "total:%s" % domain_id, "chars": _total}) + elif _total > PREFLIGHT_TOTAL_LIMIT_CHARS * 0.9: + warn("PREFLIGHT_TOTAL_NEAR_LIMIT", "%s: %d" % (domain_id, _total)) + if _over: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_PREFLIGHT_LIMIT_EXCEEDED", + "message": "worker preflight 파일이 백엔드 한도를 넘는다. 넘는 파일은 조용히 건너뛰어져 캐시 경계와 입력이 함께 깨진다.", + "over": _over, "report": preflight_report}, ensure_ascii=False)) + worker_inputs_receipt = { + "shared_source_universe_path": SHARED_UNIVERSE_PATH, + "shared_source_universe_sha256": shared_universe_sha, + "shared_vocabulary_path": SHARED_VOCAB_PATH, + "worker_input_dir": WORKER_INPUT_DIR, + "worker_input_chars": worker_input_sizes, + "preflight": preflight_report, + "equivalence_checked": sorted(worker_input_sizes), + } + + plan = domain_fanout_planner.build_fanout_plan( + manifest, registry, + activation_manifest_sha256=seal["activation_manifest_sha256"], + slice_dir=SLICE_DIR, seed_output_dir=SEED_DIR, + fanout_schema=fanout_schema) + plan_root = plan.get("domain_fanout_plan", plan) + + # barrier 기대 집합은 expected_runnable_domain_ids 다. active_domain_ids 가 아니다. + planned = sorted({row.get("domain_id") + for row in plan_root.get("task_instances") or []}) + if planned != expected_runnable: + raise RuntimeError("A0_FANOUT_SET_MISMATCH") + + write_doc(FANOUT_PATH, canonical(plan)) + + # P-2 — stage_a_context 와 원천 우주 매니페스트는 R0·F0·S0 의 소비 계약이다. + # v3 의 세 builder 를 그대로 이식한 모듈이 만든다. 여기서 모양을 짓지 않는다. + # 계산은 P-2a 에서 이미 끝났다(slice 가 같은 식별자를 써야 하므로 앞당겼다). 여기서는 기록만 한다. + write_doc(STAGE_A_PATH, canonical({"stage_a_context": stage_a})) + write_doc(SOURCE_MANIFEST_PATH, canonical(source_manifest)) + # P-13 — 판정 7. compile_domain_slices 의 반환에는 검증 수행 여부 필드가 없다. + # 스키마를 안 넘겨도 같은 모양의 성공이 돌아오므로 산출물만으로는 "통과"와 + # "안 함"을 가를 수 없다. 그래서 넘긴 사실과 대상 수를 여기에 적어 둔다. + write_doc(RECEIPT_PATH, canonical({ + "schema_version": "stage1_stage_receipt.v2", + "stage": "P2-A0", + "loader_mode": "registry_modules", + "worker_mode": "template_fanout", + "activation_source": "sg01_manifest", + "slice_sha256_by_domain": slice_hashes, + "value_facts_binding": dict(catalog["binding"], catalog_path=CATALOG_PATH), + "worker_inputs": worker_inputs_receipt, + "schema_injection": { + "slice_schema_path": SLICE_SCHEMA, + "slice_schema_sha256": sha_text(read_raw(SLICE_SCHEMA)), + "slice_schema_argument": "slice_schema", + "fanout_schema_path": FANOUT_SCHEMA, + "fanout_schema_sha256": sha_text(read_raw(FANOUT_SCHEMA)), + "fanout_schema_argument": "fanout_schema", + "validated_slice_count": len(slice_hashes), + "validated_fanout_instance_count": len(plan_root.get("task_instances") or []), + "domain_declarations_projected": sorted( + (result.get("slices") or {}).keys()), + "screening_calculation_domains": screening_calc, + "vocabulary_shared_path": SHARED_VOCAB_PATH, + "vocabulary_present": vocabulary_text != "VOCABULARY_ABSENT\n", + "keyword_support_checker": "validation_assets/routing/_check_schema_keyword_support.py", + "note": "넘김이 곧 검증은 아니다. 대상 수가 0 이면 검증도 0 회다.", + }, + "deployment_gate": { + "checked_count": len(set(list(MODULE_MIRRORS.values()) + list(PART2_REQUIRED_ASSETS))), + "runtime_manifest_sha256": sha_text(read_raw(RUNTIME_MANIFEST)), + "runtime_artifact_count": gate_manifest.get("runtime_artifact_count"), + "schema_capability_checked": ["domain_declarations", "compiled_prompt.hash_kind"], + "compiler_output_checked": True, + "overlay_codes_enforced": list(OVERLAY_ERROR_CODES), + "note": "무엇을 봤는지 적는다. 상수 PASS 는 증거가 아니다.", + }, + "created_by": TASK_NAME, + })) + + return {"status": "READY" if catalog["binding"]["status"] == "BOUND" else "READY_WITH_REVIEW", + "written": True, + "modules": staged_modules, + "expected_runnable_domain_ids": expected_runnable, + "slice_count": len(slice_hashes), + "fanout_instance_count": len(plan_root.get("task_instances") or []), + # 2026-11-03 — fan-out 부모는 Task_C_B_domain_load_fanout 이다. 그 task 가 계획 파일을 읽어 + # dynamic_fanout 을 내므로 여기서는 내지 않는다(내도 wildcard 자식이 없어 무시된다). + "digest_guard": seal, + "worker_inputs": worker_inputs_receipt, + "value_facts_binding": catalog["binding"]["status"], + "errors": ERRORS, "warnings": WARNINGS} + + + _sink = io.StringIO() + with contextlib.redirect_stdout(_sink): + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_B_domain_prewarm + description: worker 공통 prefix(system · 첫 user 프롬프트 · 정적 preflight 3종)를 무출력으로 캐시에 쓴다. 출력은 쓰지 않는다. + # 2026-11-03 캐시 — 아래 설정과 첫 user 프롬프트는 Task_C_B_domain_worker_* 와 바이트 단위로 같아야 한다(앵커 금지). + # 동적 preflight 와 둘째 user 메시지만 없다. prewarm: true 라 모델 출력이 없다. 실패해도 worker 는 돈다(비용만 는다). + max_iterations: 1 + expose_tools: false + preflight: true + llm_result_envelope: true + preflight_files: + - Default_Agent/routing/evidence_component_union.md + - runtime/shared/source_universe.json + - runtime/shared/vocabulary.md + - stage1_tmp/task_c_bo/value_facts_catalog.json + llm_provider: openai + llm_model: 'gpt-6.1-sol' + llm_endpoint: responses + llm_reasoning: medium + llm_verbosity: low + llm_prompt_cache_key: S1P2:domain_worker + use_tools: + - localdocs + cache_control: + mode: explicit + ttl: 30m + breakpoints: + - prefix + prewarm: true + prompts: + - role: user + content: |- + + Task_C_B_domain_worker + + You are an MCP-enabled LLM agent assisting plaintiff-side Korean civil/commercial + litigation counsel. Your role in this task is a **per-domain BO seed worker** within + the Stage 1 Part 2 dynamic fan-out. + + + 본 task 는 오케스트레이터가 둘째 메시지 `` 로 주입한 단일 도메인 + `domain_id` 하나만 처리한다. 다른 도메인의 사실을 자기 산출에 넣지 않는다. + 읽어야 할 것은 preflight 로 이미 실린 여섯 파일뿐이다 — 증거 구성요소 합집합 `Default_Agent/routing/evidence_component_union.md`, + 공유 출처 우주 `runtime/shared/source_universe.json`, + 공유 어휘 사전 `runtime/shared/vocabulary.md`, 회차 금액 카탈로그 `stage1_tmp/task_c_bo/value_facts_catalog.json`, + 이 도메인의 조립 프롬프트 `runtime/compiled_prompts/.md`, 이 도메인의 worker 입력 `runtime/worker_inputs/.json`. + 프롬프트를 다시 조립하지 않는다. + + + + + + - `Default_Agent/routing/evidence_component_union.md` (증거 구성요소 component_id 합집합. preflight 로 이미 실려 있다) + - `runtime/shared/source_universe.json` (전 도메인 공통 출처 우주. 최상위 키 source_universe. preflight 로 이미 실려 있다) + - `runtime/shared/vocabulary.md` (후보 어휘 사전. 조립 프롬프트의 rank 20 의존층과 같은 구속력이다. + 본문이 `VOCABULARY_ABSENT` 한 줄이면 사전이 없는 회차다 — 어휘를 추측하지 말고 review_items 에 `VOCABULARY_ABSENT` 를 남긴다) + - `stage1_tmp/task_c_bo/value_facts_catalog.json` (금액 정본 카탈로그. preflight 로 이미 실려 있다) + - `runtime/compiled_prompts/.md` (이 도메인의 조립 프롬프트. 어휘 사전은 위 공유 파일로 분리되어 있다) + - `runtime/worker_inputs/.json` (이 도메인의 worker 입력. 최상위 키 stage_b_domain_worker_input. + slice 에서 공통 출처 우주를 뺀 나머지이며, 도메인 고유 출처는 `source_universe_domain_extra` 에 있다) + + + - 응답 본문에 낸 `stage_b_domain_bo_seed_output` JSON 객체 하나. 파일은 쓰지 않는다(다음 단계의 코드가 저장한다) + + + - 다른 도메인의 worker 입력이나 seed 를 읽지 않는다. + - 프롬프트를 재조립하지 않는다. 조각을 다시 이어 붙이지 않는다. + - 최종 청구권을 고르지 않는다. 최종 요건충족을 판단하지 않는다. + - BO 식별자를 확정하지 않는다. BO_ID · Evidence · EvidenceTitles 키를 쓰지 않는다. + - 출처 우주(공유 `source_universe` 와 worker 입력의 `source_universe_domain_extra` 의 합집합) 밖 출처를 인용하지 않는다. + - amount_facts·payload·action_summary 에 금액·가액 숫자를 적지 않는다. 금액은 카탈로그의 value_id 로만 가리킨다. + 증거 `excerpt` 의 원문 인용은 숫자가 있어도 그대로 둔다. + + + + + - 조립 프롬프트는 rank 10(공통 계약) → 20(의존 공통층) → 30(도메인 overlay) + → 40(특별법 overlay) → 50(실행 가드) 순으로 이미 합성되어 있다. + - 그 본문이 이 task 의 실질 지시다. 본 래퍼는 입출력 계약만 규정한다. + - 어휘 사전(rank 20 의존층)은 조립 프롬프트에서 분리되어 공유 파일 `runtime/shared/vocabulary.md` 로 실린다. + 같은 순위·같은 구속력으로 읽는다. + - 프롬프트와 worker 입력이 어긋나 보이면 임의로 고르지 말고 review_items 에 남긴다. + + + + - 모든 근거는 출처 우주 안에 있어야 한다. 출처 우주 = 공유 파일의 `source_universe[*].source_id` + ∪ worker 입력의 `source_universe_domain_extra[*].source_id`. + - 증거 구성요소 이름은 `Default_Agent/routing/evidence_component_union.md` 의 + component_id 만 쓴다. 목록에 없는 이름을 만들지 않는다(P0 판정 A·B). + - 인용한 component_id 는 각 후보의 `registry_component_ids` 배열에 싣는다. + 그 배열이 비어 있지 않은 후보는 R0 에서 증거 유래로 인정된다. + - 붙일 근거가 출처 우주 안에서 직접 읽히지 않으면 비워 두고 review 로 남긴다. + - 상담 조항 id(`MTG.`로 시작하는 id, `1-가`처럼 숫자로 시작하는 id, `:<번호>` 형태)는 + 출처 우주 목록에 보이더라도 `source_refs`·`source_id`에 쓰지 않는다. 공유 어휘 사전 USAGE의 + "`source_refs` 는 아래 SOURCE_UNITS 목록의 값만 쓴다"는 Part 1 스크리닝용 문구이므로 이 task에서는 따르지 않는다. + 조항 내용이 판단에 필요하면 `review_items[].reason` 문장에 말로 적고(`reason` 키는 review_items 에만 있다), + `source_refs`에는 증거 index와 사건 후보 id만 적는다. + - 후보가 출처 우주의 특정 사건 후보(`source_kind: event_candidate`, `EVT-NNN-NN`)에서 나왔으면 + 그 사건 후보 id 를 `source_refs` 에 증거 index 와 함께 적는다. 요건·반대 사실 행도 사건 후보에서 읽었으면 + `source_kind: event_candidate` 와 그 id 로 적는다. 사건 후보가 없는 문서 근거만 있으면 증거 index 만 적는다. + - 예외는 하나다. `amount_facts[].source_refs` 에는 증거 index 대신 카탈로그 value_id 하나를 적는다. + + + + 금액의 정본은 Part 1 이 gate 로 검증한 `value_facts` 다. 카탈로그 `records[]` 한 행이 레코드 하나다. + - `amount_facts[]` 원소: {"amount_type": "<이 BO에서 그 금액의 역할, 소문자_스네이크>", "decimal_value": null, + "currency": null, "source_refs": ["<카탈로그 value_id 하나>"]}. 숫자와 통화는 R0 가 정본에서 채운다. + - value_id 를 쓰는 자리는 `amount_facts[].source_refs` 하나뿐이다. 후보 `source_refs`, 세 후보 배열의 + `source_id`, `review_items`, `legal_effect_candidates`, `evidence_slot_status`, `calculation_requests` 에는 + 증거 index 를 쓴다. + - 요건사실·반대사실·항변이 금액을 가리킬 때는 그 원소의 `payload.value_id` 에 적는다. payload 에 숫자를 옮기지 + 않고, payload 안에서 `source_id`·`source_refs` 라는 키 이름을 쓰지 않는다. + - `extensions.domain_payload.action_summary` 에 금액 숫자를 쓰지 않는다. + - 카탈로그에 맞는 레코드가 없으면 amount_facts 를 만들지 않는다. 대신 `review_items` 에 + {"review_code": "AMOUNT_NOT_IN_VALUE_FACTS", "severity": "review", "reason": "<어떤 금액이 없는지>", "source_refs": [<증거 index>]} + 를 남긴다. 다른 출처의 숫자로 메우지 않는다. + - 카탈로그 `binding.status` 가 BOUND 가 아니면 `records` 가 비어 있다. 그때는 amount_facts 를 모두 비우고 + AMOUNT_NOT_IN_VALUE_FACTS 도 남기지 않는다(결속 실패 review 는 R0 가 남긴다). + - 레코드는 자기 출처 우주에 있는 증거의 것을 고른다. + + + + 최상위는 `stage_b_domain_bo_seed_output` 한 키다. 스키마는 + `Default_Agent/platform/schemas/domain_seed_output.schema.v3.json` 이며 + `schema_version` 은 `task_c_bo_stage_b_domain_bo_seed.v3` 로 고정이다. + + { + "stage_b_domain_bo_seed_output": { + "schema_version": "task_c_bo_stage_b_domain_bo_seed.v3", + "status": "READY", + "task_instance_id": "", + "domain_id": "", + "registry_version": "", + "registry_index_sha256": "", + "domain_config_sha256": "", + "slice_sha256": "", + "compiled_prompt_sha256": "", + "bo_seed_candidates": [ + { + "seed_id": "<도메인슬러그-001 꼴>", + "bo_type": "", + "juristic_act_type": "<법률행위 유형 문자열 또는 null>", + "source_refs": [], + "registry_component_ids": [], + "element_fact_candidates": [], + "opposing_fact_candidates": [], + "defense_candidates": [], + "evidence_slot_status": [], + "calculation_requests": [], + "dependency_refs": [], + "legal_effect_candidates": [], + "party_roles": [], + "time_facts": [], + "object_refs": [], + "amount_facts": [], + "review_items": [], + "extensions": {"domain_payload": {"action_summary": null, "action_type": null}} + } + ], + "unknown_or_unrouted_reviews": [], + "completion_receipt": {}, + "contract_guards": { + "final_conclusion_forbidden": true, + "unknown_values_require_review": true, + "source_membership_required": true, + "strict_json_output": true + } + } + } + + 추가 제약 + - 다섯 배열(element_fact_candidates · opposing_fact_candidates · defense_candidates + · calculation_requests · dependency_refs)의 이름은 스키마가 정한 것이다. 바꾸지 않는다. + - `dependency_refs` 는 연결만 남긴다. 의존 도메인의 결론을 복사하지 않는다. + 원소는 도메인 id 문자열 하나다(예: "X2", "E-03". 증거 번호 `E-001` 같은 세 자리 값이 아니다). 객체나 근거 목록을 넣지 않는다. + - 후보를 만들 수 없으면 빈 배열로 두고 review_items 에 사유를 남긴다. + 억지로 채우는 것이 비워 두는 것보다 나쁘다. 단 `legal_effect_candidates` 는 공통 계약의 유형 규칙을 따른다. + - 아래 자리들은 BO 호환면 투영(`bo_surface_projection_policy.v1`)이 읽는 1순위 출처다. + 비워 두면 BO.json 의 해당 칸이 폴백 값으로 채워지고 schema_field_fallback 검토가 발행된다. + 출처 우주 안에 근거가 있으면 채운다. 근거가 없으면 비워 두고 사유를 남긴다 — + 추측으로 채우지 않는다. 사건종류 이름을 값으로 쓰지 않는다. + · `juristic_act_type` : 법률행위 유형 문자열 1개(없으면 null). -> JuristicAct.label + · `extensions.domain_payload.action_summary` : 이 후보가 무엇인지 한 문장. -> Action + · `extensions.domain_payload.action_type` : "법률행위(legal acts)" 또는 "사실행위(factual acts)". -> ActionType + · `legal_effect_candidates[]` : {"type_id": "<소문자_스네이크>", "source_refs": [], "registered": true|false, "review_code": null}. -> Legal_Keywords + (유형 규칙은 공통 계약을 따른다. 맞는 유형이 없어도 후보를 버리지 않고 registered:false 로 남긴다) + · `time_facts[]` : {"fact_type": "<소문자_스네이크>", "value": "<시점 문자열 또는 null>", "source_refs": []}. -> BehaviorTime · TimeText + · `object_refs[]` : 목적물 식별자 문자열. -> core_field_base.Object + 영문 식별자(`^[A-Za-z][A-Za-z0-9_.:/-]*$`)만 쓴다. + · `amount_facts[]` : {"amount_type": "<소문자_스네이크>", "decimal_value": null, "currency": null, "source_refs": ["<카탈로그 value_id 하나>"]}. -> amount + (숫자는 R0 가 정본에서 채운다. 를 따른다) + · `party_roles[]` : {"role": "<소문자_스네이크>", "party_refs": []}. 투영 대상은 아니나 스키마 필드다. + `party_refs` 도 `object_refs` 와 같이 영문 식별자만 쓴다. 출처 우주에는 당사자·목적물 전용 영문 id 가 없으므로 + 이 두 배열은 대개 빈 배열이며, 비운 것에 review_items 를 만들지 않는다. 영문 id 를 지어내지 않는다. `slot_id`·`registry_ref_hint`·증거 번호를 옮겨 쓰지 않고, + 금액 카탈로그의 `parties[].party_ref` 는 이름이므로 옮기지 않는다. 당사자 이름과 목적물 설명은 + `element_fact_candidates[].excerpt` 에 적는다(검토가 필요한 경우에만 `review_items[].reason`). + - `slice_sha256` 와 `compiled_prompt_sha256` 은 `` 가 준 값을 **글자 그대로** 옮기는 자리다. + worker 입력 본문을 뒤져 비슷한 이름을 찾지 않는다. worker 입력에서 읽어 오는 sha 는 + `domain_registry` 의 `registry_index_sha256` 과 `domain_config_sha256` 둘뿐이다 + (worker 입력의 `slice_sha256`·`shared_source_universe.sha256` 도 옮기지 않는다 — 값은 RUNTIME_PARAMETERS 에서만). + 특히 `activation.activation_manifest_sha256` 은 전 도메인이 같은 값이라 혼동하기 쉽다 — + 그것을 집으면 R0 가 전사 실수로 기록하고 이 산출에 검토 표시를 남긴다. + 다른 도메인의 sha 를 집으면 "남의 자료로 작업했다"로 판정되어 회차가 중단된다. + 그 둘 어디에도 해당하지 않는 값(어디서 왔는지 설명되지 않는 sha)을 적으면 + 더 무겁게 다뤄져 이 후보가 격리된다. 값을 지어내는 것이 가장 나쁘다. + - 아래 다섯 어휘는 스키마가 고정한 것이다. 다른 낱말을 쓰지 않는다. + · seed 최상위 `status` : READY | READY_WITH_REVIEW | NO_SUPPORT | BLOCKED | FAILED + · `evidence_slot_status[].status` : filled | partial | missing | conflicted + (요건 슬롯을 뒷받침하는 근거가 충분하면 filled, 일부만이면 partial, + 없으면 missing, 상충 근거가 함께 있으면 conflicted) + · `calculation_requests[].completeness` : ready | partial | blocked | deferred + · `review_items[].severity` 와 `unknown_or_unrouted_reviews[].severity` : info | review | hard_warning | block + · 세 후보 배열의 `source_kind` : meeting_clause | event_candidate | evidence | bo | fact + | signal | registry | law_version | calculation | other + (`law_version`·`registry` 는 스키마 어휘지만 쓰지 않는다) + - 아래 네 객체는 `additionalProperties: false` 다. 적힌 키 말고는 **한 개도** 넣지 않는다. + 필수 키를 빠뜨리거나 임의 키를 더하면 스키마 위반이다. + · `element_fact_candidates[]` · `opposing_fact_candidates[]` · `defense_candidates[]` : + {"source_id": "<출처 우주의 source_id>", "source_kind": "<위 어휘>", + "excerpt": "<선택: 근거 문구>", "payload": {}} + — 필수는 source_id · source_kind 둘이다. `slot_id` 나 `fact` 같은 키는 이 배열에 없다. + 슬롯 판정은 `evidence_slot_status[]` 가 맡는다. + · `evidence_slot_status[]` : + {"slot_id": "<요건 슬롯 id>", "status": "<위 어휘>", "source_refs": [], "review_code": null} + · `calculation_requests[]` : + {"calculation_domain": "", "completeness": "<위 어휘>", + "source_refs": [], "review_code": null} + · `review_items[]` : + {"review_code": "<대문자_스네이크>", "severity": "<위 어휘>", + "reason": "<왜 검토가 필요한지 한 문장>", "source_refs": []} + + + + - 최상위가 `stage_b_domain_bo_seed_output` 한 키인지 점검한다. + - `domain_id` 와 `task_instance_id` 가 주입값과 정확히 같은지 점검한다. + - 모든 `source_refs` 원소가 출처 우주 안에 있는지 점검한다(`amount_facts[].source_refs` 는 카탈로그 value_id 하나). + - `amount_facts[]` 의 `decimal_value`·`currency` 가 null 인지, payload·action_summary 에 금액 숫자가 없는지 점검한다. + - `bo_type` 이 worker 입력의 allowed_legal_effect_bo_types 안에 있는지 점검한다. + - `registry_component_ids` 원소가 합집합 목록 안에 있는지 점검한다. + - 금지 키(BO_ID · Evidence · EvidenceTitles · final_*)가 없는지 점검한다. + + + + - 자기 도메인 밖으로 나가지 않는다. + - 프롬프트를 다시 만들지 않는다. + - 결론을 내리지 않는다. 후보만 남긴다. + - 파일을 쓰지 않는다. 응답 본문에 JSON 객체 하나만 낸다. + + + + 이 블록은 이 실행의 입출력 방식만 정하며, 위의 입출력·도구·완료 문구 지시보다 우선한다. 판단·추출·스키마 규칙은 위 지시와 조립 프롬프트를 그대로 따른다. + - 이 실행에는 도구가 없다. `list_docs`, `read_docs`, `write_file` 등 어떤 도구도 호출하지 않는다. 파일 존재 확인은 건너뛴다. `` 의 자기 점검은 응답을 내기 전에 그대로 수행한다. + - 입력 파일은 이 대화에 미리 읽혀 제공된다. 그 내용을 도구로 읽은 내용과 같은 것으로 취급한다. 내용이 대화에 없는 입력은 입력 누락으로 보고 `FAILED` 를 출력한다. + - `` 의 최상위 객체(`stage_b_domain_bo_seed_output` 키 하나)를 응답 본문으로 출력한다. 저장은 다음 단계의 코드가 한다. + - 응답은 그 JSON 객체 하나뿐이어야 한다. 마크다운 코드 펜스, 설명, 완료 문구를 붙이지 않는다. + - 위 지시가 중단·실패를 보고하게 한 경우에는 JSON 없이 `FAILED: <사유>` 한 줄을 출력한다. + + - task_name: Task_C_B_domain_load_fanout + description: A0 성공과 fan-out 계획 sha 를 대조한 뒤 worker dynamic_fanout 을 낸다. 실패해도 raise 하지 않는다. + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: | + #!/usr/bin/env python3 + # Task_C_B_domain_load_fanout (2026-11-03, 앙상블 §3.4) + # fan-out 부모다. 부모가 raise 하면 wildcard 확장이 없어 all Task_C_B_domain_capture_* 가 영원히 기다린다 + # (Part 1 B1r 교훈). 그래서 어떤 실패도 raise 하지 않고 빈 fan-out + fanout_blocked.json 으로 끝낸다. + # 백엔드는 실패한 부모 뒤 자식도 돌리므로 A0 FAILED 뒤에도 이 task 는 돈다. 지난 회차 계획을 실행하지 않도록 + # {{prev}} 의 A0 반환(written·status)과 계획 파일의 activation_manifest_sha256 을 A0 digest_guard 와 대조한다. + # R0 는 fanout_blocked.json 이 CLEARED 가 아니면 멈춘다. + import itertools + import json + import signal + + import httpx + + TASK_NAME = "Task_C_B_domain_load_fanout" + A0_TASK = "Task_C_BO_A0_context_and_domain_slice_compiler" + FANOUT_PATH = "fanout/domain_fanout_plan.json" + BLOCKED_PATH = "stage1_tmp/task_c_bo/fanout_blocked.json" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=20) + MSG_ID_COUNTER = itertools.count(10) + RESULT = {"status": "BLOCKED_UPSTREAM", "dynamic_fanout": [], "reason": None, "count": 0} + + + def _alarm(signum, frame): + raise TimeoutError("LOAD_FANOUT_TIMEOUT") + + + signal.signal(signal.SIGALRM, _alarm) + signal.alarm(100) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": next_msg_id(), "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_json_doc(path): + p = _call("read_docs", {"doc_names": [path]}) + text = (p["result"].get("content") or [{}])[0].get("text", "") + outer = json.loads(text) + if isinstance(outer, dict) and "results" in outer: + rows = outer.get("results") or [] + if not rows or rows[0].get("error"): + raise RuntimeError("READ_FAILED:%s" % path) + inner = rows[0].get("content") + return json.loads(inner) if isinstance(inner, str) else inner + return outer + + + def write_doc(path, content): + p = _call("write_file", {"path": path, "content": content, "overwrite": True}) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if text.startswith("Error"): + raise RuntimeError("WRITE_FAILED:%s:%s" % (path, text[:200])) + + + def previous_state(raw, parent): + # Part 1 B1c · S2_10 load_fanout 과 같은 관용. 백엔드는 run_code 부모의 stdout JSON 을 dict 로 넣는다(문자열 폴백 유지). + if raw.strip().startswith("{" + "{"): + return {} + prev = json.loads(raw) + row = prev.get(parent, {}) if isinstance(prev, dict) else {} + if isinstance(row, str): + try: + row = json.loads(row) + except Exception: + return {} + if isinstance(row, dict) and "status" not in row and isinstance(row.get("json_output"), dict): + row = row["json_output"] + return row if isinstance(row, dict) else {} + + + def main(): + a0 = previous_state(r"""{{prev}}""", A0_TASK) + if a0.get("written") is not True or a0.get("status") not in ("READY", "READY_WITH_REVIEW"): + RESULT["reason"] = {"code": "A0_NOT_READY", "a0_status": a0.get("status"), "written": a0.get("written"), + "errors": (a0.get("errors") or [])[:5]} + return + expected_sha = ((a0.get("digest_guard") or {}).get("activation_manifest_sha256")) + plan = read_json_doc(FANOUT_PATH) + root = plan.get("domain_fanout_plan", plan) if isinstance(plan, dict) else {} + if not isinstance(expected_sha, str) or root.get("activation_manifest_sha256") != expected_sha: + RESULT["reason"] = {"code": "FANOUT_PLAN_STALE", "expected": expected_sha, + "actual": root.get("activation_manifest_sha256")} + return + rows = [r for r in (root.get("task_instances") or []) if isinstance(r, dict) and r.get("domain_id")] + expected = sorted(a0.get("expected_runnable_domain_ids") or []) + planned = sorted({str(r.get("domain_id")) for r in rows}) + if not rows or (expected and planned != expected): + RESULT["reason"] = {"code": "FANOUT_SET_MISMATCH", "expected": expected, "planned": planned} + return + RESULT.update({"status": "PREPARED", "dynamic_fanout": rows, "count": len(rows), "reason": None, + "activation_manifest_sha256": expected_sha}) + + + try: + _init() + try: + main() + except BaseException as exc: # TimeoutError 포함. raise 하지 않는다. + RESULT.update({"status": "BLOCKED_UPSTREAM", "dynamic_fanout": [], "count": 0, + "reason": {"code": "LOAD_FANOUT_EXCEPTION", "detail": str(exc)[:300]}}) + write_doc(BLOCKED_PATH, json.dumps({ + "status": "CLEARED" if RESULT["status"] == "PREPARED" else "BLOCKED_UPSTREAM", + "reason": RESULT.get("reason"), "count": RESULT.get("count"), "created_by": TASK_NAME}, + ensure_ascii=False, indent=2)) + except BaseException as exc: + RESULT.update({"status": "BLOCKED_UPSTREAM", "dynamic_fanout": [], "count": 0, + "reason": {"code": "LOCALDOCS_UNAVAILABLE", "detail": str(exc)[:300]}}) + signal.alarm(0) + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_B_domain_worker_* + max_concurrency: 8 + # 2026-11-03 캐시 — 도구 없는 1회 호출. 도구는 preflight 읽기에만 쓰고, 응답 봉투는 Task_C_B_domain_capture_* 가 저장한다. + # 첫 user 프롬프트는 Task_C_B_domain_prewarm 과 바이트 단위로 같다({{item.*}} 없음). 인스턴스 값은 둘째 user 메시지. + # 정적 preflight 3종은 백엔드가 이름순으로 첫 user 메시지에 inline 한다(prefix breakpoint 앞). 동적 2종은 그 뒤 [Preflight] 메시지. + max_iterations: 1 + expose_tools: false + preflight: true + llm_result_envelope: true + preflight_files: + - Default_Agent/routing/evidence_component_union.md + - runtime/shared/source_universe.json + - runtime/shared/vocabulary.md + - stage1_tmp/task_c_bo/value_facts_catalog.json + - "{{item.compiled_prompt_path}}" + - "runtime/worker_inputs/{{item.domain_id}}.json" + llm_provider: openai + llm_model: 'gpt-6.1-sol' + llm_endpoint: responses + llm_reasoning: medium + llm_verbosity: low + llm_prompt_cache_key: S1P2:domain_worker + use_tools: + - localdocs + cache_control: + mode: explicit + ttl: 30m + breakpoints: + - prefix + prompts: + - role: user + content: |- + + Task_C_B_domain_worker + + You are an MCP-enabled LLM agent assisting plaintiff-side Korean civil/commercial + litigation counsel. Your role in this task is a **per-domain BO seed worker** within + the Stage 1 Part 2 dynamic fan-out. + + + 본 task 는 오케스트레이터가 둘째 메시지 `` 로 주입한 단일 도메인 + `domain_id` 하나만 처리한다. 다른 도메인의 사실을 자기 산출에 넣지 않는다. + 읽어야 할 것은 preflight 로 이미 실린 여섯 파일뿐이다 — 증거 구성요소 합집합 `Default_Agent/routing/evidence_component_union.md`, + 공유 출처 우주 `runtime/shared/source_universe.json`, + 공유 어휘 사전 `runtime/shared/vocabulary.md`, 회차 금액 카탈로그 `stage1_tmp/task_c_bo/value_facts_catalog.json`, + 이 도메인의 조립 프롬프트 `runtime/compiled_prompts/.md`, 이 도메인의 worker 입력 `runtime/worker_inputs/.json`. + 프롬프트를 다시 조립하지 않는다. + + + + + + - `Default_Agent/routing/evidence_component_union.md` (증거 구성요소 component_id 합집합. preflight 로 이미 실려 있다) + - `runtime/shared/source_universe.json` (전 도메인 공통 출처 우주. 최상위 키 source_universe. preflight 로 이미 실려 있다) + - `runtime/shared/vocabulary.md` (후보 어휘 사전. 조립 프롬프트의 rank 20 의존층과 같은 구속력이다. + 본문이 `VOCABULARY_ABSENT` 한 줄이면 사전이 없는 회차다 — 어휘를 추측하지 말고 review_items 에 `VOCABULARY_ABSENT` 를 남긴다) + - `stage1_tmp/task_c_bo/value_facts_catalog.json` (금액 정본 카탈로그. preflight 로 이미 실려 있다) + - `runtime/compiled_prompts/.md` (이 도메인의 조립 프롬프트. 어휘 사전은 위 공유 파일로 분리되어 있다) + - `runtime/worker_inputs/.json` (이 도메인의 worker 입력. 최상위 키 stage_b_domain_worker_input. + slice 에서 공통 출처 우주를 뺀 나머지이며, 도메인 고유 출처는 `source_universe_domain_extra` 에 있다) + + + - 응답 본문에 낸 `stage_b_domain_bo_seed_output` JSON 객체 하나. 파일은 쓰지 않는다(다음 단계의 코드가 저장한다) + + + - 다른 도메인의 worker 입력이나 seed 를 읽지 않는다. + - 프롬프트를 재조립하지 않는다. 조각을 다시 이어 붙이지 않는다. + - 최종 청구권을 고르지 않는다. 최종 요건충족을 판단하지 않는다. + - BO 식별자를 확정하지 않는다. BO_ID · Evidence · EvidenceTitles 키를 쓰지 않는다. + - 출처 우주(공유 `source_universe` 와 worker 입력의 `source_universe_domain_extra` 의 합집합) 밖 출처를 인용하지 않는다. + - amount_facts·payload·action_summary 에 금액·가액 숫자를 적지 않는다. 금액은 카탈로그의 value_id 로만 가리킨다. + 증거 `excerpt` 의 원문 인용은 숫자가 있어도 그대로 둔다. + + + + + - 조립 프롬프트는 rank 10(공통 계약) → 20(의존 공통층) → 30(도메인 overlay) + → 40(특별법 overlay) → 50(실행 가드) 순으로 이미 합성되어 있다. + - 그 본문이 이 task 의 실질 지시다. 본 래퍼는 입출력 계약만 규정한다. + - 어휘 사전(rank 20 의존층)은 조립 프롬프트에서 분리되어 공유 파일 `runtime/shared/vocabulary.md` 로 실린다. + 같은 순위·같은 구속력으로 읽는다. + - 프롬프트와 worker 입력이 어긋나 보이면 임의로 고르지 말고 review_items 에 남긴다. + + + + - 모든 근거는 출처 우주 안에 있어야 한다. 출처 우주 = 공유 파일의 `source_universe[*].source_id` + ∪ worker 입력의 `source_universe_domain_extra[*].source_id`. + - 증거 구성요소 이름은 `Default_Agent/routing/evidence_component_union.md` 의 + component_id 만 쓴다. 목록에 없는 이름을 만들지 않는다(P0 판정 A·B). + - 인용한 component_id 는 각 후보의 `registry_component_ids` 배열에 싣는다. + 그 배열이 비어 있지 않은 후보는 R0 에서 증거 유래로 인정된다. + - 붙일 근거가 출처 우주 안에서 직접 읽히지 않으면 비워 두고 review 로 남긴다. + - 상담 조항 id(`MTG.`로 시작하는 id, `1-가`처럼 숫자로 시작하는 id, `:<번호>` 형태)는 + 출처 우주 목록에 보이더라도 `source_refs`·`source_id`에 쓰지 않는다. 공유 어휘 사전 USAGE의 + "`source_refs` 는 아래 SOURCE_UNITS 목록의 값만 쓴다"는 Part 1 스크리닝용 문구이므로 이 task에서는 따르지 않는다. + 조항 내용이 판단에 필요하면 `review_items[].reason` 문장에 말로 적고(`reason` 키는 review_items 에만 있다), + `source_refs`에는 증거 index와 사건 후보 id만 적는다. + - 후보가 출처 우주의 특정 사건 후보(`source_kind: event_candidate`, `EVT-NNN-NN`)에서 나왔으면 + 그 사건 후보 id 를 `source_refs` 에 증거 index 와 함께 적는다. 요건·반대 사실 행도 사건 후보에서 읽었으면 + `source_kind: event_candidate` 와 그 id 로 적는다. 사건 후보가 없는 문서 근거만 있으면 증거 index 만 적는다. + - 예외는 하나다. `amount_facts[].source_refs` 에는 증거 index 대신 카탈로그 value_id 하나를 적는다. + + + + 금액의 정본은 Part 1 이 gate 로 검증한 `value_facts` 다. 카탈로그 `records[]` 한 행이 레코드 하나다. + - `amount_facts[]` 원소: {"amount_type": "<이 BO에서 그 금액의 역할, 소문자_스네이크>", "decimal_value": null, + "currency": null, "source_refs": ["<카탈로그 value_id 하나>"]}. 숫자와 통화는 R0 가 정본에서 채운다. + - value_id 를 쓰는 자리는 `amount_facts[].source_refs` 하나뿐이다. 후보 `source_refs`, 세 후보 배열의 + `source_id`, `review_items`, `legal_effect_candidates`, `evidence_slot_status`, `calculation_requests` 에는 + 증거 index 를 쓴다. + - 요건사실·반대사실·항변이 금액을 가리킬 때는 그 원소의 `payload.value_id` 에 적는다. payload 에 숫자를 옮기지 + 않고, payload 안에서 `source_id`·`source_refs` 라는 키 이름을 쓰지 않는다. + - `extensions.domain_payload.action_summary` 에 금액 숫자를 쓰지 않는다. + - 카탈로그에 맞는 레코드가 없으면 amount_facts 를 만들지 않는다. 대신 `review_items` 에 + {"review_code": "AMOUNT_NOT_IN_VALUE_FACTS", "severity": "review", "reason": "<어떤 금액이 없는지>", "source_refs": [<증거 index>]} + 를 남긴다. 다른 출처의 숫자로 메우지 않는다. + - 카탈로그 `binding.status` 가 BOUND 가 아니면 `records` 가 비어 있다. 그때는 amount_facts 를 모두 비우고 + AMOUNT_NOT_IN_VALUE_FACTS 도 남기지 않는다(결속 실패 review 는 R0 가 남긴다). + - 레코드는 자기 출처 우주에 있는 증거의 것을 고른다. + + + + 최상위는 `stage_b_domain_bo_seed_output` 한 키다. 스키마는 + `Default_Agent/platform/schemas/domain_seed_output.schema.v3.json` 이며 + `schema_version` 은 `task_c_bo_stage_b_domain_bo_seed.v3` 로 고정이다. + + { + "stage_b_domain_bo_seed_output": { + "schema_version": "task_c_bo_stage_b_domain_bo_seed.v3", + "status": "READY", + "task_instance_id": "", + "domain_id": "", + "registry_version": "", + "registry_index_sha256": "", + "domain_config_sha256": "", + "slice_sha256": "", + "compiled_prompt_sha256": "", + "bo_seed_candidates": [ + { + "seed_id": "<도메인슬러그-001 꼴>", + "bo_type": "", + "juristic_act_type": "<법률행위 유형 문자열 또는 null>", + "source_refs": [], + "registry_component_ids": [], + "element_fact_candidates": [], + "opposing_fact_candidates": [], + "defense_candidates": [], + "evidence_slot_status": [], + "calculation_requests": [], + "dependency_refs": [], + "legal_effect_candidates": [], + "party_roles": [], + "time_facts": [], + "object_refs": [], + "amount_facts": [], + "review_items": [], + "extensions": {"domain_payload": {"action_summary": null, "action_type": null}} + } + ], + "unknown_or_unrouted_reviews": [], + "completion_receipt": {}, + "contract_guards": { + "final_conclusion_forbidden": true, + "unknown_values_require_review": true, + "source_membership_required": true, + "strict_json_output": true + } + } + } + + 추가 제약 + - 다섯 배열(element_fact_candidates · opposing_fact_candidates · defense_candidates + · calculation_requests · dependency_refs)의 이름은 스키마가 정한 것이다. 바꾸지 않는다. + - `dependency_refs` 는 연결만 남긴다. 의존 도메인의 결론을 복사하지 않는다. + 원소는 도메인 id 문자열 하나다(예: "X2", "E-03". 증거 번호 `E-001` 같은 세 자리 값이 아니다). 객체나 근거 목록을 넣지 않는다. + - 후보를 만들 수 없으면 빈 배열로 두고 review_items 에 사유를 남긴다. + 억지로 채우는 것이 비워 두는 것보다 나쁘다. 단 `legal_effect_candidates` 는 공통 계약의 유형 규칙을 따른다. + - 아래 자리들은 BO 호환면 투영(`bo_surface_projection_policy.v1`)이 읽는 1순위 출처다. + 비워 두면 BO.json 의 해당 칸이 폴백 값으로 채워지고 schema_field_fallback 검토가 발행된다. + 출처 우주 안에 근거가 있으면 채운다. 근거가 없으면 비워 두고 사유를 남긴다 — + 추측으로 채우지 않는다. 사건종류 이름을 값으로 쓰지 않는다. + · `juristic_act_type` : 법률행위 유형 문자열 1개(없으면 null). -> JuristicAct.label + · `extensions.domain_payload.action_summary` : 이 후보가 무엇인지 한 문장. -> Action + · `extensions.domain_payload.action_type` : "법률행위(legal acts)" 또는 "사실행위(factual acts)". -> ActionType + · `legal_effect_candidates[]` : {"type_id": "<소문자_스네이크>", "source_refs": [], "registered": true|false, "review_code": null}. -> Legal_Keywords + (유형 규칙은 공통 계약을 따른다. 맞는 유형이 없어도 후보를 버리지 않고 registered:false 로 남긴다) + · `time_facts[]` : {"fact_type": "<소문자_스네이크>", "value": "<시점 문자열 또는 null>", "source_refs": []}. -> BehaviorTime · TimeText + · `object_refs[]` : 목적물 식별자 문자열. -> core_field_base.Object + 영문 식별자(`^[A-Za-z][A-Za-z0-9_.:/-]*$`)만 쓴다. + · `amount_facts[]` : {"amount_type": "<소문자_스네이크>", "decimal_value": null, "currency": null, "source_refs": ["<카탈로그 value_id 하나>"]}. -> amount + (숫자는 R0 가 정본에서 채운다. 를 따른다) + · `party_roles[]` : {"role": "<소문자_스네이크>", "party_refs": []}. 투영 대상은 아니나 스키마 필드다. + `party_refs` 도 `object_refs` 와 같이 영문 식별자만 쓴다. 출처 우주에는 당사자·목적물 전용 영문 id 가 없으므로 + 이 두 배열은 대개 빈 배열이며, 비운 것에 review_items 를 만들지 않는다. 영문 id 를 지어내지 않는다. `slot_id`·`registry_ref_hint`·증거 번호를 옮겨 쓰지 않고, + 금액 카탈로그의 `parties[].party_ref` 는 이름이므로 옮기지 않는다. 당사자 이름과 목적물 설명은 + `element_fact_candidates[].excerpt` 에 적는다(검토가 필요한 경우에만 `review_items[].reason`). + - `slice_sha256` 와 `compiled_prompt_sha256` 은 `` 가 준 값을 **글자 그대로** 옮기는 자리다. + worker 입력 본문을 뒤져 비슷한 이름을 찾지 않는다. worker 입력에서 읽어 오는 sha 는 + `domain_registry` 의 `registry_index_sha256` 과 `domain_config_sha256` 둘뿐이다 + (worker 입력의 `slice_sha256`·`shared_source_universe.sha256` 도 옮기지 않는다 — 값은 RUNTIME_PARAMETERS 에서만). + 특히 `activation.activation_manifest_sha256` 은 전 도메인이 같은 값이라 혼동하기 쉽다 — + 그것을 집으면 R0 가 전사 실수로 기록하고 이 산출에 검토 표시를 남긴다. + 다른 도메인의 sha 를 집으면 "남의 자료로 작업했다"로 판정되어 회차가 중단된다. + 그 둘 어디에도 해당하지 않는 값(어디서 왔는지 설명되지 않는 sha)을 적으면 + 더 무겁게 다뤄져 이 후보가 격리된다. 값을 지어내는 것이 가장 나쁘다. + - 아래 다섯 어휘는 스키마가 고정한 것이다. 다른 낱말을 쓰지 않는다. + · seed 최상위 `status` : READY | READY_WITH_REVIEW | NO_SUPPORT | BLOCKED | FAILED + · `evidence_slot_status[].status` : filled | partial | missing | conflicted + (요건 슬롯을 뒷받침하는 근거가 충분하면 filled, 일부만이면 partial, + 없으면 missing, 상충 근거가 함께 있으면 conflicted) + · `calculation_requests[].completeness` : ready | partial | blocked | deferred + · `review_items[].severity` 와 `unknown_or_unrouted_reviews[].severity` : info | review | hard_warning | block + · 세 후보 배열의 `source_kind` : meeting_clause | event_candidate | evidence | bo | fact + | signal | registry | law_version | calculation | other + (`law_version`·`registry` 는 스키마 어휘지만 쓰지 않는다) + - 아래 네 객체는 `additionalProperties: false` 다. 적힌 키 말고는 **한 개도** 넣지 않는다. + 필수 키를 빠뜨리거나 임의 키를 더하면 스키마 위반이다. + · `element_fact_candidates[]` · `opposing_fact_candidates[]` · `defense_candidates[]` : + {"source_id": "<출처 우주의 source_id>", "source_kind": "<위 어휘>", + "excerpt": "<선택: 근거 문구>", "payload": {}} + — 필수는 source_id · source_kind 둘이다. `slot_id` 나 `fact` 같은 키는 이 배열에 없다. + 슬롯 판정은 `evidence_slot_status[]` 가 맡는다. + · `evidence_slot_status[]` : + {"slot_id": "<요건 슬롯 id>", "status": "<위 어휘>", "source_refs": [], "review_code": null} + · `calculation_requests[]` : + {"calculation_domain": "", "completeness": "<위 어휘>", + "source_refs": [], "review_code": null} + · `review_items[]` : + {"review_code": "<대문자_스네이크>", "severity": "<위 어휘>", + "reason": "<왜 검토가 필요한지 한 문장>", "source_refs": []} + + + + - 최상위가 `stage_b_domain_bo_seed_output` 한 키인지 점검한다. + - `domain_id` 와 `task_instance_id` 가 주입값과 정확히 같은지 점검한다. + - 모든 `source_refs` 원소가 출처 우주 안에 있는지 점검한다(`amount_facts[].source_refs` 는 카탈로그 value_id 하나). + - `amount_facts[]` 의 `decimal_value`·`currency` 가 null 인지, payload·action_summary 에 금액 숫자가 없는지 점검한다. + - `bo_type` 이 worker 입력의 allowed_legal_effect_bo_types 안에 있는지 점검한다. + - `registry_component_ids` 원소가 합집합 목록 안에 있는지 점검한다. + - 금지 키(BO_ID · Evidence · EvidenceTitles · final_*)가 없는지 점검한다. + + + + - 자기 도메인 밖으로 나가지 않는다. + - 프롬프트를 다시 만들지 않는다. + - 결론을 내리지 않는다. 후보만 남긴다. + - 파일을 쓰지 않는다. 응답 본문에 JSON 객체 하나만 낸다. + + + + 이 블록은 이 실행의 입출력 방식만 정하며, 위의 입출력·도구·완료 문구 지시보다 우선한다. 판단·추출·스키마 규칙은 위 지시와 조립 프롬프트를 그대로 따른다. + - 이 실행에는 도구가 없다. `list_docs`, `read_docs`, `write_file` 등 어떤 도구도 호출하지 않는다. 파일 존재 확인은 건너뛴다. `` 의 자기 점검은 응답을 내기 전에 그대로 수행한다. + - 입력 파일은 이 대화에 미리 읽혀 제공된다. 그 내용을 도구로 읽은 내용과 같은 것으로 취급한다. 내용이 대화에 없는 입력은 입력 누락으로 보고 `FAILED` 를 출력한다. + - `` 의 최상위 객체(`stage_b_domain_bo_seed_output` 키 하나)를 응답 본문으로 출력한다. 저장은 다음 단계의 코드가 한다. + - 응답은 그 JSON 객체 하나뿐이어야 한다. 마크다운 코드 펜스, 설명, 완료 문구를 붙이지 않는다. + - 위 지시가 중단·실패를 보고하게 한 경우에는 JSON 없이 `FAILED: <사유>` 한 줄을 출력한다. + + - role: user + content: |- + + domain_id: {{item.domain_id}} + task_instance_id: {{item.task_instance_id}} + slice_sha256: {{item.slice_sha256}} + compiled_prompt_sha256: {{item.compiled_prompt_sha256}} + + 응답은 stage_b_domain_bo_seed_output JSON 객체 하나뿐이다. 위 네 값은 글자 그대로 옮긴다. + - task_name: Task_C_B_domain_capture_* + description: 같은 ordinal 의 worker 응답 봉투의 JSON 을 expected_output_path 에 그대로 저장. 값을 고치지 않는다. + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: | + #!/usr/bin/env python3 + # Task_C_B_domain_capture (2026-11-03, Part 1 Task_B1c_map_doc_capture 복제) + # 같은 ordinal 의 Task_C_B_domain_worker_ 응답 봉투(llm_result_envelope)에서 JSON 객체를 꺼내 + # LLM 이 직접 쓰던 경로에 그대로 쓴다. 내용 검사는 하류 작업이 한다(V1c 와 같은 역할 분리). + # 응답이 불완전하거나 JSON 객체가 아니면 비JSON 표식을 쓴다. 지난 실행의 파일이 남아 + # 하류를 통과하지 못하게 하고, 하류가 그 파일을 읽기 실패로 보고하게 한다. + # LLM 응답 문제로는 raise 하지 않는다. 쓰기 실패만 raise 해서 백엔드 재시도를 받는다. + TASK_NAME = "Task_C_B_domain_capture" + import itertools + import json + import re + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # Task_V1c_value_facts_capture_* 와 같은 보일러플레이트다. write_doc 에만 오류 검사를 더했다. + # -------------------------------------------------------------------------- + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def write_doc(path, content): + # localdocs 는 실패도 정상 응답 본문의 "Error: ..." 로 돌려준다. + p = _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if text.startswith("Error"): + raise RuntimeError("WRITE_FAILED:%s:%s" % (path, text[:200])) + + + class CaptureError(Exception): + def __init__(self, code, detail=""): + super().__init__("%s:%s" % (code, detail)) + self.code = code + self.detail = detail + + + def parse_model(env): + # Task_V2_value_facts_gate_merger 의 parse_model 을 따르되 본문 우선이고, SKILL.md 6.7·12.3 의 허용을 더했다. + status = str(env.get("status", env.get("finish_reason", "UNKNOWN"))).lower() + if status not in {"completed", "success", "ok", "stop"}: + raise CaptureError("MODEL_INCOMPLETE", status) + finish = str(env.get("finish_reason") or "").lower() + if finish in {"length", "max_tokens", "max_output_tokens"}: + raise CaptureError("MODEL_INCOMPLETE", finish) + # json_output 은 쓰지 않는다. 백엔드가 깨진 본문에서 첫 중첩 객체를 뽑아 넣을 수 있어, + # 잘린 응답의 조각이 정상 part 로 저장된다. 본문 전체만 믿는다. + raw = env.get("content") if env.get("content") is not None else env.get("output") + if isinstance(raw, dict): + return raw + if raw is None or (isinstance(raw, str) and not raw.strip()): + raise CaptureError("MODEL_OUTPUT_MISSING") + if not isinstance(raw, str): + raise CaptureError("MODEL_NOT_JSON_OBJECT", str(raw)[:200]) + s = raw.strip() + if not s.startswith("{"): + m = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", s) + if not m: + raise CaptureError("MODEL_NOT_JSON_OBJECT", s[:200]) + s = m.group(1) + try: + obj, _ = json.JSONDecoder(strict=False).raw_decode(s) + except json.JSONDecodeError as exc: + raise CaptureError("MODEL_PARSE_FAILED", str(exc)[:200]) + if not isinstance(obj, dict): + raise CaptureError("MODEL_NOT_JSON_OBJECT", s[:200]) + return obj + + + def extract(prev_text, llm_task): + try: + prev = json.loads(prev_text) + except Exception as exc: + raise CaptureError("PREV_PARSE_FAILED", str(exc)[:200]) + env = prev.get(llm_task) if isinstance(prev, dict) else None + if isinstance(env, str): + try: + env = json.loads(env) + except Exception: + env = {"content": env, "json_output": None, "status": "UNKNOWN"} + if not isinstance(env, dict): + raise CaptureError("MISSING_TASK_OUTPUT", llm_task) + return parse_model(env), env.get("status") + + ITEM = json.loads(r"""{{item_json}}""") + ORDINAL = int(r"""{{ordinal}}""") + LLM_TASK = "Task_C_B_domain_worker_%d" % ORDINAL + OUTPUT_PATH = ITEM["expected_output_path"] + RESULT = {"status": "CAPTURED", "output_path": OUTPUT_PATH, "llm_task": LLM_TASK} + try: + OBJ, RESULT["llm_status"] = extract(r"""{{prev}}""", LLM_TASK) + CONTENT = json.dumps(OBJ, ensure_ascii=False, indent=2) + # echo 대조는 기록만 한다. 파일은 고치지 않는다 — R0 의 SEED_ECHO_* 판정이 worker 가 어느 자료로 작업했는지를 + # 이 값으로 가린다. 여기서 덮으면 그 방어선이 사라진다. + _seed = OBJ.get("stage_b_domain_bo_seed_output") if isinstance(OBJ, dict) else None + if isinstance(_seed, dict): + RESULT["echo_mismatch"] = sorted( + k for k in ("domain_id", "task_instance_id", "slice_sha256", "compiled_prompt_sha256") + if str(_seed.get(k)) != str(ITEM.get(k))) + else: + RESULT["echo_mismatch"] = ["stage_b_domain_bo_seed_output"] + except CaptureError as exc: + CONTENT = "CAPTURE_FAILED %s: %s\n" % (exc.code, exc.detail) + RESULT.update({"status": "CAPTURE_FAILED", "code": exc.code, "detail": exc.detail}) + _init() + write_doc(OUTPUT_PATH, CONTENT) + RESULT["chars"] = len(CONTENT) + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_BO_R0_seed_reducer_and_exception_planner + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: httpx + network: agent-network + timeout: 240 + code: |- + #!/usr/bin/env python3 + # Task_C_BO_R0_seed_reducer_and_exception_planner (v3) + # publisher + domain_join + PostB_1 통합 결정적 reducer. + # Spec: Part_2_Improvement_Strategy_Claude_v1.md §7 (defer policy = 개선전략서 X-2, pack 조건 = X-3) + from __future__ import annotations + import copy + import hashlib + import itertools + import json + import re + import sys + from typing import Any + import httpx + + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=60) + MSG_ID = itertools.count(10) + JSON_DECODER = json.JSONDecoder() + + # v4 — {{prev.Task_C_BO_Stage_B_B*}} 다섯을 걷어냈다. + # worker 산출은 wildcard fan-out 인스턴스가 파일로 남기므로 경로로 읽는다. + # v4 — seed 목록은 상수가 아니라 A0 의 fan-out 계획이 정한다. + FANOUT_PLAN_PATH = "fanout/domain_fanout_plan.json" + SLICE_DIR = "runtime/domain_slices" + # 2026-11-03 — load_fanout 이 쓰는 상태 파일. CLEARED 가 아니면(없음 포함) 낡은 계획·seed 로 진행하지 않는다. + FANOUT_BLOCKED_PATH = "stage1_tmp/task_c_bo/fanout_blocked.json" + SEED_SCHEMA_PATH = "Default_Agent/platform/schemas/domain_seed_output.schema.v3.json" + # R0-6 — 전체 스키마 검증은 신설이 아니다. worker_output_validator 가 이미 + # schema_subset_validator 로 전 계약을 검사하고 있었고(13도메인 1,151건 실측), + # R0 가 그 결과를 guard_warnings 로 강등하고 있었다. 이 정책은 그 결과에 처분을 준다. + SEED_ADMISSION_POLICY_PATH = "Default_Agent/stage1_runtime/seed_admission_policy.v1.json" + SEED_ADMISSION_SCHEMA_VERSION = "stage1_seed_admission_policy.v1" + SEED_SCHEMA_VERSION = "task_c_bo_stage_b_domain_bo_seed.v3" + SLICE_ROOT_KEY = "stage_b_domain_slice" + # R-4 — 머리말이 약속한 worker_output_validator 를 실제로 부른다. 반입은 D0 규약 R-1~R-5. + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + EXECUTION_ROOT = "/tmp/s1_r0" + VALIDATOR_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "registry_loader": "Default_Agent/stage1_runtime/registry_loader.txt", + "worker_output_validator": "Default_Agent/stage1_runtime/worker_output_validator.txt", + } + + def _seed_docs_from_plan(plan): + # v5 — 경로만이 아니라 계획 행 전체를 보관한다. validate_seed_object 가 + # slice_sha256 · compiled_prompt_sha256 기대값을 이 행에서 대조한다(R0-6). + root = plan.get("domain_fanout_plan", plan) + out = {} + rows = {} + for row in root.get("task_instances") or []: + domain_id = row.get("domain_id") + path = row.get("expected_output_path") + if isinstance(domain_id, str) and isinstance(path, str) and domain_id and path: + out[domain_id] = path + rows[domain_id] = row + if not out: + raise RuntimeError("R0_FANOUT_PLAN_EMPTY") + return out, rows + # v4 — 계획이 정하는 두 목록. 상수가 아니므로 비워 두고 main 에서 내용만 채운다. + # 재바인딩하지 않고 갱신만 하므로 아래 도우미들이 같은 객체를 본다. + SEED_DOCS: dict[str, str] = {} + PLAN_ROWS: dict[str, dict[str, Any]] = {} + DOMAIN_ORDER: list[str] = [] + + # DOMAIN_ORDER 는 fan-out 계획의 등재 순서를 그대로 쓴다. 상수 순서를 두지 않는다. + def _domain_order(seed_docs): + return list(seed_docs.keys()) + # v5 — 구 이름 표(DOMAIN_LABELS)와 _domain_label 을 걷어냈다. 유일 소비처가 되쓰기 + # (R0-5 에서 삭제)의 transport_metadata 였다. 이로써 R0 에 구 명세서(B1~B5) 이름 의존이 없다. + STAGE_A_PATH = "stage1_tmp/task_c_bo/stage_a_context.json" + MANIFEST_PATH = "stage1_tmp/task_c_bo/source_universe_manifest.json" + LEDGER_PATH = "stage1_tmp/task_c_bo/postb_seed_ledger.json" + ADMITTED_SEED_DIR = "stage1_tmp/task_c_bo/admitted_seeds" + PACK_PATH = "quality_gates/stage1_part2_exception_pack.json" + REVIEW_HANDOFF_PATH = "quality_gates/stage1_part2_review_handoff.json" + # 가액금액 정본 결속(2026-10-30, 개정계획서 §3.3). A0 가 쓴 회차 카탈로그만 읽는다. + CATALOG_PATH = "stage1_tmp/task_c_bo/value_facts_catalog.json" + # 참고 형식. 판정은 카탈로그 소속으로 한다(gate_check 가 {seq:03d} 라 1000번째부터 네 자리). + VALUE_ID_RE = re.compile(r"^E-\d{3}-VF-\d{3,}$") + # R0-1 — BO 투영 정책. 투영 규칙의 정본은 코드가 아니라 이 선언 자산이다. + BO_PROJECTION_POLICY = "Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json" + BO_PROJECTION_SCHEMA_VERSION = "stage1_bo_surface_projection_policy.v1" + # v3 계약이 정본이다. 도메인 ID 는 registry 값(E-00 · EC-00 · X1 …)이고 구 이름도 아직 들어올 수 있으므로 + # 접두사는 도메인에 묶지 않고 형식만 본다 — 도메인 일치는 validate_candidate 의 prefix 검사가 맡는다. + CANDIDATE_REF_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,63}:[0-9]{3}$") + REVIEW_ISSUE_ENUM = { + "missing_source", "source_conflict", "cross_domain_merge_needed", + "amount_or_date_uncertain", "legal_effect_uncertain", "review_required", + "legal_theory_required", "near_duplicate_kept_separate", + "meeting_only_evidence_gap", "schema_field_fallback", "prior_link_ambiguous", + } + DOWNSTREAM_OWNER_ENUM = {"publisher", "domain_join", "C0", "C1", "C2", "C3", "C5", "D", "E", "Stage2"} + # v5 — ALLOWED_SEED_KEYS(v2 화이트리스트)를 걷어냈다. v3 후보 18필드와의 교집합이 + # extensions 하나뿐이라 워커 산출을 통째로 버리던 자리다(C-1). 원장 payload 의 + # 키 집합은 project_to_bo_surface 의 반환문이 유일한 정의다. + + def _mid() -> int: + return next(MSG_ID) + + def _init() -> None: + r = CLIENT.post( + LOCALDOCS_URL, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": { + "name": "task-c-bo-r0-seed-reducer-and-exception-planner", + "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}", + }, + }, + }, + headers=MCP_HEADERS, + ) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS, + ).raise_for_status() + + def _parse_mcp(text: str) -> Any: + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + pass + try: + return json.loads(text) + except Exception: + return None + + def _call(name: str, args: dict[str, Any]) -> Any: + r = CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "id": _mid(), "method": "tools/call", + "params": {"name": name, "arguments": args}}, + headers=MCP_HEADERS, + ) + r.raise_for_status() + payload = _parse_mcp(r.text) + if not payload or "result" not in payload: + raise RuntimeError(f"MCP {name} failed") + return payload + + def read_raw(name: str) -> str: + # 재직렬화 없이 원문 그대로 돌려준다. 미러 해시 대조의 전제다. + p = _call("read_docs", {"doc_names": [name]}) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + # ------------------------------------------------------------------ + # F-4 — 자기 입력의 배포 무결성. A0 게이트가 앞에서 걸러 주지만 이 task 는 + # 개별 재실행이 가능하다(예행 하네스가 실제로 task 단위로 돌린다). + # 매니페스트는 task 당 한 번만 읽는다. 호출마다 읽으면 S0 의 $ref 폐포 walk 에서만 19 회다. + # ------------------------------------------------------------------ + PART2_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + _MANIFEST_MAP = None + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART2_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART2_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical: str) -> str: + """원문을 돌려준다. 반환값을 소비해야 읽기 횟수가 늘지 않는다.""" + body = read_raw(logical) + want = _manifest_map().get(logical[len("Default_Agent/"):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != hashlib.sha256(body.encode("utf-8")).hexdigest(): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + def _assert_mirror_consistent(logical: str) -> None: + """F-4b — 부재는 통과(materialize_validator 의 기존 관용 유지). 미등재·불일치만 막는다. + + 예외 종류를 바꿔 try 를 뚫는 우회(SystemExit 등)는 쓰지 않는다. 그것은 __main__ 가드의 + stdout 출력과 예행 하네스의 단계 기록까지 건너뛴다. 판정을 try 밖으로 옮기는 것이 답이다. + """ + try: + body = read_raw(logical) + except Exception: + return + want = _manifest_map().get(logical[len("Default_Agent/"):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != hashlib.sha256(body.encode("utf-8")).hexdigest(): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + + + def materialize_validator() -> list[str]: + """worker_output_validator 와 그 의존 셋을 반입한다. 실패는 경고로 남기고 진행한다. + + 이 검증은 덧붙이는 층이다 — 반입이 안 되는 배포에서도 R0 본체는 돌아야 한다. + """ + import hashlib + import os + import pathlib + rt = pathlib.Path(EXECUTION_ROOT) / "_rt" + rt.mkdir(parents=True, exist_ok=True) + manifest_doc = json.loads(read_raw(RUNTIME_MANIFEST)) + expected = {row["path"]: row["sha256"] for row in manifest_doc.get("entries") or []} + staged: list[str] = [] + for name, logical in VALIDATOR_MIRRORS.items(): + body = read_raw(logical) + raw = body.encode("utf-8") + want = expected.get(logical[len("Default_Agent/"):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (rt / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(rt) not in sys.path: + sys.path.insert(0, str(rt)) + return staged + + + def read_json_doc(path: str) -> Any: + result = _call("read_docs", {"doc_names": [path]}) + content = result["result"].get("content", []) + text = content[0].get("text", "") if content else "" + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + raise RuntimeError(f"Invalid read_docs envelope for {path}") from exc + if isinstance(parsed, dict) and "results" in parsed: + rows = parsed.get("results") or [] + if not rows or rows[0].get("error"): + raise RuntimeError(f"read_docs failed for {path}: {rows[:1]}") + inner = rows[0].get("content") or "" + if isinstance(inner, str): + try: + return json.loads(inner) + except json.JSONDecodeError: + obj, end = JSON_DECODER.raw_decode(inner.strip()) + if inner.strip()[end:].strip(): + raise RuntimeError(f"{path}: non-json tail") + return obj + return inner + return parsed + + def write_doc(path: str, content: str) -> None: + _call("write_file", {"path": path, "content": content, "overwrite": True}) + + + + def _dict(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + def _list(value: Any) -> list[Any]: + return value if isinstance(value, list) else [] + + def _strings(value: Any) -> list[str]: + out: list[str] = [] + for item in _list(value): + if item is None: + continue + text = str(item).strip() + if text and text not in out: + out.append(text) + return out + + def clip(value: Any, limit: int = 120) -> str: + text = " ".join(str(value or "").split()) + return text if len(text) <= limit else text[:limit].rstrip() + "..." + + # v4 — parse_llm_json 을 걷어냈다. worker 가 {{item.expected_output_path}} 에 + # strict JSON 파일을 직접 쓰므로 LLM 원문 관용 파싱 경로가 없어졌다. + # salvage_notes 는 산출 스키마에 남지만 v4 에서는 항상 빈 목록이다 — 구제할 원문이 없다. + # v5 — DOMAIN_PAYLOAD_CANON · _canon_payload 를 걷어냈다. canon 키가 구 이름(B1~B4)뿐이라 + # registry ID 26종 전부에서 no-op 였다(사문 코드). 확장 payload 는 워커 발행 형태 그대로 둔다. + def ensure_candidate_ref(cand: dict[str, Any], domain_id: str, idx: int) -> dict[str, Any]: + """v3 워커 출력에는 candidate_ref 가 없다 — seed 스키마가 additionalProperties: false 로 봉인돼 + 워커가 실을 수 없는 필드다. v3 이 주는 순번에서 R0 내부 식별자를 결정적으로 만든다. + 이미 실려 있으면(구 판본 산출) 그대로 둔다.""" + ref = cand.get("candidate_ref") + if isinstance(ref, str) and ref: + return cand + out = dict(cand) + out["candidate_ref"] = "%s:%03d" % (domain_id, idx + 1) + return out + + AMOUNT_TYPE_RE = re.compile(r"^[a-z][a-z0-9_]{1,127}$") + + def bind_value_ids(seed_obj: dict[str, Any], records: dict[str, dict[str, Any]], domain_id: str, + admission_records: list[dict[str, Any]], + slice_ids: set[str]) -> tuple[dict[int, list[str]], dict[int, set[str]], int]: + """수용 검증 전에 value_id 를 옆 표로 떼어 내고 그 자리를 레코드의 증거 index 로 바꾼다(§3.3 a). + + worker_output_validator 는 seed 안의 모든 source_refs·source_id 를 slice universe 와 대조한다. + value_id 는 slice 에 없으므로 그대로 두면 후보 전체가 격리된다. 돌려주는 것: + amount_bindings {id(amount_fact): [카탈로그 value_id, ...]} + cand_value_refs {id(candidate): {amount_facts 밖에서 만난 카탈로그 value_id}} + ignored worker 가 적은 숫자·통화 건수(쓰지 않고 지운다, 계획 §3.3 c 의 info) + amount_facts 의 숫자 칸은 결속 여부와 무관하게 null 로 덮는다. 숫자는 정본에서만 오고, 남겨 두면 + 패턴 위반 복구가 원소를 통째로 들어내 금액이 소리 없이 사라진다. + 증거 index 는 이 slice universe 안에 있는 것만 남긴다(slice 를 못 읽었으면 거르지 않는다). + 객체 id 로 묶는다 — 수용 단계가 원소를 들어내도 dict 객체는 그대로라 짝이 어긋나지 않는다. + worker seed 파일은 다시 쓰지 않는다(R0-5). 메모리 안의 seed 를 바꾸고, R0 가 수용본을 따로 쓴다. + """ + amount_bindings: dict[int, list[str]] = {} + cand_value_refs: dict[int, set[str]] = {} + ignored = 0 + + def swap(values: list[Any], seen: set[str]) -> list[Any]: + out: list[Any] = [] + for value in values: + if isinstance(value, str) and value in records: + seen.add(value) + value = records[value].get("evidence_index") + if not value or (slice_ids and value not in slice_ids): + continue + if value not in out: + out.append(value) + return out + + def walk(node: Any, seen: set[str]) -> None: + if isinstance(node, dict): + for key, child in list(node.items()): + if key == "source_refs" and isinstance(child, list): + node[key] = swap(child, seen) + elif key == "source_id" and isinstance(child, str) and child in records: + seen.add(child) + evidence = records[child].get("evidence_index") + if evidence and (not slice_ids or evidence in slice_ids): + node[key] = evidence + if node.get("source_kind") == "fact": + node["source_kind"] = "evidence" + else: + admission_records.append({ + "domain_id": domain_id, "code": "AMOUNT_VALUE_OUT_OF_SLICE", + "path": "source_id", "action": "review", "received": child, + "applied": None, "rule_id": "value_id_evidence_outside_slice"}) + else: + walk(child, seen) + elif isinstance(node, list): + for child in node: + walk(child, seen) + + for c_idx, cand in enumerate(_list(seed_obj.get("bo_seed_candidates"))): + if not isinstance(cand, dict): + continue + if isinstance(cand.get("amount_facts"), list): + kept: list[Any] = [] + for a_idx, fact in enumerate(cand["amount_facts"]): + if not isinstance(fact, dict): + kept.append(fact) + continue + refs = _strings(fact.get("source_refs")) + # worker 가 value_id 를 따로 키로 쓴 경우 — 그대로 두면 초과 속성으로 수확돼 UNBOUND 가 된다. + extra = fact.pop("value_id", None) + if isinstance(extra, str) and extra.strip() and extra.strip() not in refs: + refs.append(extra.strip()) + # 카탈로그에도 slice 에도 없는 ref 는 지어낸 것이다(자릿수 오타 포함). slice 를 못 읽었으면 형식으로 본다. + unknown = [v for v in refs if v not in records + and (v not in slice_ids if slice_ids else VALUE_ID_RE.fullmatch(v))] + if unknown: + # 지어낸 id — 그 원소만 지운다. 회차도 후보도 죽이지 않는다. + admission_records.append({ + "domain_id": domain_id, "code": "AMOUNT_VALUE_ID_UNKNOWN", + "path": "$.stage_b_domain_bo_seed_output.bo_seed_candidates[%d].amount_facts[%d]" % (c_idx, a_idx), + "action": "repair_evict", "received": unknown, "applied": "dropped_amount_fact", + "rule_id": "value_id_not_in_catalog", "candidate_ref": cand.get("seed_id")}) + continue + ids = [v for v in refs if v in records] + amount_bindings[id(fact)] = ids + outside = [v for v in ids if slice_ids and records[v].get("evidence_index") not in slice_ids] + if outside: + admission_records.append({ + "domain_id": domain_id, "code": "AMOUNT_VALUE_OUT_OF_SLICE", + "path": "$.stage_b_domain_bo_seed_output.bo_seed_candidates[%d].amount_facts[%d]" % (c_idx, a_idx), + "action": "review", "received": outside, "applied": "binding_kept", + "rule_id": "value_id_evidence_outside_slice", "candidate_ref": cand.get("seed_id")}) + fact["source_refs"] = swap(refs, set()) + if fact.get("decimal_value") is not None or fact.get("currency") is not None: + ignored += 1 + fact["decimal_value"], fact["currency"] = None, None + if not (isinstance(fact.get("amount_type"), str) and AMOUNT_TYPE_RE.fullmatch(fact["amount_type"])): + fact["amount_type"] = "amount" + kept.append(fact) + cand["amount_facts"] = kept + seen: set[str] = set() + for key in list(cand.keys()): + if key == "amount_facts": + continue + if key == "source_refs" and isinstance(cand[key], list): + cand[key] = swap(cand[key], seen) + else: + walk(cand[key], seen) + if seen: + cand_value_refs[id(cand)] = seen + # 뿌리 검토 목록도 같은 규칙이다. 후보에 매이지 않으므로 value_refs 로는 남기지 않는다. + walk(seed_obj.get("unknown_or_unrouted_reviews"), set()) + return amount_bindings, cand_value_refs, ignored + + def select_amount(resolved: list[dict[str, Any]], domain_id: str, + selection: dict[str, Any]) -> tuple[dict[str, Any] | None, list[str]]: + """§3.3 d — MONEY · amount_value 있음 · per 없음 가운데 policy amount_selection 단계표 순서로 하나를 고른다. + + 덮어쓰기는 도메인 단위다. registry bo_type 은 event·state 같은 범용 값이라 담보 BO 를 가려내지 못한다. + 돌려주는 것: (BO amount 또는 None, 고른 단계 안에서 값이 둘 이상으로 갈리면 그 단계의 value_id 목록) + """ + rank: dict[str, tuple[float, int]] = {} + for pos, kind in enumerate(_strings(_dict(selection.get("domain_overrides")).get(str(domain_id)))): + rank[kind] = (0, pos) + tiers = [_strings(t) for t in _list(selection.get("tiers"))] + for t_idx, kinds in enumerate(tiers, start=1): + for kind in kinds: + rank.setdefault(kind, (t_idx, 0)) + last = (len(tiers) + 1, 0) + sum_kind = selection.get("sum_total_kind") + includes = selection.get("sum_total_includes_relation") + + def key(rec: dict[str, Any]) -> tuple[Any, ...]: + r = rank.get(str(rec.get("value_kind")), last) + if (r[0] > 0 and rec.get("value_kind") == sum_kind + and any(_dict(x).get("type") == includes for x in _list(rec.get("relations")))): + r = (0.5, 0) # 구성요소를 포함하는 합계는 T1 보다 앞선다 + return (r, str(rec.get("value_id"))) + + eligible = [r for r in resolved if r.get("value_type") == "MONEY" + and r.get("amount_value") is not None and not r.get("per")] + if not eligible: + return None, [] + pick = sorted(eligible, key=key)[0] + # 원금(T1)과 이자(T3)가 함께 있는 것은 정상이다. 고른 단계 안에서 값이 갈릴 때만 검토로 올린다. + same_tier = [r for r in eligible if key(r)[0] == key(pick)[0]] + split = len({(str(r.get("amount_value")), r.get("currency")) for r in same_tier}) > 1 + return ({"value_text": pick.get("amount_text"), "numeric_value": pick.get("amount_value"), + "currency": pick.get("currency"), "value_id": pick.get("value_id")}, + [str(r.get("value_id")) for r in same_tier] if split else []) + + def project_to_bo_surface(cand: dict[str, Any], domain_id: str, universe: dict[str, set[str]], + policy: dict[str, Any], allowed_bo_types: set[str], + reviews: list[dict[str, Any]], value_ctx: dict[str, Any]) -> dict[str, Any]: + """v3 후보를 BO 호환면으로 투영한다. 값의 정본은 registry 이고 규칙은 정책 파일이 선언한다. + + 전임자 둘(expand_candidate + _seed_payload)은 v2 키를 기본값으로 깔고 v2 화이트리스트로 + 걸렀다. v3 후보를 넣으면 워커가 실은 값이 extensions 하나만 남았고, 그 결과 중복 판정 키 + 여덟 성분이 전부 비어 사건 전체가 한 버킷으로 접혔다(C-1·C-2). 여기서는 v3 필드에서 + 끌어오고, registry 가 말해 주지 않는 칸은 채우지 않고 reviews 에 올린다. + 반환 키 집합은 입력과 무관하게 고정이다 — 이 반환문이 원장 payload 키 집합의 유일한 정의다. + """ + ref = str(cand.get("candidate_ref")) + + def note(issue_type: str, field: str, source: str, value_ids: list[str] | None = None) -> None: + item = {"issue_type": issue_type, "candidate_ref": ref, "field": field, "source": source} + if value_ids: + item["value_ids"] = sorted(value_ids) + reviews.append(item) + + refs = _strings(cand.get("source_refs")) + evidence = sorted(set(refs) & universe["source_evidence_indexes"]) + events = sorted(set(refs) & universe["source_event_candidate_ids"]) + clauses = sorted(set(refs) & universe["source_meeting_clause_ids"]) + + norm = _dict(policy.get("f0_normalization")) + bo_type = cand.get("bo_type") + if not isinstance(bo_type, str): + # 워커가 문자열이 아닌 값을 넣으면 집합 비교가 터진다(dict 면 unhashable). + # 수용 단계가 걸러야 하지만 투영은 마지막 방어선이라 여기서도 막는다 — + # 여기서 죽으면 회차 전체가 죽고, 원인이 워커 값이라는 것도 드러나지 않는다. + note("schema_field_fallback", "BOType", "non_string:%s" % type(bo_type).__name__) + bo_type = norm.get("bo_type_default") + if allowed_bo_types and bo_type not in allowed_bo_types: + note("legal_effect_uncertain", "BOType", "bo_type") + + ext = dict(_dict(cand.get("extensions"))) + if not isinstance(ext.get("domain_payload"), dict): + ext["domain_payload"] = {} + domain_payload = _dict(ext.get("domain_payload")) + + action_type = domain_payload.get("action_type") + if not (isinstance(action_type, str) and action_type in set(_strings(norm.get("action_type_enum")))): + # registry 근거가 없는 칸이다. 기본값은 선언이며 추정이 아니다 — 반드시 검토로 올린다. + action_type = norm.get("action_type_default") + note("schema_field_fallback", "ActionType", "policy_default") + + effect_type_ids = sorted({str(e.get("type_id")).strip() + for e in _list(cand.get("legal_effect_candidates")) + if isinstance(e, dict) and str(e.get("type_id") or "").strip()}) + action_summary = domain_payload.get("action_summary") + if isinstance(action_summary, str) and action_summary.strip(): + action = action_summary.strip() + elif effect_type_ids: + # 값은 registry token 또는 그 대체 표지이지 서술문이 아니다. Stage 2 는 review_handoff 의 action_source 를 함께 읽는다. + action = "%s:%s" % (bo_type, effect_type_ids[0]) + note("schema_field_fallback", "Action", "legal_effect_type_id") + else: + # bo_type 만 쓰면 S2_00 이 PLACEHOLDER 로 빼서 이 BO 가 S2_10 에 가지 않는다. + action = "%s:effect_unspecified" % bo_type + note("schema_field_fallback", "Action", "bo_type") + + time_facts = [t for t in _list(cand.get("time_facts")) if isinstance(t, dict)] + behavior_time = None + time_text = None + if time_facts: + pick = sorted(time_facts, key=lambda t: (str(t.get("fact_type") or ""), str(t.get("value") or "")))[0] + behavior_time = pick.get("value") + time_text = pick.get("value") + distinct_times = {str(t.get("value") or "").strip() for t in time_facts if str(t.get("value") or "").strip()} + if len(distinct_times) > 1: + note("amount_or_date_uncertain", "core_field_base.BehaviorTime", "time_facts") + + object_refs = sorted(_strings(cand.get("object_refs"))) + + # 가액금액 §3.3 c·d — worker 가 적은 숫자는 쓰지 않는다. value_id 로 정본을 찾아 채운다. + records = value_ctx["records"] + value_refs = set(value_ctx["cand_refs"]) + resolved: list[dict[str, Any]] = [] + ambiguous: set[str] = set() + for fact in [a for a in _list(cand.get("amount_facts")) if isinstance(a, dict)]: + ids = value_ctx["amount_bindings"].get(id(fact)) or [] + if len(ids) == 1: + value_refs.add(ids[0]) + resolved.append(records[ids[0]]) + else: + ambiguous.update(ids) + note("amount_or_date_uncertain", "amount", + "AMOUNT_MULTIPLE_VALUE_IDS" if ids else "AMOUNT_UNBOUND", ids) + for name in ("element_fact_candidates", "opposing_fact_candidates", "defense_candidates"): + for row in _list(cand.get(name)): + vid = _dict(_dict(row).get("payload")).get("value_id") + if isinstance(vid, str) and vid: + if vid in records: + value_refs.add(vid) + else: + # payload.value_id 는 검증기도 signal gate 도 보지 않는다. 이 필터가 유일한 방어다. + note("review_required", "payload.value_id", "AMOUNT_VALUE_ID_UNKNOWN", [vid]) + amount, same_tier_ids = select_amount(resolved, domain_id, value_ctx["selection"]) + if same_tier_ids: + note("amount_or_date_uncertain", "amount", "AMOUNT_MULTIPLE_DISTINCT_VALUES", + [str(r.get("value_id")) for r in resolved]) + + return { + "candidate_ref": ref, + "source_domain": domain_id, + "BOType": bo_type, + "ActionType": action_type, + "JuristicAct": _normalize_juristic(cand.get("juristic_act_type")), + "Action": action, + "Reason": None, + "PriorAct": None, + "ReasonRefs": [], + "Legal_Keywords": effect_type_ids, + "core_field_base": {"BehaviorTime": behavior_time, "TimeText": time_text, + "Object": object_refs[0] if object_refs else None, + "StatementType": bo_type}, + "amount": amount, + "amount_same_tier_ids": sorted(set(same_tier_ids) | ambiguous), + "value_refs": sorted(value_refs | ambiguous), + "source_evidence_indexes": evidence, + "provenance": {"source_event_candidate_ids": events, + "source_meeting_clause_ids": clauses, + "source_evidence_indexes": evidence, + "source_domain": domain_id}, + "downstream_seed_refs": {}, + "extensions": ext, + "registry_component_ids": _strings(cand.get("registry_component_ids")), + } + + def expand_review_item(item: Any, domain_id: str, idx: int) -> dict[str, Any]: + """v3 검토 항목(후보별 review_items · 루트 unknown_or_unrouted_reviews)을 handoff 항목형으로 사상한다. + + 구판은 v3 루트 13키에 없는 domain_review_queue 를 읽었다 — 봉인(additionalProperties: false)이 + 워커에게 발행을 금지한 키라 워커 검토가 한 건도 도달하지 못했다(C-6). 사상 규칙은 정책 + review_item_projection 이 선언한다. 원본 코드는 덧붙이기 키 source_review_code 로 보존한다. + """ + src = _dict(item) + raw_type = str(src.get("unresolved_type") or "").strip() + raw_code = str(src.get("review_code") or "").strip() + severity = src.get("severity") if src.get("severity") in ("SOFT_WARNING", "HARD_WARNING") else "SOFT_WARNING" + return { + "review_id": str(src.get("review_id") or f"{domain_id}:review:{idx:03d}"), + "issue_type": raw_type if raw_type in REVIEW_ISSUE_ENUM else "review_required", + "severity": severity, + # 원본 review_code(v3 필수 키)를 잃지 않는다 — 정책 additive_keys 의 목적이 그것이다. + "source_review_code": raw_code or raw_type or None, + "reason": str(src.get("reason") or "").strip(), + "source_refs": _strings(src.get("source_refs")), + "recommended_downstream_owner": src.get("recommended_downstream_owner") or "Stage2", + } + + # ---------- 워커 출력 수용 검증 (v3 계약 정본 · 정책 status_policy · 계획 해시 대조) ---------- + def validate_seed_object(seed_obj: dict[str, Any], domain_id: str, plan_row: dict[str, Any], warnings: list[dict[str, Any]], echo_mismatches: list[dict[str, Any]] | None = None) -> None: + """v3 seed 루트를 검증한다. status 는 v3 enum 5종을 정책 status_policy 로 가른다. + + 구판은 READY 계열 2종만 허용해 계약상 적법한 NO_SUPPORT 가 R0 전체를 중단시켰고(C-11), + 신선도는 워커가 실을 수 없는 transport_metadata.slice_guard 를 읽는 죽은 검사였다. + 신선도의 제 필드는 v3 루트의 slice_sha256 · compiled_prompt_sha256 이고(둘 다 required + — 워커가 반드시 echo 한다), 기대값은 fan-out 계획 행이 든다. + """ + if seed_obj.get("schema_version") != SEED_SCHEMA_VERSION: + raise ValueError(f"{domain_id}: seed schema_version mismatch") + if seed_obj.get("domain_id") != domain_id: + raise ValueError(f"{domain_id}: seed domain_id mismatch") + status = seed_obj.get("status") + if status in ("BLOCKED", "FAILED"): + # 워커 실패 신호다. fail-open 은 활성화 판정의 원칙이고, 실패의 침묵 흡수는 금지 원칙이 막는다. + raise ValueError(f"{domain_id}: worker reported {status}") + if status == "NO_SUPPORT": + # 적법한 "실을 것 없음". 후보가 있으면 상태·내용 모순이다. + if _list(seed_obj.get("bo_seed_candidates")): + raise ValueError(f"{domain_id}: NO_SUPPORT with non-empty bo_seed_candidates") + elif status not in ("READY", "READY_WITH_REVIEW"): + raise ValueError(f"{domain_id}: seed status outside v3 enum: {status!r}") + # R0-7 — 신선도를 워커의 자기 신고로 판정하지 않는다. + # echo 된 sha 는 모델이 옮겨 적은 값이라 전사 실수가 곧 회차 사망이 된다. + # 실측: E-00 이 slice_sha256 자리에 슬라이스 안의 activation_manifest_sha256 을 집었고, + # 그 값은 14개 슬라이스 전부에 같은 값으로 들어 있어 어느 도메인에서든 재발할 수 있다. + # 진짜 신선도는 모델을 거치지 않는 실물 두 값(계획서 sha ↔ R0 가 직접 읽은 문서 sha)이 + # 말한다. 그 대조는 호출부가 하고(PART2_SLICE_STALE), 여기서는 echo 불일치를 + # 수용 정책 관할로 넘길 수 있도록 모아만 둔다. + _echo = echo_mismatches if echo_mismatches is not None else [] + for key in ("slice_sha256", "compiled_prompt_sha256"): + want = plan_row.get(key) + if isinstance(want, str) and want: + if seed_obj.get(key) != want: + _echo.append({"domain_id": domain_id, "key": key, + "expected": want, "received": seed_obj.get(key)}) + else: + warnings.append({"domain_id": domain_id, "warning": f"fanout plan carries no {key} expectation"}) + + def validate_candidate(cand: dict[str, Any], domain_id: str, idx: int) -> None: + prefix = domain_id + ref = cand.get("candidate_ref") + if not isinstance(ref, str) or not CANDIDATE_REF_RE.fullmatch(ref): + raise ValueError(f"{domain_id}.bo_seed_candidates[{idx}].candidate_ref invalid") + if not ref.startswith(prefix + ":"): + raise ValueError(f"{domain_id}.bo_seed_candidates[{idx}].candidate_ref prefix mismatch") + for forbidden in ("BO_ID", "id", "Evidence", "EvidenceTitles"): + if forbidden in cand: + raise ValueError(f"{domain_id}.{ref}: final field {forbidden} is prohibited") + if cand.get("Reason") is not None: + raise ValueError(f"{domain_id}.{ref}: Reason must be null/absent") + if cand.get("PriorAct") is not None: + raise ValueError(f"{domain_id}.{ref}: PriorAct must be null/absent") + if cand.get("ReasonRefs") not in ([], None): + raise ValueError(f"{domain_id}.{ref}: ReasonRefs must be []/absent") + + # ------------------------------------------------------------------ + # R0-6 — 시드 수용(admission). 검증 결과에 등급을 준다. + # 구조 위반은 막고(block), 어휘·형태 위반은 정규화·수확으로 살리고(repair), + # 살릴 수 없는 것은 후보 하나만 격리한다(quarantine). 회차 전체를 죽이지 않는다. + # 값을 지어내지 않는다 — 표에 없는 낱말과 universe 에 없는 참조는 복구 대상이 아니다. + # 예외 하나: 슬롯 status 는 행을 잃으면 Part 4 조건이 꺼지므로 enum_unmapped_fallback 값으로 남긴다. + # ------------------------------------------------------------------ + PATH_INDEX_RE = re.compile(r"\[(\d+)\]") + + def _norm_path(path: str) -> str: + """검증기 경로를 정책 키 모양으로 바꾼다. 인덱스는 [] 로 접는다.""" + body = path.replace("$.stage_b_domain_bo_seed_output.", "").replace("$.stage_b_domain_bo_seed_output", "") + return PATH_INDEX_RE.sub("[]", body).lstrip(".") + + def _path_tokens(path: str) -> list[Any]: + body = path.replace("$.stage_b_domain_bo_seed_output.", "").replace("$.stage_b_domain_bo_seed_output", "") + tokens: list[Any] = [] + for part in body.lstrip(".").split("."): + if not part: + continue + name = part.split("[", 1)[0] + if name: + tokens.append(name) + for hit in PATH_INDEX_RE.findall(part): + tokens.append(int(hit)) + return tokens + + def _resolve_parent(root: Any, tokens: list[Any]) -> tuple[Any, Any]: + """마지막 토큰의 부모 컨테이너와 그 토큰을 돌려준다. 못 찾으면 (None, None).""" + node = root + for tok in tokens[:-1]: + if isinstance(tok, int): + if not isinstance(node, list) or tok >= len(node): + return (None, None) + node = node[tok] + else: + if not isinstance(node, dict) or tok not in node: + return (None, None) + node = node[tok] + return (node, tokens[-1]) if tokens else (None, None) + + def _candidate_index(tokens: list[Any]) -> int | None: + for pos, tok in enumerate(tokens): + if tok == "bo_seed_candidates" and pos + 1 < len(tokens) and isinstance(tokens[pos + 1], int): + return tokens[pos + 1] + return None + + def _sink_for(seed_obj: dict[str, Any], tokens: list[Any], policy: dict[str, Any], norm: str): + """초과 정보를 담을 자리 두 곳을 돌려준다: (컨테이너 지역 payload, 후보 수준 보관 목록). + + 지역 payload 의 키는 **잎 이름 그대로** 쓴다 — 하류 어댑터가 + payload["status"] 처럼 짧은 이름으로 읽기 때문이다. 정규경로를 키로 쓰면 + 바이트는 남아도 아무도 읽지 못한다. + 후보 수준 보관은 dict 가 아니라 **덧붙이기 전용 목록**이다. 같은 정규경로의 + 두 번째 값이 첫 번째를 조용히 덮는 사고를 구조적으로 막는다. + """ + sink_cfg = _dict(policy.get("surplus_sink")) + local: dict[str, Any] | None = None + by_container = _dict(sink_cfg.get("by_container")) + container_key = norm.rsplit(".", 1)[0] if "." in norm else norm + local_name = by_container.get(container_key) + if local_name: + parent, _ = _resolve_parent(seed_obj, tokens) + # 지역 칸 자리에 비객체가 있으면 쓰지 않는다. 덮으면 그 값이 사라지고, 칸 자체가 + # 옮길 값이면 자기 참조가 되어 수용본 직렬화가 실패한다. + if isinstance(parent, dict) and isinstance(parent.get(local_name, {}), dict): + local = parent.setdefault(local_name, {}) + shelf: list[Any] | None = None + cand_idx = _candidate_index(tokens) + cands = seed_obj.get("bo_seed_candidates") + if cand_idx is not None and isinstance(cands, list) and cand_idx < len(cands) and isinstance(cands[cand_idx], dict): + node: Any = cands[cand_idx] + steps = str(sink_cfg.get("candidate_path") or "extensions.worker_surplus").split(".") + for step in steps[:-1]: + nxt = node.get(step) + if not isinstance(nxt, dict): + nxt = {} + node[step] = nxt + node = nxt + leaf = steps[-1] + if not isinstance(node.get(leaf), list): + node[leaf] = [] + shelf = node[leaf] + return (local, shelf) + + def _universe_kind(value: str, universe: dict[str, set]) -> str | None: + if value in universe["source_evidence_indexes"]: + return "evidence" + if value in universe["source_event_candidate_ids"]: + return "event_candidate" + if value in universe["source_meeting_clause_ids"]: + return "meeting_clause" + return None + + def _derive_required(seed_obj, tokens, norm, rule, universe, ctx): + """선언된 규칙으로만 채운다. 규칙이 없거나 실패하면 (False, None).""" + parent, key = _resolve_parent(seed_obj, tokens) + if not isinstance(parent, dict): + return (False, None) + how = str(rule.get("rule") or "") + if how == "constant": + value = rule.get("value") + return (True, copy.deepcopy(value)) if "value" in rule else (False, None) + if how == "from_context": + ckey = str(rule.get("key") or "") + return (True, copy.deepcopy(ctx[ckey])) if ckey in ctx else (False, None) + if how == "first_universe_member_of_sibling_array": + known = (universe["source_evidence_indexes"] | universe["source_event_candidate_ids"] + | universe["source_meeting_clause_ids"]) + for sib in rule.get("sibling_candidates") or []: + raw = parent.get(sib) + values = raw if isinstance(raw, list) else ([raw] if isinstance(raw, str) else []) + for item in values: + if isinstance(item, str) and item in known: + return (True, item) + return (False, None) + if how == "universe_kind_of_sibling": + sib = parent.get(str(rule.get("sibling") or "")) + kind = _universe_kind(sib, universe) if isinstance(sib, str) else None + if not kind: + # 형제가 아직 채워지지 않았을 수 있다. 같은 원소의 참조 배열에서 직접 읽는다. + for name in rule.get("fallback_sibling_arrays") or []: + raw = parent.get(name) + values = raw if isinstance(raw, list) else ([raw] if isinstance(raw, str) else []) + for item in values: + if isinstance(item, str): + kind = _universe_kind(item, universe) + if kind: + break + if kind: + break + return (True, kind) if kind else (False, None) + if how == "rename_sibling": + # 워커가 같은 뜻을 다른 이름으로 적었을 때 이름만 바로잡는다. 값은 그대로 옮긴다. + # 옮긴 뒤 원래 키를 지운다 — 남겨 두면 다음 패스에서 초과 속성으로 다시 걸린다. + for sib in rule.get("sibling_candidates") or []: + if sib in parent and parent.get(sib) not in (None, ""): + return (True, parent.pop(sib)) + return (False, None) + if how == "sibling_matching_pattern": + pat = re.compile(str(rule.get("pattern") or "^$")) + for sib in rule.get("sibling_candidates") or []: + value = parent.get(sib) + if isinstance(value, str) and pat.fullmatch(value): + return (True, value) + for sib in rule.get("fallback_rename_sibling") or []: + if sib in parent and parent.get(sib) not in (None, ""): + return (True, parent.pop(sib)) + return (False, None) + return (False, None) + + def _promote_alias(parent, key, norm, policy, record): + """수확 직전에 한 번 더 본다 — 이 키가 선언된 자리의 다른 이름일 뿐인가. + + 그렇다면 자유 공간으로 밀어 넣지 않고 제 자리로 올린다. 워커가 excerpt 를 + value·content 로 부르는 표류가 실측됐고, 그 값은 하류가 실제로 읽는 칸이다. + """ + if not isinstance(parent, dict) or not isinstance(key, str): + return False + container = norm.rsplit(".", 1)[0] if "." in norm else "" + for target_path, rule in _dict(policy.get("required_derivation")).items(): + if str(rule.get("rule") or "") != "rename_sibling": + continue + if target_path.rsplit(".", 1)[0] != container: + continue + target = target_path.rsplit(".", 1)[-1] + if target in parent and parent.get(target) not in (None, ""): + continue + if key in (rule.get("sibling_candidates") or []): + parent[target] = parent.pop(key) + record["received"] = _clip(parent[target]) + record["applied"] = "promoted_to:%s" % target + record["rule_id"] = "alias_promotion:%s" % target_path + return True + return False + + def _harvest(seed_obj, tokens, policy, norm, record): + """규약 밖 값을 버리지 않고 자유 공간으로 옮긴다. 옮긴 사실을 기록한다.""" + parent, key = _resolve_parent(seed_obj, tokens) + if parent is None: + return False + if _promote_alias(parent, key, norm, policy, record): + return True + local, shelf = _sink_for(seed_obj, tokens, policy, norm) + if isinstance(parent, list) and isinstance(key, int): + if key >= len(parent): + return False + moved = parent.pop(key) + leaf = None + elif isinstance(parent, dict): + if key not in parent: + return False + moved = parent.pop(key) + leaf = key + else: + return False + placed = [] + # 1) 컨테이너 지역 payload — 하류가 읽는 짧은 이름으로. 이미 있으면 덮지 않는다. + if isinstance(local, dict) and isinstance(leaf, str) and leaf not in local: + local[leaf] = moved + placed.append("payload.%s" % leaf) + # 2) 후보 수준 보관 — 덧붙이기 전용이라 어떤 값도 덮이지 않는다. 원래 경로를 함께 남긴다. + if isinstance(shelf, list): + # D11 — norm 은 인덱스를 접으므로 같은 컨테이너의 두 값이 구별되지 않는다. + # 원본 경로를 함께 남겨야 부모 원소와의 결합(예: role ↔ party_refs)을 복원할 수 있다. + shelf.append({"path": norm, "source_path": record.get("path"), "value": moved}) + placed.append("worker_surplus[]") + if not placed: + # 보관할 자리가 없으면 지우지 않는다. 되돌려 놓고 실패로 돌려주면 + # 이 위반은 잔여로 남아 정책이 정한 처분(기본 review)으로 간다. + # 뿌리 수준 배열(unknown_or_unrouted_reviews 등)이 여기 해당한다 — + # 후보에 매이지 않아 보관처가 없는데, 그렇다고 사건 자료를 버릴 수는 없다. + if isinstance(parent, list) and isinstance(key, int): + parent.insert(key, moved) + elif isinstance(parent, dict) and isinstance(key, str): + parent[key] = moved + return False + record["received"] = _clip(moved) + record["applied"] = "+".join(placed) + # 기계적 키 이동과, 실질 서술을 담은 채 **객체째** 밀려난 것은 검토 무게가 다르다. + # 후자를 같은 등급에 섞으면 1,200건 속 몇 건을 사람이 찾아내야 한다. + # 판정은 dict 로 좁힌다 — 스칼라 한 개의 자리 이동(당사자 이름·slot_id 문자열)은 + # 원소가 사라진 것이 아니라 키가 옮겨진 것이라 무게가 다르다. + if isinstance(moved, dict): + for _k in ("excerpt", "value", "fact", "content", "reason", "statement"): + _v = moved.get(_k) + if isinstance(_v, str) and _v.strip(): + record["content_bearing"] = True + break + return True + + def _evict(seed_obj, tokens, policy, norm, record, quarantined=None): + """복구 불가한 객체 하나를 배열에서 들어내 보관한다. 후보 자체는 삭제하지 않는다. + + D4·D8 — 후보를 pop 하면 ① 예산에 잡히지 않아 소리 없이 사라지고 + ② 뒤 후보의 인덱스가 밀려 이미 기록한 격리 표시가 다른 후보를 가리킨다. + 후보 수준이면 삭제 대신 격리로 돌린다. + """ + trimmed = list(tokens) + while trimmed and not isinstance(trimmed[-1], int): + trimmed.pop() + if not trimmed: + return False + if len(trimmed) == 2 and trimmed[0] == "bo_seed_candidates": + if quarantined is None: + return False + quarantined.add(trimmed[1]) + record["applied"] = "quarantined_candidate" + return True + return _harvest(seed_obj, trimmed, policy, _norm_path("$.stage_b_domain_bo_seed_output." + norm), record) + + def _clip(value: Any, limit: int = 200) -> Any: + try: + text = json.dumps(value, ensure_ascii=False) + except Exception: + text = str(value) + return text if len(text) <= limit else text[:limit] + "…" + + def _path_sort_key(path: Any) -> str: + return PATH_INDEX_RE.sub(lambda m: "[%05d]" % int(m.group(1)), str(path or "")) + + def _record_repair(seed_obj, tokens, rec, records): + cand_idx = _candidate_index(tokens) + if cand_idx is not None: + cand = _list(seed_obj.get("bo_seed_candidates")) + if cand_idx < len(cand): + rec["candidate_ref"] = _dict(cand[cand_idx]).get("candidate_ref") or _dict(cand[cand_idx]).get("seed_id") + records.append(rec) + + def admit_seed(seed_obj, domain_id, schema, slice_doc, universe, policy, records, plan_row=None, validator=None): + """검증 -> 처분 -> 복구를 수렴할 때까지 돌리고, 남은 것은 후보 격리로 넘긴다. + + 돌려주는 것: (수용된 seed, 격리된 후보 인덱스 집합, 경성 중단 사유 목록) + """ + # D1 — 검증기는 인자로 받는다. main() 지역 이름을 전역처럼 읽으면 NameError 로 즉사한다. + if validator is None: + return (seed_obj, set(), []) + + def _raw_validate(obj): + return validator.validate_worker_output( + {"stage_b_domain_bo_seed_output": obj}, schema=schema, + expected_domain_id=domain_id, slice_document=slice_doc) + + def _validate(obj): + """검증기 자체가 터질 수 있다(예: bo_type 이 dict 면 unhashable). + + D9 — 예외를 코드로 바꾸기만 하면 부족하다. 그 오류의 path 는 뿌리라 + 후보를 지목하지 못하고, 처분이 뿌리 잔여(review)로 강등돼 문제 후보가 + 그대로 투영으로 흘러 project_to_bo_surface 에서 다시 죽는다. + 그래서 **어느 후보가 터뜨렸는지 후보 단위로 좁혀** path 에 인덱스를 실어 준다. + """ + try: + return _raw_validate(obj) + except Exception as exc: + detail = "%s: %s" % (type(exc).__name__, str(exc)[:160]) + errors = [] + cands = _list(obj.get("bo_seed_candidates")) + for idx in range(len(cands)): + probe = dict(obj) + probe["bo_seed_candidates"] = [cands[idx]] + try: + _raw_validate(probe) + except Exception: + errors.append({"code": "VALIDATOR_CRASHED", + "path": "$.stage_b_domain_bo_seed_output.bo_seed_candidates[%d]" % idx, + "message": detail}) + if errors: + # 죽은 후보 자리를 비우고 나머지를 다시 검증한다. 안 그러면 같은 도메인의 + # 정상 후보가 수리를 받지 못한 채 투영과 S0 로 간다. + crashed = {_candidate_index(_path_tokens(e["path"])) for e in errors} + probe = dict(obj) + probe["bo_seed_candidates"] = [{"seed_id": _dict(c).get("seed_id")} if i in crashed else c + for i, c in enumerate(cands)] + try: + for item in _raw_validate(probe).get("errors") or []: + if _candidate_index(_path_tokens(str(item.get("path") or ""))) not in crashed: + errors.append(item) + except Exception: + pass + if not errors: + # 후보를 좁히지 못했다. 뿌리 문제이므로 명시적으로 끊는다 — + # review 로 강등해 투영에서 죽게 두는 것이 최악이다. + errors.append({"code": "VALIDATOR_CRASHED_ROOT", + "path": "$.stage_b_domain_bo_seed_output", "message": detail}) + return {"errors": errors, "warnings": []} + disposition = _dict(policy.get("disposition_by_code")) + unknown_disp = str(policy.get("unknown_code_disposition") or "quarantine") + synonyms = _dict(policy.get("enum_synonyms")) + case_fold = bool(policy.get("enum_case_fold")) + enum_unmapped = str(policy.get("enum_unmapped_disposition") or "repair_evict") + derivations = _dict(policy.get("required_derivation")) + derive_failed = str(policy.get("derivation_failed_disposition") or "repair_evict") + order = [str(v) for v in (policy.get("repair_order") or [])] + max_passes = int(policy.get("max_repair_passes") or 3) + blocks: list[dict[str, Any]] = [] + quarantined: set[int] = set() + + # 슬롯 id 패턴은 소문자만 받는다. 대소문자 때문에 슬롯 행을 잃지 않게 먼저 맞춘다. + for _ci, _cand in enumerate(_list(seed_obj.get("bo_seed_candidates"))): + for _si, _slot in enumerate(_list(_dict(_cand).get("evidence_slot_status"))): + _sid = _dict(_slot).get("slot_id") + if isinstance(_sid, str) and _sid != _sid.lower(): + _slot["slot_id"] = _sid.lower() + records.append({"domain_id": domain_id, "code": "SLOT_ID_LOWERED", "action": "repair_normalize", + "path": "$.stage_b_domain_bo_seed_output.bo_seed_candidates[%d].evidence_slot_status[%d].slot_id" % (_ci, _si), + "received": _sid, "applied": _sid.lower(), "rule_id": "slot_id_lowercase"}) + + for _pass in range(max_passes): + cands = _list(seed_obj.get("bo_seed_candidates")) + # task_instance_id 는 지어내지 않는다 — A0 의 fan-out 계획 행이 든 값을 쓴다. + ctx = {"domain_id": domain_id, "seed_count": len(cands), + "emitted_seed_ids": [str(_dict(c).get("seed_id") or "") for c in cands]} + _plan_tid = _dict(plan_row).get("task_instance_id") + if isinstance(_plan_tid, str) and _plan_tid: + ctx["task_instance_id"] = _plan_tid + # r0_membership_key 는 R0 가 자기 관측으로 결정적으로 만든다(워커가 알 수 없는 값이다). + ctx["r0_membership_key"] = "%s:%s" % ( + domain_id, hashlib.sha256(json.dumps(ctx["emitted_seed_ids"], ensure_ascii=False, + sort_keys=True).encode("utf-8")).hexdigest()[:32]) + report = _validate(seed_obj) + errors = [e for e in (report.get("errors") or []) if isinstance(e, dict)] + if not errors: + break + buckets: dict[str, list[dict[str, Any]]] = {} + for err in errors: + disp = str(disposition.get(str(err.get("code"))) or unknown_disp) + # 격리한 후보의 오류는 다시 처분하지 않는다. 같은 오류가 회차를 소진해 다른 후보의 복구를 막는다. + if disp != "block" and _candidate_index(_path_tokens(str(err.get("path") or ""))) in quarantined: + continue + buckets.setdefault(disp, []).append(err) + for err in buckets.get("block") or []: + blocks.append({"code": err.get("code"), "path": err.get("path"), "message": err.get("message")}) + if blocks: + return (seed_obj, quarantined, blocks) + for err in buckets.get("review") or []: + records.append({"domain_id": domain_id, "code": err.get("code"), "path": err.get("path"), + "action": "review", "received": None, "applied": None, + "rule_id": "disposition:review"}) + progressed = False + for action in order: + # harvest 는 원소를 들어내므로 내림차순으로 돈다 — 앞 인덱스를 먼저 지우면 뒤 경로가 밀린다. + # 값을 채우는 처분(normalize·derive)은 오름차순이다: source_kind 는 형제 source_id 를 읽는다. + evictions: list[tuple[list[Any], str, dict[str, Any]]] = [] + for err in sorted(buckets.get(action) or [], + key=lambda e: _path_sort_key(e.get("path")), + reverse=action == "repair_harvest"): + path = str(err.get("path") or "") + tokens = _path_tokens(path) + if not tokens: + continue + norm = _norm_path(path) + rec = {"domain_id": domain_id, "code": err.get("code"), "path": path, + "action": action, "received": None, "applied": None, "rule_id": None} + done = False + if action == "repair_normalize": + parent, key = _resolve_parent(seed_obj, tokens) + table = _dict(synonyms.get(norm)) + if isinstance(parent, dict) and key in parent and table: + raw = parent.get(key) + probe = raw.casefold() if (case_fold and isinstance(raw, str)) else raw + mapped = table.get(probe) if isinstance(probe, str) else None + if mapped is not None: + rec["received"], rec["applied"] = _clip(raw), mapped + rec["rule_id"] = "enum_synonyms:%s" % norm + parent[key] = mapped + done = True + fallback = _dict(_dict(policy.get("enum_unmapped_fallback")).get(norm)) + if not done and fallback and isinstance(parent, dict) and key in parent: + rec["received"], rec["applied"] = _clip(parent.get(key)), fallback.get("value") + rec["rule_id"] = "enum_unmapped_fallback:%s" % norm + parent[key] = fallback.get("value") + if not parent.get("review_code"): + parent["review_code"] = fallback.get("review_code") + done = True + if not done and enum_unmapped == "repair_evict": + rec["rule_id"] = "enum_unmapped:%s" % norm + evictions.append((tokens, norm, rec)) + elif action == "repair_derive": + rule = _dict(derivations.get(norm)) + if rule: + ok, value = _derive_required(seed_obj, tokens, norm, rule, universe, ctx) + if ok: + parent, key = _resolve_parent(seed_obj, tokens) + if isinstance(parent, dict): + if key in parent and parent[key] == value: + continue # 같은 값을 다시 쓰는 것은 복구가 아니다. 회차만 소비한다. + rec["received"], rec["applied"] = None, _clip(value) + rec["rule_id"] = "required_derivation:%s" % norm + parent[key] = value + done = True + if not done and derive_failed == "repair_evict": + rec["rule_id"] = "derivation_failed:%s" % norm + evictions.append((tokens, norm, rec)) + elif action == "repair_harvest": + rec["rule_id"] = "surplus_sink:%s" % norm + done = _harvest(seed_obj, tokens, policy, norm, rec) + elif action == "repair_evict": + rec["rule_id"] = "evict:%s" % norm + evictions.append((tokens, norm, rec)) + elif action == "quarantine": + idx = _candidate_index(tokens) + if idx is not None: + quarantined.add(idx) + rec["rule_id"] = "quarantine:%s" % norm + done = True + if done: + _record_repair(seed_obj, tokens, rec, records) + progressed = True + # 행 제거는 값 처분이 끝난 뒤 내림차순으로, 행마다 한 번만 한다. 앞 행을 먼저 지우면 뒤 경로가 밀린다. + evicted_rows: set[tuple[Any, ...]] = set() + for tokens, norm, rec in sorted(evictions, key=lambda row: _path_sort_key(row[2]["path"]), reverse=True): + row = list(tokens) + while row and not isinstance(row[-1], int): + row.pop() + # 같은 행이나 바깥 행을 이미 처리했으면 이 경로는 다른 행을 가리킨다. 지우지 않고 기록만 남긴다. + if any(tuple(row[:n]) in evicted_rows for n in range(1, len(row) + 1)): + rec["applied"] = "quarantined_candidate" if len(row) == 2 and row[0] == "bo_seed_candidates" else "row_already_evicted" + else: + if not _evict(seed_obj, tokens, policy, norm, rec, quarantined): + continue + evicted_rows.add(tuple(row)) + _record_repair(seed_obj, tokens, rec, records) + progressed = True + if progressed: + break + if not progressed: + break + + # 수렴하지 않고 남은 위반은 후보 단위로 격리한다. 회차는 계속된다. + report = _validate(seed_obj) + for err in (report.get("errors") or []): + if not isinstance(err, dict): + continue + # review 로 수용하기로 선언된 코드는 남아 있는 것이 정상이다. 다시 격리하지 않는다. + if str(disposition.get(str(err.get("code"))) or "") == "review": + records.append({"domain_id": domain_id, "code": err.get("code"), "path": err.get("path"), + "action": "review", "received": None, "applied": None, + "rule_id": "disposition:review(residual)"}) + continue + tokens = _path_tokens(str(err.get("path") or "")) + idx = _candidate_index(tokens) + if idx is None: + root_disp = str(policy.get("residual_root_disposition") or "review") + if root_disp == "block": + blocks.append({"code": err.get("code"), "path": err.get("path"), + "message": err.get("message"), "note": "root-level residue"}) + else: + records.append({"domain_id": domain_id, "code": err.get("code"), "path": err.get("path"), + "action": "review", "received": None, "applied": None, + "rule_id": "residual_root"}) + else: + quarantined.add(idx) + records.append({"domain_id": domain_id, "code": err.get("code"), "path": err.get("path"), + "action": "quarantine", "received": None, "applied": None, + "rule_id": "residual_after_repair"}) + return (seed_obj, quarantined, blocks) + + # ---------- PostB_1 이식: sort key / duplicate keys / schema risk ---------- + def _source_refs(seed: dict[str, Any]) -> dict[str, list[str]]: + provenance = _dict(seed.get("provenance")) + return { + "source_evidence_indexes": _strings(seed.get("source_evidence_indexes") or provenance.get("source_evidence_indexes")), + "source_event_candidate_ids": _strings(provenance.get("source_event_candidate_ids")), + "source_meeting_clause_ids": _strings(provenance.get("source_meeting_clause_ids")), + } + + def _sort_key(seed: dict[str, Any]) -> dict[str, Any]: + core = _dict(seed.get("core_field_base")) + domain = seed.get("source_domain") + juristic = _dict(seed.get("JuristicAct")) + return { + "BehaviorTime": core.get("BehaviorTime"), + "domain_order": DOMAIN_ORDER.index(domain) if domain in DOMAIN_ORDER else len(DOMAIN_ORDER), + "BOType": seed.get("BOType"), + "ActionType": seed.get("ActionType"), + "JuristicActLabel": juristic.get("label"), + "Action": seed.get("Action"), + "candidate_ref": seed.get("candidate_ref"), + } + + def _duplicate_key(seed: dict[str, Any]) -> tuple[Any, ...]: + core = _dict(seed.get("core_field_base")) + juristic = _dict(seed.get("JuristicAct")) + refs = _source_refs(seed) + return ( + tuple(sorted(refs["source_evidence_indexes"])), + tuple(sorted(refs["source_event_candidate_ids"])), + seed.get("BOType"), + seed.get("ActionType"), + juristic.get("label"), + str(seed.get("Action") or "").strip(), + str(core.get("BehaviorTime") or "").strip(), + str(core.get("Object") or "").strip(), + # 가액금액 §3.3 f — value_id 만 다른 두 후보(같은 증거 안의 차용증 2건 등)를 정확 중복으로 합치지 않는다. + tuple(sorted(_strings(seed.get("value_refs")))), + ) + + def _normalize_juristic(value: Any) -> Any: + if value is None: + return None + if isinstance(value, dict): + label = value.get("label") + return {"label": str(label).strip()} if label not in (None, "") else {"label": None} + text = str(value).strip() + return {"label": text} if text else None + + def _compact_exception_payload(seeds: list[dict[str, Any]]) -> list[dict[str, Any]]: + compact = [] + for seed in seeds: + compact.append({ + "candidate_ref": seed.get("candidate_ref"), + "source_domain": seed.get("source_domain"), + "BOType": seed.get("BOType"), + "ActionType": seed.get("ActionType"), + "JuristicAct": seed.get("JuristicAct"), + "Action": seed.get("Action"), + "core_field_base": seed.get("core_field_base"), + "amount": seed.get("amount"), + "value_refs": seed.get("value_refs"), + "source_refs": _source_refs(seed), + }) + return compact + + def main() -> None: + _init() + # 2026-11-03 — fan-out 부모(load_fanout)의 판정. 파일이 없거나 CLEARED 가 아니면 멈춘다. + # 없음도 실패다: load_fanout 은 성공·실패 모두 이 파일을 쓰므로 없음은 그 task 가 돌지 않았다는 뜻이다. + try: + _fanout_state = _dict(read_json_doc(FANOUT_BLOCKED_PATH)) + except Exception as exc: + _fanout_state = {"status": "MISSING", "reason": str(exc)[:200]} + if _fanout_state.get("status") != "CLEARED": + raise RuntimeError(json.dumps({ + "reason_code": "PART2_FANOUT_BLOCKED_UPSTREAM", + "message": "load_fanout 이 worker fan-out 을 내지 못했다. A0 실패 또는 계획 sha 불일치다. seed 를 읽지 않는다.", + "state": _fanout_state}, ensure_ascii=False)) + # F-4a — 자기 정적 입력. try 밖이어야 한다. 안에 넣으면 아래 except Exception 이 + # 삼켜 WORKER_VALIDATOR_UNAVAILABLE 경고로 강등되고 R0 이 계속 돈다. + _seed_schema_body = _verify_asset(SEED_SCHEMA_PATH) + # R0-1 — 투영 정책 반입 (F-4a 와 같은 규율: try 밖 경성). 정책이 없거나 낡았는데 + # 조용히 옛 규칙으로 도는 것이 이번 결손(v2 잔재)의 재발 경로다. + projection_policy = _dict(json.loads(_verify_asset(BO_PROJECTION_POLICY))) + if projection_policy.get("schema_version") != BO_PROJECTION_SCHEMA_VERSION: + raise RuntimeError("PART2_PROJECTION_POLICY_INVALID") + amount_selection = _dict(projection_policy.get("amount_selection")) + if not _list(amount_selection.get("tiers")): + raise RuntimeError("PART2_PROJECTION_POLICY_STALE: amount_selection.tiers") + # 가액금액 §3.3 — A0 가 쓴 카탈로그. BOUND 가 아니면 records 가 비어 있다. + catalog = _dict(read_json_doc(CATALOG_PATH)) + catalog_binding = _dict(catalog.get("binding")) + catalog_records = {str(r["value_id"]): r for r in _list(catalog.get("records")) + if isinstance(r, dict) and r.get("value_id")} + worker_numbers_ignored = 0 + # F-4b — 미러 넷의 무결성. 부재는 통과시키고 미등재·불일치만 막는다. + for _mirror in VALIDATOR_MIRRORS.values(): + _assert_mirror_consistent(_mirror) + salvage_notes: list[dict[str, Any]] = [] + guard_warnings: list[dict[str, Any]] = [] + # v4 — seed 목록과 그 순서는 A0 의 fan-out 계획이 정한다. 이 파일은 목록을 만들지 않는다. + worker_validator = None + seed_schema = None + try: + materialize_validator() + import worker_output_validator as worker_validator + seed_schema = json.loads(_seed_schema_body) + except Exception as exc: + guard_warnings.append({"code": "WORKER_VALIDATOR_UNAVAILABLE", "message": str(exc)[:200]}) + worker_validator = None + _docs, _rows = _seed_docs_from_plan(_dict(read_json_doc(FANOUT_PLAN_PATH))) + SEED_DOCS.update(_docs) + PLAN_ROWS.update(_rows) + DOMAIN_ORDER.extend(_domain_order(SEED_DOCS)) + stage_a_outer = read_json_doc(STAGE_A_PATH) + stage_a = _dict(_dict(stage_a_outer).get("stage_a_context") or stage_a_outer) + if stage_a.get("schema_version") != "task_c_bo_stage_a_context.v1" or stage_a.get("status") != "READY": + raise RuntimeError("Stage A context must be READY task_c_bo_stage_a_context.v1") + manifest = _dict(read_json_doc(MANIFEST_PATH)) + universe = { + "source_event_candidate_ids": set(_strings(manifest.get("event_candidate_ids"))), + "source_evidence_indexes": set(_strings(manifest.get("evidence_index_set"))), + "source_meeting_clause_ids": set(_strings(manifest.get("meeting_clause_ids"))), + } + if not universe["source_evidence_indexes"]: + raise RuntimeError("source universe manifest has no evidence indexes") + + # 1) 워커 출력 수용: 검증 -> 투영. 워커 seed 파일은 손대지 않는다 — + # 선언표(stage1_part_interface.v1)가 기록자를 워커 하나로 정했다(R0-5). + admission_policy = _dict(json.loads(_verify_asset(SEED_ADMISSION_POLICY_PATH))) + if admission_policy.get("schema_version") != SEED_ADMISSION_SCHEMA_VERSION: + raise RuntimeError("PART2_SEED_ADMISSION_POLICY_INVALID") + admission_enforcing = str(admission_policy.get("enforcement") or "enforce") == "enforce" + admission_records: list[dict[str, Any]] = [] + declared_candidate_total = 0 + admission_blocks: list[dict[str, Any]] = [] + quarantined_by_domain: dict[str, set] = {} + admitted_total = 0 + quarantined_total = 0 + + seed_objects: dict[str, dict[str, Any]] = {} + projected_candidates: dict[str, list[dict[str, Any]]] = {} + review_handoff_items: list[dict[str, Any]] = [] + allowed_bo_types_by_domain: dict[str, set[str]] = {} + projection_review_counter = 0 + for domain_id in DOMAIN_ORDER: + # v4 — worker 가 {{item.expected_output_path}} 에 자기 seed 를 직접 쓴다. + # {{prev}} 원문 관용 파싱이 아니라 계획이 정한 경로에서 읽는다. + try: + outer = _dict(read_json_doc(SEED_DOCS[domain_id])) + except Exception as exc: + # capture 가 비JSON 표식(CAPTURE_FAILED …)을 썼거나 파일이 없다. 이름 없는 JSONDecodeError 대신 사유를 남긴다. + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SEED_CAPTURE_FAILED", "domain_id": domain_id, + "path": SEED_DOCS[domain_id], "detail": str(exc)[:200]}, ensure_ascii=False)) + seed_obj = _dict(outer.get("stage_b_domain_bo_seed_output")) + if not seed_obj: + raise RuntimeError(f"{domain_id}: stage_b_domain_bo_seed_output missing") + # 메모리 수리 전에 잰다. S0 가 같은 worker 산출인지 대조한다. + raw_seed_sha256 = hashlib.sha256(json.dumps(outer, sort_keys=True).encode("utf-8")).hexdigest() + # validate_seed_object 가 수용 정책보다 먼저 돈다. 등록된 status 동의어는 여기서 적용한다. + _raw_status = seed_obj.get("status") + _status_table = _dict(_dict(admission_policy.get("enum_synonyms")).get("status")) + if admission_enforcing and isinstance(_raw_status, str) and _status_table.get(_raw_status.casefold(), _raw_status) != _raw_status: + seed_obj["status"] = _status_table[_raw_status.casefold()] + admission_records.append({"domain_id": domain_id, "code": "SEED_STATUS_NORMALIZED", + "path": "$.stage_b_domain_bo_seed_output.status", "action": "repair_normalize", + "received": _raw_status, "applied": seed_obj["status"], + "rule_id": "enum_synonyms:status"}) + _plan_row = PLAN_ROWS.get(domain_id) or {} + _echo_mismatches: list[dict[str, Any]] = [] + validate_seed_object(seed_obj, domain_id, _plan_row, guard_warnings, _echo_mismatches) + # 슬라이스는 검증기 유무와 무관하게 읽는다 — worker_output_validator 와 + # BOType 허용 어휘(allowed_legal_effect_bo_types, registry 유래)가 이 값을 쓴다. + # 원문도 함께 든다 — 신선도 판정의 실물 근거가 이 바이트열의 해시다. + # D3 — 원문 읽기가 실패해도 문서 자체는 기존 경로로 다시 시도한다. read_raw 는 봉투가 + # 다르면 raise 하므로, 그것 때문에 slice_doc 까지 잃으면 allowed_legal_effect_bo_types 가 + # 조용히 빈 집합이 된다. + _slice_raw = None + slice_doc = None + try: + _slice_raw = read_raw("%s/%s.json" % (SLICE_DIR, domain_id)) + slice_doc = json.loads(_slice_raw) + except Exception: + _slice_raw = None + try: + slice_doc = read_json_doc("%s/%s.json" % (SLICE_DIR, domain_id)) + except Exception: + slice_doc = None + # R0-7a — 신선도의 실물 근거. 계획서가 든 sha 와 R0 가 지금 읽은 문서의 sha 를 맞춘다. + # 둘 다 모델을 거치지 않으므로 여기서 어긋나면 정말로 낡았거나 배포가 어긋난 것이다. + _want_slice = _plan_row.get("slice_sha256") + if isinstance(_want_slice, str) and _want_slice and _slice_raw is not None: + # sha_text 는 A0 블록 전용이다. R0 는 이 블록의 관용대로 인라인으로 센다. + _actual_slice = hashlib.sha256(_slice_raw.encode("utf-8")).hexdigest() + if _actual_slice != _want_slice: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SLICE_STALE", + "message": "fan-out 계획이 든 slice sha 와 실제 slice 문서가 다르다. 시드가 아니라 슬라이스가 어긋났다.", + "domain_id": domain_id, "expected": _want_slice, "actual": _actual_slice, + }, ensure_ascii=False)) + # R0-7b — echo 불일치의 등급은 정책이 정한다. 다만 두 실패는 성격이 다르므로 코드를 가른다. + # · 다른 슬라이스의 sha 를 echo 했다 = 워커가 **엉뚱한 슬라이스로 작업**했다는 뜻이다. + # 실물 대조로는 원리상 못 잡는다(그 도메인 슬라이스는 멀쩡하다). 중대 위반이다. + # · 그 밖(예: activation_manifest_sha256 을 집음)은 전사 실수다. 검토로 족하다. + # D2 — 슬라이스를 못 읽어 실물 대조를 못 한 도메인은 신선도 방어가 0 이 된다. + # 그 경우에는 echo 를 검토로 강등하지 않는다. + # 판정은 slice 에 한정하지 않는다 — 다른 도메인의 compiled_prompt sha 를 집은 것도 + # 그 도메인 자료를 읽었다는 뜻이라 같은 무게다. 두 필드를 합쳐 "남의 자료" 집합을 만든다. + _foreign_material_shas = set() + _own_material_shas = {str(_plan_row.get(_mk)) for _mk in ("slice_sha256", "compiled_prompt_sha256") + if _plan_row.get(_mk)} + for _d2, _r in PLAN_ROWS.items(): + if _d2 == domain_id or not isinstance(_r, dict): + continue + for _mk in ("slice_sha256", "compiled_prompt_sha256"): + if _r.get(_mk): + _foreign_material_shas.add(str(_r.get(_mk))) + # D7 — 두 도메인의 자료가 우연히 같아지면(예: 빈 도메인 둘) 정상 산출이 남의 것으로 오판된다. + # 자기 값을 빼서 원천 차단한다. 현 데이터에는 중복이 없지만 데이터의 성질에 기대지 않는다. + _foreign_material_shas -= _own_material_shas + # D8 — 우리가 양성으로 아는 유일한 오집합은 activation_manifest_sha256 이다(값으로 식별된다). + # 그것만 전사 실수로 보고, 설명되지 않는 값은 미상으로 두어 더 무겁게 다룬다. + _known_slip_sha = str(_dict(_dict(_dict(slice_doc).get(SLICE_ROOT_KEY)).get("activation")).get( + "activation_manifest_sha256") or "") + _disp_map = _dict(admission_policy.get("disposition_by_code")) + for _em in _echo_mismatches: + _rcv = str(_em.get("received")) + if _rcv in _foreign_material_shas: + _code = "SEED_ECHO_FOREIGN_SLICE" + elif _slice_raw is None: + # 원문이 없으면 실물 대조가 불가능하다. 이 상태에서는 known slip 이라도 강등하지 않는다 — + # activation_manifest_sha256 은 전 도메인이 공유하는 값이라 어느 슬라이스를 읽었는지에 + # 대해 아무것도 말해 주지 않는다. 그것을 근거로 가볍게 볼 수 없다. + _code = "SEED_ECHO_SHA_UNVERIFIABLE" + elif _known_slip_sha and _rcv == _known_slip_sha: + _code = "SEED_ECHO_SHA_MISMATCH" + else: + _code = "SEED_ECHO_SHA_UNEXPLAINED" + _disp = str(_disp_map.get(_code) or ("block" if _code == "SEED_ECHO_FOREIGN_SLICE" + else "review" if _code == "SEED_ECHO_SHA_MISMATCH" + else "quarantine")) + if _disp == "block": + raise RuntimeError(json.dumps(dict( + {"reason_code": "PART2_%s" % _code}, **_em), ensure_ascii=False)) + admission_records.append({ + "domain_id": domain_id, "code": _code, + "path": "$.stage_b_domain_bo_seed_output.%s" % _em["key"], + "action": _disp, "received": _em.get("received"), "applied": None, + "rule_id": "echo_sha_not_trusted:%s" % _em["key"]}) + slice_root = _dict(_dict(slice_doc).get(SLICE_ROOT_KEY)) if isinstance(slice_doc, dict) else {} + allowed_bo_types = set(_strings(slice_root.get("allowed_legal_effect_bo_types"))) + allowed_bo_types_by_domain[domain_id] = allowed_bo_types + # R0-6 — 검증 결과를 경고로 흘리지 않고 등급대로 처분한다. + # shadow 모드에서는 계산·기록만 하고 seed 를 바꾸지 않는다(첫 전환 회차용). + # D13 — 회계 누적은 검증기 유무와 무관하다. 분기 안에 두면 검증기 반입이 + # 실패한 회차에서 declared=0 · admitted=N 이 되어 헛경보(lost 음수)가 난다. + declared_candidate_total += len(_list(seed_obj.get("bo_seed_candidates"))) + # 가액금액 §3.3 a — 아래 경고 전용 검증과 admit_seed 보다 앞이다. enforce·shadow 모두 적용한다. + _slice_ids = {str(_dict(x).get("source_id")) for x in _list(slice_root.get("source_universe")) + if _dict(x).get("source_id")} + amount_bindings, cand_value_refs, _ignored = bind_value_ids( + seed_obj, catalog_records, domain_id, admission_records, _slice_ids) + worker_numbers_ignored += _ignored + if worker_validator is not None: + # 이 호출은 경고만 모은다. 검증기가 죽는 입력은 뒤의 admit_seed 가 후보 단위로 격리한다. + try: + _worker_warnings = worker_validator.validate_worker_output( + {"stage_b_domain_bo_seed_output": seed_obj}, schema=seed_schema, + expected_domain_id=domain_id, slice_document=slice_doc).get("warnings") or [] + except Exception: + _worker_warnings = [] + for item in _worker_warnings: + guard_warnings.append({"code": "WORKER_OUTPUT_REVIEW", "domain_id": domain_id, + "detail": item}) + # 처분이 review 인 경고는 handoff 로 올린다. audit_trace 에만 두면 아무도 보지 못한다. + if _dict(admission_policy.get("disposition_by_code")).get(_dict(item).get("code")) == "review": + _at = re.search(r"bo_seed_candidates\[(\d+)\]", str(_dict(item).get("path") or "")) + admission_records.append({ + "domain_id": domain_id, "code": _dict(item).get("code"), + "path": _dict(item).get("path") or "$", "action": "review", + "received": _dict(item).get("message") or _dict(item).get("status"), + "applied": None, "rule_id": "worker_output_warning", + "candidate_ref": "%s:%03d" % (domain_id, int(_at.group(1)) + 1) if _at else None}) + work_obj = seed_obj if admission_enforcing else copy.deepcopy(seed_obj) + admitted_obj, quarantined_idx, blocks = admit_seed( + work_obj, domain_id, seed_schema, slice_doc, universe, + admission_policy, admission_records, PLAN_ROWS.get(domain_id) or {}, + worker_validator) + if blocks: + admission_blocks.extend({"domain_id": domain_id, **b} for b in blocks) + if admission_enforcing: + seed_obj = admitted_obj + quarantined_by_domain[domain_id] = quarantined_idx + else: + quarantined_by_domain[domain_id] = set() + for b in blocks: + guard_warnings.append({"code": "SEED_ADMISSION_SHADOW_BLOCK", + "domain_id": domain_id, "detail": b}) + cands = _list(seed_obj.get("bo_seed_candidates")) + projected: list[dict[str, Any]] = [] + projection_reviews: list[dict[str, Any]] = [] + skip_idx = quarantined_by_domain.get(domain_id) or set() + for idx, cand in enumerate(cands): + if idx in skip_idx: + quarantined_total += 1 + continue + if not isinstance(cand, dict): + raise RuntimeError(f"{domain_id}.bo_seed_candidates[{idx}] must be object") + # 복사 전 원본 객체로 찾는다(ensure_candidate_ref 가 dict 를 복사한다). + value_ctx = {"records": catalog_records, "amount_bindings": amount_bindings, + "cand_refs": cand_value_refs.get(id(cand), set()), "selection": amount_selection} + cand = ensure_candidate_ref(cand, domain_id, idx) + validate_candidate(cand, domain_id, idx) + # R0-6′ — 근거 참조가 하나도 없는 후보는 투영하지 않는다. 후보 소실 경로는 격리(D4) 하나뿐이다. + if admission_enforcing and not _strings(cand.get("source_refs")): + quarantined_total += 1 + admission_records.append({"domain_id": domain_id, "code": "EMPTY_SEED_DROPPED", + "path": "$.stage_b_domain_bo_seed_output.bo_seed_candidates[%d]" % idx, + "action": "quarantine", "received": [], "applied": None, + "rule_id": "quarantine:empty_source_refs", "candidate_ref": cand.get("candidate_ref")}) + continue + # membership 검사 — v3 의 평평한 source_refs 를 universe 와 대조 (hard BLOCK). + # 이쪽을 보지 않으면 membership 게이트가 v3 산출에서는 통과만 하는 빈 검사가 된다. + # 가액금액 §3.3 b — 정본 id 도 소속으로 본다(전처리가 놓친 경우의 방어선, 필수). + known_sources = (universe["source_event_candidate_ids"] | universe["source_meeting_clause_ids"] + | universe["source_evidence_indexes"] | set(catalog_records)) + ref_bad = [v for v in _strings(cand.get("source_refs")) if v not in known_sources] + if ref_bad: + raise RuntimeError(f"BLOCK: {domain_id}.{cand.get('candidate_ref')}: source_refs outside Stage A universe: {ref_bad}") + projected.append(project_to_bo_surface(cand, domain_id, universe, projection_policy, + allowed_bo_types, projection_reviews, value_ctx)) + # R0-5 — 워커 파일은 되쓰지 않는다. 수용본은 따로 쓰고, S0 가 이것과 원본 행을 함께 읽는다. + # 투영본은 projected_candidates 가 따로 든다(R0-2 배선). + seed_objects[domain_id] = seed_obj + write_doc("%s/%s.json" % (ADMITTED_SEED_DIR, domain_id), + json.dumps({"stage_b_domain_bo_seed_output": seed_obj, "raw_seed_sha256": raw_seed_sha256})) + projected_candidates[domain_id] = projected + # R0-4 — v3 검토 채널: 후보별 review_items + 루트 unknown_or_unrouted_reviews. + # list(...) 복사는 워커 원본 목록을 제자리 변형하지 않기 위한 것이다. + worker_reviews = list(_list(seed_obj.get("unknown_or_unrouted_reviews"))) + for cand in _list(seed_obj.get("bo_seed_candidates")): + worker_reviews.extend(_list(_dict(cand).get("review_items"))) + if seed_obj.get("status") == "NO_SUPPORT": + worker_reviews.append({"review_id": f"{domain_id}:status:NO_SUPPORT", + "review_code": "NO_SUPPORT", + "unresolved_type": "review_required", + "severity": "SOFT_WARNING", + "reason": "worker reported NO_SUPPORT (nothing to carry for this domain)"}) + for idx, item in enumerate(worker_reviews, start=1): + mapped = expand_review_item(item, domain_id, idx) + refs = set(mapped.get("source_refs") or []) + review_handoff_items.append({ + "review_id": mapped["review_id"], + "source_domain": domain_id, + "severity": mapped["severity"], + "issue_type": mapped["issue_type"], + "source_review_code": mapped.get("source_review_code"), + "source_event_candidate_ids": sorted(refs & universe["source_event_candidate_ids"]), + "source_evidence_indexes": sorted(refs & universe["source_evidence_indexes"]), + "source_meeting_clause_ids": sorted(refs & universe["source_meeting_clause_ids"]), + "downstream_owner": mapped["recommended_downstream_owner"] if mapped.get("recommended_downstream_owner") in DOWNSTREAM_OWNER_ENUM else "Stage2", + "template_note": mapped.get("reason") or "후속 단계에서 해당 review 항목의 증거와 법률상 의미를 재검토한다.", + }) + for note_item in projection_reviews: + projection_review_counter += 1 + entry = { + "review_id": "R0:projection:%03d" % projection_review_counter, + "source_domain": domain_id, + "severity": "SOFT_WARNING", + "issue_type": note_item["issue_type"], + "source_review_code": note_item.get("field"), + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "투영 규칙이 채우지 못했거나 기본값을 적용한 칸이다: %s ← %s (%s)" % ( + note_item.get("field"), note_item.get("source"), note_item.get("candidate_ref")), + } + if note_item.get("field") == "Action": + entry["action_source"] = note_item.get("source") + # 금액 칸은 field 가 늘 같으므로 코드(source)를 review code 로 쓴다. + if note_item.get("field") in ("amount", "payload.value_id"): + entry["source_review_code"] = note_item.get("source") + # §3.3 g — handoff 의 세 ref 집합에는 value_id 가 남지 않으므로 따로 둔다. + if note_item.get("value_ids"): + entry["source_value_fact_ids"] = note_item["value_ids"] + review_handoff_items.append(entry) + + if worker_numbers_ignored: + guard_warnings.append({"code": "AMOUNT_WORKER_VALUE_IGNORED", "count": worker_numbers_ignored}) + # 가액금액 §3.1 — 정본을 쓰지 못한 회차는 BO amount 가 모두 null 이다. 그 사실을 검토로 남긴다. + for _bd in (DOMAIN_ORDER if catalog_binding.get("status") != "BOUND" else []): + _mismatch = catalog_binding.get("status") == "MISMATCH" + review_handoff_items.append({ + "review_id": "R0:value_facts:binding:%s" % _bd, + "source_domain": _bd, + "severity": "HARD_WARNING" if _mismatch else "SOFT_WARNING", + "issue_type": "amount_or_date_uncertain", + "source_review_code": "VALUE_FACTS_INTEGRITY_MISMATCH" if _mismatch else "VALUE_FACTS_ABSENT", + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "가액금액 정본을 결속하지 못해 BO amount 를 채우지 않았다: %s (%s)" % ( + catalog_binding.get("status"), catalog_binding.get("reason")), + }) + + # R0-6b — 수용 결산. 격리는 후보 단위이고, 회차 중단은 예산을 넘을 때만이다. + admitted_total = sum(len(v) for v in projected_candidates.values()) + # D4 — 수용 단계에서 후보가 사라지는 경로는 격리 하나뿐이어야 한다. + # 원본 후보 수와 (수용 + 격리)가 맞지 않으면 소리 없이 없어진 것이 있다는 뜻이다. + if admission_enforcing and declared_candidate_total != admitted_total + quarantined_total: + guard_warnings.append({"code": "SEED_ADMISSION_ACCOUNTING_DRIFT", + "declared": declared_candidate_total, "admitted": admitted_total, + "quarantined": quarantined_total, + "lost": declared_candidate_total - admitted_total - quarantined_total}) + if admission_blocks and admission_enforcing: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SEED_ADMISSION_BLOCKED", + "message": "시드 뿌리 계약이 깨졌다. 복구 대상이 아니다.", + "blocks": admission_blocks[:20], "block_count": len(admission_blocks), + }, ensure_ascii=False)) + budget = _dict(admission_policy.get("quarantine_budget")) + seen_total = admitted_total + quarantined_total + ratio = (quarantined_total / seen_total) if seen_total else 0.0 + max_ratio = budget.get("max_quarantined_candidate_ratio") + min_admitted = budget.get("min_admitted_candidates_run") + if admission_enforcing and isinstance(max_ratio, (int, float)) and seen_total and ratio > float(max_ratio): + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", + "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", + "quarantined": quarantined_total, "seen": seen_total, + "ratio": round(ratio, 4), "max_ratio": max_ratio, + }, ensure_ascii=False)) + if admission_enforcing and isinstance(min_admitted, int) and admitted_total < min_admitted: + raise RuntimeError(json.dumps({ + "reason_code": "PART2_SEED_ADMISSION_EMPTY", + "message": "수용된 후보가 없다.", "admitted": admitted_total, + }, ensure_ascii=False)) + _adm_review = _dict(admission_policy.get("review")) + _adm_counter = 0 + for rec in admission_records: + _adm_counter += 1 + _is_q = rec.get("action") == "quarantine" + _is_c = bool(rec.get("content_bearing")) and not _is_q + review_handoff_items.append({ + "review_id": "R0:admission:%03d" % _adm_counter, + "source_domain": rec.get("domain_id"), + "severity": str((_adm_review.get("quarantine_severity") if _is_q + else _adm_review.get("evicted_with_content_severity") if _is_c + else _adm_review.get("severity")) or "SOFT_WARNING"), + "issue_type": str((_adm_review.get("quarantine_issue_type") if _is_q + else _adm_review.get("evicted_with_content_issue_type") if _is_c + else _adm_review.get("issue_type")) or "seed_admission_repair"), + "source_review_code": rec.get("code"), + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": str(_adm_review.get("downstream_owner") or "Stage2"), + "template_note": "수용 단계 처분: %s · 경로 %s · 규칙 %s · 원값 %s -> 적용 %s (후보 %s)" % ( + rec.get("action"), rec.get("path"), rec.get("rule_id"), + rec.get("received"), rec.get("applied"), rec.get("candidate_ref")), + }) + guard_warnings.append({"code": "SEED_ADMISSION_SUMMARY", + "enforcement": admission_policy.get("enforcement"), + "repairs": sum(1 for r in admission_records if str(r.get("action") or "").startswith("repair")), + "reviews": sum(1 for r in admission_records if r.get("action") == "review"), + "quarantined_candidates": quarantined_total, + "admitted_candidates": admitted_total, + "quarantine_ratio": round(ratio, 4)}) + + # 2) ledger 구성 — 원장은 워커 원본이 아니라 투영본을 읽는다 (R0-2 배선). + # 워커 원본에는 candidate_ref 가 없으므로(봉인 스키마) 원본을 넣으면 아래 검사에서 즉사한다. + input_candidate_total = 0 + seeds: list[dict[str, Any]] = [] + for domain_id in DOMAIN_ORDER: + projected = projected_candidates[domain_id] + input_candidate_total += len(projected) + seeds.extend(projected) + if not seeds: + raise RuntimeError("no seed candidate from Stage B workers") + + seen_refs: set[str] = set() + ledger_candidates: list[dict[str, Any]] = [] + deterministic_decisions: list[dict[str, Any]] = [] + exceptions: list[dict[str, Any]] = [] + duplicate_buckets: dict[tuple[Any, ...], list[dict[str, Any]]] = {} + policy_review_counter = 0 + + def add_policy_review(domain_id: str, issue_type: str, refs: dict[str, list[str]], severity: str = "SOFT_WARNING") -> None: + nonlocal policy_review_counter + policy_review_counter += 1 + review_handoff_items.append({ + "review_id": f"R0:policy:{policy_review_counter:03d}", + "source_domain": domain_id, + "severity": severity, + "issue_type": issue_type, + "source_event_candidate_ids": refs.get("source_event_candidate_ids", []), + "source_evidence_indexes": refs.get("source_evidence_indexes", []), + "source_meeting_clause_ids": refs.get("source_meeting_clause_ids", []), + "downstream_owner": "Stage2", + "template_note": "결정적 defer 정책에 의해 보존된 검토 항목이다.", + }) + + for seed in seeds: + ref = seed.get("candidate_ref") + if not isinstance(ref, str) or not CANDIDATE_REF_RE.fullmatch(ref): + raise RuntimeError(f"invalid candidate_ref: {ref!r}") + if ref in seen_refs: + raise RuntimeError(f"duplicate candidate_ref: {ref}") + seen_refs.add(ref) + refs = _source_refs(seed) + # hard BLOCK: universe 밖 ref는 soft-strip 이후에도 남아있으면 안 된다 (방어적 재검사) + for key, values in refs.items(): + allowed = universe.get(key, set()) + outside = [v for v in values if allowed and v not in allowed] + if outside: + raise RuntimeError(f"{ref}: {key} outside Stage A universe: {outside}") + flags: list[str] = [] + # 결정적 defer 정책 (개선전략서 X-2): + # C-2 (P0 판정 B) — 증거 단계에서 붙은 registry 구성요소는 증거 유래 근거다. + # _source_refs 가 seed 루트와 provenance 를 모두 보는 관례를 그대로 따른다. + registry_components = [ + str(value) + for value in (seed.get("registry_component_ids") + or _dict(seed.get("provenance")).get("registry_component_ids") + or []) + if isinstance(value, str) and value + ] + if not refs["source_evidence_indexes"] and not registry_components: + flags.append("meeting_only_evidence_gap") + add_policy_review(seed.get("source_domain"), "meeting_only_evidence_gap", refs) + domain_allowed = allowed_bo_types_by_domain.get(str(seed.get("source_domain"))) or set() + if (domain_allowed and seed.get("BOType") not in domain_allowed) or not seed.get("ActionType") or not ( + seed.get("Action") or _dict(_dict(seed.get("extensions")).get("domain_payload")).get("action_summary") + ): + flags.append("schema_field_fallback") + add_policy_review(seed.get("source_domain"), "schema_field_fallback", refs) + link_candidates = _strings(_dict(seed.get("downstream_seed_refs")).get("prior_candidate_refs")) + if len(link_candidates) > 1: + flags.append("prior_link_ambiguous") + add_policy_review(seed.get("source_domain"), "prior_link_ambiguous", refs) + duplicate_buckets.setdefault(_duplicate_key(seed), []).append(seed) + ledger_candidates.append({ + "candidate_ref": ref, + "source_domain": seed.get("source_domain"), + "seed_payload": seed, + "source_refs": refs, + "deterministic_sort_key": _sort_key(seed), + "flags": flags, + }) + + # exact duplicate: provenance union 무손실이므로 canonical merge (v2 규칙 계승) + for bucket in duplicate_buckets.values(): + if len(bucket) <= 1: + continue + canonical = bucket[0].get("candidate_ref") + duplicates = [item.get("candidate_ref") for item in bucket[1:]] + deterministic_decisions.append({ + "decision_type": "EXACT_DUPLICATE_MERGE", + "canonical_candidate_ref": canonical, + "duplicate_candidate_refs": duplicates, + "basis": "exact duplicate deterministic rule (provenance-lossless union)", + }) + + # near duplicate: KEEP_SEPARATE + cluster id + review (LLM 금지 — defer 정책) + near_buckets: dict[tuple[Any, ...], list[dict[str, Any]]] = {} + for seed in seeds: + refs = _source_refs(seed) + # 개정전략서_part_2_11_04_4pm H-4 — 사건 id 가 있으면 사건 단위, 없으면 문서 단위로 묶는다. + events = tuple(sorted(refs["source_event_candidate_ids"])) + if events: + key = ("event", events, seed.get("BOType"), seed.get("ActionType")) + else: + key = ("document", tuple(sorted(refs["source_evidence_indexes"])), + seed.get("BOType"), seed.get("ActionType")) + near_buckets.setdefault(key, []).append(seed) + near_cluster_count = 0 + pack_field_conflicts: list[dict[str, Any]] = [] + for bucket in near_buckets.values(): + if len(bucket) <= 1 or len({_duplicate_key(s) for s in bucket}) <= 1: + continue + near_cluster_count += 1 + cluster_id = f"near-dup-{near_cluster_count:03d}" + cluster_refs = [str(s.get("candidate_ref")) for s in bucket] + for item in ledger_candidates: + if item["candidate_ref"] in cluster_refs: + item.setdefault("near_dup_cluster_id", cluster_id) + if "near_duplicate_kept_separate" not in item["flags"]: + item["flags"].append("near_duplicate_kept_separate") + add_policy_review(bucket[0].get("source_domain"), "near_duplicate_kept_separate", + {"source_evidence_indexes": _source_refs(bucket[0])["source_evidence_indexes"], + "source_event_candidate_ids": _source_refs(bucket[0])["source_event_candidate_ids"], + "source_meeting_clause_ids": []}) + # 같은 near cluster 에서 BehaviorTime 또는 amount 가 서로 다르면 같은 행위의 상충일 수 있다. + # R1 이 병합·보존·사람 판정을 정한다. BLOCK_REVIEW 이면 후보는 따로 보존되고 F0 가 사람 판정 review 로 넘긴다(H-1). + times = {str(_dict(s.get("core_field_base")).get("BehaviorTime")) for s in bucket if _dict(s.get("core_field_base")).get("BehaviorTime")} + amounts = set() + for s in bucket: + av = s.get("amount") + if isinstance(av, dict) and av.get("value_text"): + amounts.add("%s (%s)" % (av.get("value_text"), av.get("value_id")) if av.get("value_id") + else str(av.get("value_text"))) + elif isinstance(av, str) and av.strip(): + amounts.add(av.strip()) + if len(times) > 1 or len(amounts) > 1: + pack_field_conflicts.append({ + "exception_id": f"EX-FIELD-{len(pack_field_conflicts) + 1:03d}", + "exception_type": "field_conflict", + "candidate_refs": cluster_refs, + "reason": "same-source candidates carry conflicting BehaviorTime/amount values", + "conflicting_values": {"BehaviorTime": sorted(times), "amount": sorted(amounts)}, + "compact_candidate_payload": _compact_exception_payload(bucket), + "allowed_decisions": ["KEEP_SEPARATE", "MERGE", "SPLIT", "DROP", "BLOCK_REVIEW"], + "escalation_flag": True, + }) + + exceptions.extend(pack_field_conflicts) + has_exceptions = bool(exceptions) + + # 3) conservation invariant (write 전) + merged_absorbed = sum(len(_strings(d.get("duplicate_candidate_refs"))) for d in deterministic_decisions) + if len(ledger_candidates) != input_candidate_total: + raise RuntimeError(f"ledger candidate count {len(ledger_candidates)} != input candidates {input_candidate_total}") + if len(seen_refs) != input_candidate_total: + raise RuntimeError("candidate_ref conservation failed") + + ledger = { + "postb_seed_ledger": { + "schema_version": "task_c_bo_postb_seed_ledger.v1", + "status": "READY", + "source_stage_a_created_at_utc": stage_a.get("created_at_utc"), + "input_digests_sha256": stage_a.get("input_digests_sha256"), + "source_universe": { + "source_event_candidate_ids": sorted(universe["source_event_candidate_ids"]), + "source_evidence_indexes": sorted(universe["source_evidence_indexes"]), + "source_meeting_clause_ids": sorted(universe["source_meeting_clause_ids"]), + }, + "stage_b_source_contract": { + "schema_version": "task_c_bo_stage_b_bo_seed_universe.compat_from_r0.v1", + "status": "READY", + "compatibility_source": "r0_seed_reducer.direct_worker_outputs", + }, + "ledger_candidates": sorted(ledger_candidates, key=lambda item: ( + item["deterministic_sort_key"].get("BehaviorTime") is None, + item["deterministic_sort_key"].get("BehaviorTime") or "", + item["deterministic_sort_key"].get("domain_order", 99), + item["deterministic_sort_key"].get("BOType") or "", + item["deterministic_sort_key"].get("ActionType") or "", + item["deterministic_sort_key"].get("JuristicActLabel") or "", + item["deterministic_sort_key"].get("Action") or "", + item["deterministic_sort_key"].get("candidate_ref") or "", + )), + "deterministic_decisions": deterministic_decisions, + "exception_pack": { + "has_exceptions": has_exceptions, + "clusters": [], + "field_conflicts": pack_field_conflicts, + "link_ambiguities": [], + "schema_risks": [], + }, + "audit_trace": { + "removed_or_sidecar_fields": [], + "source_membership_policy": "outside-universe source ref => hard BLOCK (defer 정책 §7)", + "normalization_notes": salvage_notes + guard_warnings, + }, + } + } + write_doc(LEDGER_PATH, json.dumps(ledger, ensure_ascii=False, indent=2)) + + pack = { + "schema_version": "stage1_part2_exception_pack.v1", + "has_exceptions": has_exceptions, + "exception_count": len(exceptions), + "exceptions": exceptions, + "budget": {"max_candidates_per_exception": 8, "max_payload_chars_per_candidate": 2000}, + } + write_doc(PACK_PATH, json.dumps(pack, ensure_ascii=False, indent=2)) + + handoff = { + "schema_version": "stage1_part2_review_handoff.v1", + "status": "PENDING_FINALIZE", + "review_items": review_handoff_items, + } + write_doc(REVIEW_HANDOFF_PATH, json.dumps(handoff, ensure_ascii=False, indent=2)) + + print(json.dumps({ + "status": "READY", + "message": "R0 seed reducer 완료: ledger/exception pack/review handoff 생성", + "ledger_path": LEDGER_PATH, + "exception_pack_path": PACK_PATH, + "review_handoff_path": REVIEW_HANDOFF_PATH, + "has_exceptions": has_exceptions, + "exception_count": len(exceptions), + "candidate_counts": { + "input": input_candidate_total, + "ledger": len(ledger_candidates), + "exact_duplicate_absorbed": merged_absorbed, + "near_dup_clusters": near_cluster_count, + }, + "review_item_count": len(review_handoff_items), + "salvage_count": len(salvage_notes), + }, ensure_ascii=False)) + + if __name__ == "__main__": + try: + main() + except Exception as exc: + print(json.dumps({"status": "FAILED", "message": "R0 seed reducer 실패: downstream 진행 금지", + "reason": str(exc)}, ensure_ascii=False)) + raise + + - task_name: Task_C_BO_R1_exception_adjudicator + llm_provider: google + llm_model: gemini-3.5-flash-lite + llm_reasoning: low + llm_verbosity: low + max_iterations: 1 + use_tools: + - localdocs + cache_control: + mode: auto + ttl: 20m + preflight: true + preflight_files: + - quality_gates/stage1_part2_exception_pack.json + prompts: + - role: user + content: |- + + + - You are executing one LLM sub-task inside Stage 1 of a Korean civil-litigation complaint-generation pipeline. + - The current task's static block, role overlay, assigned inputs, output schema, and writer boundary control. + - This common prefix cannot expand the current task's input set, output set, legal domain, validation authority, writer authority, or reasoning depth. + - If any common rule appears broader than the current task, apply only the narrower current-task version. + - Stage 1 prepares verified structured artifacts. Do not draft complaint prose or final counsel-level conclusions unless the current task explicitly authorizes a validation or gate conclusion. + + + + - Use only assigned files, provided context inputs, prior outputs, and allowed tools. + - Do not import facts, law, procedural history, parties, dates, amounts, IDs, document contents, or source meanings from memory, outside knowledge, or unassigned files. + - Treat prior outputs as authority only to the extent the current task names them or provides them as context. + - If a value is unsupported, missing, conflicting, stale, or out of scope, use only the current schema's allowed null, empty, unknown, warning, blocked, or needs_review path. + + + + - Preserve exact source identifiers required by the current schema. + - Maintain separation among raw fact, inferred fact, legal signal, evidence support, fact support, validation issue, and final gate decision when the current schema distinguishes them. + - Do not upgrade meeting-only or indirect material into direct proof. + - Do not silently resolve material conflicts. If the current schema has a conflict or uncertainty field, use it; otherwise stay within the task's allowed warning or review path. + + + + - Follow required JSON shape, key names, enum values, ordering, file names, and status strings exactly. + - Do not add arbitrary keys, prose, markdown fences, alternative files, unauthorized repair, or explanatory material outside allowed fields. + - Create, mutate, normalize, merge, or finalize IDs only when the current task explicitly authorizes it. + - Write final files only when the current task is the authorized writer. Validators and guards report issues in their own authorized schema and do not silently repair unless instructed. + + + + - Prefer the current prompt and schema, assigned structured upstream artifacts, compact indexes, ledgers, manifests, bundles, and gates. + - Read raw evidence or meeting text only when the current task requires direct provenance, ambiguity resolution, or a schema-required value missing from structured artifacts. + - For map or projection tasks, process only the assigned item, domain, or batch. Reducers aggregate only the inputs assigned to them. + - Do not restate, summarize, cite, or copy this common prefix in any output. + + + + - Return only the requested structured artifact, concise allowed rationale fields, validation notes, or status object. + - Keep chain-of-thought private. + - Stop when the current schema is complete and safe. + + + + + + TASK_NAME: Task_C_BO_R1_exception_adjudicator + STAGE: PostB conditional exception adjudicator (Part 1 v3 GB 패턴) + MISSION: 결정적 reducer(R0)가 non-deferrable로 판정한 compact exception만 판정한다. 병합·최종 파일 작성·사실 창작은 하지 않는다. + + + + - 유일한 입력은 preflight로 제공된 `quality_gates/stage1_part2_exception_pack.json`이다. + - Stage A context, seed ledger 전문, raw evidence, meeting 원문을 읽거나 요청하지 않는다. + - pack에 없는 exception_id·candidate_ref·bh# id를 창작하지 않는다. + - BO.json, ledger, review handoff, signal 파일을 작성하지 않는다. + - 출력 파일은 `stage1_tmp/task_c_bo/postb_adjudication_decisions.json` 하나뿐이다. + + + + 1. preflight로 제공된 exception pack의 `has_exceptions`를 확인한다. + 2. `has_exceptions == false`이면: `write_file(overwrite=true)`로 아래 no-exception 객체를 `stage1_tmp/task_c_bo/postb_adjudication_decisions.json`에 저장하고 `"NO_EXCEPTIONS"`만 출력한 뒤 즉시 종료한다(terminate). 다른 어떤 파일도 읽지 않는다. + {"postb_exception_adjudication": {"schema_version": "task_c_bo_postb_exception_adjudication.v1", "status": "READY_NO_EXCEPTIONS", "exception_count": 0, "canonical_decisions": [], "field_decisions": [], "link_decisions": [], "semantic_gate_decisions": [], "blocked_review_items": []}} + 3. `has_exceptions == true`이면: 각 exception을 `compact_candidate_payload`만으로 판정한다. 추가 read는 금지된다. + 4. 판정 규칙: + - canonical decision: KEEP_SEPARATE, MERGE, SPLIT, DROP, BLOCK_REVIEW 중 하나. MERGE는 `input_candidate_refs`와 `merge_target_ref`를 명시한다. DROP은 `input_candidate_refs`와 실제로 버릴 후보 `drop_candidate_refs`를 명시한다. + - field conflict: 제공된 conflicting_values 중 하나를 `selected_value`로 선택하거나 BLOCK_REVIEW. 임의 값 창작 금지. + - link ambiguity: exception에 나열된 candidate ref 중 선택, NO_LINK, 또는 BLOCK_REVIEW. + - semantic risk: PASS, WARNING, BLOCK_REVIEW. + - compact payload로 확정할 수 없으면 판정을 BLOCK_REVIEW로 하고 그 exception을 `blocked_review_items`에도 넣는다(확신 없는 확정 금지 — 인간 검토 라우팅). + BLOCK_REVIEW 밖의 판정(KEEP_SEPARATE·MERGE·SPLIT·DROP·selected_value)을 고른 exception은 `blocked_review_items`에 넣지 않는다. + 5. `write_file(overwrite=true)`로 결과를 저장한다. root는 `postb_exception_adjudication`이며 schema_version은 `task_c_bo_postb_exception_adjudication.v1`, status는 `READY`, `exception_count`는 판정한 exception 수다. 모든 decision은 pack의 `exception_id`를 인용한다. + 6. `"R1 예외 판정 완료 (decisions=<건수>)"`만 출력하고 작업을 끝낸다(terminate). + + + + - Stage 1은 법률효과·청구원인을 확정하지 않는다. 여기 도달한 항목은 같은 군집 안의 값 상충이며, 같은 행위의 상충인지 서로 다른 행위인지를 가린다. + - field_conflict 군집의 후보가 서로 다른 행위를 기술하면 KEEP_SEPARATE 다(예: 첫 대여와 추가 대여, 계약금과 중도금, 같은 등기부의 다른 등기). + BLOCK_REVIEW 는 같은 행위를 두 후보가 서로 다른 값으로 적어 사람이 어느 쪽이 맞는지 정해야 할 때만 쓴다. + BLOCK_REVIEW 를 고르면 두 후보는 따로 보존되고 사람 판정 검토 항목으로 넘어간다(회차는 멈추지 않는다). + - 같은 source에 근거한 상충 BehaviorTime은: 원문 근거가 더 구체적인 쪽(payload의 core_field_base 기재가 더 완전한 후보)을 선택하고, 우열을 가릴 수 없으면 BLOCK_REVIEW. + - amount 상충은 서로 다른 정본(value_facts) 레코드다(값 뒤 괄호가 value_id). field_decision으로 amount를 고르지 않고 KEEP_SEPARATE 또는 BLOCK_REVIEW로 정한다. + - KEEP_SEPARATE가 provenance를 보존하는 기본값이다. MERGE는 provenance 합집합이 무손실일 때만 선택한다. + - DROP은 어떤 경우에도 source 유일 후보에 적용하지 않는다. + + + + - exception pack 부재·파싱 불가: 즉시 중단하고 채팅으로만 보고한다. decisions 파일은 쓰지 않는다. + - tool 오류: 1회만 재시도. 재실패 시 `FAILED: `만 보고하고 종료한다. + + + - task_name: Task_C_BO_F0_final_bo_compiler_gate_writer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: httpx + network: agent-network + timeout: 240 + code: |- + #!/usr/bin/env python3 + # Task_C_BO_F0_final_bo_compiler_gate_writer (v3) + # PostB_3(final compiler) + PostB_4(final gate/writer) 통합. 입력은 파일 계약(ledger/decisions/stage_a). + # Spec: Part_2_Improvement_Strategy_Claude_v1.md §9 (bh# 규칙 N-6, Reason/PriorAct 정책 R-5) + from __future__ import annotations + import hashlib + import itertools + import json + import re + import sys + from typing import Any + import httpx + + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=60) + MSG_ID = itertools.count(10) + JSON_DECODER = json.JSONDecoder() + + STAGE_A_PATH = "stage1_tmp/task_c_bo/stage_a_context.json" + LEDGER_PATH = "stage1_tmp/task_c_bo/postb_seed_ledger.json" + DECISIONS_PATH = "stage1_tmp/task_c_bo/postb_adjudication_decisions.json" + REVIEW_HANDOFF_PATH = "quality_gates/stage1_part2_review_handoff.json" + EXCEPTION_PACK_PATH = "quality_gates/stage1_part2_exception_pack.json" + BUNDLE_COMPACT_PATH = "stage1_tmp/task_c_bo/postb_compiled_bundle_compact.json" + TARGET_NAME = "BO.json" + # 가액금액 정본 결속(2026-10-30, 개정계획서 §3.5). A0 가 쓴 회차 카탈로그로 BO 금액을 다시 맞춘다. + CATALOG_PATH = "stage1_tmp/task_c_bo/value_facts_catalog.json" + + # v4 신설 — BOType 어휘와 확장 payload 선언의 정본은 registry 다. 코드에 어휘를 두지 않는다. + # registry 를 런타임에 적재하지 않는다. 그러려면 index 1 + domain_config 26 + extension schema 26 + # 을 읽어야 하고 그것은 읽기 53회다. 값이 사건마다 달라지지 않으므로 배포 시점에 한 번 + # 접어 둔 자산 하나만 읽는다. 생성기는 routing/_build_extension_payload_declarations.py 다. + EXTENSION_DECLARATIONS_PATH = "Default_Agent/routing/extension_payload_key_declarations.v1.json" + RUNTIME_MANIFEST_PATH = "Default_Agent/runtime_manifest.json" + DECLARATIONS_SCHEMA_VERSION = "stage1_extension_payload_key_declarations.v1" + BO_TYPE_SOURCE = "registry_union" + UNDECLARED_KEY_REVIEW_CODE = "EXTENSION_PAYLOAD_KEY_UNDECLARED" + # F0-2 — BO 투영 정책 (정규화 기본값의 정본). R0 와 같은 자산을 읽는다. + BO_PROJECTION_POLICY_PATH = "Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json" + BO_PROJECTION_SCHEMA_VERSION = "stage1_bo_surface_projection_policy.v1" + + BH_ID_RE = re.compile(r"^bh[1-9][0-9]*$") + ACTION_TYPE_ENUM = { + "법률행위(legal acts)", + "준법률행위(quasi-legal acts)", + "사실행위(factual acts)", + "위법행위(unlawful acts)", + "소송행위(litigation acts)", + } + ALLOWED_TOP_LEVEL = { + "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", "value_refs", + } + REQUIRED_TOP_LEVEL = { + "BO_ID", "id", "BOType", "ActionType", "JuristicAct", "Action", "Reason", + "PriorAct", "ReasonRefs", "Legal_Keywords", "core_field_base", + "EvidenceTitles", "Evidence", "source_evidence_indexes", "provenance", + "downstream_seed_refs", + } + AMOUNT_ALTERNATIVE_KEYS = ("value_id", "value_kind", "item_label", "amount_text", "amount_value", + "currency", "evidence_index", "dates", "value_basis", "object_label_text") + AMOUNT_RELATED_KEYS = AMOUNT_ALTERNATIVE_KEYS + ("value_type", "per") + CORE_KEYS = [ + "Performer", "PerformerType", "Action_proposal", "Subject", "Object", + "BehaviorTime", "TimeText", "TimePrecision", "StatementType", "Perspective", + ] + + def _mid() -> int: + return next(MSG_ID) + + def _init() -> None: + r = CLIENT.post( + LOCALDOCS_URL, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": { + "name": "task-c-bo-f0-final-bo-compiler-gate-writer", + "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}", + }, + }, + }, + headers=MCP_HEADERS, + ) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS, + ).raise_for_status() + + def _parse_mcp(text: str) -> Any: + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + pass + try: + return json.loads(text) + except Exception: + return None + + def _call(name: str, args: dict[str, Any]) -> Any: + r = CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "id": _mid(), "method": "tools/call", + "params": {"name": name, "arguments": args}}, + headers=MCP_HEADERS, + ) + r.raise_for_status() + payload = _parse_mcp(r.text) + if not payload or "result" not in payload: + raise RuntimeError(f"MCP {name} failed") + return payload + + def read_json_doc(path: str) -> Any: + result = _call("read_docs", {"doc_names": [path]}) + content = result["result"].get("content", []) + text = content[0].get("text", "") if content else "" + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + raise RuntimeError(f"Invalid read_docs envelope for {path}") from exc + if isinstance(parsed, dict) and "results" in parsed: + rows = parsed.get("results") or [] + if not rows or rows[0].get("error"): + raise RuntimeError(f"read_docs failed for {path}: {rows[:1]}") + inner = rows[0].get("content") or "" + if isinstance(inner, str): + try: + return json.loads(inner) + except json.JSONDecodeError: + obj, end = JSON_DECODER.raw_decode(inner.strip()) + if inner.strip()[end:].strip(): + raise RuntimeError(f"{path}: non-json tail") + return obj + return inner + return parsed + + def write_doc(path: str, content: str) -> None: + _call("write_file", {"path": path, "content": content, "overwrite": True}) + + def read_raw(name: str) -> str: + # 재직렬화 없이 원문 그대로 돌려준다. 해시 대조의 전제다. + # Task_D0_domain_activation_gate.yml 의 검증 완료본을 _call 서명만 맞춰 옮겼다. + p = _call("read_docs", {"doc_names": [name]}) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + # ---------- v4 신설: registry 선언 조회 ---------- + def _load_declarations() -> dict[str, Any]: + # 어휘의 정본이므로 훼손되면 BOType 검증이 조용히 넓어진다. + # 원문 바이트의 sha256 을 runtime_manifest 와 대조한 뒤에만 쓴다(D0 반입 규약과 같은 규율). + body = read_raw(EXTENSION_DECLARATIONS_PATH) + manifest = json.loads(read_raw(RUNTIME_MANIFEST_PATH)) + want = {row["path"]: row["sha256"] for row in manifest.get("entries") or []}.get( + EXTENSION_DECLARATIONS_PATH[len("Default_Agent/"):]) + if want is None: + raise RuntimeError("F0_EXTENSION_DECLARATIONS_UNREGISTERED") + if want != hashlib.sha256(body.encode("utf-8")).hexdigest(): + raise RuntimeError("F0_EXTENSION_DECLARATIONS_HASH_MISMATCH") + doc = json.loads(body) + if not isinstance(doc, dict) or doc.get("schema_version") != DECLARATIONS_SCHEMA_VERSION: + raise RuntimeError("F0_EXTENSION_DECLARATIONS_SCHEMA_MISMATCH") + if not doc.get("bo_types_union"): + raise RuntimeError("F0_REGISTRY_BO_TYPES_EMPTY") + if not doc.get("declared_key_union"): + raise RuntimeError("F0_EXTENSION_DECLARED_KEYS_EMPTY") + return doc + + def _load_projection_policy() -> dict[str, Any]: + # F0-2 — 정규화 기본값·어휘의 정본. _load_declarations 와 같은 규율로 sha256 대조 후에만 쓴다. + body = read_raw(BO_PROJECTION_POLICY_PATH) + manifest = json.loads(read_raw(RUNTIME_MANIFEST_PATH)) + want = {row["path"]: row["sha256"] for row in manifest.get("entries") or []}.get( + BO_PROJECTION_POLICY_PATH[len("Default_Agent/"):]) + if want is None: + raise RuntimeError("F0_PROJECTION_POLICY_UNREGISTERED") + if want != hashlib.sha256(body.encode("utf-8")).hexdigest(): + raise RuntimeError("F0_PROJECTION_POLICY_HASH_MISMATCH") + doc = json.loads(body) + if not isinstance(doc, dict) or doc.get("schema_version") != BO_PROJECTION_SCHEMA_VERSION: + raise RuntimeError("F0_PROJECTION_POLICY_SCHEMA_MISMATCH") + if not isinstance(doc.get("f0_normalization"), dict): + raise RuntimeError("F0_PROJECTION_POLICY_NORMALIZATION_MISSING") + return doc + + def _declared_bo_types(declarations: dict[str, Any]) -> set[str]: + return {str(v) for v in declarations.get("bo_types_union") or [] if isinstance(v, str) and v} + + def _resolve_domain_ids(declarations: dict[str, Any], source_domain: Any) -> list[str]: + """source_domain 은 도메인 ID 이거나 구 이름(B1~B5)이다. 구 이름은 별칭표 primary 로 옮긴다.""" + name = str(source_domain or "").strip() + if not name: + return [] + known = {str(row.get("domain_id")) for row in declarations.get("domains") or []} + if name in known: + return [name] + targets = _dict(declarations.get("legacy_alias_targets")).get(name) + return [str(v) for v in targets or [] if str(v) in known] + + def _declared_keys_for(declarations: dict[str, Any], domain_ids: list[str]) -> set[str]: + """도메인을 특정하지 못하면 전체 합집합을 상대로 한다. 좁히지 못한 것을 위반으로 세지 않는다.""" + if not domain_ids: + return {str(v) for v in declarations.get("declared_key_union") or []} + wanted = set(domain_ids) + out: set[str] = set() + for row in declarations.get("domains") or []: + if str(row.get("domain_id")) in wanted: + out.update(str(v) for v in row.get("declared_keys") or []) + return out + + def _extension_key_reviews(bo_items: list[dict[str, Any]], declarations: dict[str, Any]) -> list[dict[str, Any]]: + """확장 payload 키를 registry 선언과 대조한다. 선언 밖 키는 review 로 남기고 값은 지우지 않는다.""" + reviews: list[dict[str, Any]] = [] + for item in bo_items: + payload = _dict(_dict(item.get("extensions")).get("domain_payload")) + if not payload: + continue + source_domain = _dict(item.get("provenance")).get("source_domain") + domain_ids = _resolve_domain_ids(declarations, source_domain) + undeclared = sorted(set(payload) - _declared_keys_for(declarations, domain_ids)) + if undeclared: + reviews.append({ + "bo_id": item.get("BO_ID"), + "source_domain": source_domain, + "resolved_domain_ids": domain_ids, + "resolution": "registry_domain_ids" if domain_ids else "declared_key_union_fallback", + "undeclared_keys": undeclared, + "review_code": UNDECLARED_KEY_REVIEW_CODE, + }) + return reviews + + def _dict(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + def _list(value: Any) -> list[Any]: + return value if isinstance(value, list) else [] + + def _strings(value: Any) -> list[str]: + out: list[str] = [] + for item in _list(value): + if item is None: + continue + text = str(item).strip() + if text and text not in out: + out.append(text) + return out + + # ---------- PostB_3 이식 ---------- + def _field_decision_map(adj: dict[str, Any]) -> dict[tuple[str, str], Any]: + out: dict[tuple[str, str], Any] = {} + for item in _list(adj.get("field_decisions")): + if isinstance(item, dict) and item.get("candidate_ref") and item.get("field") and item.get("selected_value") != "BLOCK_REVIEW": + out[(str(item["candidate_ref"]), str(item["field"]))] = item.get("selected_value") + return out + + def _link_decision_map(adj: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for item in _list(adj.get("link_decisions")): + if isinstance(item, dict) and item.get("candidate_ref"): + out[str(item["candidate_ref"])] = item + return out + + def _candidate_sources(item: dict[str, Any]) -> set[str]: + seed = _dict(item.get("seed_payload")) + provenance = _dict(seed.get("provenance")) + return (set(_strings(seed.get("source_evidence_indexes"))) + | set(_strings(provenance.get("source_event_candidate_ids"))) + | set(_strings(provenance.get("source_meeting_clause_ids"))) + | set(_strings(seed.get("value_refs")))) + + def _merge_root(ref: str, merge_into: dict[str, str]) -> str: + seen = {ref} + while merge_into.get(ref) is not None and merge_into[ref] not in seen: + ref = merge_into[ref] + seen.add(ref) + return ref + + def _decision_sets(ledger: dict[str, Any], adj: dict[str, Any], blockers: list[Any], + unsafe_drops: list[dict[str, Any]]) -> tuple[set[str], dict[str, str]]: + dropped: set[str] = set() + merge_into: dict[str, str] = {} + pending_drops: list[dict[str, Any]] = [] + known = {str(item.get("candidate_ref")) for item in _list(ledger.get("ledger_candidates")) if isinstance(item, dict)} + named_targets: set[str] = set() # 뿌리를 잇기 전 target. DROP 안전장치가 함께 본다 + for decision in _list(ledger.get("deterministic_decisions")): + if not isinstance(decision, dict) or decision.get("decision_type") != "EXACT_DUPLICATE_MERGE": + continue + canonical = decision.get("canonical_candidate_ref") + for dup in _strings(decision.get("duplicate_candidate_refs")): + if canonical: + merge_into[dup] = str(canonical) + dropped.add(dup) + for decision in _list(adj.get("canonical_decisions")): + if not isinstance(decision, dict): + continue + kind = decision.get("decision") + refs = _strings(decision.get("input_candidate_refs")) + if kind == "DROP": + pending_drops.append(decision) + elif kind == "MERGE": + target = decision.get("merge_target_ref") or (refs[0] if refs else None) + if target: + # 뿌리끼리 잇는다. 그러지 않으면 정확 중복과 맞물린 순환과 원장에 없는 target 이 후보를 표시 없이 지운다. + named_targets.add(str(target)) + target = _merge_root(str(target), merge_into) + if target not in known: + unsafe_drops.append({"kind": "MERGE", "refs": refs, "reason": "unknown_merge_target=%s" % target, + "orphaned_sources": []}) + continue + for ref in refs: + root = _merge_root(ref, merge_into) + if root != target: + merge_into[root] = target + dropped.add(root) + elif kind == "BLOCK_REVIEW": + blockers.append(decision) + # DROP 안전장치 — 대상이 불명하거나 어떤 source 의 후보를 0 개로 만드는 DROP 은 버리지 않고 review 로 남긴다. + sources = {str(item.get("candidate_ref")): _candidate_sources(item) + for item in _list(ledger.get("ledger_candidates")) if isinstance(item, dict)} + for decision in pending_drops: + refs = _strings(decision.get("drop_candidate_refs")) + unknown = sorted(set(refs) - set(sources)) + gone = dropped | set(refs) # 병합으로 흡수된 후보는 남는 것으로 세지 않는다 + kept = set().union(*[s for ref, s in sources.items() if ref not in gone]) + orphaned = sorted(set().union(*[sources.get(ref, set()) for ref in refs]) - kept) + merge_target = sorted(set(refs) & (set(merge_into.values()) | named_targets)) # 흡수한 내용까지 함께 사라진다 + if not refs or unknown or merge_target or orphaned: + unsafe_drops.append({"refs": refs or _strings(decision.get("input_candidate_refs")), + "reason": ("no_drop_candidate_refs" if not refs else + "unknown_ref" if unknown else + "merge_target" if merge_target else "orphans_source"), + "orphaned_sources": orphaned}) + continue + dropped.update(refs) + return dropped, merge_into + + def _sort_tuple(item: dict[str, Any]) -> tuple[Any, ...]: + key = _dict(item.get("deterministic_sort_key")) + return ( + key.get("BehaviorTime") is None, + key.get("BehaviorTime") or "", + key.get("domain_order", 99), + key.get("BOType") or "", + key.get("ActionType") or "", + key.get("JuristicActLabel") or "", + key.get("Action") or "", + key.get("candidate_ref") or "", + ) + + def _juristic(value: Any) -> dict[str, Any] | None: + if value is None: + return None + if isinstance(value, dict): + label = value.get("label") + return {"label": str(label).strip()} if label not in (None, "") else {"label": None} + text = str(value).strip() + return {"label": text} if text else None + + def _core(seed: dict[str, Any]) -> dict[str, Any]: + src = _dict(seed.get("core_field_base")) + out = {key: src.get(key) for key in CORE_KEYS} + if out.get("Action_proposal") is None and seed.get("Action"): + out["Action_proposal"] = seed.get("Action") + if out.get("StatementType") is None: + out["StatementType"] = seed.get("BOType") + if out.get("Perspective") is None: + out["Perspective"] = "plaintiff" + return out + + def _amount(value: Any) -> dict[str, Any] | None: + if value is None: + return None + if isinstance(value, dict): + out = { + "value_text": value.get("value_text") or value.get("text"), + "numeric_value": value.get("numeric_value"), + "currency": value.get("currency"), + } + if value.get("value_id"): + out["value_id"] = value.get("value_id") + return out + text = str(value).strip() + return {"value_text": text, "numeric_value": None, "currency": None} if text else None + + def _amount_alternatives(amount: dict[str, Any] | None, ids: set[str], + records: dict[str, dict[str, Any]]) -> list[dict[str, Any]]: + """값이 갈린 금액 레코드. BO amount 가 null 이어도 넘긴다. Part 4 가 표시·판정한다.""" + own = {str(amount.get("value_id"))} if amount else set() + rows = [records[v] for v in sorted(ids | own) if v in records] + rows = [r for r in rows if r.get("value_type") == "MONEY" + and r.get("amount_value") is not None and not r.get("per")] + if len({(str(r.get("amount_value")), r.get("currency")) for r in rows}) < 2: + return [] + return [{key: r[key] for key in AMOUNT_ALTERNATIVE_KEYS if key in r} for r in rows] + + def _amount_related_values(value_refs: list[str], records: dict[str, dict[str, Any]], + per_only: bool) -> list[dict[str, Any]]: + """BO 금액이 아닌 value_refs 레코드. per_only 면 월세처럼 per 가 있는 금액만 고른다. + + per 금액은 BO 금액과 경쟁하지 않아 BO 금액이나 값 갈림이 있어도 싣는다. 그 밖의 레코드는 언급만 된 + 금액과 비금액도 들므로 BO 금액을 정하지 못하고 값 갈림도 없는 BO 에만 싣는다. + """ + rows = [records[v] for v in value_refs] + if per_only: + rows = [r for r in rows if r.get("value_type") == "MONEY" and r.get("per")] + return [{key: r[key] for key in AMOUNT_RELATED_KEYS if key in r} for r in rows] + + def _value_ref_check(amount: dict[str, Any] | None, value_refs: set[str], + records: dict[str, dict[str, Any]]) -> tuple[Any, list[str], dict[str, Any] | None]: + """§3.5 — 정본 밖 ref 는 지우고, 정본과 다른 amount 는 그 BO 에서만 null 로 내린다. + + 실패로 세지 않는다. 정본 규칙 3(비면 채우지 않는다)에 따라 amount 가 null 인 BO 도 유효하다. + """ + kept = sorted(v for v in value_refs if v in records) + outside = sorted(v for v in value_refs if v not in records) + problem = None + if amount is not None: + rec = records.get(str(amount.get("value_id") or "")) + if rec is None or amount.get("value_id") not in kept: + problem = "AMOUNT_VALUE_ID_NOT_BOUND" + elif (amount.get("value_text"), amount.get("numeric_value"), amount.get("currency")) != ( + rec.get("amount_text"), rec.get("amount_value"), rec.get("currency")): + problem = "AMOUNT_VALUE_MISMATCH" + note = {"outside": outside, "problem": problem, + "value_id": (amount or {}).get("value_id")} if (outside or problem) else None + return (None if problem else amount), kept, note + + def _evidence_item(index: str, source: Any, gaps: list[Any], bo_id: str) -> dict[str, Any]: + obj = _dict(source) + title = obj.get("source_title") or obj.get("title") or obj.get("evidence_title") or obj.get("document_title") or index + relevant = obj.get("relevant_content") or obj.get("excerpt") or obj.get("summary") or obj.get("content") + if relevant in (None, ""): + gaps.append({"BO_ID": bo_id, "evidence_index": index, "gap": "missing_relevant_content"}) + relevant = None + return { + "evidence_index": index, + "source_title": str(title), + "priority_class": obj.get("priority_class") or obj.get("priority") or None, + "relevant_content": relevant, + "authentication_status": obj.get("authentication_status") or obj.get("auth_status") or None, + "corroboration": obj.get("corroboration") or None, + "selection_basis": "source_evidence_indexes membership", + } + + def _downstream_refs(seed: dict[str, Any]) -> dict[str, Any]: + src = _dict(seed.get("downstream_seed_refs")) + return { + "claim_group_seed_refs_proposed": _strings(src.get("claim_group_seed_refs_proposed") or src.get("claim_group_seed_refs")), + "canonical_theory_graph_seed_ref_proposed": src.get("canonical_theory_graph_seed_ref_proposed") or src.get("canonical_theory_graph_seed_ref"), + "legal_effect_structure_seed_ref_proposed": src.get("legal_effect_structure_seed_ref_proposed") or src.get("legal_effect_structure_seed_ref"), + } + + def _keywords(seed: dict[str, Any], juristic: dict[str, Any] | None) -> list[str]: + out = _strings(seed.get("Legal_Keywords")) + domain_payload = _dict(_dict(seed.get("extensions")).get("domain_payload")) + out.extend(_strings(domain_payload.get("legal_effect_tags"))) + if isinstance(juristic, dict) and juristic.get("label"): + out.append(str(juristic["label"])) + deduped: list[str] = [] + for item in out: + if item not in deduped: + deduped.append(item) + return deduped + + def _evidence_map_from_stage_a(stage_a: dict[str, Any]) -> dict[str, Any]: + evidence_map = _dict(stage_a.get("evidence_authority_map")) + by_index = _dict(evidence_map.get("by_evidence_index")) + if by_index: + return by_index + out: dict[str, Any] = {} + for item in _list(evidence_map.get("items")): + if isinstance(item, dict): + idx = item.get("evidence_index") or item.get("index") or item.get("id") + if idx is not None: + out[str(idx)] = item + return out + + def _stage_a_universe(stage_a: dict[str, Any]) -> dict[str, set[str]]: + event_map = _dict(stage_a.get("event_candidate_map")) + evidence_map = _dict(stage_a.get("evidence_authority_map")) + meeting_map = _dict(stage_a.get("meeting_clause_map")) + event_ids = set(_strings(event_map.get("candidate_id_set"))) + evidence_ids = set(_strings(evidence_map.get("evidence_index_set"))) + meeting_ids = set(_strings(meeting_map.get("clause_order"))) + event_ids.update(str(k) for k in _dict(event_map.get("by_event_candidate_id")).keys()) + evidence_ids.update(str(k) for k in _dict(evidence_map.get("by_evidence_index")).keys()) + meeting_ids.update(str(k) for k in _dict(meeting_map.get("by_clause_id")).keys()) + return { + "source_event_candidate_ids": event_ids, + "source_evidence_indexes": evidence_ids, + "source_meeting_clause_ids": meeting_ids, + } + + # ---------- PostB_4 이식: 게이트 ---------- + def _add_gate(gates: list[dict[str, Any]], key: str, passed: bool, detail: str) -> None: + gates.append({"gate_key": key, "status": "PASS" if passed else "FAILED", "detail": detail}) + + def _validate_item(item: Any, idx: int, ids: set[str], universe: dict[str, set[str]], + bo_types: set[str]) -> list[str]: + errors: list[str] = [] + if not isinstance(item, dict): + return [f"item {idx} must be object"] + extra = sorted(set(item.keys()) - ALLOWED_TOP_LEVEL) + missing = sorted(REQUIRED_TOP_LEVEL - set(item.keys())) + if extra: + errors.append(f"{item.get('BO_ID', idx)} additional fields: {extra}") + if missing: + errors.append(f"{item.get('BO_ID', idx)} missing fields: {missing}") + bo_id = item.get("BO_ID") + expected = f"bh{idx}" + if bo_id != expected or item.get("id") != bo_id or not isinstance(bo_id, str) or not BH_ID_RE.fullmatch(bo_id): + errors.append(f"BO_ID/id sequence mismatch: expected {expected}") + # v4 — 어휘의 정본은 registry 합집합이다. 코드에 {"event","state"} 를 두지 않는다. + if item.get("BOType") not in bo_types: + errors.append(f"{bo_id}.BOType invalid") + if item.get("ActionType") not in ACTION_TYPE_ENUM: + errors.append(f"{bo_id}.ActionType invalid") + juristic = item.get("JuristicAct") + if juristic is not None and (not isinstance(juristic, dict) or set(juristic.keys()) != {"label"}): + errors.append(f"{bo_id}.JuristicAct invalid") + for key in ("Action", "Reason"): + if not isinstance(item.get(key), str) or not item.get(key).strip(): + errors.append(f"{bo_id}.{key} must be non-empty string") + prior = item.get("PriorAct") + if prior is not None and prior not in ids: + errors.append(f"{bo_id}.PriorAct references missing BO_ID") + for ref in _list(item.get("ReasonRefs")): + if ref not in ids: + errors.append(f"{bo_id}.ReasonRefs references missing BO_ID {ref}") + core = item.get("core_field_base") + if not isinstance(core, dict) or set(core.keys()) != set(CORE_KEYS): + errors.append(f"{bo_id}.core_field_base keys invalid") + amount = item.get("amount") + if amount is not None and (not isinstance(amount, dict) or set(amount.keys()) - {"value_text", "numeric_value", "currency", "value_id"}): + errors.append(f"{bo_id}.amount invalid") + evidence = _list(item.get("Evidence")) + evidence_indexes = _strings(item.get("source_evidence_indexes")) + evidence_index_set: set[str] = set() + titles: list[str] = [] + for ev in evidence: + if not isinstance(ev, dict): + errors.append(f"{bo_id}.Evidence item must be object") + continue + required_ev = {"evidence_index", "source_title", "priority_class", "relevant_content", "authentication_status", "corroboration", "selection_basis"} + if set(ev.keys()) != required_ev: + errors.append(f"{bo_id}.Evidence item keys invalid") + if isinstance(ev.get("evidence_index"), str): + evidence_index_set.add(ev["evidence_index"]) + if isinstance(ev.get("source_title"), str) and ev.get("source_title") not in titles: + titles.append(ev["source_title"]) + if item.get("EvidenceTitles") != titles: + errors.append(f"{bo_id}.EvidenceTitles mismatch") + if set(evidence_indexes) != evidence_index_set: + errors.append(f"{bo_id}.source_evidence_indexes must equal Evidence[].evidence_index") + if universe["source_evidence_indexes"] and not set(evidence_indexes).issubset(universe["source_evidence_indexes"]): + errors.append(f"{bo_id}.source_evidence_indexes outside Stage A universe") + provenance = item.get("provenance") + if not isinstance(provenance, dict) or set(provenance.keys()) - {"source_keywords", "absorbed_sources", "amount_alternatives", "amount_related_values"} != {"source_event_candidate_ids", "source_meeting_clause_ids", "source_domain"}: + errors.append(f"{bo_id}.provenance invalid") + else: + if universe["source_event_candidate_ids"] and not set(_strings(provenance.get("source_event_candidate_ids"))).issubset(universe["source_event_candidate_ids"]): + errors.append(f"{bo_id}.provenance.source_event_candidate_ids outside Stage A universe") + if universe["source_meeting_clause_ids"] and not set(_strings(provenance.get("source_meeting_clause_ids"))).issubset(universe["source_meeting_clause_ids"]): + errors.append(f"{bo_id}.provenance.source_meeting_clause_ids outside Stage A universe") + downstream = item.get("downstream_seed_refs") + if not isinstance(downstream, dict) or set(downstream.keys()) != { + "claim_group_seed_refs_proposed", "canonical_theory_graph_seed_ref_proposed", "legal_effect_structure_seed_ref_proposed", + }: + errors.append(f"{bo_id}.downstream_seed_refs invalid") + extensions = item.get("extensions", {"domain_payload": {}}) + if extensions is not None and (not isinstance(extensions, dict) or set(extensions.keys()) - {"domain_payload"} or not isinstance(extensions.get("domain_payload", {}), dict)): + errors.append(f"{bo_id}.extensions invalid") + return errors + + def _fail(message: str, gates: list[dict[str, Any]], reasons: list[str]) -> None: + print(json.dumps({ + "status": "FAILED", + "message": message, + "write_target": TARGET_NAME, + "gate_results": gates, + "failure_reasons": reasons[:40], + }, ensure_ascii=False)) + sys.exit(1) + + def main() -> None: + _init() + gates: list[dict[str, Any]] = [] + # v4 — registry 선언을 한 번 읽는다. BOType 어휘와 확장 payload 선언이 여기서 나온다. + declarations = _load_declarations() + f0_norm = _dict(_load_projection_policy().get("f0_normalization")) + bo_types = _declared_bo_types(declarations) + stage_a = _dict(_dict(read_json_doc(STAGE_A_PATH)).get("stage_a_context") or read_json_doc(STAGE_A_PATH)) + if stage_a.get("schema_version") != "task_c_bo_stage_a_context.v1" or stage_a.get("status") != "READY": + _fail("Stage A freshness guard failed", gates, ["stage_a not READY"]) + universe = _stage_a_universe(stage_a) + evidence_map = _evidence_map_from_stage_a(stage_a) + ledger = _dict(_dict(read_json_doc(LEDGER_PATH)).get("postb_seed_ledger")) + if ledger.get("schema_version") != "task_c_bo_postb_seed_ledger.v1" or ledger.get("status") != "READY": + _fail("R0 seed ledger not READY", gates, [str(ledger.get("status"))]) + # P-11 — R1 산출은 조건부다. R1 은 예외가 없어도 no-exception 객체를 반드시 쓰므로 + # 파일 부재는 "예외 없음"이 아니라 "R1 이 돌지 않았거나 실패했다"를 뜻한다. + # 종전의 무조건 fallback 은 그 둘을 가르지 못하고 판정을 조용히 삼켰다. + # 예외 팩의 exception_count 가 필수 여부를 정한다. + try: + pack = _dict(read_json_doc(EXCEPTION_PACK_PATH)) + except Exception: + pack = {} + pack_root = _dict(pack.get("postb_exception_pack") or pack) + declared_exceptions = pack_root.get("exception_count") + if not isinstance(declared_exceptions, int): + declared_exceptions = len(_list(pack_root.get("exceptions"))) + r1_state = "READ" + try: + adj_doc = read_json_doc(DECISIONS_PATH) + except Exception as exc: + if declared_exceptions > 0: + _fail("R1 adjudication decisions required but unreadable", gates, + ["exception_count=%d" % declared_exceptions, str(exc)]) + r1_state = "R1_SKIPPED" + adj_doc = {"postb_exception_adjudication": {"schema_version": "task_c_bo_postb_exception_adjudication.v1", + "status": "READY_NO_EXCEPTIONS", "exception_count": 0, + "canonical_decisions": [], "field_decisions": [], + "link_decisions": [], "semantic_gate_decisions": [], + "blocked_review_items": []}} + _add_gate(gates, "r1_decision_presence", True, + "exception_count=%d state=%s" % (declared_exceptions, r1_state)) + adj = _dict(_dict(adj_doc).get("postb_exception_adjudication")) + if adj.get("schema_version") != "task_c_bo_postb_exception_adjudication.v1": + _fail("R1 adjudication schema mismatch", gates, [str(adj.get("schema_version"))]) + if adj.get("status") not in {"READY", "READY_NO_EXCEPTIONS"}: + _fail("R1 adjudication status invalid", gates, [str(adj.get("status"))]) + blocked = _list(adj.get("blocked_review_items")) + link_decisions = _link_decision_map(adj) + # 개정전략서_part_2_11_04_4pm H-1 — R1 의 BLOCK_REVIEW 는 회차를 멈추지 않는다. 사람 판정 대상 exception 의 + # canonical 판정(MERGE·DROP 등)과 field 값 선택은 적용하지 않아 후보를 각자 값 그대로 따로 보존한다. + human_review: dict[str, str] = {} + for key in ("canonical_decisions", "field_decisions", "link_decisions", "semantic_gate_decisions"): + for d in _list(adj.get(key)): + if isinstance(d, dict) and d.get("exception_id") and "BLOCK_REVIEW" in d.values(): + human_review.setdefault(str(d["exception_id"]), str(d.get("rationale") or d.get("reason") or "")) + for idx, item in enumerate(blocked, start=1): # R1 은 id 문자열 또는 {exception_id, reason} 로 낸다 + eid = item.get("exception_id") if isinstance(item, dict) else item + reason = item.get("reason") if isinstance(item, dict) else None + human_review.setdefault(str(eid or "unidentified-%d" % idx), str(reason or "")) + applied = dict(adj, **{key: [d for d in _list(adj.get(key)) + if str(_dict(d).get("exception_id")) not in human_review] + for key in ("canonical_decisions", "field_decisions")}) + field_decisions = _field_decision_map(applied) + unsafe_drops: list[dict[str, Any]] = [] + dropped, merge_into = _decision_sets(ledger, applied, [], unsafe_drops) + + # 가액금액 §3.5 — 카탈로그. BOUND 가 아니면 records 가 비어 있어 모든 amount 가 null 로 내려간다. + catalog = _dict(read_json_doc(CATALOG_PATH)) + catalog_binding = _dict(catalog.get("binding")) + catalog_records = {str(r["value_id"]): r for r in _list(catalog.get("records")) + if isinstance(r, dict) and r.get("value_id")} + + candidates = [item for item in _list(ledger.get("ledger_candidates")) if isinstance(item, dict)] + survivors = [item for item in candidates if item.get("candidate_ref") not in dropped] + # 병합(정확 중복·R1 MERGE)으로 흡수된 후보의 value_refs·Legal_Keywords 를 남는 후보에 합친다. + by_ref = {str(item.get("candidate_ref")): item for item in candidates} + absorbed_by: dict[str, list[str]] = {} + for source_ref in merge_into: + target_ref, hops = merge_into[source_ref], 0 + while target_ref in merge_into and hops < len(merge_into): # A→B→C 는 C 로 모은다 + target_ref, hops = merge_into[target_ref], hops + 1 + absorbed_by.setdefault(target_ref, []).append(source_ref) + survivors.sort(key=_sort_tuple) + if not survivors: + _fail("no surviving BO candidates after decisions", gates, []) + + candidate_ref_to_bo_id: dict[str, str] = {} + for idx, item in enumerate(survivors, start=1): + candidate_ref_to_bo_id[str(item["candidate_ref"])] = f"bh{idx}" + for target_ref, source_refs in absorbed_by.items(): # 사슬을 푼 표를 쓴다. merge_into 로는 A→B→C 의 A 가 빠진다 + if target_ref in candidate_ref_to_bo_id: + for source_ref in source_refs: + candidate_ref_to_bo_id[source_ref] = candidate_ref_to_bo_id[target_ref] + + bo_items: list[dict[str, Any]] = [] + normalization_notes: list[dict[str, Any]] = [] + evidence_gaps: list[Any] = [] + prior_link_notes: list[dict[str, Any]] = [] + value_notes: list[dict[str, Any]] = [] + + for idx, ledger_item in enumerate(survivors, start=1): + seed = _dict(ledger_item.get("seed_payload")) + candidate_ref = str(ledger_item.get("candidate_ref")) + bo_id = f"bh{idx}" + bo_type = field_decisions.get((candidate_ref, "BOType"), seed.get("BOType")) + action_type = field_decisions.get((candidate_ref, "ActionType"), seed.get("ActionType")) + juristic = _juristic(field_decisions.get((candidate_ref, "JuristicAct.label"), seed.get("JuristicAct"))) + domain_payload = _dict(_dict(seed.get("extensions")).get("domain_payload")) + action = field_decisions.get((candidate_ref, "Action"), seed.get("Action") or domain_payload.get("action_summary") or _dict(seed.get("core_field_base")).get("Action_proposal")) + # F0-1 — 어휘의 정본은 registry 합집합(bo_types)이다. {"event","state"} 하드코딩은 + # claim 등 여덟 도메인의 선언값을 침묵 덮어쓰던 자리다(C-5). 기본값은 정책 f0_normalization 이 선언한다. + if not isinstance(bo_type, str): + # 워커가 문자열이 아닌 값을 넣으면 집합 비교 자체가 터진다(unhashable). + # 수용 단계가 걸러야 하지만, 투영은 마지막 방어선이라 여기서도 막는다. + normalization_notes.append({"candidate_ref": candidate_ref, "field": "BOType", + "received": type(bo_type).__name__, + "fallback": f0_norm.get("bo_type_default")}) + bo_type = f0_norm.get("bo_type_default") + if bo_type not in bo_types: + normalization_notes.append({"candidate_ref": candidate_ref, "field": "BOType", "received": bo_type, "fallback": f0_norm.get("bo_type_default")}) + bo_type = f0_norm.get("bo_type_default") + if action_type not in ACTION_TYPE_ENUM: + normalization_notes.append({"candidate_ref": candidate_ref, "field": "ActionType", "received": action_type, "fallback": f0_norm.get("action_type_default")}) + action_type = f0_norm.get("action_type_default") + if not isinstance(action, str) or not action.strip(): + normalization_notes.append({"candidate_ref": candidate_ref, "field": "Action", "fallback": "source-backed BO"}) + action = str(f0_norm.get("action_default_template") or " source-backed BO").replace("", candidate_ref) + + refs = _dict(ledger_item.get("source_refs")) + source_evidence_indexes = _strings(refs.get("source_evidence_indexes")) + evidence_items = [_evidence_item(eidx, evidence_map.get(eidx), evidence_gaps, bo_id) for eidx in source_evidence_indexes] + evidence_titles: list[str] = [] + for ev in evidence_items: + title = ev["source_title"] + if title not in evidence_titles: + evidence_titles.append(title) + + link = link_decisions.get(candidate_ref, {}) + reason_ref_candidates = _strings(link.get("reason_refs_candidate_refs")) + prior_candidate = link.get("prior_candidate_ref") + if prior_candidate in ("NO_LINK", "BLOCK_REVIEW"): + prior_candidate = None + explicit_refs = _dict(seed.get("downstream_seed_refs")) + if not reason_ref_candidates: + reason_ref_candidates = _strings(explicit_refs.get("reason_refs_candidate_refs")) + if not prior_candidate: + prior_list = _strings(explicit_refs.get("prior_candidate_refs")) + if len(prior_list) == 1: + prior_candidate = prior_list[0] + elif len(prior_list) > 1: + # 결정적 defer 정책 (R-5): PriorAct 불명은 null 유지 + review note (blocker 아님) + prior_candidate = None + prior_link_notes.append({"candidate_ref": candidate_ref, "prior_candidates": prior_list, + "policy": "prior_link_ambiguous_kept_null"}) + reason_refs = [candidate_ref_to_bo_id[ref] for ref in reason_ref_candidates if ref in candidate_ref_to_bo_id and candidate_ref_to_bo_id[ref] != bo_id] + if prior_candidate and prior_candidate in candidate_ref_to_bo_id: + prior_act = candidate_ref_to_bo_id[prior_candidate] + elif reason_refs: + prior_act = reason_refs[0] + else: + prior_act = None + reason = "ReasonRefs에 기재된 선행 BO와 source evidence/event chain으로 연결됨" if reason_refs else "source evidence 및 event candidate에 의해 독립적으로 확인되는 BO" + value_refs = set(_strings(seed.get("value_refs"))) + alternative_ids = set(_strings(seed.get("amount_same_tier_ids"))) + base_amount = seed.get("amount") + absorbed_amounts: list[Any] = [] + absorbed_keywords: list[str] = [] + source_keywords = _keywords(seed, juristic) + absorbed_domains: dict[str, list[str]] = {} + for source_ref in absorbed_by.get(candidate_ref, []): + absorbed_seed = _dict(_dict(by_ref.get(source_ref)).get("seed_payload")) + seed_keywords = _strings(absorbed_seed.get("Legal_Keywords")) + value_refs.update(_strings(absorbed_seed.get("value_refs"))) + alternative_ids.update(_strings(absorbed_seed.get("amount_same_tier_ids"))) + alternative_ids.update(_strings([_dict(absorbed_seed.get("amount")).get("value_id")])) + if absorbed_seed.get("amount"): + absorbed_amounts.append(absorbed_seed["amount"]) + absorbed_keywords.extend(seed_keywords) + if absorbed_seed.get("source_domain") == seed.get("source_domain"): + source_keywords.extend(seed_keywords) + elif seed_keywords: + absorbed_domains.setdefault(str(absorbed_seed.get("source_domain")), []).extend(seed_keywords) + # 남는 후보가 금액을 못 골랐으면 흡수 후보의 값이 하나일 때만 잇는다. 갈리면 고르지 않고 표시로 넘긴다. + if not base_amount and len({(str(_dict(a).get("numeric_value")), _dict(a).get("currency")) + for a in absorbed_amounts}) == 1: + base_amount = min(absorbed_amounts, key=lambda a: str(_dict(a).get("value_id"))) + amount, value_refs_kept, value_note = _value_ref_check(_amount(base_amount), value_refs, catalog_records) + if value_note: + value_notes.append(dict(value_note, bo_id=bo_id, candidate_ref=candidate_ref)) + + provenance = { + "source_event_candidate_ids": _strings(refs.get("source_event_candidate_ids")), + "source_meeting_clause_ids": _strings(refs.get("source_meeting_clause_ids")), + "source_domain": seed.get("source_domain"), + } + if absorbed_domains: + # 도메인을 건너 병합된 BO — Part 3 조인이 유형마다 그 유형을 낸 도메인에만 붙인다. + provenance["source_keywords"] = sorted(set(source_keywords)) + provenance["absorbed_sources"] = [{"source_domain": domain, "Legal_Keywords": sorted(set(keywords))} + for domain, keywords in sorted(absorbed_domains.items())] + alternatives = _amount_alternatives(amount, alternative_ids, catalog_records) + if alternatives: + provenance["amount_alternatives"] = alternatives + related = _amount_related_values(value_refs_kept, catalog_records, + amount is not None or bool(alternatives)) + if related: + provenance["amount_related_values"] = related + bo_items.append({ + "BO_ID": bo_id, + "id": bo_id, + "BOType": bo_type, + "ActionType": action_type, + "JuristicAct": juristic, + "Action": str(action).strip(), + "Reason": reason, + "PriorAct": prior_act, + "ReasonRefs": reason_refs, + "Legal_Keywords": list(dict.fromkeys(_keywords(seed, juristic) + absorbed_keywords)), + "core_field_base": _core(seed), + "amount": amount, + "value_refs": value_refs_kept, + "EvidenceTitles": evidence_titles, + "Evidence": evidence_items, + "source_evidence_indexes": source_evidence_indexes, + "provenance": provenance, + "downstream_seed_refs": _downstream_refs(seed), + "extensions": {"domain_payload": domain_payload}, + }) + + # ---------- conservation + 게이트 (PostB_4 이식) ---------- + total_ledger = len(candidates) + absorbed = len(dropped) + _add_gate(gates, "candidate_conservation", len(bo_items) + absorbed == total_ledger, + f"BO {len(bo_items)} + absorbed {absorbed} == ledger {total_ledger}") + _add_gate(gates, "bo_items_array_non_empty", len(bo_items) > 0, "bo_items must be non-empty array") + ids = {item["BO_ID"] for item in bo_items} + errors: list[str] = [] + for idx, item in enumerate(bo_items, start=1): + errors.extend(_validate_item(item, idx, ids, universe, bo_types)) + _add_gate(gates, "bo_schema_and_reference_validation", not errors, "BO_JSON_Schema target validation") + # v4 신설 — 확장 payload 키를 registry 선언과 대조한다. + # 실패로 세지 않는다. 선언 밖 키는 review 로 남기고 값은 그대로 둔다. + extension_key_reviews = _extension_key_reviews(bo_items, declarations) + _add_gate(gates, "extension_payload_key_declaration_check", True, + f"bo_type_source={BO_TYPE_SOURCE} bo_types={len(bo_types)} " + f"declared_keys={len(declarations.get('declared_key_union') or [])} " + f"undeclared_records={len(extension_key_reviews)}") + # 가액금액 §3.5 — 실패로 세지 않는다. 내린 건수만 적는다. + _add_gate(gates, "value_ref_check", True, + "binding=%s downgraded=%d outside_ref_bo=%d bo_with_amount=%d" % ( + catalog_binding.get("status"), sum(1 for n in value_notes if n.get("problem")), + sum(1 for n in value_notes if n.get("outside")), + sum(1 for b in bo_items if b.get("amount") is not None))) + if any(g["status"] != "PASS" for g in gates) or errors: + _fail("pre-write gate failed", gates, errors) + + payload = json.dumps(bo_items, ensure_ascii=False, indent=2) + "\n" + write_doc(TARGET_NAME, payload) + reread = read_json_doc(TARGET_NAME) + _add_gate(gates, "post_write_json_parse", isinstance(reread, list) and len(reread) == len(bo_items), "BO.json reread JSON parse") + if not isinstance(reread, list) or len(reread) != len(bo_items): + _fail("post-write verification failed", gates, ["reread mismatch"]) + + write_doc(BUNDLE_COMPACT_PATH, json.dumps({ + "schema_version": "task_c_bo_postb_compiled_bundle_compact.v1", + "status": "READY", + "candidate_ref_to_bo_id": candidate_ref_to_bo_id, + "bo_item_count": len(bo_items), + "normalization_notes": normalization_notes, + "evidence_gap_items": evidence_gaps, + "prior_link_notes": prior_link_notes, + "extension_key_reviews": extension_key_reviews, + "human_review_count": len(human_review), + }, ensure_ascii=False, indent=2)) + + # review handoff 최종 status 갱신 + try: + handoff = _dict(read_json_doc(REVIEW_HANDOFF_PATH)) + except Exception: + handoff = {"schema_version": "stage1_part2_review_handoff.v1", "review_items": []} + handoff["status"] = "FINALIZED" + handoff["bo_item_count"] = len(bo_items) + handoff["value_facts_binding"] = dict( + catalog_binding, bo_with_amount=sum(1 for b in bo_items if b.get("amount") is not None), + amount_downgraded=sum(1 for n in value_notes if n.get("problem"))) + pack_refs = {str(e.get("exception_id")): _strings(e.get("candidate_refs")) + for e in _list(pack_root.get("exceptions")) if isinstance(e, dict)} + for exception_id, reason in sorted(human_review.items()): + refs = pack_refs.get(exception_id) or [] + handoff.setdefault("review_items", []).append({ + "review_id": "F0:human_review:%s" % exception_id, + "source_domain": refs[0].split(":")[0] if refs else None, + "severity": "HARD_WARNING", + "issue_type": "human_judgment_required", + "source_review_code": "R1_BLOCK_REVIEW", + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "사람 판정이 필요해 후보를 따로 보존했다(후보 %s): %s" + % (", ".join(refs), reason[:300]), + }) + for drop_no, drop in enumerate(unsafe_drops, start=1): + handoff.setdefault("review_items", []).append({ + "review_id": "F0:drop:%03d" % drop_no, + "source_domain": str((drop["refs"] or [""])[0]).split(":")[0] or None, + "severity": "HARD_WARNING", + "issue_type": "review_required", + "source_review_code": "R1_%s_REJECTED" % drop.get("kind", "DROP"), + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "R1 %s 을 적용하지 않고 후보를 남겼다(%s): %s%s" % ( + drop.get("kind", "DROP"), drop["reason"], ", ".join(drop["refs"]), + "" if drop.get("kind") == "MERGE" else " · 근거가 끊기는 source: %s" % (", ".join(drop["orphaned_sources"]) or "없음")), + }) + for note in value_notes: + handoff.setdefault("review_items", []).append({ + "review_id": "F0:value_ref:%s" % note["bo_id"], + "source_domain": str(note.get("candidate_ref") or "").split(":")[0] or None, + "severity": "HARD_WARNING", + "issue_type": "amount_or_date_uncertain", + "source_review_code": note.get("problem") or "VALUE_REF_OUTSIDE_CATALOG", + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "source_value_fact_ids": sorted(set(note.get("outside") or []) | ({note["value_id"]} if note.get("value_id") else set())), + "downstream_owner": "Stage2", + "template_note": "BO 금액이 정본 카탈로그와 맞지 않아 amount 를 null 로 내렸거나 정본 밖 value_id 를 지웠다.", + }) + for review in extension_key_reviews: + handoff.setdefault("review_items", []).append({ + "review_id": f"F0:extension_key:{review['bo_id']}", + "source_domain": review["source_domain"], + "severity": "SOFT_WARNING", + "issue_type": UNDECLARED_KEY_REVIEW_CODE, + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "확장 payload 에 registry 선언 밖 키가 있다: " + + ", ".join(review["undeclared_keys"][:12]), + }) + for note in prior_link_notes: + handoff.setdefault("review_items", []).append({ + "review_id": f"F0:prior:{note['candidate_ref']}", + "source_domain": None, + "severity": "SOFT_WARNING", + "issue_type": "prior_link_ambiguous", + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "선행행위 후보가 복수여서 PriorAct를 null로 보존하였다.", + }) + # F0-2 — 정규화는 노트로 끝내지 않고 handoff 에도 올린다. 침묵하는 폴백과 + # 선언된 기본값의 차이는 관측 가능성이다 (M-f 관측점). + for note in normalization_notes: + handoff.setdefault("review_items", []).append({ + "review_id": "F0:normalization:%s:%s" % (note.get("candidate_ref"), note.get("field")), + "source_domain": str(note.get("candidate_ref") or "").split(":")[0] or None, + "severity": "SOFT_WARNING", + "issue_type": "schema_field_fallback", + "source_review_code": note.get("field"), + "source_event_candidate_ids": [], + "source_evidence_indexes": [], + "source_meeting_clause_ids": [], + "downstream_owner": "Stage2", + "template_note": "F0 정규화가 적용된 칸이다. 값의 출처와 타당성을 재검토한다.", + }) + write_doc(REVIEW_HANDOFF_PATH, json.dumps(handoff, ensure_ascii=False, indent=2)) + + print(json.dumps({ + "status": "PASS", + "message": f"BO.json 작성 완료 (BO {len(bo_items)}건)", + "write_target": TARGET_NAME, + "bo_item_count": len(bo_items), + "absorbed_by_merge": absorbed, + "gate_results": gates, + "bundle_compact_path": BUNDLE_COMPACT_PATH, + "bo_type_source": BO_TYPE_SOURCE, + "registry_version": declarations.get("generated_from", {}).get("registry_version"), + "extension_key_review_count": len(extension_key_reviews), + "value_facts_binding": catalog_binding.get("status"), + "amount_downgraded": sum(1 for n in value_notes if n.get("problem")), + "r1_decision_state": r1_state, + "declared_exception_count": declared_exceptions, + "human_review_count": len(human_review), + }, ensure_ascii=False)) + + if __name__ == "__main__": + main() + + - task_name: Task_C_BO_S0_signal_bundle_writer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: httpx + network: agent-network + timeout: 300 + code: |- + #!/usr/bin/env python3 + # Task_C_BO_S0_signal_bundle_writer (v4) + # 정본 signal 거래 1건을 기록한다. 생성기·사영기·기록기는 조립본 모듈이며 여기서 만들지 않는다. + # Spec: stage_1_part_2_optimal_update_strategy_v.2.md §6.5 + from __future__ import annotations + import contextlib + import hashlib + import io + import itertools + import json + import pathlib + import posixpath + import re + import sys + from typing import Any + import httpx + + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=60) + MSG_ID = itertools.count(10) + JSON_DECODER = json.JSONDecoder() + + # ---- 실행 뿌리 셋 — D-5 §2.4 0-c-2 확정값 ---- + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + LOGICAL_ROOT = "/tmp/s1" + WORK = pathlib.Path(EXECUTION_ROOT) + # 모듈의 디렉터리 산술을 그대로 재현한다(머리말 '반입 배치' 참조). + # SIGNALS_ROOT.parents[1] == ANCHOR 이므로 계약은 ANCHOR/contracts 아래다. + ANCHOR = WORK / "_sig" + SIGNALS_ROOT = ANCHOR / "pkg" / "signals" + CONTRACT_DIR = ANCHOR / "contracts" + OUTPUT_DIR = WORK / "_signal_out" + + # ---- 반입 대상 ---- + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + COMPILER_MODULES = ["common", "projections", "schema_validator", "signal_compiler", + "signal_gate", "transaction_writer", "writer_boundary"] + ADAPTER_MODULES = ["s3_domain_seed_adapter", "s3_envelope_migration_adapter", + "s4_calculation_adapter", "sg01_activation_adapter"] + EMITTER_MODULES = ["emitter_runtime"] + ["emit_sg%02d" % n for n in range(2, 14)] + SIGNAL_REGISTRY = "Default_Agent/signals/signal_registry.v2.json" + EXECUTION_CONTRACT = "Default_Agent/contracts/signals/s5_execution_contract.v2.json" + + # ---- 사건 입력 ---- + # v4 — 구 경로·정적 이름을 걷어냈다. seed 는 fan-out 계획의 expected_output_path 로 읽는다. + ACTIVATION_MANIFEST_PATH = "routing/domain_activation_manifest.json" + # 실패결과보고서_1_part_2 S-1 — D0 의 negative·conflict ref(MTG.*)의 정본 목록. S-2 — F0 완료 표식. + SCREENING_PATH = "routing/domain_screening.json" + REVIEW_HANDOFF_PATH = "quality_gates/stage1_part2_review_handoff.json" + FANOUT_PLAN_PATH = "fanout/domain_fanout_plan.json" + SOURCE_UNIVERSE_PATH = "stage1_tmp/task_c_bo/source_universe_manifest.json" + BO_PATH = "BO.json" + BUNDLE_COMPACT_PATH = "stage1_tmp/task_c_bo/postb_compiled_bundle_compact.json" + SEED_SCHEMA_VERSION = "task_c_bo_stage_b_domain_bo_seed.v3" + ADMITTED_SEED_DIR = "stage1_tmp/task_c_bo/admitted_seeds" + # 수용본에서 R0 가 옮기거나 고친 행은 signal·review 를 바꾼다. 행 내용과 멈춤 범위를 현행대로 두려고 + # 이 키들만 worker 원본을 쓴다. 슬롯 · dependency_refs · 그 밖의 뿌리 값은 수용본을 쓴다. + RAW_ROW_KEYS = ("element_fact_candidates", "opposing_fact_candidates", "defense_candidates", + "legal_effect_candidates", "calculation_requests", "review_items", "seed_id") + # R-5 — 도메인이 선언한 방출 signal 집합. A0 가 슬라이스에 실어 둔 것을 읽는다. + # registry 를 여기서 다시 적재하지 않는다. + SLICE_DIR = "runtime/domain_slices" + SLICE_ROOT_KEY = "stage_b_domain_slice" + DECLARED_EMISSION_REVIEW_CODE = "SIGNAL_EMISSION_NOT_DECLARED" + + # ---- 산출 ---- + SIGNAL_OUTPUT_PREFIX = "signals/" + TRANSACTION_ID_RE = r"^S5TX-[a-f0-9]{20}$" + CANONICAL_WRITER_MODULE = "compiler/transaction_writer.py" + COMPATIBILITY_ROOT_ALIASES = { + "compatibility_views/actio_case_signals.json": "actio_case_signals.json", + "compatibility_views/case_liability_signals.json": "case_liability_signals.json", + "compatibility_views/legal_effect_signals.json": "legal_effect_signals.json", + } + # 각 호환 뷰가 어느 정본 signal 의 사영인지. projections.py 의 서명이 정본이다. + COMPATIBILITY_VIEW_SOURCES = { + "compatibility_views/actio_case_signals.json": [], + "compatibility_views/case_liability_signals.json": ["SG-05", "SG-08"], + "compatibility_views/legal_effect_signals.json": ["SG-13"], + } + SIGNAL_FILE_BY_CODE = { + "SG-05": "legal_relation_lifecycle_signals.json", + "SG-08": "liability_causation_damage_signals.json", + "SG-13": "legal_effect_routes.json", + } + COMPATIBILITY_EMPTY_REVIEW_CODE = "COMPATIBILITY_VIEW_EMPTY" + + + def _mid() -> int: + return next(MSG_ID) + + def _init() -> None: + r = CLIENT.post( + LOCALDOCS_URL, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": { + "name": "task-c-bo-s0-signal-bundle-writer", + "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}", + }, + }, + }, + headers=MCP_HEADERS, + ) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS, + ).raise_for_status() + + def _parse_mcp(text: str) -> Any: + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + pass + try: + return json.loads(text) + except Exception: + return None + + def _call(name: str, args: dict[str, Any]) -> Any: + r = CLIENT.post( + LOCALDOCS_URL, + json={"jsonrpc": "2.0", "id": _mid(), "method": "tools/call", + "params": {"name": name, "arguments": args}}, + headers=MCP_HEADERS, + ) + r.raise_for_status() + payload = _parse_mcp(r.text) + if not payload or "result" not in payload: + raise RuntimeError(f"MCP {name} failed") + return payload + + def read_json_doc(path: str) -> Any: + result = _call("read_docs", {"doc_names": [path]}) + content = result["result"].get("content", []) + text = content[0].get("text", "") if content else "" + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + raise RuntimeError(f"Invalid read_docs envelope for {path}") from exc + if isinstance(parsed, dict) and "results" in parsed: + rows = parsed.get("results") or [] + if not rows or rows[0].get("error"): + raise RuntimeError(f"read_docs failed for {path}: {rows[:1]}") + inner = rows[0].get("content") or "" + if isinstance(inner, str): + try: + return json.loads(inner) + except json.JSONDecodeError: + obj, end = JSON_DECODER.raw_decode(inner.strip()) + if inner.strip()[end:].strip(): + raise RuntimeError(f"{path}: non-json tail") + return obj + return inner + return parsed + + def write_doc(path: str, content: str) -> None: + _call("write_file", {"path": path, "content": content, "overwrite": True}) + + + def read_raw(name: str) -> str: + # 파일 내용을 재직렬화 없이 원문 그대로 돌려준다. + # 모듈 미러의 sha256 은 원문 바이트의 해시여야 하므로 재직렬화를 허용하지 않는다. + # Task_D0_domain_activation_gate.yml 의 검증 완료본을 _call 서명만 맞춰 옮겼다. + p = _call("read_docs", {"doc_names": [name]}) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + # ------------------------------------------------------------------ + # F-4 — 자기 입력의 배포 무결성. A0 게이트가 앞에서 걸러 주지만 이 task 는 + # 개별 재실행이 가능하다(예행 하네스가 실제로 task 단위로 돌린다). + # 매니페스트는 task 당 한 번만 읽는다. 호출마다 읽으면 S0 의 $ref 폐포 walk 에서만 19 회다. + # ------------------------------------------------------------------ + PART2_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + _MANIFEST_MAP = None + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART2_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART2_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical: str) -> str: + """원문을 돌려준다. 반환값을 소비해야 읽기 횟수가 늘지 않는다.""" + body = read_raw(logical) + want = _manifest_map().get(logical[len("Default_Agent/"):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != hashlib.sha256(body.encode("utf-8")).hexdigest(): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + # ------------------------------------------------------------------ + # 1) 자산 반입 — D0 반입 규약 R-1~R-5 를 그대로 따른다. + # + # 디렉터리 산술을 흉내내야 하는 이유(실측). + # signals/compiler/*.py 는 _SIGNALS_ROOT = Path(__file__).resolve().parents[1] + # 로 signals 뿌리를 잡고, 실행 계약을 _SIGNALS_ROOT.parents[1]/contracts/ + # s5_execution_contract.v2.json 에서 읽는다. 즉 계약은 signals 의 조부모 아래다. + # 조립본은 계약을 Default_Agent/contracts/signals/ 에 두므로 그 산술이 조립본 + # 배치로는 풀리지 않는다. 반입 시에는 우리가 배치를 정하므로 모듈이 기대하는 + # 산술을 그대로 재현한다 — signals 를 /pkg/signals 에 두고 계약을 + # /contracts 에 둔다. 모듈 원문은 한 글자도 고치지 않는다. + # ------------------------------------------------------------------ + def _relative_refs(node: Any) -> list[str]: + """상대 파일 $ref 만 모은다. 로컬 포인터(#/...)는 검증기가 스스로 푼다.""" + out: list[str] = [] + if isinstance(node, dict): + ref = node.get("$ref") + if isinstance(ref, str) and ref and not ref.startswith("#"): + out.append(ref.split("#", 1)[0]) + for value in node.values(): + out.extend(_relative_refs(value)) + elif isinstance(node, list): + for value in node: + out.extend(_relative_refs(value)) + return [item for item in out if item] + + + def _stage_bytes(target, body: str) -> int: + raw = body.encode("utf-8") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + return len(raw) + + + def materialize() -> dict[str, Any]: + SIGNALS_ROOT.mkdir(parents=True, exist_ok=True) + CONTRACT_DIR.mkdir(parents=True, exist_ok=True) + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) + manifest_doc = json.loads(read_raw(RUNTIME_MANIFEST)) + expected = {row["path"]: row["sha256"] for row in manifest_doc.get("entries") or []} + + staged: dict[str, Any] = {"modules": [], "schemas": [], "unregistered": []} + for sub, names in (("compiler", COMPILER_MODULES), + ("adapters", ADAPTER_MODULES), + ("emitters", EMITTER_MODULES)): + for name in names: + logical = "%ssignals/%s/%s.txt" % (ASSET_ROOT, sub, name) + body = read_raw(logical) + raw = body.encode("utf-8") + want = expected.get(logical[len(ASSET_ROOT):]) + got = hashlib.sha256(raw).hexdigest() + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != got: + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + _stage_bytes(SIGNALS_ROOT / sub / (name + ".py"), body) + staged["modules"].append("%s/%s" % (sub, name)) + + _stage_bytes(SIGNALS_ROOT / "signal_registry.v2.json", _verify_asset(SIGNAL_REGISTRY)) + _stage_bytes(CONTRACT_DIR / "s5_execution_contract.v2.json", _verify_asset(EXECUTION_CONTRACT)) + + # 스키마 목록을 이 코드가 만들지 않는다. registry 가 선언한 참조에서 출발해 + # 상대 파일 $ref 를 따라간다. _common/ 아래 조각도 그렇게 저절로 딸려 온다. + registry = json.loads((SIGNALS_ROOT / "signal_registry.v2.json").read_text(encoding="utf-8")) + pending = list(dict.fromkeys( + [str(row["schema"]) for row in registry["entries"] if row.get("schema")] + + [str(registry["domain_envelope"]), str(registry["manifest_schema"])])) + seen: set[str] = set() + while pending: + rel = posixpath.normpath(pending.pop(0)) + if rel in seen or rel.startswith(".."): + continue + seen.add(rel) + # F-4c — 이 한 줄이 폐포가 끌어오는 signal 스키마 전부를 덮는다. + # 목록을 상수로 굳히지 않는다 — registry 가 바뀌면 조용히 어긋난다. + body = _verify_asset("%ssignals/%s" % (ASSET_ROOT, rel)) + _stage_bytes(SIGNALS_ROOT / rel, body) + staged["schemas"].append(rel) + for child in _relative_refs(json.loads(body)): + pending.append(posixpath.join(posixpath.dirname(rel), child)) + + sys.path.insert(0, str(SIGNALS_ROOT)) + staged["signals_root"] = str(SIGNALS_ROOT) + staged["module_count"] = len(staged["modules"]) + staged["schema_count"] = len(staged["schemas"]) + return staged + + + # ------------------------------------------------------------------ + # 2) 입력 조립 — 정적 어휘를 두지 않는다. 계획서와 매니페스트가 목록을 정한다. + # ------------------------------------------------------------------ + def build_inputs() -> tuple[dict[str, Any], dict[str, Any]]: + bo_items = read_json_doc(BO_PATH) + # S-2 — 백엔드는 F0 가 실패해도 S0 를 돌린다. 그때 BO.json 은 지난 회차 것이다. + review_handoff = read_json_doc(REVIEW_HANDOFF_PATH) + review_handoff = review_handoff if isinstance(review_handoff, dict) else {} + if (review_handoff.get("status") != "FINALIZED" + or review_handoff.get("bo_item_count") != (len(bo_items) if isinstance(bo_items, list) else None)): + raise RuntimeError("S0_UPSTREAM_F0_NOT_FINALIZED:status=%s bo_item_count=%s bo_json=%s" % ( + review_handoff.get("status"), review_handoff.get("bo_item_count"), + len(bo_items) if isinstance(bo_items, list) else None)) + activation = read_json_doc(ACTIVATION_MANIFEST_PATH) + if not isinstance(activation, dict) or not isinstance( + activation.get("domain_activation_manifest"), dict): + raise RuntimeError("SG01_INPUT_REQUIRED: Part 1 activation gate output is required") + + plan = read_json_doc(FANOUT_PLAN_PATH) + plan_root = plan.get("domain_fanout_plan") if isinstance(plan, dict) else None + plan_root = plan_root if isinstance(plan_root, dict) else (plan if isinstance(plan, dict) else {}) + instances = [x for x in (plan_root.get("task_instances") or []) if isinstance(x, dict)] + if not instances: + raise RuntimeError("S0_FANOUT_PLAN_EMPTY") + + # BO 가 된 후보 표. 없는 후보는 표시만 한다. 효과 후보를 비우지 않는다(전략서 v.2 축 C). + compact = read_json_doc(BUNDLE_COMPACT_PATH) + bo_refs = compact.get("candidate_ref_to_bo_id") if isinstance(compact, dict) else None + if not isinstance(bo_refs, dict) or not bo_refs: + raise RuntimeError("S0_CANDIDATE_MAP_MISSING:%s" % BUNDLE_COMPACT_PATH) + + seeds: dict[str, Any] = {} + seed_paths: list[str] = [] + declared_emissions: dict[str, list[str]] = {} + bo_absent_count = 0 + for instance in instances: + path = instance.get("expected_output_path") + domain_id = str(instance.get("domain_id") or "") + if not isinstance(path, str) or not path or not domain_id: + raise RuntimeError("S0_FANOUT_INSTANCE_INVALID:%s" % json.dumps(instance, ensure_ascii=False)[:120]) + raw_document = read_json_doc(path) + raw_root = raw_document.get("stage_b_domain_bo_seed_output") if isinstance(raw_document, dict) else None + if not isinstance(raw_root, dict): + raise RuntimeError("S0_SEED_ROOT_MISSING:%s" % path) + admitted_path = "%s/%s.json" % (ADMITTED_SEED_DIR, domain_id) + document = read_json_doc(admitted_path) + root = document.get("stage_b_domain_bo_seed_output") if isinstance(document, dict) else None + if not isinstance(root, dict): + raise RuntimeError("S0_SEED_ROOT_MISSING:%s" % admitted_path) + raw_sha256 = hashlib.sha256(json.dumps(raw_document, sort_keys=True).encode("utf-8")).hexdigest() + if document.get("raw_seed_sha256") != raw_sha256: + raise RuntimeError("S0_ADMITTED_SEED_DRIFT:%s" % domain_id) + if root.get("schema_version") != SEED_SCHEMA_VERSION: + raise RuntimeError("S3_SEED_SCHEMA_VERSION_MISMATCH:%s" % admitted_path) + if root.get("domain_id") != domain_id: + raise RuntimeError("S0_SEED_DOMAIN_MISMATCH:%s" % admitted_path) + root["unknown_or_unrouted_reviews"] = raw_root.get("unknown_or_unrouted_reviews") + # R0 ensure_candidate_ref 와 같은 공식이다(원래 목록 위치). 메모리에만 붙인다. + # R0 는 후보를 배열에서 빼지 않고, 위 해시가 같은 산출임을 보장하므로 위치로 짝짓는다. + for position, (cand, raw_cand) in enumerate(zip(root.get("bo_seed_candidates") or [], + raw_root.get("bo_seed_candidates") or []), start=1): + if not isinstance(cand, dict): + continue + for key in RAW_ROW_KEYS: + cand[key] = raw_cand.get(key) + cand["candidate_ref"] = "%s:%03d" % (domain_id, position) + cand.pop("bo_absent", None) # 수용 전 worker 값이 남는 경로(shadow·검증기 미가용)가 있다 + if cand["candidate_ref"] not in bo_refs: + cand["bo_absent"] = True + bo_absent_count += 1 + seeds[domain_id] = document + seed_paths.append(admitted_path) + # R-5 — 같은 도메인의 슬라이스에서 emits_signals 선언을 읽는다. 부재는 조용히 넘긴다. + try: + slice_doc = read_json_doc("%s/%s.json" % (SLICE_DIR, domain_id)) + slice_root = slice_doc.get(SLICE_ROOT_KEY) if isinstance(slice_doc, dict) else None + slice_root = slice_root if isinstance(slice_root, dict) else (slice_doc if isinstance(slice_doc, dict) else {}) + declarations = slice_root.get("domain_declarations") + codes = [str(v) for v in ((declarations or {}).get("emits_signals") or []) + if isinstance(v, str) and v] + if codes: + declared_emissions[domain_id] = sorted(set(codes)) + except Exception: + pass + + universe_doc = read_json_doc(SOURCE_UNIVERSE_PATH) + universe_doc = universe_doc if isinstance(universe_doc, dict) else {} + bo_ids = sorted({str(x.get("BO_ID")) for x in bo_items + if isinstance(x, dict) and x.get("BO_ID")}) if isinstance(bo_items, list) else [] + evidence_ids = sorted({str(v) for v in (universe_doc.get("evidence_index_set") or [])}) + event_ids = sorted({str(v) for v in (universe_doc.get("event_candidate_ids") or [])}) + meeting_ids = sorted({str(v) for v in (universe_doc.get("meeting_clause_ids") or [])}) + if not (evidence_ids or event_ids or meeting_ids): + raise RuntimeError("S0_SOURCE_UNIVERSE_EMPTY:%s" % SOURCE_UNIVERSE_PATH) + + # 가액금액 §3.6 — fact_ids 는 A0 가 이 매니페스트에 덧붙인 회차 카탈로그의 value_id 다(필수). + # 행은 worker 원본에서 온다. worker 가 규칙을 어기고 value_id 를 review_items·source_id 에 적으면 + # 이 선언 없이는 domain_source_membership 에 걸린다. + # law_version_ids 는 이 매니페스트가 선언하지 않는다. 봉투 행의 그런 ref 는 adapter 가 + # extensions.unverified_refs 로 옮긴다. Stage 1 은 판본을 추적하지 않는다. + fact_ids = sorted({str(v) for v in (universe_doc.get("value_fact_ids") or [])}) + # S-1 — Part 1 스크리닝 단위(MTG.*). meeting_clause_ids(stage_a 형식)와 체계가 달라 all_source_refs 에만 둔다. + screening_doc = read_json_doc(SCREENING_PATH) + screening_root = screening_doc.get("domain_screening", screening_doc) if isinstance(screening_doc, dict) else {} + screening_unit_ids = sorted({str(v) for v in (screening_root.get("source_document_refs") or []) + if isinstance(v, str) and v}) + source_universe = { + "bo_ids": bo_ids, + "fact_ids": fact_ids, + "evidence_ids": evidence_ids, + "meeting_clause_ids": meeting_ids, + "law_version_ids": [], + "event_ids": event_ids, + "all_source_refs": sorted(set(bo_ids) | set(evidence_ids) | set(event_ids) | set(meeting_ids) + | set(fact_ids) | set(screening_unit_ids)), + "unrouted_evidence_count": int(len( + activation["domain_activation_manifest"].get("unrouted_material") or [])), + } + inputs = { + "declared_emissions": declared_emissions, + "domain_activation_manifest": activation, + "domain_seed_outputs": seeds, + "source_universe": source_universe, + # v4 — 구 signal 원문을 넣지 않는다. 세 호환 뷰는 정본 signal 의 사영일 뿐이다. + "legacy_signals": {}, + "signal_candidates": {}, + } + receipt = { + "seed_count": len(seeds), + "declared_emission_domains": sorted(declared_emissions), + "seed_paths": seed_paths, + "bo_id_count": len(bo_ids), + "evidence_count": len(evidence_ids), + "event_count": len(event_ids), + "meeting_count": len(meeting_ids), + "fact_ids_declared": True, + "fact_id_count": len(fact_ids), + "law_version_ids_declared": False, + "bo_absent_candidates": bo_absent_count, + } + return inputs, receipt + + + # ------------------------------------------------------------------ + # 3) 생성기 12 · 사영기 3 · 단일 기록기 호출 + # 호출 본문은 이 한 함수뿐이다. 생성기와 사영기는 순수 함수이며 파일을 쓰지 않는다. + # 실행기 안에서 파일을 쓰는 것은 compiler/transaction_writer.py 하나다 — + # signal_gate 의 canonical_writer_uniqueness 가 그것을 강제한다. + # ------------------------------------------------------------------ + def compile_and_validate(inputs: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + from compiler.signal_compiler import compile_transaction + from compiler.signal_gate import validate_output + + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + manifest = compile_transaction(inputs, OUTPUT_DIR) + gate = validate_output(inputs, OUTPUT_DIR, SIGNALS_ROOT) + if not re.fullmatch(TRANSACTION_ID_RE, str(manifest.get("transaction_id") or "")): + raise RuntimeError("S0_TRANSACTION_ID_PATTERN:%s" % manifest.get("transaction_id")) + if gate.get("canonical_writer_modules") != [CANONICAL_WRITER_MODULE]: + raise RuntimeError("S0_CANONICAL_WRITER_NOT_UNIQUE:%s" + % json.dumps(gate.get("canonical_writer_modules"), ensure_ascii=False)) + if gate.get("status") != "PASS": + raise RuntimeError("S0_SIGNAL_GATE_FAILED:%s" + % json.dumps(gate.get("errors")[:8], ensure_ascii=False)) + return manifest, gate + + + # ------------------------------------------------------------------ + # 4) 반출 — 거래가 낸 바이트를 그대로 옮긴다. 재직렬화하지 않는다. + # ------------------------------------------------------------------ + def publish(manifest: dict[str, Any]) -> dict[str, Any]: + written: list[dict[str, Any]] = [] + local: dict[str, bytes] = {} + for path in sorted(OUTPUT_DIR.rglob("*.json")): + rel = path.relative_to(OUTPUT_DIR).as_posix() + raw = path.read_bytes() + local[rel] = raw + write_doc(SIGNAL_OUTPUT_PREFIX + rel, raw.decode("utf-8")) + written.append({"path": SIGNAL_OUTPUT_PREFIX + rel, + "sha256": hashlib.sha256(raw).hexdigest(), "bytes": len(raw)}) + + # 구 이름 세 개는 Part 3·4 가 읽는 최대 호환면이다. 같은 바이트를 그대로 한 벌 더 놓는다. + # 두 번째 생산자가 아니라 운반이다 — 내용은 거래가 낸 것과 바이트 동일하다. + aliases: list[dict[str, Any]] = [] + for canonical_rel, alias in COMPATIBILITY_ROOT_ALIASES.items(): + raw = local.get(canonical_rel) + if raw is None: + raise RuntimeError("S0_COMPATIBILITY_VIEW_MISSING:%s" % canonical_rel) + write_doc(alias, raw.decode("utf-8")) + aliases.append({"alias": alias, "canonical": SIGNAL_OUTPUT_PREFIX + canonical_rel, + "sha256": hashlib.sha256(raw).hexdigest()}) + + # 기록 후 재읽기. 봉인 파일 하나를 원문 바이트로 되읽어 해시를 대조한다. + reread = read_raw(SIGNAL_OUTPUT_PREFIX + "signal_manifest.json").encode("utf-8") + if hashlib.sha256(reread).hexdigest() != hashlib.sha256(local["signal_manifest.json"]).hexdigest(): + raise RuntimeError("S0_POST_WRITE_MANIFEST_HASH_MISMATCH") + return {"written": written, "compatibility_root_aliases": aliases, + "file_count": len(written)} + + + def emission_notices(manifest: dict[str, Any], + declared_emissions: dict[str, list[str]]) -> list[dict[str, Any]]: + """도메인이 선언한 emits_signals 와 기록이 실린 정본 signal 을 대조한다. + + 실패로 세지 않는다. 선언은 registry 의 것이고 실제 방출은 사건 재료에 달려 있어 + 선언보다 적게 나오는 것은 정상이다. 반대로 **선언 밖에서 기록이 나오면** 어휘 밖의 + 산출이므로 지목한다 — 137종 일반성은 그 어휘 안에서 성립해야 한다. + """ + if not declared_emissions: + return [] + union: set[str] = set() + for codes in declared_emissions.values(): + union.update(codes) + by_path = {row["path"]: row for row in manifest.get("files") or []} + emitted: set[str] = set() + for code, filename in SIGNAL_FILE_BY_CODE.items(): + if (by_path.get(filename) or {}).get("record_count"): + emitted.add(code) + undeclared = sorted(code for code in emitted if code not in union) + if not undeclared: + return [] + return [{ + "review_code": DECLARED_EMISSION_REVIEW_CODE, + "undeclared_signals": undeclared, + "declared_union": sorted(union), + "declared_by_domain": {k: v for k, v in sorted(declared_emissions.items())}, + "note": "선언 밖 signal 에 기록이 실렸다. registry 의 emits_signals 를 넓히거나 산출을 좁힌다.", + }] + + + def compatibility_notices(manifest: dict[str, Any]) -> list[dict[str, Any]]: + """호환 뷰가 비었는데 정본 signal 에는 기록이 있으면 조용히 넘기지 않고 지목한다. + + v3 은 세 파일을 BO.json 에서 직접 만들었고, v4 는 정본 signal 의 사영으로 만든다. + 사영 대상은 compatibility_key/compatibility_route 를 단 기록뿐이며 그 표식은 + 구 signal 원문에서만 붙는다. 따라서 구 원문을 넣지 않는 v4 에서는 뷰가 빌 수 있다. + Part 3·4 는 signal_manifest.downstream_read_sets 가 선언한 정본 집합으로 옮겨야 한다. + 그 이관은 Part 3·4 개정의 몫이므로 여기서는 사실만 남긴다. + """ + by_path = {row["path"]: row for row in manifest.get("files") or []} + notices: list[dict[str, Any]] = [] + for canonical_rel, alias in COMPATIBILITY_ROOT_ALIASES.items(): + view = by_path.get(canonical_rel) or {} + if view.get("state") != "empty": + continue + sources = COMPATIBILITY_VIEW_SOURCES[canonical_rel] + populated = sorted(code for code in sources + if (by_path.get(SIGNAL_FILE_BY_CODE.get(code, "")) or {}).get("record_count")) + if populated: + notices.append({ + "review_code": COMPATIBILITY_EMPTY_REVIEW_CODE, + "alias": alias, + "canonical_view": canonical_rel, + "populated_canonical_signals": populated, + "downstream_read_sets": manifest.get("downstream_read_sets"), + "note": "구 이름 파일이 비었다. Part 3·4 는 정본 signal 집합으로 읽어야 한다.", + }) + return notices + + + def main() -> None: + _init() + staged = materialize() + inputs, input_receipt = build_inputs() + manifest, gate = compile_and_validate(inputs) + published = publish(manifest) + notices = compatibility_notices(manifest) + notices.extend(emission_notices(manifest, inputs.get("declared_emissions") or {})) + + print(json.dumps({ + "status": "READY_WITH_REVIEW" if notices else "READY", + "message": "정본 signal 거래 1건 기록 완료 (파일 %d종)" % published["file_count"], + "schema_version": "stage1_canonical_signal_writer.v1", + "transaction_id": manifest.get("transaction_id"), + "manifest_status": manifest.get("status"), + "signal_manifest_path": SIGNAL_OUTPUT_PREFIX + "signal_manifest.json", + "module_import": { + "module_count": staged["module_count"], + "schema_count": staged["schema_count"], + "hash_source": RUNTIME_MANIFEST, + "signals_root": staged["signals_root"], + }, + "inputs": input_receipt, + "gate": { + "status": gate.get("status"), + "error_count": gate.get("error_count"), + "canonical_writer_modules": gate.get("canonical_writer_modules"), + "source_membership_pass": gate.get("source_membership_pass"), + "domain_source_membership_pass": gate.get("domain_source_membership_pass"), + "meeting_only_promotion_pass": gate.get("meeting_only_promotion_pass"), + "negative_conflict_preservation_pass": gate.get("negative_conflict_preservation_pass"), + "compatibility_projection_pass": gate.get("compatibility_projection_pass"), + "manifest_hash_pass": gate.get("manifest_hash_pass"), + "forbidden_conclusion_key_pass": gate.get("forbidden_conclusion_key_pass"), + }, + "published": published, + "active_domains": manifest.get("active_domains"), + "unrouted_counts": manifest.get("unrouted_counts"), + "compatibility_notices": notices, + }, ensure_ascii=False)) + + + if __name__ == "__main__": + try: + main() + except Exception as exc: + print(json.dumps({"status": "FAILED", "message": "S0 signal bundle writer 실패", + "reason": str(exc)}, ensure_ascii=False)) + raise + + task_procedure: + # A0 가 fan-out 계획을 낸 뒤 load_fanout 이 그것을 읽어야 worker 인스턴스가 생긴다. 그래서 직렬이다. + IN: + nexts: ["Task_C_BO_A0_context_and_domain_slice_compiler"] + wait_until: [] + + # 2026-11-03 캐시 — A0 → (prewarm ‖ load_fanout) → worker_* → capture_{same_ordinal} → R0. + # prewarm 은 A0 가 쓴 뒤에만 돈다(when). load_fanout 은 A0·prewarm 둘을 기다린다. prewarm 이 SKIPPED·FAILED 여도 + # 이벤트는 set 되므로 load_fanout 은 막히지 않는다. fan-out 부모는 load_fanout 이고 raise 하지 않는다. + Task_C_BO_A0_context_and_domain_slice_compiler: + nexts: + - task: Task_C_B_domain_prewarm + when: output.written == true + - Task_C_B_domain_load_fanout + wait_until: ["IN"] + + Task_C_B_domain_prewarm: + nexts: ["Task_C_B_domain_load_fanout"] + wait_until: ["Task_C_BO_A0_context_and_domain_slice_compiler"] + + Task_C_B_domain_load_fanout: + nexts: ["Task_C_B_domain_worker_*"] + wait_until: ["Task_C_BO_A0_context_and_domain_slice_compiler", "Task_C_B_domain_prewarm"] + + # 활성 도메인 병렬 x M. 인스턴스는 load_fanout 의 dynamic_fanout(= domain_fanout_plan.task_instances[])이 만든다. + Task_C_B_domain_worker_*: + nexts: ["Task_C_B_domain_capture_{same_ordinal}"] + wait_until: ["Task_C_B_domain_load_fanout"] + + Task_C_B_domain_capture_*: + nexts: ["Task_C_BO_R0_seed_reducer_and_exception_planner"] + wait_until: ["Task_C_B_domain_worker_{same_ordinal}"] + + # barrier — 정확 일치. 누락·초과·중복 모두 실패다. 빈 fan-out 이면 바로 풀리고 R0 가 fanout_blocked.json 으로 멈춘다. + Task_C_BO_R0_seed_reducer_and_exception_planner: + nexts: ["Task_C_BO_R1_exception_adjudicator"] + wait_until: ["all Task_C_B_domain_capture_*"] + + # 조건부. 예외 pack 이 비면 통과만 한다. + Task_C_BO_R1_exception_adjudicator: + nexts: ["Task_C_BO_F0_final_bo_compiler_gate_writer"] + wait_until: ["Task_C_BO_R0_seed_reducer_and_exception_planner"] + + Task_C_BO_F0_final_bo_compiler_gate_writer: + nexts: ["Task_C_BO_S0_signal_bundle_writer"] + wait_until: ["Task_C_BO_R1_exception_adjudicator"] + + Task_C_BO_S0_signal_bundle_writer: + nexts: ["OUT"] + wait_until: ["Task_C_BO_F0_final_bo_compiler_gate_writer"] + + OUT: + nexts: [] + wait_until: ["Task_C_BO_S0_signal_bundle_writer"] + + prevs: [] + nexts: [] diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_3_v.8_11_05_5_22pm.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_3_v.8_11_05_5_22pm.yml new file mode 100644 index 00000000..e2986956 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_3_v.8_11_05_5_22pm.yml @@ -0,0 +1,2589 @@ +# ============================================================================= +# Liti-agent Stage 1 Part 3 v.8 — 법률효과 구조 · 통합 실행본 +# +# 정본 근거 +# 전략 : stage_1_part_3_개정_신전략서.md (D-4 결정안 §2 · 작업 명세 §4 · 자산 §5) +# 상위 계약 : stage_1_part_1_v.8.yml · stage_1_part_2_v.8.yml 의 실산출 +# 진입 계약 : signals/signal_manifest.json (downstream_read_sets.part3_L0 = +# SG-02 · SG-05 · SG-07 · SG-11 · SG-13) + SG-01 + BO.json +# +# 구성 — task 7종 (L1 = 후보 유형 추천기(JEV), 2026-11-05 신설 · glossary 11-05 오후) +# [신설] Task_C_LE_L0_structure_seed_reducer Θ 조립 · 구조 seed · 조인 · 검토 +# [신설] Task_C_LE_L1_glossary gemini-3.8-flash low: 유형 정의·조문 초안(미검증, 11-05 오후) +# [신설] Task_C_LE_L1_candidate_planner glossary 검사 · 후보·쌍 계획 · jev dynamic_fanout (raise 금지) +# [신설] Task_C_LE_L1_recommender_* jev: 쌍마다 choice 질문 1개 +# [신설] Task_C_LE_L1_capture_* jev 응답 → 답 파일 +# [신설] Task_C_LE_L1_apply decide(결정론) · 번들·handoff 반영 · 영수증 +# [신설] Task_C_LE_L2_final_structure_index_writer 보존 등식 셋 · 역인덱스 셋 · 최종 기록 +# +# 확정 계약 +# Θ SG-01.expected_runnable_domain_ids 의 domain_config.structure_types 합집합 +# 구조 레코드 (도메인, type_id) 쌍마다 하나 · 도메인 간 병합 금지 +# 전순서 (priority_rank, registry_index entries 위치, type_id) +# seed bundle stage1_tmp/task_le/structure_seed_bundle.json stage1_structure_seed_bundle.v1 +# 최종 산출 legal_effect_structures.json stage1_legal_effect_structures.v1 +# 역인덱스 by_domain_id · by_module · by_bo_id (by_claim_form 금지 — D-4 라) +# 정책 자산 Default_Agent/stage1_runtime/structure_index_policy.v1.json +# +# 2026-10-30 Part 1·2 정합 (가액금액반영후_part_3_개정전략서_v.2.md) +# L0 SG-01 사본을 봉인본과 대조 · 읽는 SG 코드를 downstream_read_sets.part3_L0 와 대조 · +# E-13 확장 키를 실행 계약과 대조 · manifest BLOCKED 는 멈추지 않고 HARD_WARNING 으로 전파 +# L2 전파된 항목이 review_queue 와 READY_WITH_REVIEW 로 옮겨진다(코드 변경 없음) +# 컴파일러 bo_absent route 는 붙이고 PART3_ROUTE_CANDIDATE_NOT_IN_BO 를 단다 · 잔여 도메인은 kind=="residual" 로 판정 +# 금액은 다루지 않는다. Part 4 가 by_bo_id 로 BO 의 value_refs 를 찾는다. +# +# 2026-10-31 Part 2 추가 개정 정합 (개정전략서_part_3_v.2.md) +# 상류 Part 2 67c26487… · runtime_manifest 3cc02470… 위에서만 돈다. 이 파일이 고치는 자산은 없다. +# L0 SG-13 사본의 비문자열 type_id 를 null 로 고쳐 Θ 밖 경로로 보내고 앞 200자를 review 의 raw_type_id 에 싣는다 · +# route 만 있고 BO 가 없는 구조를 PART3_ROUTE_CANDIDATE_NOT_IN_BO 로 표시한다 · receipt 에 raw_type_id_routes 를 남긴다 +# L0·L2 복구 안내를 Part 2 문구로 맞춘다. 서버에는 미배포 파일 전체와 runtime_manifest.json 을 함께 덮어쓴다. +# manifest 가 옛 판이면 Part 2 A0 가 PART2_RUNTIME_MANIFEST_STALE 로 멈춘다. +# Part 3 자산만 옛 판이면 L0 가 PART3_ASSET_DEPLOYMENT_INCOMPLETE 로 멈추고, 그 밖의 옛 .txt·정책은 A0·S0·Part 4 게이트가 잡는다. +# +# 2026-11-05 L1 후보 유형 추천기(JEV) 신설 (개정전략서_part_3_v2_with_part_1_2.md, YAML 한 파일 대안) +# 목적 4차 실행 BO 78건 중 15건 미부착(P3-02). worker 의 registered:false 유형 id 를 JEV choice 로 +# "독립 효과 / 선언 유형의 일부 / 표현 차이" 중 하나로 판정해, 일부·표현 차이면 선언 유형 레코드에 BO 를 붙인다(2:39pm 부터 넷째 "무관" unrelated). +# 범위 이 파일만 바꾼다. 정책·컴파일러·manifest·스키마·레지스트리·사이드카·Part 1·2·4 변경 없음, 서버 자산 재배포 불필요. +# L0·L2 코드는 바이트 그대로다. task_procedure 간선 두 곳(L0 nexts, L2 wait_until)만 바뀐다. +# JEV jev: task(SKILL.md §3.4) · model jev-1.14.0 고정(전략서 1.13.0 → SKILL 11-05 실호출 확인판) · 키는 백엔드 env JEV_API_KEY · state 는 식별자(11-05 오후부터 + 미검증 정의·BO 문맥). +# 수용 대상 T 에서 포괄 유형 general_legal_effect 를 뺀다(침묵 일반화 금지). 독립 효과는 레코드를 만들지 않고 +# PART3_PROMOTION_PROPOSED 로만 넘긴다. 수용 건은 decided_by:"recommender" SOFT 검토 + 레코드 review_required. +# 첫 실행은 그림자 실행(apply SHADOW_RUN=True: 수용·승격 비활성, 점수만 영수증 part3_recommender_receipt.json). +# 주의 이 부착 경로는 정책 structure_index_policy.v1.json 의 bo_attachment.join 서술과 다르다(판정 규칙이 봉인 자산이 아니라 YAML 코드). +# 프로브 전략서 §7 은 별도 프로브 YAML(P-1~P-4)을 먼저 돌리라 한다. 이 판은 그림자 실행을 그 프로브로 삼는다(3:30pm 부터는 실제 부착과 함께 돈다): +# P-1 jev wildcard·state_json 전달·retry/description 키·JEV_API_KEY · P-2 실패 인스턴스 뒤 capture/apply/L2 진행 · +# P-3 빈 fan-out 장벽·planner→apply 간선 · P-4 capture 의 prev 형태. 결과를 보고 capture 제거(P-4)·state 방식(P-1)을 정한다. +# SKILL.md §2.3·§3.4 규칙 9(11-05)가 P-2·P-4 를 문서로 답하지만 실측 전까지 capture 를 유지한다. +# 한계: 4차 데이터의 그림자 실행은 빈 fan-out 장벽(P-3 절반)과 실패한 jev 인스턴스(P-2)를 시험하지 못한다. +# 장벽이 멈추면 L2·Part 4 가 막히므로, 배포 전 작은 프로브(0 건 fan-out · 2 건 중 1 건 잘못된 state)를 권한다. +# 되돌릴 판은 stage_1_part_3_v.8_11_05_10_30am.yml 이다. +# +# 2026-11-05 오후 L1 glossary 신설 — JEV 입력에 "뜻"을 싣는다 (첫 실행: JEV 가 17쌍 중 16쌍을 independent_effect 로 기울임) +# 간선 L0 nexts 에 glossary 추가 · glossary 노드 신설(L0 대기) · planner wait_until 에 glossary 추가. +# L0→planner 간선은 남긴다(planner 가 prev 로 L0 반환을 받는 경로 — 오전 판과 같다). 10:30 판 대비 L0·L2 코드는 여전히 바이트 그대로다. +# Task_C_LE_L1_glossary gemini-3.8-flash · llm_reasoning low · 도구 없는 1회 호출 · seed bundle 하나만 preflight. +# 출력은 {"schema_version", "glossary": {type_id: {...}}} 봉투다(planner 는 맨 {type_id: {...}} 도 받는다). +# 선언 유형(general_legal_effect 제외)과 후보 유형마다 definition_ko(80자 이내 한 줄)·statutes(조문 0~3) 초안. +# planner prev 의 glossary 봉투를 검사(식별자 정규식 · 요청 집합 밖 제거 · 정의 길이 · 조문 개수·길이 · kind 재판정)해 +# stage1_tmp/task_le/type_glossary.json 에 쓰고, 쌍 state 에 T 의 정의·조문 · k 의 정의 · BO 문맥 +# (함께 달린 Legal_Keywords · BOType · payload 키 이름 — 식별자 정규식 통과값만) · glossary_source:"llm_unverified" 를 싣는다. +# BO 에는 요건 행 칸이 없어 payload 키 이름을 가장 가까운 추상 구조로 쓴다. 한글 키워드·payload 값·본문은 싣지 않는다. +# 생략 사람의 law.go.kr 원문 대조 · JSON 자산 봉인(이번 단계 범위 밖). 모든 정의는 verified:false 다. +# 실패 glossary 가 없거나 틀린 유형은 정의 없이 보낸다. apply 가 handoff 에 PART3_GLOSSARY_MISSING(SOFT_WARNING) 한 건을 남긴다 +# (planner 는 fan-out 부모라 handoff 를 쓰지 않는다 — handoff sha 신선도 검사와 되돌림은 apply 한 곳에 둔다). +# 영수증 part3_recommender_receipt.json 의 glossary 에 sha·미검증 항목 수·정의 없이 보낸 유형을 남긴다. +# planner timeout 120 → 300초(BO.json 읽기·정의표 쓰기가 늘었다 — fan-out 부모가 시간 초과로 죽으면 장벽이 멈춘다). +# 3:30pm 결정 ① SHADOW_RUN = False — 시작 임계값(수용 0.80·마진 0.20·승격 0.80·독립 하한 0.50)이 실제로 적용된다. +# 실행 3 데이터면 E-02 4 후보(BO 5건)가 money_claim 에 붙고 HARD 미부착 15 → 10. 정의·조문은 여전히 미검증이다. +# ② part_of 예시를 시험 후보 밖 항목(채무면제·혼동 → 금전채권의 소멸·금액. 상계는 반대채권이 필요하고 레지스트리에 별도 구조로 있어 뺐다)으로 바꿨다(예시 효과 제거). +# ③ 목표 무관 안내 — UNDECIDED 후보의 모든 쌍에서 unrelated 가 최댓값이면 SOFT PART3_RECOMMENDER_TARGET_UNRELATED +# (domain_id·candidate_type_id·decided_by·pair_scores) 한 건. HARD 미부착은 남는다. +# 정의표 고정은 추후 Liti-agent 개정으로 미룬다. 되돌릴 판은 stage_1_part_3_v.8_11_05_3_30pm.yml 이다. +# 첫 실행에서 볼 것: 붙은 BO 행에 Part 4 가 money_claim 레코드의 calculation_request_refs·domain_effects 를 복사하므로 +# 해당 행의 calculation_requests 가 청구 계산 요청을 되풀이하는지 확인한다(보존 등식은 통과한다). +# JEV unrelated 11-05 2:39pm 사용자 승인으로 넷째 선택지 unrelated("선언 유형과 법적 관계 없음 — 목표가 틀림")를 더했다. +# apply: RELATION_KEYS 4키(옛 3키 답은 형식 불일치로 답 누락 처리) · 수용은 part_of 또는 wording 이 네 확률 중 최댓값일 때만 · +# 승격 제안은 모든 쌍의 비부착 질량(independent + unrelated) ≥ INDEPENDENT_MIN 이고, 한 쌍 이상에서 +# independent ≥ 0.50(INDEPENDENT_FLOOR, 절반 이상). 모든 쌍이 "무관" 우세면 UNDECIDED(HARD 미부착을 사람에게 남긴다 — 보수적 선택). +# unrelated 설명은 "관계가 없으면 독립 구조여도 independent 대신 이것"이라고 우선순위를 적어 둘의 경계를 정했다(independent 설명은 2:25pm 그대로). +# 영수증 v2: relation_keys · pair_scores.non_attach_score · thresholds.independent_floor. 기존 임계값은 그대로이고(SHADOW_RUN 은 3:30pm 에 끔) +# INDEPENDENT_FLOOR(0.50)만 새로 생겼다(independent_min 은 이제 비부착 질량의 하한). +# 결과: 선언 목표가 모두 "무관"인 후보(X1 6종은 쌍이 하나씩)는 승격 제안에 오르지 않고 HARD 미부착으로 남는다 — +# "목표 무관" 판단은 영수증에만 남는다(handoff 에 SOFT 로 알리는 항목은 새 승인 사항 — 3:30pm 해소, 위 3:30pm 결정 ③). +# 기대값(확인 예정): X1 → unrelated · E-12 공유 유형 쌍 → independent 또는 part_of(단독소유 주장은 공유와 경합하므로 무관 아님) · +# E-12 경계 쌍 → unrelated 또는 independent · E-02 → unrelated 질량이 part_of 가 아니라 independent 에서 빠져야 한다 · E-15 → 기록만. +# 되돌릴 판은 stage_1_part_3_v.8_11_05_2_39pm.yml 이다. +# JEV criteria 11-05 2:25pm 사용자 승인으로 independent_effect(좁힘)·part_of_declared_type(넓힘) 설명 두 줄만 바꿨다. +# (2:25pm 기준) 키 3개·wording_variant·instructions·apply 는 그대로. 되돌릴 판은 stage_1_part_3_v.8_11_05_2_25pm.yml 이다. +# 효과 확인(확인 예정, 미실행): E-02 5쌍의 part_of 상승, X1·sole_ownership_assertion 은 independent 유지(2:39pm 이후 기대값은 위 JEV unrelated). +# 판정 주의 ① (3:30pm 에 예시를 바꿔 해소) part_of 예시가 E-02 시험 후보 셋(partial_payment·demand_notice·debt_acknowledgement)을 직접 부르므로 +# 규칙의 효과는 예시에 없는 due_date_modification·guarantor_procurement_promise 와 E-12·X1·E-15 로 본다. +# ② 두 선택지 모두 "defense" 를 담아 X1(통지 → 항변)·E-12(단독소유 주장 → 공유 성립)가 part_of 로 끌릴 수 있다 — +# 승자만이 아니라 2차 회차 대비 확률·confidence 를 쌍마다 비교한다. E-15(상속 지위 → 승계 항변)의 기대값은 사양에 없다. +# (2:39pm 에 "무관" 키 unrelated 를 더했다 — 위 JEV unrelated 참조. X1 은 unrelated, E-12 는 위 기대값을 본다.) +# ③ glossary 는 회차마다 다시 생성되므로 "같은 입력"이 아니다 — 비교표에 glossary_sha256(2차 3cb6348f…)을 함께 적는다. +# JEV 지시문 11-05 2pm 사용자 결정으로 recommender instructions 를 "Use only the information given in state" 로 바꿨다 +# (2pm 시점에 JEV 이후 구간에서 바뀐 유일한 줄. criteria 는 2:25pm 에 따로 바뀌었다). 되돌릴 판은 stage_1_part_3_v.8_11_05_2pm.yml 이다. +# 주의 pair_id 가 state sha 를 품으므로 이전 회차와 pair_id 가 달라진다. 임계값은 그대로다(SHADOW_RUN 은 3:30pm 에 끔). +# 효과 확인: 같은 입력으로 다시 돌려 17쌍 확률을 비교한다(partial_payment·demand_notice·debt_acknowledgement → money_claim 의 part_of 상승). +# (2:25pm criteria 개정 이후로는 위 JEV criteria 의 판정 주의 ① 을 따른다 — 3:30pm 이전에는 이 셋이 part_of 예시에 이름이 나왔다.) +# 정의는 회차마다 LLM 이 새로 쓰므로 pair_id 가 매번 바뀐다 — 비교는 pair_id 앞 d|k|T 로 맞추고 glossary_sha256 을 함께 적는다. +# 그림자 실행이어도 정의 없는 유형이 있으면 apply 가 handoff 를 다시 쓴다(PART3_GLOSSARY_MISSING). 쌍 0건·apply SKIPPED 면 남기지 않는다. +# 되돌릴 판은 stage_1_part_3_v.8_11_05_1_30pm.yml 이다. +# +# 제약 1 — v.7/Claude_YAML 의 어떤 파일도 읽지 않는다. 구 Part 3 명세에 의존하지 않는다. +# 137종 — 사건 이름·도메인 목록·유형 열거를 코드에 두지 않는다. +# 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. +# ============================================================================= +--- +Agent: + name: Liti-agent_Civil_Suit_Plaintiff_Stage_1_Part_3 + description: 민사소송 원고 송무 초지능 AI변호사 - Stage 1 Part 3 + version: v.2 + Stages: + - name: stage1_법률효과구조_생성 + description: 법률효과 구조 생성, 색인 작성 + llm_provider: openai + llm_model: gpt-4o-2024-08-06 + tools: + mcpServers: + localdocs: + type: streamable-http + url: http://mcp-localdocs:8012/mcp + description: Get the content of local documents + code-executor: + type: streamable-http + url: https://code-executor.mcp.eroomai.com/mcp + description: Run scripts of programming languages + headers: + Authorization: Bearer rR8OXqWrVZA1gFEo8oWfBkw2XgpWoGrrspw5ObsxTCM= + tasks: + - task_name: Task_C_LE_L0_structure_seed_reducer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 240 + code: |- + #!/usr/bin/env python3 + # Task_C_LE_L0_structure_seed_reducer (v1) + # 0) 배포 게이트 -> 1) 모듈 반입 -> 2) 정책 반입 -> 3) 의미 검사 둘 -> + # 4) 진입 봉인 둘 -> 5) 입력 적재 -> 6) compile_structure_seeds -> + # 7) bundle · review handoff · receipt 기록 + import contextlib + import hashlib + import io + import itertools + import json + import pathlib + import re + import sys + + import httpx + + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) — Part 2 A0 검증 완료본 복사. + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # ------------------------------------------------------------------ + TASK_NAME = "Task_C_LE_L0_structure_seed_reducer" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 재직렬화 없이 원문 그대로. 봉인·미러 해시 대조의 전제다. + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def try_read_json(name): + try: + return read_json(name) + except Exception: + return None + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + # ------------------------------------------------------------------ + # 실행 뿌리 — /tmp/s1 공유(신전략서 §4.2 도입부. 새 뿌리를 만들지 않는다). + # ------------------------------------------------------------------ + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + RT = pathlib.Path(EXECUTION_ROOT) / "_rt" + + MODULE_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "registry_loader": "Default_Agent/stage1_runtime/registry_loader.txt", + "structure_index_compiler": "Default_Agent/stage1_runtime/structure_index_compiler.txt", + } + MODULES = ["runtime_common", "schema_subset_validator", "registry_loader", + "structure_index_compiler"] + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + RUNTIME_MANIFEST_SCHEMA = "stage1_runtime_manifest.v1" + + # 정적 자산 (I-9 ~ I-14) + REGISTRY_INDEX = "Default_Agent/domains/_registry_index.json" + POLICY = "Default_Agent/stage1_runtime/structure_index_policy.v1.json" + POLICY_SCHEMA_VERSION = "stage1_structure_index_policy.v1" + ALIAS_DECLARATIONS = "Default_Agent/routing/extension_payload_key_declarations.v1.json" + SEED_SCHEMA = "Default_Agent/platform/schemas/structure_seed_bundle.schema.json" + INDEX_SCHEMA = "Default_Agent/platform/schemas/legal_effect_structures.schema.json" + SIGNAL_REGISTRY = "Default_Agent/signals/signal_registry.v2.json" + EXECUTION_CONTRACT = "Default_Agent/contracts/signals/s5_execution_contract.v2.json" + + # 사건 산출물 (I-1 ~ I-8) — Part 1·2 가 낸 것만 읽는다. + SIGNAL_MANIFEST = "signals/signal_manifest.json" + SG13_PATH = "signals/legal_effect_routes.json" + SG05_PATH = "signals/legal_relation_lifecycle_signals.json" + SG11_PATH = "signals/calculation_requirements.json" + SG02_PATH = "signals/procedural_posture_relief_signals.json" + SG07_PATH = "signals/asset_right_state_signals.json" + SG01_SEALED_PATH = "signals/domain_activation_manifest.json" + # 읽는 SG 코드 표. 경로 상수는 그대로 두고 manifest·registry 와 대조만 한다. + PART3_SIGNAL_PATHS = {"SG-02": SG02_PATH, "SG-05": SG05_PATH, "SG-07": SG07_PATH, + "SG-11": SG11_PATH, "SG-13": SG13_PATH} + MANIFEST_BLOCKED_CODE = "PART3_SIGNAL_MANIFEST_BLOCKED" + DOMAIN_SIGNAL_DIR = "signals/domain_signals" + ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" + BO_PATH = "BO.json" + SLICE_DIR = "runtime/domain_slices" + + # 산출 + BUNDLE_PATH = "stage1_tmp/task_le/structure_seed_bundle.json" + HANDOFF_PATH = "quality_gates/stage1_part3_review_handoff.json" + RECEIPT_PATH = "validation_assets/routing/part3_receipt.json" + + # F-2 상당 — 배포 게이트가 한 벌로 검사하는 필수 자산 10 리터럴(신전략서 §5.5). + # 사이드카 50 은 여기 넣지 않는다 — expected_runnable 도메인 것만 읽는 시점에 + # _verify_asset 으로 지킨다. domains/_registry_index.json 은 매니페스트 등재 + # 대상이 아니므로 SG-01 봉인이 지킨다(I-11 · §1.10 규율). + PART3_REQUIRED_ASSETS = ( + SEED_SCHEMA, + INDEX_SCHEMA, + POLICY, + ALIAS_DECLARATIONS, + SIGNAL_REGISTRY, + EXECUTION_CONTRACT, + "Default_Agent/stage1_runtime/structure_index_compiler.txt", + "Default_Agent/stage1_runtime/runtime_common.txt", + "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "Default_Agent/stage1_runtime/registry_loader.txt", + ) + PART3_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + + TRANSACTION_ID_RE = re.compile(r"^S5TX-[a-f0-9]{20}$") + + ERRORS = [] + WARNINGS = [] + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + # ------------------------------------------------------------------ + # 0) 배포 게이트 — 등재·sha256·가독을 한 벌로. 첫 실패에서 멈추지 않고 모은다. + # ------------------------------------------------------------------ + def assert_deployment(): + manifest = json.loads(read_raw(RUNTIME_MANIFEST)) + if manifest.get("schema_version") != RUNTIME_MANIFEST_SCHEMA: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_RUNTIME_MANIFEST_INVALID", "detail": "schema_version", + "expected": RUNTIME_MANIFEST_SCHEMA, "actual": manifest.get("schema_version"), + }, ensure_ascii=False)) + expected = {row["path"]: row["sha256"] + for row in (manifest.get("entries") or []) if isinstance(row, dict)} + unregistered, mismatch, unreadable = [], [], [] + for logical in sorted(set(list(MODULE_MIRRORS.values()) + list(PART3_REQUIRED_ASSETS))): + rel = logical[len(ASSET_ROOT):] + want = expected.get(rel) + if want is None: + unregistered.append(rel) + try: + body = read_raw(logical) + except Exception: + unreadable.append(rel) + continue + if want is not None and want != sha_text(body): + mismatch.append({"path": rel, "expected": want, "actual": sha_text(body)}) + if unregistered or mismatch or unreadable: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_ASSET_DEPLOYMENT_INCOMPLETE", + "message": "배포 원본에 Part 3 자산이 한 벌로 반영되지 않았다.", + "unregistered": unregistered, "hash_mismatch": mismatch, + "unreadable": unreadable, "remedy": PART3_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + return manifest + + + _MANIFEST_MAP = None + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART3_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART3_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical): + """원문을 돌려준다. 등재·해시 대조를 통과해야만 소비된다.""" + body = read_raw(logical) + want = _manifest_map().get(logical[len(ASSET_ROOT):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != sha_text(body): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + # ------------------------------------------------------------------ + # 1) 모듈 반입 — R-1~R-5. + # ------------------------------------------------------------------ + def materialize_modules(): + RT.mkdir(parents=True, exist_ok=True) + expected = _manifest_map() + staged = [] + for name in MODULES: + logical = MODULE_MIRRORS[name] + raw = read_raw(logical).encode("utf-8") + want = expected.get(logical[len(ASSET_ROOT):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (RT / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(RT) not in sys.path: + sys.path.insert(0, str(RT)) + return staged + + + # ------------------------------------------------------------------ + # 3) 의미 검사 — 장부 검사만으로는 닫히지 않는다(Part 2 R-b/R-g2 교훈). + # 각 검사는 자기가 쓰는 산출물의 스키마만 본다. by_module 은 L2 몫이다. + # ------------------------------------------------------------------ + def assert_seed_schema_capability(seed_schema): + bundle_props = (((seed_schema.get("properties") or {}) + .get("structure_seed_bundle") or {}).get("properties") or {}) + record_props = ((((bundle_props.get("structure_records") or {}) + .get("items") or {}).get("properties") or {})) + missing = [] + if "theta" not in bundle_props: + missing.append("theta") + if "admission_policy" not in record_props: + missing.append("structure_records[].admission_policy") + if missing: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_STRUCTURE_SCHEMA_STALE", + "message": "seed 스키마가 Part 3 계약 필드를 모른다. 배포 원본의 스키마가 개정 전 판본이다.", + "missing": missing, "remedy": PART3_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + def assert_compiler_capability(result): + bundle = (result or {}).get("structure_seed_bundle") or {} + records = bundle.get("structure_records") + bad = ("theta" not in bundle + or not isinstance(records, list) + or any("order_key" not in record for record in records + if isinstance(record, dict))) + if bad: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_COMPILER_STALE", + "message": "컴파일러 산출에 theta·order_key 가 실려 나오지 않는다. " + "배포 원본의 structure_index_compiler 가 개정 전 판본이다.", + "remedy": PART3_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + # ------------------------------------------------------------------ + # 4) 진입 봉인 둘 (신전략서 §4.2-5) + # ------------------------------------------------------------------ + def verify_signal_seal(): + doc = read_json(SIGNAL_MANIFEST) + root = doc.get("signal_manifest", doc) if isinstance(doc, dict) else {} + transaction_id = root.get("transaction_id") + if not isinstance(transaction_id, str) or not TRANSACTION_ID_RE.match(transaction_id): + raise RuntimeError(json.dumps({ + "reason_code": "PART3_SIGNAL_SEAL_FAILED", "detail": "transaction_id", + "actual": transaction_id}, ensure_ascii=False)) + checked = 0 + for row in root.get("files") or []: + if not isinstance(row, dict): + continue + # files[].path 에는 signals/ 접두사가 없다(I-1 주의). 붙여서 대조한다. + rel = str(row.get("path") or "") + actual = sha_text(read_raw("signals/" + rel)) + if actual != row.get("file_sha256"): + raise RuntimeError(json.dumps({ + "reason_code": "PART3_SIGNAL_SEAL_FAILED", "detail": "file_sha256", + "path": rel, "expected": row.get("file_sha256"), "actual": actual, + }, ensure_ascii=False)) + checked += 1 + return {"transaction_id": transaction_id, "files_checked": checked, "root": root} + + + def verify_read_set(manifest_root): + """읽는 SG 코드가 manifest 의 part3_L0 와 같고, 파일이 registry 선언과 같아야 한다.""" + declared = sorted((manifest_root.get("downstream_read_sets") or {}).get("part3_L0") or []) + registry = json.loads(_verify_asset(SIGNAL_REGISTRY)) + files = {row.get("signal_id"): row.get("file") + for row in (registry.get("entries") or []) if isinstance(row, dict)} + wrong_file = sorted(code for code, path in PART3_SIGNAL_PATHS.items() + if "signals/%s" % files.get(code) != path) + if declared != sorted(PART3_SIGNAL_PATHS) or wrong_file: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_READ_SET_MISMATCH", "declared": declared, + "read": sorted(PART3_SIGNAL_PATHS), "wrong_file": wrong_file}, ensure_ascii=False)) + return declared + + + def verify_sealed_activation(activation_doc): + # routing 사본을 계속 읽는다(sha 계보가 Part 2·4 와 같다). 내용만 봉인본과 대조한다. + if read_json(SG01_SEALED_PATH) != activation_doc: + raise RuntimeError(json.dumps({"reason_code": "PART3_SG01_COPY_MISMATCH"}, ensure_ascii=False)) + + + def verify_extension_key(policy): + rule = policy.get("extension_key_rule") or {} + contract = json.loads(_verify_asset(EXECUTION_CONTRACT)) + declared = {row.get("domain_id"): row.get("extension_key") + for row in (contract.get("e13_extension_domains") or []) if isinstance(row, dict)} + if not rule.get("extension_key") or declared.get(rule.get("domain_id")) != rule.get("extension_key"): + raise RuntimeError(json.dumps({ + "reason_code": "PART3_POLICY_INVALID", "detail": "extension_key_rule", + "policy": rule.get("extension_key"), "contract": declared.get(rule.get("domain_id"))}, + ensure_ascii=False)) + + + def verify_registry_index_seal(activation_root, index_raw): + declared = activation_root.get("registry_index_sha256") + actual = sha_text(index_raw) + if declared != actual: + # 전순서 둘째 키가 이 색인의 배열 위치에 걸려 있다. 매니페스트 등재 대상이 + # 아니므로 이 봉인만이 색인 교체를 잡는다(L-d2). + raise RuntimeError(json.dumps({ + "reason_code": "PART3_REGISTRY_INDEX_SEAL_FAILED", + "declared": declared, "actual": actual}, ensure_ascii=False)) + return actual + + + def normalize_route_fields(rows): + # S0 는 효과 행을 worker 원본으로 싣는다. 닫힌 스키마가 받지 못하는 type_id 를 이 파싱 사본에서만 고친다. + # null 로 바꿔 Θ 밖 경로로 보내고, 앞 200자는 그 review 항목의 raw_type_id 에 싣는다. + # 봉인된 SG-13 파일과 L2 의 route 총수는 그대로다. 온전한 원값은 SG-13 에 남는다. + raw_type_ids = {} + for row in rows: + details = row.get("details") + type_id = details.get("type_id") if isinstance(details, dict) else None + if (row.get("record_type") == "legal_effect_route" and type_id is not None + and not isinstance(type_id, str)): + raw_type_ids[str(row.get("signal_id"))] = json.dumps( + type_id, ensure_ascii=False, sort_keys=True)[:200] + details["type_id"] = None + return raw_type_ids + + + def mark_route_gaps(bundle, review_items, review_code): + # 표시만 한다. 부착과 등식은 바꾸지 않는다. + # route 만 있고 BO 가 없는 구조다. registered 이상으로 BO 키워드에서 유형이 빠졌거나, + # 비병합 BO 가 자기 도메인이 선언하지 않은 유형이라 구조에 닿지 못한 경우다. + for record in bundle.get("structure_records") or []: + if not record.get("routes") or record.get("source_bo_ids") or review_code in record["review_codes"]: + continue + record["review_codes"].append(review_code) + record["review_codes"].sort() + record["review_required"] = True + review_items.append({"review_code": review_code, "severity": "SOFT_WARNING", + "domain_id": record.get("domain_id"), "type_id": record.get("type_id"), + "detail": "structure_routes_without_bo"}) + + + def main(): + gate_manifest = assert_deployment() + staged = materialize_modules() + import structure_index_compiler + + # 2) 정책 반입 — 판본 불일치는 PART3_POLICY_INVALID. + policy = json.loads(_verify_asset(POLICY)) + if policy.get("schema_version") != POLICY_SCHEMA_VERSION: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_POLICY_INVALID", + "expected": POLICY_SCHEMA_VERSION, + "actual": policy.get("schema_version")}, ensure_ascii=False)) + + # 3) 의미 검사 (입력 쪽) + seed_schema = json.loads(_verify_asset(SEED_SCHEMA)) + assert_seed_schema_capability(seed_schema) + + # 4) 진입 봉인 둘 + seal = verify_signal_seal() + read_set = verify_read_set(seal["root"]) + verify_extension_key(policy) + activation_doc = read_json(ACTIVATION_MANIFEST) + verify_sealed_activation(activation_doc) + activation_root = activation_doc.get("domain_activation_manifest", activation_doc) + index_raw = read_raw(REGISTRY_INDEX) + registry_index_sha = verify_registry_index_seal(activation_root, index_raw) + registry_index = json.loads(index_raw) + index_root = registry_index.get("domain_registry_index", registry_index) + + expected_runnable = [d for d in (activation_root.get("expected_runnable_domain_ids") or []) + if isinstance(d, str)] + + # 5) 입력 적재 + # I-9 domain_config — 무결성은 SG-01 봉인 -> _registry_index -> config_sha256 사슬. + config_sha = {row.get("domain_id"): row.get("config_sha256") + for row in (index_root.get("entries") or []) if isinstance(row, dict)} + domain_configs = {} + domain_sidecars = {} + for domain_id in expected_runnable: + raw = read_raw("Default_Agent/domains/%s/domain_config.json" % domain_id) + if config_sha.get(domain_id) and sha_text(raw) != config_sha[domain_id]: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_REGISTRY_INDEX_SEAL_FAILED", + "detail": "config_sha256", "domain_id": domain_id}, ensure_ascii=False)) + config = json.loads(raw) + domain_configs[domain_id] = config + config_root = config.get("domain_config", config) + declared = [row for row in (config_root.get("structure_types") or []) + if isinstance(row, dict)] + if declared: + # 사이드카 부재 규칙(§5.5) — 선언 있는 도메인의 부재·미등재는 경성 실패. + domain_sidecars[domain_id] = { + "structure_types": json.loads(_verify_asset( + "Default_Agent/domains/%s/structure_types.json" % domain_id)), + "module_role_projection": json.loads(_verify_asset( + "Default_Agent/domains/%s/module_role_projection.json" % domain_id)), + } + + alias_declarations = json.loads(_verify_asset(ALIAS_DECLARATIONS)) + + def records_of(doc): + if not isinstance(doc, dict): + return [] + return [row for row in (doc.get("records") or []) if isinstance(row, dict)] + + # 경로 상수를 read_json 에 직접 넘긴다 — 선언표 검사기(U4)가 읽기를 코드에서 + # 확인할 수 있는 형태다. 간접 호출로 감싸면 소비 선언이 실측 불가가 된다. + sg13_records = records_of(read_json(SG13_PATH)) + raw_type_ids = normalize_route_fields(sg13_records) + sg05_records = records_of(read_json(SG05_PATH)) + sg11_records = records_of(read_json(SG11_PATH)) + # 읽되 비어 있음을 정상 처리(§3) — 조인 코드를 두지 않고 형식화된 사실로 남긴다. + sg02_rows = records_of(read_json(SG02_PATH)) + sg07_rows = records_of(read_json(SG07_PATH)) + empty_read_set = [ + {"signal_id": "SG-02", "transform": "passthrough", "producer_count": 0, + "record_count": len(sg02_rows), + "reason": "closed schema declares no claim-form vocabulary"}, + {"signal_id": "SG-07", "transform": "passthrough", "producer_count": 0, + "record_count": len(sg07_rows), + "reason": "closed schema declares no claim-form vocabulary"}, + ] + + domain_envelopes = {} + for domain_id in expected_runnable: + doc = try_read_json("%s/%s.json" % (DOMAIN_SIGNAL_DIR, domain_id)) + if doc is not None: + domain_envelopes[domain_id] = doc + + bo_doc = try_read_json(BO_PATH) + bo_records = bo_doc if isinstance(bo_doc, list) else [] + bo_raw = read_raw(BO_PATH) if bo_doc is not None else "" + + slice_documents = {} + for domain_id in expected_runnable: + doc = try_read_json("%s/%s.json" % (SLICE_DIR, domain_id)) + if doc is not None: + slice_documents[domain_id] = doc + + # 6) 모듈 호출 — 판정 규칙을 이 파일에 쓰지 않는다. + try: + result = structure_index_compiler.compile_structure_seeds( + activation_doc, registry_index, domain_configs, domain_sidecars, + policy, alias_declarations, sg13_records, sg05_records, sg11_records, + domain_envelopes, bo_records, slice_documents) + except TypeError as exc: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_COMPILER_STALE", "detail": "signature_mismatch", + "signature_error": str(exc)[:200], + "remedy": PART3_DEPLOYMENT_REMEDY}, ensure_ascii=False)) + assert_compiler_capability(result) + + bundle = result["structure_seed_bundle"] + review_items = result["review_items"] + for item in review_items: + if str(item.get("signal_id")) in raw_type_ids: + item["raw_type_id"] = raw_type_ids[str(item.get("signal_id"))] + mark_route_gaps(bundle, review_items, structure_index_compiler.REVIEW_ROUTE_NO_BO) + if review_items: + bundle["status"] = "READY_WITH_REVIEW" + audit = result["audit"] + # 진입 봉인의 거래 식별자를 bundle 에 부착한다 — L2 는 signal_manifest 를 + # 다시 읽지 않고(§4.3 입력 계약 밖) 이 값을 승계한다. + bundle["signal_manifest_transaction_id"] = seal["transaction_id"] + # BLOCKED 는 요건 결손을 뜻한다. 멈추지 않고 표시한다. 항목에 status·blocked 키를 쓰지 않는다(S2_00 이 멈춘다). + manifest_status = seal["root"].get("status") + if manifest_status == "BLOCKED": + review_items.append({"review_code": MANIFEST_BLOCKED_CODE, "severity": "HARD_WARNING", + "signal_manifest_transaction_id": seal["transaction_id"]}) + bundle["status"] = "READY_WITH_REVIEW" + + # 자기 산출을 닫힌 스키마로 검증한다. + import schema_subset_validator + schema_errors = schema_subset_validator.validate( + {"structure_seed_bundle": bundle}, seed_schema) + if schema_errors: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_FINAL_SCHEMA_VALIDATION_FAILED", + "stage": "L0", "errors": schema_errors[:10]}, ensure_ascii=False)) + + # 7) 기록 — bundle · handoff(OPEN) · receipt(실측값. 상수 PASS 금지). + write_doc(BUNDLE_PATH, canonical({"structure_seed_bundle": bundle})) + write_doc(HANDOFF_PATH, canonical({"stage1_part3_review_handoff": { + "schema_version": "stage1_part3_review_handoff.v1", + "status": "OPEN", + "review_items": review_items, + "counts": {"review_items": len(review_items)}, + "created_by": TASK_NAME, + }})) + order_table = ["%s|%s|%s|%s|%s" % ( + record.get("priority_rank"), record.get("domain_id"), + record.get("type_id"), record.get("module"), + record.get("admission_policy")) + for record in bundle.get("structure_records") or []] + write_doc(RECEIPT_PATH, canonical({ + "schema_version": "stage1_part3_receipt.v1", + "stage": "P3-L0", + "deployment_gate": { + "checked_count": len(set(list(MODULE_MIRRORS.values()) + + list(PART3_REQUIRED_ASSETS))), + "runtime_manifest_sha256": sha_text(read_raw(RUNTIME_MANIFEST)), + "runtime_artifact_count": gate_manifest.get("runtime_artifact_count"), + "schema_capability_checked": ["theta", "structure_records[].admission_policy"], + "compiler_output_checked": ["theta", "structure_records[].order_key"], + "policy_schema_version": policy.get("schema_version"), + "note": "무엇을 봤는지 적는다. 상수 PASS 는 증거가 아니다.", + }, + "entry_seals": { + "signal_manifest_transaction_id": seal["transaction_id"], + "signal_files_checked": seal["files_checked"], + "signal_manifest_status": manifest_status, + "read_set_checked": read_set, + "registry_index_sha256": registry_index_sha, + "config_sha256_chain_checked": len(domain_configs), + }, + "join_counts": bundle.get("counts"), + "empty_read_set_signals": empty_read_set, + "sidecar_dialects": audit.get("sidecar_dialects"), + "unlinked_sg11": audit.get("unlinked_sg11"), + "dangling_calculation_refs": audit.get("dangling_calculation_refs"), + "input_gaps": audit.get("input_gaps"), + "raw_type_id_routes": sorted(raw_type_ids), + "bo_input": {"sha256": sha_text(bo_raw) if bo_raw else None, + "record_count": len(bo_records), + "note": "BO.json 은 무봉인 입력이다 — signal 5종은 I-1 봉인, " + "registry 는 SG-01 봉인이 지키는 비대칭을 관찰로 남긴다."}, + "resolved_order_table": order_table, + "created_by": TASK_NAME, + })) + + return {"status": bundle.get("status"), + "modules": staged, + "expected_runnable_domain_ids": expected_runnable, + "theta_count": len(bundle.get("theta") or []), + "structure_record_count": len(bundle.get("structure_records") or []), + "review_item_count": len(review_items), + "counts": bundle.get("counts"), + "errors": ERRORS, "warnings": WARNINGS} + + + _sink = io.StringIO() + with contextlib.redirect_stdout(_sink): + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + # L1 glossary (2026-11-05 오후) — JEV 판정 직전, 선언 유형·후보 유형마다 법적 효과 정의 한 줄과 근거 조문 초안을 만든다. + # 도구 없는 1회 호출. 읽는 것은 preflight 로 실린 seed bundle 하나뿐이다(식별자·참조 id 만 있고 사건 서술이 없다). + # 결과는 llm_result_envelope 봉투로 Task_C_LE_L1_candidate_planner 가 받아 형식 검사 후 type_glossary.json 에 쓴다. + # 사람의 law.go.kr 원문 대조·JSON 자산 봉인은 이번 단계에서 생략한다 — 모든 항목이 verified:false 이고 + # JEV state 에는 glossary_source:"llm_unverified" 가 붙는다. 조문 오인용이 판정에 섞일 수 있으므로 + # 이 판의 점수는 임계값 보정 근거로만 쓰고 수용·승격을 켜는 근거로 쓰지 않는다(SHADOW_RUN 유지). + # 3:30pm 사용자 결정으로 SHADOW_RUN 을 껐다 — 미검증 정의가 실린 판정으로 BO 가 붙는다(수용 건은 SOFT 검토 항목이 남는다). + # 이 task 가 실패해도 planner 는 돈다(백엔드는 실패한 task 뒤에도 하류를 돌린다 — Part 2 F0 실패 뒤 S0 실행 선례) — 정의 없이 식별자만 보낸다. + # 출력 상한 32000 — 대상 약 50개 × 한글 한 줄. Gemini 는 사고 토큰을 따로 세므로 low 에서 비용이 늘지 않는다. + # 모델 id·허용값은 SKILL.md §3.1(gemini-3.8-flash: low|medium|high). 사고 수준은 llm_reasoning 한 키로만 준다. + - task_name: Task_C_LE_L1_glossary + description: 선언 유형·후보 유형의 법적 효과 정의 한 줄과 근거 조문 초안(미검증)을 JSON 으로 낸다 + llm_provider: google + llm_model: gemini-3.8-flash + llm_reasoning: low + llm_token_limit: 32000 + llm_result_envelope: true + max_iterations: 1 + expose_tools: false + use_tools: + - localdocs + preflight: true + preflight_files: + - stage1_tmp/task_le/structure_seed_bundle.json + prompts: + - role: system + content: |- + + 당신은 한국 민사법 용어 사전 편집자다. 법률효과 유형 식별자마다 그 법률효과가 무엇인지 일반적인 정의 한 문장과 + 근거 조문 초안을 쓴다. 사건의 사실관계는 보지도 쓰지도 않는다. 유형 사이의 관계(포함·동의어·독립)는 판정하지 않는다 — + 그 판정은 다음 단계의 별도 모델이 한다. + + + JSON 객체 하나만 출력한다. 앞뒤 설명·마크다운 코드펜스를 쓰지 않는다. 도구를 호출하지 않는다. + {"schema_version": "stage1_part3_type_glossary.v1", + "glossary": {"": {"kind": "declared 또는 candidate", + "definition_ko": "<한 문장, 60자 이내>", + "statutes": ["<법령명> 제조"]}}} + + - role: user + content: |- + + preflight 로 실린 stage1_tmp/task_le/structure_seed_bundle.json 하나만 읽는다(structure_seed_bundle 객체). + + + 1. declared — structure_records[] 의 type_id 전부. 단 general_legal_effect 는 뺀다. + 같은 type_id 가 여러 도메인에 있어도 한 번만 쓴다. 그 레코드의 module · role_projection · domain_id 는 뜻을 좁히는 참고로만 쓴다. + 2. candidate — unattached_routes[] 의 type_id 중 영문 소문자·숫자·밑줄 식별자이면서 declared 에 없는 것 전부. 한 번씩만 쓴다. + 목록 밖의 type_id 를 만들지 않는다. 대상을 빠뜨리지 않는다. + + + - definition_ko: 한국 민사·상사법에서 그 식별자가 가리키는 법률효과(또는 법률요건 사실)를 일반론으로 정의한 한 문장. 60자 이내(80자를 넘으면 버려진다). + candidate 는 식별자 이름이 가리키는 법률 개념을 정의한다(예: *_notice_lifecycle 은 해당 통지·최고의 발송부터 도달·효력까지). + - 당사자 이름·금액·날짜·증거 번호·사건 사실을 쓰지 않는다. 값 안에 큰따옴표와 역슬래시를 쓰지 않는다. + - statutes: 근거 조문 0~3개. "민법 제390조", "민법 제168조 제3호"처럼 법령명과 조 번호로 쓴다. 판례는 쓰지 않는다. + 한 항목에 조문 하나만 쓴다. 조문 제목·괄호·「」·본문/단서·여러 조 묶음(예: 제168조 제1호, 제174조)을 쓰지 않는다. + 조 번호를 확신하지 못하면 그 조문을 빼고, 하나도 확신하지 못하면 빈 배열을 쓴다. + - kind: declared 대상은 "declared", candidate 대상은 "candidate". + + + - task_name: Task_C_LE_L1_candidate_planner + description: glossary 를 검사·기록하고, 미부착 BO 를 만든 후보 유형과 선언 유형의 쌍(정의·BO 문맥 포함 state)을 계획해 jev dynamic_fanout 을 낸다. raise 하지 않는다. + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 300 + code: |- + #!/usr/bin/env python3 + # Task_C_LE_L1_candidate_planner (2026-11-05, 개정전략서_part_3_v2_with_part_1_2.md §2.1·§2.3·§3.1; 11-05 오후 glossary 개정) + # fan-out 부모다. 어떤 실패도 raise 하지 않는다 — 부모가 raise 하면 wildcard 확장이 없어 + # all Task_C_LE_L1_capture_* 가 영원히 기다린다(Part 2 load_fanout 과 같은 규칙). 실패하면 빈 dynamic_fanout 과 + # planned:false 요청 파일로 끝낸다. when 을 쓰지 않는다(S2_10 V0: when-SKIPPED 부모 뒤 all 대기가 멈췄다). + # prev(L0 반환)가 READY 계열이고 structure_record_count 가 번들의 레코드 수와 같을 때만 계획한다 + # (지난 회차 번들을 외부 JEV 로 보내지 않는다). 모듈·정적 자산을 읽지 않는다. + # 후보 (d, k): k 가 type_id 패턴에 맞고 · 번들 unattached_routes[].type_id 에 있고 · + # handoff PART3_BO_UNATTACHED 항목의 legal_keywords 에 있으며 d 가 그 항목의 resolved_domains 에 있다. + # 쌍 (d, k, T): T 는 도메인 d 의 선언 유형 중 EXCLUDED_TARGET_TYPE_IDS(포괄 유형) 밖. 쌍마다 jev 요청 1건. + # glossary(11-05 오후): prev 의 Task_C_LE_L1_glossary 응답 봉투에서 유형 정의표를 꺼내 형식을 검사하고 + # type_glossary.json 에 쓴 뒤, 쌍 state 에 T 의 정의·조문과 k 의 정의를 싣는다. 사람 대조·봉인 전이므로 + # 모든 항목은 verified:false 다. state 의 glossary_source 는 정의가 하나라도 실리면 "llm_unverified", 없으면 "none". + # glossary 가 없거나 형식이 틀린 유형은 정의 없이(식별자만) 보내고, 그 목록을 요청 파일 glossary 에 남긴다 — + # handoff 의 PART3_GLOSSARY_MISSING(SOFT) 한 건은 apply 가 쓴다(fan-out 부모는 handoff 를 쓰지 않는다). + # 조문은 "법령명 제N조(의N)( 제N항)( 제N호)" 형식만 남긴다. 표는 {"glossary": {...}} 봉투와 맨 {type_id: {...}} 둘 다 받는다. + # state 의 BO 문맥은 식별자 정규식을 통과한 값만 싣는다 — 함께 달린 Legal_Keywords · BOType · + # extensions.domain_payload.payload 의 키 이름(BO 에 요건 행 칸이 없어 가장 가까운 추상 구조다). + # BO 본문·당사자·금액·날짜·payload 값·한글 키워드는 싣지 않는다(외부 JEV 로 사건 서술을 보내지 않는다). + import hashlib + import itertools + import json + import re + + import httpx + + TASK_NAME = "Task_C_LE_L1_candidate_planner" + L0_TASK = "Task_C_LE_L0_structure_seed_reducer" + GLOSSARY_TASK = "Task_C_LE_L1_glossary" + BUNDLE_PATH = "stage1_tmp/task_le/structure_seed_bundle.json" + HANDOFF_PATH = "quality_gates/stage1_part3_review_handoff.json" + BO_PATH = "BO.json" + REQUEST_PATH = "stage1_tmp/task_le/recommender_requests.json" + GLOSSARY_PATH = "stage1_tmp/task_le/type_glossary.json" + ANSWER_DIR = "stage1_tmp/task_le/recommender_answers" + REQUEST_SCHEMA = "stage1_part3_recommender_requests.v1" + GLOSSARY_SCHEMA = "stage1_part3_type_glossary.v1" + GLOSSARY_SOURCE = "llm_unverified" + UNATTACHED_CODE = "PART3_BO_UNATTACHED" + GLOSSARY_MISSING_CODE = "PART3_GLOSSARY_MISSING" + TYPE_ID_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,127}$") + EXCLUDED_TARGET_TYPE_IDS = ("general_legal_effect",) + COOCCUR_MAX = 20 + PAYLOAD_KEY_MAX = 20 + # 조문 정규화: 끝의 괄호 제목 · 「」 · 본문/단서/전단/후단을 떼고 나서 형식을 본다. + STATUTE_TRIM = re.compile(r"\s*(\([^)]*\)|본문|단서|전단|후단)\s*$") + STATUTE_PATTERN = re.compile(r"^[가-힣A-Za-z·ㆍ ]{2,30} 제\d+조(의\d+)?( 제\d+항)?( 제\d+호)?$") + DEFINITION_MAX_CHARS = 80 + STATUTE_MAX_ITEMS = 3 + STATUTE_MAX_CHARS = 40 + RESULT = {"status": "NOT_PLANNED", "dynamic_fanout": [], "count": 0, "reason": None} + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) — L2 사본에 Part 2 capture 의 write_doc(오류 검사)를 붙였다. + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # ------------------------------------------------------------------ + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def parse_json_text(raw): + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def read_json(name): + return parse_json_text(read_raw(name)) + + + def write_doc(path, content): + # localdocs 는 실패도 정상 응답 본문의 "Error: ..." 로 돌려준다(Part 2 capture 와 같은 검사). + p = _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if text.startswith("Error"): + raise RuntimeError("WRITE_FAILED:%s:%s" % (path, text[:200])) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + + def is_type_id(value): + return isinstance(value, str) and TYPE_ID_PATTERN.fullmatch(value) is not None + + + def load_prev(raw): + # prev 전체를 한 번만 파싱한다. 반환 (dict, 오류 코드|None). 치환되지 않은 템플릿이면 빈 dict(오류 아님 — L0_NOT_READY 로 끝난다). + if raw.strip().startswith("{" + "{"): + return {}, None + try: + prev = json.loads(raw) + except Exception as exc: + return {}, "PREV_UNPARSEABLE:%s" % str(exc)[:200] + return (prev, None) if isinstance(prev, dict) else ({}, "PREV_NOT_OBJECT") + + + def previous_state(prev, parent): + # Part 2 load_fanout 과 같은 관용. + row = prev.get(parent, {}) + if isinstance(row, str): + try: + row = json.loads(row) + except Exception: + return {} + if isinstance(row, dict) and "status" not in row and isinstance(row.get("json_output"), dict): + row = row["json_output"] + return row if isinstance(row, dict) else {} + + + def glossary_object(prev): + # Task_C_LE_L1_glossary 응답 봉투(llm_result_envelope)에서 JSON 객체를 꺼낸다. 반환 (객체 | None, 상태 코드). + # Part 2 Task_C_B_domain_capture 의 parse_model 과 같은 규칙: 완료 상태만 · json_output 대신 본문 전체. + env = prev.get(GLOSSARY_TASK) + if env is None: + return None, "GLOSSARY_TASK_OUTPUT_MISSING" + if isinstance(env, str): + try: + env = json.loads(env) + except Exception: + env = {"content": env, "status": "completed"} + if not isinstance(env, dict): + return None, "GLOSSARY_ENVELOPE_INVALID" + status = str(env.get("status", "completed")).lower() + finish = str(env.get("finish_reason") or "").lower() + if status not in ("completed", "success", "ok", "stop"): + return None, "GLOSSARY_MODEL_INCOMPLETE:%s" % status + if finish in ("length", "max_tokens", "max_output_tokens"): + return None, "GLOSSARY_MODEL_INCOMPLETE:%s" % finish + raw = env.get("content") + if raw is None and "glossary" in env: + raw = env + if (raw is None or (isinstance(raw, str) and not raw.strip())) and isinstance(env.get("json_output"), dict): + raw = env["json_output"] # 본문이 비고 봉투가 객체를 뽑아 둔 경우 + if isinstance(raw, dict): + return raw, "OK" + if not isinstance(raw, str) or not raw.strip(): + return None, "GLOSSARY_OUTPUT_MISSING" + text = raw.strip() + if not text.startswith("{"): + match = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", text) + if match: + text = match.group(1) + elif "{" in text: + text = text[text.find("{"):] # 펜스 없이 앞에 설명이 붙은 경우 + else: + return None, "GLOSSARY_NOT_JSON_OBJECT" + try: + obj, _ = json.JSONDecoder(strict=False).raw_decode(text) + except Exception: + return None, "GLOSSARY_PARSE_FAILED" + if not isinstance(obj, dict): + return None, "GLOSSARY_NOT_JSON_OBJECT" + return obj, "OK" + + + def requested_type_ids(bundle): + # glossary 프롬프트가 요청한 집합과 같은 규칙. declared ∩ candidate 는 비어야 한다(k 는 Θ 밖). + declared = {r.get("type_id") for r in (bundle.get("structure_records") or []) + if isinstance(r, dict) and is_type_id(r.get("type_id")) + and r.get("type_id") not in EXCLUDED_TARGET_TYPE_IDS} + candidate = {row.get("type_id") for row in (bundle.get("unattached_routes") or []) + if isinstance(row, dict) and is_type_id(row.get("type_id"))} - declared + return declared, candidate + + + def clean_glossary(obj, declared, candidate): + # 순수 함수. 형식 검사를 통과한 항목만 남긴다. 반환 (entries, dropped). + # kind 는 모델 값을 믿지 않고 요청 집합에서 다시 정한다(어긋나면 dropped 에 남기지 않고 kind_corrected 로 센다). + table = obj.get("glossary") if isinstance(obj, dict) else None + if table is None and isinstance(obj, dict) and obj and all( + is_type_id(k) and isinstance(v, dict) for k, v in obj.items()): + table = obj # 봉투 없이 맨 {type_id: {...}} 로 낸 경우 + entries = {} + dropped = [] + if not isinstance(table, dict): + return entries, [{"type_id": None, "reason": "GLOSSARY_TABLE_MISSING"}] + for type_id in sorted(table, key=str): + row = table[type_id] + if not is_type_id(type_id): + dropped.append({"type_id": str(type_id)[:128], "reason": "TYPE_ID_PATTERN"}) + continue + if type_id not in declared and type_id not in candidate: + dropped.append({"type_id": type_id, "reason": "NOT_REQUESTED"}) + continue + if not isinstance(row, dict): + dropped.append({"type_id": type_id, "reason": "ROW_NOT_OBJECT"}) + continue + definition = row.get("definition_ko") + definition = " ".join(definition.split()) if isinstance(definition, str) else "" + if not definition or len(definition) > DEFINITION_MAX_CHARS: + dropped.append({"type_id": type_id, "reason": "DEFINITION_LENGTH"}) + continue + statutes = [] + statutes_dropped = 0 + for statute in row.get("statutes") if isinstance(row.get("statutes"), list) else []: + statute = " ".join(statute.split()) if isinstance(statute, str) else "" + statute = statute.replace("「", "").replace("」", "") + while STATUTE_TRIM.search(statute): + statute = STATUTE_TRIM.sub("", statute) + if (len(statute) <= STATUTE_MAX_CHARS and STATUTE_PATTERN.fullmatch(statute) + and statute not in statutes): + statutes.append(statute) + else: + statutes_dropped += 1 + kind = "declared" if type_id in declared else "candidate" + entries[type_id] = {"definition_ko": definition, "statutes": statutes[:STATUTE_MAX_ITEMS], + "kind": kind, "kind_corrected": row.get("kind") != kind, + "statutes_dropped": statutes_dropped + + max(0, len(statutes) - STATUTE_MAX_ITEMS), + "verified": False} + return entries, dropped + + + def bo_context(bo_records, bo_ids): + # BO 들의 추상 구조만 모은다(식별자 정규식 통과값만). BOType 은 소문자로 맞춰 검사한다. + bo_types = set() + payload_keys = {} + for bo_id in bo_ids: + record = bo_records.get(bo_id) + if not isinstance(record, dict): + continue + bo_type = record.get("BOType") + if isinstance(bo_type, str) and is_type_id(bo_type.lower()): + bo_types.add(bo_type.lower()) + extensions = record.get("extensions") if isinstance(record.get("extensions"), dict) else {} + domain_payload = (extensions.get("domain_payload") + if isinstance(extensions.get("domain_payload"), dict) else {}) + payload = domain_payload.get("payload") if isinstance(domain_payload.get("payload"), dict) else {} + for key in payload: + if is_type_id(key): + payload_keys[key] = payload_keys.get(key, 0) + 1 + # 여러 BO 에 자주 나온 키를 먼저 남긴다(같으면 이름순). 잘렸는지는 반환값 셋째로 알린다. + ranked = sorted(payload_keys, key=lambda k: (-payload_keys[k], k)) + return sorted(bo_types), ranked[:PAYLOAD_KEY_MAX], len(ranked) > PAYLOAD_KEY_MAX + + + def build_plan(bundle, handoff, glossary, bo_records): + # 순수 함수. 후보와 쌍, fan-out item 을 만든다. 반환 (candidates, fanout, 정의 없이 보낸 유형 목록). + records = [r for r in (bundle.get("structure_records") or []) if isinstance(r, dict)] + unattached_type_ids = {row.get("type_id") for row in (bundle.get("unattached_routes") or []) + if isinstance(row, dict) and isinstance(row.get("type_id"), str)} + targets_by_domain = {} + for record in records: + if is_type_id(record.get("type_id")) and record["type_id"] not in EXCLUDED_TARGET_TYPE_IDS: + targets_by_domain.setdefault(record.get("domain_id"), []).append(record) + found = {} + for item in handoff.get("review_items") or []: + if not isinstance(item, dict) or item.get("review_code") != UNATTACHED_CODE: + continue + keywords = sorted({k for k in (item.get("legal_keywords") or []) if is_type_id(k)}) + domains = sorted({d for d in (item.get("resolved_domains") or []) if isinstance(d, str)}) + for k in keywords: + if k not in unattached_type_ids: + continue + for d in domains: + entry = found.setdefault((d, k), {"cooccur": set(), "bo_count": 0, "bo_ids": set()}) + entry["cooccur"].update(x for x in keywords if x != k) + entry["bo_count"] += 1 + if isinstance(item.get("bo_id"), str): + entry["bo_ids"].add(item["bo_id"]) + candidates = [] + fanout = [] + without_definition = set() + for (d, k) in sorted(found): + entry = found[(d, k)] + cooccur = sorted(entry["cooccur"])[:COOCCUR_MAX] + bo_types, payload_keys, payload_truncated = bo_context(bo_records, sorted(entry["bo_ids"])) + k_gloss = glossary.get(k) + pairs = [] + for record in sorted(targets_by_domain.get(d, []), key=lambda r: r["type_id"]): + target = record["type_id"] + if target == k: + continue + t_gloss = glossary.get(target) + candidate_state = {"type_id": k, "cooccurring_keywords": cooccur, + "bo_types": bo_types, "payload_keys": payload_keys} + if payload_truncated: + candidate_state["payload_keys_truncated"] = True + declared_state = { + "type_id": target, + "module": record.get("module") if is_type_id(record.get("module")) else None, + "role_projection": (record.get("role_projection") + if is_type_id(record.get("role_projection")) else None)} + if k_gloss: + candidate_state["definition_ko"] = k_gloss["definition_ko"] + else: + without_definition.add(k) + if t_gloss: + declared_state["definition_ko"] = t_gloss["definition_ko"] + declared_state["statutes"] = t_gloss["statutes"] + else: + without_definition.add(target) + state = {"domain_id": d, "candidate": candidate_state, "declared_type": declared_state} + state["glossary_source"] = GLOSSARY_SOURCE if (k_gloss or t_gloss) else "none" + # ensure_ascii=False — 한글 정의를 \\uXXXX 로 늘리지 않는다(백엔드가 문자열을 객체로 풀지 못해도 읽힌다). + state_json = json.dumps(state, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + # pair_id 에 state sha 를 넣는다 — 같은 쌍이라도 질문 자료가 바뀌면 지난 회차 답 파일이 맞지 않는다. + pair_id = "%s|%s|%s|%s" % (d, k, target, sha_text(state_json)[:12]) + answer_path = "%s/pair_%04d.json" % (ANSWER_DIR, len(fanout)) + pairs.append({"pair_id": pair_id, "target_type_id": target, "answer_path": answer_path}) + fanout.append({"pair_id": pair_id, "domain_id": d, "candidate_type_id": k, + "target_type_id": target, "answer_path": answer_path, + "state_json": state_json}) + candidates.append({"domain_id": d, "candidate_type_id": k, + "unattached_bo_item_count": entry["bo_count"], "pairs": pairs}) + return candidates, fanout, sorted(without_definition) + + + def glossary_doc(entries, dropped, glossary_status, obj, requested): + return {"schema_version": GLOSSARY_SCHEMA, "glossary_source": GLOSSARY_SOURCE, + "verified": False, "glossary_status": glossary_status, + "model_schema_version": obj.get("schema_version") if isinstance(obj, dict) else None, + "requested_count": len(requested), "accepted_count": len(entries), + "unverified_count": len(entries), "entries": entries, "dropped": dropped, + "missing_type_ids": sorted(requested - set(entries)), "created_by": TASK_NAME, + "note": "LLM 초안이다. law.go.kr 원문 대조·봉인 전이므로 조문·정의를 사실로 쓰지 않는다."} + + + def load_glossary(prev, bundle): + # glossary 를 꺼내 검사하고 type_glossary.json 에 쓴다. 쓰기에 실패하면 정의를 쓰지 않는다 + # (state 에 실은 정의와 파일이 어긋나지 않게) — 식별자만으로 계획을 이어 간다. + declared, candidate = requested_type_ids(bundle) + requested = declared | candidate + obj, glossary_status = glossary_object(prev) + entries, dropped = clean_glossary(obj, declared, candidate) if obj is not None else ({}, []) + if glossary_status == "OK": + # 파싱은 됐어도 표가 없거나 일부만 통과했으면 그렇게 적는다(영수증·검토 항목이 "OK" 로 오도하지 않게). + if not entries and any(d.get("reason") == "GLOSSARY_TABLE_MISSING" for d in dropped): + glossary_status = "GLOSSARY_TABLE_MISSING" + elif not entries: + glossary_status = "GLOSSARY_EMPTY" + elif len(entries) < len(requested): + glossary_status = "OK_PARTIAL" + text = canonical(glossary_doc(entries, dropped, glossary_status, obj, requested)) + try: + write_doc(GLOSSARY_PATH, text) + except Exception as exc: + glossary_status = "GLOSSARY_WRITE_FAILED:%s" % str(exc)[:120] + entries = {} + text = None + return entries, {"glossary_status": glossary_status, + "glossary_sha256": sha_text(text) if text else None, + "requested_count": len(requested), "accepted_count": len(entries), + "unverified_count": len(entries), "dropped_count": len(dropped), + "kind_corrected_count": sum(1 for e in entries.values() if e["kind_corrected"]), + "statutes_dropped_count": sum(e["statutes_dropped"] for e in entries.values())} + + + def load_bo_records(): + # BO.json 은 무봉인 입력이다. 읽지 못하면 BO 문맥 없이 계획한다(정의·식별자만). + try: + doc = read_json(BO_PATH) + except Exception: + return {}, "BO_UNREADABLE" + rows = doc if isinstance(doc, list) else (doc.get("BO") if isinstance(doc, dict) else None) + if not isinstance(rows, list): + return {}, "BO_INVALID" + out = {} + for row in rows: + if isinstance(row, dict): + bo_id = row.get("BO_ID") if isinstance(row.get("BO_ID"), str) else row.get("id") + if isinstance(bo_id, str): + out[bo_id] = row + return out, "OK" + + + def main(): + prev, prev_error = load_prev(r"""{{prev}}""") + if prev_error: + return {"code": "PREV_UNPARSEABLE", "detail": prev_error} + l0 = previous_state(prev, L0_TASK) + count = l0.get("structure_record_count") + if l0.get("status") not in ("READY", "READY_WITH_REVIEW") or not isinstance(count, int): + return {"code": "L0_NOT_READY", "l0_status": l0.get("status")} + bundle_doc = read_json(BUNDLE_PATH) + bundle = bundle_doc.get("structure_seed_bundle", bundle_doc) if isinstance(bundle_doc, dict) else {} + records = [r for r in (bundle.get("structure_records") or []) if isinstance(r, dict)] + if len(records) != count: + return {"code": "BUNDLE_STALE", "l0_structure_record_count": count, + "bundle_structure_record_count": len(records)} + handoff_raw = read_raw(HANDOFF_PATH) + handoff_doc = parse_json_text(handoff_raw) + handoff = (handoff_doc.get("stage1_part3_review_handoff", handoff_doc) + if isinstance(handoff_doc, dict) else {}) + glossary, glossary_summary = load_glossary(prev, bundle) + bo_records, bo_status = load_bo_records() + candidates, fanout, without_definition = build_plan(bundle, handoff, glossary, bo_records) + glossary_summary["pair_types_without_definition"] = without_definition + write_doc(REQUEST_PATH, canonical({ + "schema_version": REQUEST_SCHEMA, "planned": True, "reason": None, + "handoff_sha256": sha_text(handoff_raw), + "structure_record_count": count, + "excluded_target_type_ids": list(EXCLUDED_TARGET_TYPE_IDS), + "glossary": glossary_summary, "bo_context_status": bo_status, + "candidate_count": len(candidates), "pair_count": len(fanout), + "candidates": candidates, "created_by": TASK_NAME})) + RESULT.update({"status": "PLANNED", "dynamic_fanout": fanout, "count": len(fanout), + "candidate_count": len(candidates), + "glossary_status": glossary_summary["glossary_status"], + "glossary_accepted": glossary_summary["accepted_count"], + "pair_types_without_definition": len(without_definition)}) + return None + + + try: + _init() + try: + _reason = main() + except BaseException as exc: # raise 하지 않는다. + _reason = {"code": "PLANNER_EXCEPTION", "detail": str(exc)[:300]} + if _reason is not None: + RESULT.update({"status": "NOT_PLANNED", "dynamic_fanout": [], "count": 0, "reason": _reason}) + try: # 지난 회차 정의표가 이번 회차 것으로 읽히지 않게(최선 노력). + write_doc(GLOSSARY_PATH, canonical({"schema_version": GLOSSARY_SCHEMA, "planned": False, + "reason": _reason, "entries": {}, "created_by": TASK_NAME})) + except Exception: + pass + write_doc(REQUEST_PATH, canonical({ + "schema_version": REQUEST_SCHEMA, "planned": False, "reason": _reason, + "candidates": [], "created_by": TASK_NAME})) + except BaseException as exc: + RESULT.update({"status": "NOT_PLANNED", "dynamic_fanout": [], "count": 0, + "reason": {"code": "LOCALDOCS_UNAVAILABLE", "detail": str(exc)[:300]}}) + print(json.dumps(RESULT, ensure_ascii=False)) + + # L1 추천기 — 후보×선언 유형 쌍마다 JEV choice 질문 1개(SKILL.md §3.4). 프롬프트·도구·preflight 없음. + # 키는 백엔드 env JEV_API_KEY(api_keys["jev"])에서 읽는다. YAML 에 api_key 를 쓰지 않는다. + # provider 는 jev 로 명시한다(스테이지 llm_provider: openai 가 새어 gpt-6-luna 로 바뀌는 일을 막는다). + # model 은 고정한다(jev-latest 는 표류). 전략서는 jev-1.13.0 이었으나 SKILL.md §3.4(11-05 갱신)의 실호출 확인판·고정 권고인 + # jev-1.14.0 으로 고정한다(보정된 임계값이 아직 없어 잃는 것이 없다). 판을 바꾸면 임계값을 다시 보정한다. 응답의 model 은 capture·영수증에 남는다. + # criteria 키 집합(2:39pm 부터 4개)은 Task_C_LE_L1_apply 의 RELATION_KEYS 와 같아야 한다. + # state 는 planner 가 만든 정렬 JSON 문자열 — "JSON 문자열이면 객체로 전달"(§3.4) 경로를 쓴다. + # 11-05 오후부터 식별자 외에 glossary 정의(미검증)·조문·BO 문맥(BOType·payload 키)이 실린다. + # instructions 는 11-05 2pm 사용자 결정으로 "identifiers" → "information" 으로 바꿨다(JEV 가 새 정의를 쓰게). + # 비교 실행에서 정의 효과와 지시문 효과는 함께 측정된다. 되돌릴 판은 stage_1_part_3_v.8_11_05_2pm.yml 이다. + # criteria(11-05 2:25pm 사용자 승인) — 키 3개는 그대로, 설명 두 개만 바꿨다. 2차 실행에서 정의를 싣자 17쌍 모두 + # independent 로 기울었다(실행결과보고서_2_part_3.md §4): "고유한 효과가 있는가"를 독립의 기준으로 삼은 문장이 원인. + # part_of_declared_type 은 "고유 효과가 있어도 선언 유형의 성립·소멸·시효·금액·이행기·행사 가능성(exercisability)에 작용하는 사건·요건·항변"으로 넓히고, + # independent_effect 는 "별개의 청구·항변 구조라 독립 구조 레코드가 필요할 때만"으로 좁혔다. wording_variant 는 그대로. + # (2:25pm 기준) 키 이름이 같으므로 apply 의 RELATION_KEYS·decide·임계값·영수증은 바뀌지 않는다. 되돌릴 판은 stage_1_part_3_v.8_11_05_2_25pm.yml 이다. + # unrelated(11-05 2:39pm 사용자 승인) — 넷째 키. 관계없는 쌍이 independent 로 몰리지 않게 하는 "해당 없음" 자리(§3.4 규칙 4). + # 키가 바뀌었으므로 apply 의 RELATION_KEYS(4키)·decide(수용 차단·승격 기준)를 함께 고쳤다. 되돌릴 판은 stage_1_part_3_v.8_11_05_2_39pm.yml 이다. + - task_name: Task_C_LE_L1_recommender_* + description: 후보×선언 유형 쌍마다 관계 하나를 고르는 JEV choice 질문 + jev: + provider: jev + model: jev-1.14.0 + state: "{{item.state_json}}" + questions: + relation: + type: choice + instructions: >- + Decide how the candidate legal-effect type relates to the declared type. + Use only the information given in state. + criteria: + independent_effect: "Choose this only when the candidate forms a claim or defense structure separate from the declared type and needs its own structure record. Having its own legal effect or its own statute is not by itself independence." + part_of_declared_type: "Choose this when the candidate is an event, requirement or defense that acts on the declared type's formation, extinction, limitation period, amount, due date or exercisability, even if the candidate has its own legal effect. For example, a release of the debt and a merger of the creditor's and the debtor's positions are events that act on the extinction and amount of a money claim, so they belong here." + wording_variant: "The candidate is another name for the same legal effect as the declared type; the legal meaning is identical." + unrelated: "Choose this when the candidate has no legal relationship with the declared type: it does not act on the declared type's formation, extinction, limitation period, amount, due date or exercisability, it is not another name for it, and it is not a claim or defense that competes with or responds to it. When the candidate is unrelated to the declared type, choose this rather than independent_effect even if the candidate would need its own structure record. The declared type is simply the wrong target for this candidate." + retry: {max_attempts: 2, backoff_sec: 5} + + - task_name: Task_C_LE_L1_capture_* + description: 같은 ordinal 의 jev 응답에서 answers.relation 을 꺼내 item.answer_path 에 쓴다. 응답 문제는 FAILED 표식. + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: |- + #!/usr/bin/env python3 + # Task_C_LE_L1_capture (2026-11-05, 개정전략서_part_3_v2_with_part_1_2.md §3.1 · Part 2 Task_C_B_domain_capture 를 따른다) + # 같은 ordinal 의 Task_C_LE_L1_recommender_(jev) 응답 JSON 에서 answers.relation 을 꺼내 + # item.answer_path 에 {pair_id, status, model, usage, relation} 으로 쓴다. 판정은 apply 가 한다. + # 응답 문제(인스턴스 실패로 prev 에 없음 · answers.relation 없음 · 형식 이탈)로는 raise 하지 않고 + # status:"FAILED" 표식을 쓴다 — 지난 회차 답 파일이 남아 apply 를 통과하지 못하게 한다. + # 쓰기 실패만 raise 한다(code task 에는 백엔드 재시도가 없다 — 답 파일이 없거나 지난 회차 것이면 + # apply 의 pair_id 대조가 ANSWER_MISSING 으로 처리한다). + import hashlib + import itertools + import json + + import httpx + + TASK_NAME = "Task_C_LE_L1_capture" + + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) — L2 사본에 Part 2 capture 의 write_doc(오류 검사)를 붙였다. + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # ------------------------------------------------------------------ + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def parse_json_text(raw): + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def read_json(name): + return parse_json_text(read_raw(name)) + + + def write_doc(path, content): + # localdocs 는 실패도 정상 응답 본문의 "Error: ..." 로 돌려준다(Part 2 capture 와 같은 검사). + p = _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if text.startswith("Error"): + raise RuntimeError("WRITE_FAILED:%s:%s" % (path, text[:200])) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + class CaptureError(Exception): + def __init__(self, code, detail=""): + super().__init__("%s:%s" % (code, detail)) + self.code = code + self.detail = detail + + + def _as_dict(value): + if isinstance(value, str): + try: + value = json.loads(value) + except Exception: + return None + return value if isinstance(value, dict) else None + + + def extract(prev_text, jev_task): + # jev task 의 결과는 응답 JSON 전체다(SKILL.md §3.4). 봉투(json_output·content·output)로 오면 한 겹 벗긴다. + if prev_text.strip().startswith("{" + "{"): + raise CaptureError("PREV_NOT_RENDERED") + try: + prev = json.loads(prev_text) + except Exception as exc: + raise CaptureError("PREV_PARSE_FAILED", str(exc)[:200]) + resp = _as_dict(prev.get(jev_task)) if isinstance(prev, dict) else None + if resp is None: + raise CaptureError("MISSING_TASK_OUTPUT", jev_task) + if "answers" not in resp: + for key in ("json_output", "content", "output"): + inner = _as_dict(resp.get(key)) + if inner is not None and "answers" in inner: + resp = inner + break + answers = resp.get("answers") + relation = answers.get("relation") if isinstance(answers, dict) else None + if not isinstance(relation, dict): + raise CaptureError("ANSWER_RELATION_MISSING", str(resp)[:200]) + if not isinstance(relation.get("probabilities"), dict): + raise CaptureError("ANSWER_PROBABILITIES_MISSING", str(relation)[:200]) + return {"type": relation.get("type"), "choice": relation.get("choice"), + "probabilities": relation.get("probabilities"), + "confidence": relation.get("confidence")}, resp.get("model"), resp.get("usage") + + + ITEM = json.loads(r"""{{item_json}}""") + ORDINAL = int(r"""{{ordinal}}""") + JEV_TASK = "Task_C_LE_L1_recommender_%d" % ORDINAL + OUTPUT_PATH = ITEM["answer_path"] + RESULT = {"status": "ANSWERED", "answer_path": OUTPUT_PATH, "jev_task": JEV_TASK, + "pair_id": ITEM.get("pair_id")} + try: + _relation, _model, _usage = extract(r"""{{prev}}""", JEV_TASK) + DOC = {"pair_id": ITEM.get("pair_id"), "status": "ANSWERED", "model": _model, + "usage": _usage if isinstance(_usage, dict) else None, + "relation": _relation, "created_by": TASK_NAME} + RESULT["choice"] = _relation.get("choice") + except CaptureError as exc: + DOC = {"pair_id": ITEM.get("pair_id"), "status": "FAILED", "code": exc.code, + "detail": exc.detail, "created_by": TASK_NAME} + RESULT.update({"status": "FAILED", "code": exc.code}) + _init() + write_doc(OUTPUT_PATH, canonical(DOC)) + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_LE_L1_apply + description: 쌍 답을 결정론적으로 판정(decide)해 번들·handoff 에 반영하고 영수증을 쓴다. + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 180 + code: |- + #!/usr/bin/env python3 + # Task_C_LE_L1_apply (2026-11-05, 개정전략서_part_3_v2_with_part_1_2.md §2.4·§2.5·§3.1) + # 번들·handoff 쓰기가 실패하면 바꾼 파일을 각각 읽은 원본으로 되돌리고 실패 영수증을 남긴 뒤 raise 한다(반쪽 상태 차단). + # 1) 요청 파일 확인(planned · handoff_sha256 신선도) -> 2) 답 파일 적재·유효성 -> + # 3) decide(순수 함수) -> 4) 반영: 번들 -> handoff -> 영수증(각 쓰기 재읽기 sha 대조) + # 모듈·정적 자산·시드 스키마를 읽지 않는다. 고친 structure_records 는 L2 가 최종 색인 스키마로, + # unattached_bo·counts 는 L2 의 BO 보존 등식이 다시 잡는다. + # 대상 BO 는 handoff 의 PART3_BO_UNATTACHED 항목에서 고른다(번들 unattached_bo 아님 — 부분 실패 재실행 대비). + # 후보가 0 이거나 바뀐 BO 가 없으면 번들·handoff 를 다시 쓰지 않는다. 영수증은 항상 쓴다. + # 검토 항목에 status·blocked 키를 쓰지 않는다(S2_00 이 멈춘다). 심각도 리터럴은 HARD_WARNING/SOFT_WARNING 뿐. + # 이 경로는 정책 structure_index_policy.v1.json 의 bo_attachment.join 서술과 다른 부착 경로다. + import hashlib + import itertools + import json + import math + + import httpx + + TASK_NAME = "Task_C_LE_L1_apply" + BUNDLE_PATH = "stage1_tmp/task_le/structure_seed_bundle.json" + HANDOFF_PATH = "quality_gates/stage1_part3_review_handoff.json" + REQUEST_PATH = "stage1_tmp/task_le/recommender_requests.json" + RECEIPT_PATH = "validation_assets/routing/part3_recommender_receipt.json" + UNATTACHED_CODE = "PART3_BO_UNATTACHED" + + # 임계값 — 시작값이며 검증되지 않았다(§2.4). 첫 온라인 실행들은 그림자 실행이었다(11-05 실행 1~3): + # ACCEPT_MIN·INDEPENDENT_MIN 을 1.01 로 두어 수용·승격 제안을 끄고 점수만 영수증에 남긴다. + # SHADOW_RUN = True 면 두 임계값을 1.01 로 두어 수용·승격을 끈다. accept_min 을 0.5 근처까지 낮춰도 최댓값 조건은 항상 붙는다. + # 2026-11-05 3:30pm 사용자 결정으로 끈다(사람 라벨 보정 없이) — 시작 임계값이 실제로 적용된다(실행 3 데이터 기준 수용 4건·BO 5건). + SHADOW_RUN = False + ACCEPT_MIN_START = 0.80 + MARGIN_MIN = 0.20 + INDEPENDENT_MIN_START = 0.80 + ACCEPT_MIN = 1.01 if SHADOW_RUN else ACCEPT_MIN_START + INDEPENDENT_MIN = 1.01 if SHADOW_RUN else INDEPENDENT_MIN_START + # 2:39pm 신설 — 승격 제안에 필요한 independent 의 쌍별 하한(절반 이상). 그림자 실행에서는 INDEPENDENT_MIN 이 먼저 막는다. + INDEPENDENT_FLOOR = 0.50 + # 부동소수 비교 허용오차(0.7-0.5 = 0.19999… 가 마진 0.20 에 떨어지지 않게). + EPS = 1e-9 + + DECIDED_BY = "recommender" + CODE_ATTACHED = "PART3_BO_ATTACHED_BY_RECOMMENDER" + CODE_PROMOTION = "PART3_PROMOTION_PROPOSED" + CODE_MISSING = "PART3_RECOMMENDER_ANSWER_MISSING" + # 목표 무관(3:30pm) — UNDECIDED 후보의 모든 쌍에서 unrelated 가 네 확률 중 최댓값이면 후보마다 한 건(SOFT). + # HARD PART3_BO_UNATTACHED 는 남는다. 검토자가 "레지스트리 승격 / 다른 도메인 대상 / 버림"을 바로 판단하게 하는 안내다. + CODE_TARGET_UNRELATED = "PART3_RECOMMENDER_TARGET_UNRELATED" + # planner 가 정의 없이(식별자만) 보낸 유형이 있으면 한 건 남긴다(11-05 오후 glossary 개정). + CODE_GLOSSARY_MISSING = "PART3_GLOSSARY_MISSING" + PLANNER_TASK = "Task_C_LE_L1_candidate_planner" + # Task_C_LE_L1_recommender_* 의 jev criteria 키와 같아야 한다(2벌 — 오프라인 검사가 대조한다). + # unrelated(11-05 2:39pm 사용자 승인) — 선언 유형과 법적 관계가 없는 쌍의 자리(SKILL.md §3.4 규칙 4 "그 외/해당 없음"). + # 부착 질량 = part_of + wording · 비부착 질량 = independent + unrelated. + # 수용: 부착 질량 ≥ ACCEPT_MIN · 마진 · part_of 또는 wording 이 네 확률 중 최댓값(independent·unrelated 가 최댓값이면 막는다). + # 승격 제안: 모든 쌍에서 비부착 질량 ≥ INDEPENDENT_MIN 이고, 적어도 한 쌍에서 independent ≥ INDEPENDENT_FLOOR(절반 이상). + # (independent ≥ unrelated 만으로는 0.41 대 0.40 같은 약한 근거도 통과한다 — 절반 이상 하한이 독립 구조라는 최소 근거다.) + # 결과: 선언 목표가 모두 "무관"인 후보(X1 처럼 쌍이 하나뿐인 후보 포함)는 승격 제안에 오르지 않는다 — 승격은 이제 + # "독립 구조가 필요하고 어떤 선언 유형과는 관계가 있음"을 뜻한다. 그런 후보의 판단은 3:30pm 부터 handoff SOFT + # PART3_RECOMMENDER_TARGET_UNRELATED 로도 남는다. + # 모든 쌍이 "무관" 우세면 독립 구조라는 근거가 없으므로 UNDECIDED 로 두어 HARD 미부착 항목을 사람 검토에 남긴다(보수적 선택). + RELATION_KEYS = ("independent_effect", "part_of_declared_type", "wording_variant", "unrelated") + INDEPENDENT = "independent_effect" + UNRELATED = "unrelated" + PART_OF = "part_of_declared_type" + WORDING = "wording_variant" + + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) — L2 사본에 Part 2 capture 의 write_doc(오류 검사)를 붙였다. + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # ------------------------------------------------------------------ + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def parse_json_text(raw): + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def read_json(name): + return parse_json_text(read_raw(name)) + + + def write_doc(path, content): + # localdocs 는 실패도 정상 응답 본문의 "Error: ..." 로 돌려준다(Part 2 capture 와 같은 검사). + p = _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if text.startswith("Error"): + raise RuntimeError("WRITE_FAILED:%s:%s" % (path, text[:200])) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + def write_checked(path, text): + write_doc(path, text) + if sha_text(read_raw(path)) != sha_text(text): + raise RuntimeError("PART3_L1_WRITE_REREAD_MISMATCH:%s" % path) + + + # ------------------------------------------------------------------ + # 순수 함수 — 외부 호출 없음. 입력은 요청 파일의 쌍과 답 파일뿐이다. + # ------------------------------------------------------------------ + def normalized_probabilities(pair, answer): + # 유효 답이면 네 확률을 합으로 나눈 dict, 아니면 None(= 답 누락). 키 집합이 다르면(옛 3키 답 포함) 누락이다. + if not isinstance(answer, dict) or answer.get("status") != "ANSWERED": + return None + if answer.get("pair_id") != pair.get("pair_id"): + return None + relation = answer.get("relation") + if not isinstance(relation, dict) or relation.get("type") != "choice": + return None + probs = relation.get("probabilities") + if not isinstance(probs, dict) or set(probs) != set(RELATION_KEYS): + return None + values = {} + for key in RELATION_KEYS: + value = probs[key] + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + value = float(value) + if not math.isfinite(value) or value < 0.0 or value > 1.0: + return None + values[key] = value + total = sum(values.values()) + if total <= 0.0: + return None + return {key: values[key] / total for key in RELATION_KEYS} + + + def decide(pairs, answers): + # pairs: [{pair_id, target_type_id}] · answers: {pair_id: 답 파일 dict 또는 None} + if not pairs: + return {"outcome": "NO_PAIRS"} + scored = [] + missing = [] + for pair in pairs: + norm = normalized_probabilities(pair, answers.get(pair.get("pair_id"))) + if norm is None: + missing.append(pair.get("pair_id")) + continue + scored.append({"pair_id": pair.get("pair_id"), "target_type_id": pair.get("target_type_id"), + "attach_score": norm[PART_OF] + norm[WORDING], + "non_attach_score": norm[INDEPENDENT] + norm[UNRELATED], + "probabilities": norm}) + pair_scores = [{"pair_id": row["pair_id"], "target_type_id": row["target_type_id"], + "attach_score": round(row["attach_score"], 6), + "non_attach_score": round(row["non_attach_score"], 6), + "probabilities": {k: round(v, 6) for k, v in row["probabilities"].items()}} + for row in scored] + if missing: + return {"outcome": "ANSWER_MISSING", "missing_pair_ids": missing, "pair_scores": pair_scores} + ranked = sorted(scored, key=lambda row: (-row["attach_score"], str(row["target_type_id"]))) + best = ranked[0] + margin = None if len(ranked) == 1 else best["attach_score"] - ranked[1]["attach_score"] + norm = best["probabilities"] + non_attach_is_max = max(norm[INDEPENDENT], norm[UNRELATED]) >= max(norm[PART_OF], norm[WORDING]) + if (best["attach_score"] + EPS >= ACCEPT_MIN and (margin is None or margin + EPS >= MARGIN_MIN) + and not non_attach_is_max): + relation = WORDING if norm[WORDING] >= norm[PART_OF] else PART_OF + return {"outcome": "ACCEPT", "attached_type_id": best["target_type_id"], + "pair_id": best["pair_id"], "relation": relation, + "accept_score": round(best["attach_score"], 6), + "margin": None if margin is None else round(margin, 6), + "pair_scores": pair_scores} + if (all(row["non_attach_score"] + EPS >= INDEPENDENT_MIN for row in scored) + and any(row["probabilities"][INDEPENDENT] + EPS >= INDEPENDENT_FLOOR for row in scored)): + return {"outcome": "PROMOTION", "pair_scores": pair_scores} + return {"outcome": "UNDECIDED", "pair_scores": pair_scores} + + + def bo_counts(bundle): + # 영수증용. 전후 모두 같은 방식(레코드 source_bo_ids 고유 id · unattached_bo 길이)으로 센다. + attached = set() + for record in bundle.get("structure_records") or []: + if isinstance(record, dict): + attached.update(b for b in (record.get("source_bo_ids") or []) if isinstance(b, str)) + return {"bo_attached": len(attached), "bo_unattached": len(bundle.get("unattached_bo") or [])} + + + def item_key(item): + return (item.get("review_code"), item.get("domain_id"), item.get("candidate_type_id"), + item.get("bo_id")) + + + def apply_decisions(bundle, handoff, decisions, models, glossary=None): + # 번들·handoff 를 제자리에서 고친다. 반환: (번들 변경 여부, handoff 변경 여부, 수용 BO 목록) + records = {(r.get("domain_id"), r.get("type_id")): r + for r in (bundle.get("structure_records") or []) if isinstance(r, dict)} + accepted = {(row["domain_id"], row["candidate_type_id"]): row for row in decisions + if row["decision"]["outcome"] == "ACCEPT"} + items = [i for i in (handoff.get("review_items") or [])] + existing = {item_key(i) for i in items if isinstance(i, dict)} + kept = [] + added = [] + attached_bo = [] + bundle_changed = False + removed_bo_ids = set() + for item in items: + if not isinstance(item, dict) or item.get("review_code") != UNATTACHED_CODE: + kept.append(item) + continue + keywords = [k for k in (item.get("legal_keywords") or []) if isinstance(k, str)] + domains = [d for d in (item.get("resolved_domains") or []) if isinstance(d, str)] + bo_id = item.get("bo_id") + matches = sorted({(d, k) for d in domains for k in keywords if (d, k) in accepted}) + if not matches or not isinstance(bo_id, str): + kept.append(item) + continue + for (d, k) in matches: + row = accepted[(d, k)] + decision = row["decision"] + record = records.get((d, decision["attached_type_id"])) + if record is None: + continue + if bo_id not in record.get("source_bo_ids", []): + record["source_bo_ids"] = sorted(set(record.get("source_bo_ids") or []) | {bo_id}) + bundle_changed = True + if CODE_ATTACHED not in (record.get("review_codes") or []): + record["review_codes"] = sorted(set(record.get("review_codes") or []) | {CODE_ATTACHED}) + bundle_changed = True + if record.get("review_required") is not True: + record["review_required"] = True + bundle_changed = True + new_item = {"review_code": CODE_ATTACHED, "severity": "SOFT_WARNING", + "domain_id": d, "bo_id": bo_id, "candidate_type_id": k, + "attached_type_id": decision["attached_type_id"], + "relation": decision["relation"], "decided_by": DECIDED_BY, + "accept_score": decision["accept_score"], "margin": decision["margin"], + "model": models.get(decision["pair_id"])} + if item_key(new_item) not in existing: + existing.add(item_key(new_item)) + added.append(new_item) + attached_bo.append({"bo_id": bo_id, "domain_id": d, "candidate_type_id": k, + "attached_type_id": decision["attached_type_id"]}) + if any(records.get((d, accepted[(d, k)]["decision"]["attached_type_id"])) is not None + for (d, k) in matches): + removed_bo_ids.add(bo_id) + else: + kept.append(item) + unattached = [row for row in (bundle.get("unattached_bo") or []) if isinstance(row, dict)] + remaining = [row for row in unattached if row.get("bo_id") not in removed_bo_ids] + if len(remaining) != len(unattached): + bundle["unattached_bo"] = remaining + bundle_changed = True + if bundle_changed: + # 차감하지 않고 배열에서 다시 센다(L2 가 원본 BO.json 으로 같은 등식을 잰다). + counts = bundle.setdefault("counts", {}) + attached_ids = set() + for record in records.values(): + attached_ids.update(b for b in (record.get("source_bo_ids") or []) if isinstance(b, str)) + counts["bo_attached"] = len(attached_ids) + counts["bo_unattached"] = len(bundle["unattached_bo"]) + # 승격 제안 · 답 누락 — 후보 단위. 기존 PART3_BO_UNATTACHED 는 남긴다. + for row in decisions: + outcome = row["decision"]["outcome"] + if outcome not in ("PROMOTION", "ANSWER_MISSING"): + continue + new_item = {"review_code": CODE_PROMOTION if outcome == "PROMOTION" else CODE_MISSING, + "severity": "SOFT_WARNING", "domain_id": row["domain_id"], + "candidate_type_id": row["candidate_type_id"], "decided_by": DECIDED_BY} + if outcome == "PROMOTION": + new_item["pair_scores"] = row["decision"]["pair_scores"] + else: + new_item["missing_pair_ids"] = row["decision"]["missing_pair_ids"] + if item_key(new_item) not in existing: + existing.add(item_key(new_item)) + added.append(new_item) + # 목표 무관 — UNDECIDED 후보 중 모든 쌍의 최댓값이 unrelated 인 후보마다 한 건(ACCEPT·PROMOTION 과는 구조상 겹치지 않는다). + # 동률이면 RELATION_KEYS 순서상 unrelated 가 지므로(마지막 키) 보수적으로 남기지 않는다. + for row in decisions: + decision = row["decision"] + scores = decision.get("pair_scores") or [] + if decision["outcome"] != "UNDECIDED": + continue + if not all(max(RELATION_KEYS, key=lambda key: s["probabilities"][key]) == UNRELATED for s in scores): + continue + new_item = {"review_code": CODE_TARGET_UNRELATED, "severity": "SOFT_WARNING", + "domain_id": row["domain_id"], "candidate_type_id": row["candidate_type_id"], + "decided_by": DECIDED_BY, "pair_scores": scores} + if item_key(new_item) not in existing: + existing.add(item_key(new_item)) + added.append(new_item) + # glossary 누락 — 회차 단위 한 건. 정의 없이 보낸 유형이 없으면 남기지 않는다. 그림자 실행에서도 남긴다. + glossary = glossary if isinstance(glossary, dict) else {} + without = [t for t in (glossary.get("pair_types_without_definition") or []) if isinstance(t, str)] + if without: + new_item = {"review_code": CODE_GLOSSARY_MISSING, "severity": "SOFT_WARNING", + "type_ids_without_definition": sorted(without), + "glossary_reason": glossary.get("glossary_status"), + "detected_by": PLANNER_TASK} + if item_key(new_item) not in existing: + existing.add(item_key(new_item)) + added.append(new_item) + new_items = kept + added + handoff_changed = len(new_items) != len(items) or any(a is not b for a, b in zip(new_items, items)) + if handoff_changed: + handoff["review_items"] = new_items + handoff.setdefault("counts", {})["review_items"] = len(new_items) + return bundle_changed, handoff_changed, attached_bo + + + def fail_receipt(receipt, reason): + # raise 경로에서도 지난 회차 영수증이 남지 않게 실패 사유를 남긴다(최선 노력 — 실패해도 원래 오류를 올린다). + receipt.update({"applied": False, "reason": reason}) + try: + write_doc(RECEIPT_PATH, canonical(receipt)) + except Exception: + pass + + + def main(): + receipt = {"schema_version": "stage1_part3_recommender_receipt.v2", "stage": "P3-L1", + "shadow_run": SHADOW_RUN, + # v2(2:39pm): 4키 · pair_scores.non_attach_score · independent_min 은 비부착 질량 하한 · independent_floor 신설. + "relation_keys": list(RELATION_KEYS), + "thresholds": {"accept_min": ACCEPT_MIN, "margin_min": MARGIN_MIN, + "independent_floor": INDEPENDENT_FLOOR, + "independent_min": INDEPENDENT_MIN, + "accept_min_start": ACCEPT_MIN_START, + "independent_min_start": INDEPENDENT_MIN_START}, + "decided_by": DECIDED_BY, "applied": False, "reason": None, + "created_by": TASK_NAME} + request_raw = None + try: + request_raw = read_raw(REQUEST_PATH) + request = parse_json_text(request_raw) + except Exception as exc: + request = None + receipt["reason"] = {"code": "REQUEST_UNREADABLE", "detail": str(exc)[:200]} + if request is not None: + receipt["request_sha256"] = sha_text(request_raw) + if isinstance(request, dict) and request.get("planned") is not True: + receipt["reason"] = {"code": "NOT_PLANNED", "planner_reason": request.get("reason")} + if receipt["reason"] is None and not isinstance(request, dict): + receipt["reason"] = {"code": "REQUEST_INVALID"} + try: + handoff_raw = read_raw(HANDOFF_PATH) + except Exception as exc: + fail_receipt(receipt, {"code": "HANDOFF_UNREADABLE", "detail": str(exc)[:200]}) + raise + if receipt["reason"] is None and request.get("handoff_sha256") != sha_text(handoff_raw): + receipt["reason"] = {"code": "HANDOFF_CHANGED_OR_ALREADY_APPLIED", + "expected": request.get("handoff_sha256"), + "actual": sha_text(handoff_raw)} + if receipt["reason"] is not None: + write_checked(RECEIPT_PATH, canonical(receipt)) + return {"status": "SKIPPED", "reason": receipt["reason"]} + + candidates = [c for c in (request.get("candidates") or []) if isinstance(c, dict)] + answer_files = {} + answers = {} + models = {} + input_tokens = 0 + model_names = set() + for candidate in candidates: + for pair in candidate.get("pairs") or []: + if not isinstance(pair, dict): + continue + path = pair.get("answer_path") + raw = None + try: + raw = read_raw(path) + answer = parse_json_text(raw) + except Exception: + answer = None + answer_files[pair.get("pair_id")] = sha_text(raw) if raw else None + answers[pair.get("pair_id")] = answer + if isinstance(answer, dict) and answer.get("status") == "ANSWERED": + models[pair.get("pair_id")] = answer.get("model") + if isinstance(answer.get("model"), str): + model_names.add(answer["model"]) + usage = answer.get("usage") if isinstance(answer.get("usage"), dict) else {} + if isinstance(usage.get("input_tokens"), int): + input_tokens += usage["input_tokens"] + decisions = [] + for candidate in candidates: + decisions.append({"domain_id": candidate.get("domain_id"), + "candidate_type_id": candidate.get("candidate_type_id"), + "decision": decide([p for p in (candidate.get("pairs") or []) + if isinstance(p, dict)], answers)}) + + bundle_raw = read_raw(BUNDLE_PATH) + bundle_doc = parse_json_text(bundle_raw) + bundle = bundle_doc.get("structure_seed_bundle", bundle_doc) + handoff_doc = parse_json_text(handoff_raw) + handoff = handoff_doc.get("stage1_part3_review_handoff", handoff_doc) + before = bo_counts(bundle) + bundle_changed, handoff_changed, attached_bo = apply_decisions(bundle, handoff, decisions, models, + request.get("glossary")) + # 쓰기 순서: 번들 -> handoff -> 영수증. created_by·schema_version·status 는 덮어쓰지 않는다. + try: + if bundle_changed: + write_checked(BUNDLE_PATH, canonical({"structure_seed_bundle": bundle})) + if handoff_changed: + write_checked(HANDOFF_PATH, canonical({"stage1_part3_review_handoff": handoff})) + except Exception as exc: + # code task 는 백엔드 재시도가 없고 apply 실패 뒤에도 L2 가 돈다. 반쪽 상태(번들에는 붙었는데 + # handoff 에 HARD 가 남거나, 그 반대)가 L2 로 가지 않도록 바꾼 파일을 각각 읽은 원본으로 되돌린다. + restore = {} + for path, raw, changed in ((BUNDLE_PATH, bundle_raw, bundle_changed), + (HANDOFF_PATH, handoff_raw, handoff_changed)): + if not changed: + continue + try: + write_checked(path, raw) + restore[path] = "RESTORED" + except Exception as restore_exc: + restore[path] = "RESTORE_FAILED:%s" % str(restore_exc)[:150] + fail_receipt(receipt, {"code": "WRITE_FAILED", "detail": str(exc)[:200], "restore": restore}) + raise + outcome_counts = {} + for row in decisions: + outcome_counts[row["decision"]["outcome"]] = outcome_counts.get(row["decision"]["outcome"], 0) + 1 + receipt.update({ + "applied": True, + "models": sorted(model_names), + "usage_input_tokens": input_tokens, + "candidate_count": len(candidates), + "pair_count": sum(len(c.get("pairs") or []) for c in candidates), + "answer_file_sha256": answer_files, + # glossary 는 LLM 초안(미검증)이다. sha·미검증 항목 수로 회차 간 점수 비교의 전제를 남긴다. + "glossary": request.get("glossary"), + "decisions": decisions, + "outcome_counts": outcome_counts, + "attached_bo": attached_bo, + "bo_counts": {"before": before, "after": bo_counts(bundle)}, + "bundle_rewritten": bundle_changed, + "handoff_rewritten": handoff_changed, + "note": "L0 영수증 part3_receipt.json 의 join_counts 는 L1 이전 값이다.", + }) + write_checked(RECEIPT_PATH, canonical(receipt)) + return {"status": "APPLIED", "candidate_count": len(candidates), + "outcome_counts": outcome_counts, "attached_bo_count": len(attached_bo), + "bundle_rewritten": bundle_changed, "handoff_rewritten": handoff_changed} + + + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_LE_L2_final_structure_index_writer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 240 + code: |- + #!/usr/bin/env python3 + # Task_C_LE_L2_final_structure_index_writer (v1) + # 1) 게이트·정책·의미 검사 -> 2) bundle·handoff·원본 적재 -> + # 3) 보존 등식 셋(바깥 수 직접 계수) -> 4) 역인덱스 셋 -> + # 5) 닫힌 스키마 검증 -> 6) 기록·재읽기 -> 7) handoff FINALIZED + import contextlib + import hashlib + import io + import itertools + import json + import pathlib + import sys + + import httpx + + TASK_NAME = "Task_C_LE_L2_final_structure_index_writer" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + RT = pathlib.Path(EXECUTION_ROOT) / "_rt" + + MODULE_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + } + MODULES = ["runtime_common", "schema_subset_validator"] + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + + POLICY = "Default_Agent/stage1_runtime/structure_index_policy.v1.json" + POLICY_SCHEMA_VERSION = "stage1_structure_index_policy.v1" + INDEX_SCHEMA = "Default_Agent/platform/schemas/legal_effect_structures.schema.json" + REGISTRY_INDEX = "Default_Agent/domains/_registry_index.json" + + BUNDLE_PATH = "stage1_tmp/task_le/structure_seed_bundle.json" + HANDOFF_PATH = "quality_gates/stage1_part3_review_handoff.json" + ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" + SG13_PATH = "signals/legal_effect_routes.json" + BO_PATH = "BO.json" + TARGET_PATH = "legal_effect_structures.json" + + PART3_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + + _MANIFEST_MAP = None + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART3_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART3_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical): + body = read_raw(logical) + want = _manifest_map().get(logical[len(ASSET_ROOT):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != sha_text(body): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + def materialize_modules(): + RT.mkdir(parents=True, exist_ok=True) + expected = _manifest_map() + staged = [] + for name in MODULES: + logical = MODULE_MIRRORS[name] + raw = read_raw(logical).encode("utf-8") + want = expected.get(logical[len(ASSET_ROOT):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (RT / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(RT) not in sys.path: + sys.path.insert(0, str(RT)) + return staged + + + def assert_index_schema_capability(index_schema): + # 의미 검사(자기 스키마) — by_module · by_bo_id 를 아는가(PART3_INDEX_SCHEMA_STALE). + index_props = (((index_schema.get("properties") or {}) + .get("structure_index") or {}).get("properties") or {}) + missing = [key for key in ("by_module", "by_bo_id") if key not in index_props] + if missing: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_INDEX_SCHEMA_STALE", + "message": "색인 스키마가 by_module·by_bo_id 를 모른다. " + "배포 원본의 legal_effect_structures.schema.json 이 개정 전 판본이다.", + "missing": missing, "remedy": PART3_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + def main(): + staged = materialize_modules() + import schema_subset_validator + + policy = json.loads(_verify_asset(POLICY)) + if policy.get("schema_version") != POLICY_SCHEMA_VERSION: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_POLICY_INVALID", + "expected": POLICY_SCHEMA_VERSION, + "actual": policy.get("schema_version")}, ensure_ascii=False)) + index_schema = json.loads(_verify_asset(INDEX_SCHEMA)) + assert_index_schema_capability(index_schema) + + # 입력은 전부 파일 계약. 판정 파일은 없다(L1 부재 — §4.1). + bundle_doc = read_json(BUNDLE_PATH) + bundle = bundle_doc.get("structure_seed_bundle", bundle_doc) + records = [row for row in (bundle.get("structure_records") or []) + if isinstance(row, dict)] + handoff_doc = read_json(HANDOFF_PATH) + handoff = handoff_doc.get("stage1_part3_review_handoff", handoff_doc) + activation_doc = read_json(ACTIVATION_MANIFEST) + activation_root = activation_doc.get("domain_activation_manifest", activation_doc) + expected_runnable = [d for d in (activation_root.get("expected_runnable_domain_ids") or []) + if isinstance(d, str)] + # ------------------------------------------------------------------ + # 보존 등식 셋 — 바깥 수를 원본에서 직접 센다. + # ------------------------------------------------------------------ + # (1) 선언 보존 — Σ(expected_runnable 도메인의 structure_types 개수). + # domain_config 무결성은 SG-01 봉인 -> _registry_index -> config_sha256 사슬 재사용. + index_raw = read_raw(REGISTRY_INDEX) + if activation_root.get("registry_index_sha256") != sha_text(index_raw): + raise RuntimeError(json.dumps({ + "reason_code": "PART3_REGISTRY_INDEX_SEAL_FAILED", + "stage": "L2"}, ensure_ascii=False)) + registry_index = json.loads(index_raw) + index_root = registry_index.get("domain_registry_index", registry_index) + config_sha = {row.get("domain_id"): row.get("config_sha256") + for row in (index_root.get("entries") or []) if isinstance(row, dict)} + declared_total = 0 + for domain_id in expected_runnable: + raw = read_raw("Default_Agent/domains/%s/domain_config.json" % domain_id) + if config_sha.get(domain_id) and sha_text(raw) != config_sha[domain_id]: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_REGISTRY_INDEX_SEAL_FAILED", + "detail": "config_sha256", "domain_id": domain_id}, ensure_ascii=False)) + config = json.loads(raw) + config_root = config.get("domain_config", config) + declared_total += len([row for row in (config_root.get("structure_types") or []) + if isinstance(row, dict)]) + declaration_pass = (len(records) == declared_total) + + # (2) 근거 보존 — SG-13 원본에서 legal_effect_route 총수를 직접 센다. + # 붙은 route 는 레코드에서 재계수한다(bundle counts 를 믿지 않는다). + sg13_doc = read_json(SG13_PATH) + sg13_total = len([row for row in (sg13_doc.get("records") or []) + if isinstance(row, dict) + and row.get("record_type") == "legal_effect_route"]) + attached_signal_ids = set() + for record in records: + for ref in record.get("routes") or []: + if isinstance(ref, dict) and isinstance(ref.get("signal_id"), str): + attached_signal_ids.add(ref["signal_id"]) + routes_unattached = len(bundle.get("unattached_routes") or []) + route_pass = (len(attached_signal_ids) + routes_unattached == sg13_total) + + # (3) BO 보존 — BO.json 원본에서 총수를 직접 센다. + bo_doc = read_json(BO_PATH) + bo_total = len(bo_doc) if isinstance(bo_doc, list) else 0 + attached_bo = set() + for record in records: + for bo_id in record.get("source_bo_ids") or []: + if isinstance(bo_id, str): + attached_bo.add(bo_id) + bo_unattached = len(bundle.get("unattached_bo") or []) + bo_pass = (len(attached_bo) + bo_unattached == bo_total) + + failures = [] + if not declaration_pass: + failures.append({"reason_code": "PART3_STRUCTURE_COUNT_BROKEN", + "records": len(records), "declared_total": declared_total}) + if not route_pass: + failures.append({"reason_code": "PART3_ROUTE_CONSERVATION_BROKEN", + "attached": len(attached_signal_ids), + "unattached": routes_unattached, "sg13_total": sg13_total}) + if not bo_pass: + failures.append({"reason_code": "PART3_BO_CONSERVATION_BROKEN", + "attached": len(attached_bo), + "unattached": bo_unattached, "bo_total": bo_total}) + if failures: + raise RuntimeError(json.dumps({"conservation_failures": failures}, + ensure_ascii=False)) + + # ------------------------------------------------------------------ + # 역인덱스 셋 — ID 목록만 담는다. 본문을 복제하지 않는다. + # ------------------------------------------------------------------ + by_domain_id = {} + by_module = {} + by_bo_id = {} + for record in records: + structure_id = record.get("structure_id") + by_domain_id.setdefault(record.get("domain_id"), []).append(structure_id) + if record.get("module"): + by_module.setdefault(record["module"], []).append(structure_id) + for bo_id in record.get("source_bo_ids") or []: + by_bo_id.setdefault(bo_id, []).append(structure_id) + for index in (by_domain_id, by_module, by_bo_id): + for key in index: + index[key] = sorted(set(index[key])) + + # 검토 재산정 — handoff 항목을 코드·심각도로 묶는다. review 는 근거 없이 줄지 않는다. + review_queue = [] + queue_keys = {} + for item in handoff.get("review_items") or []: + if not isinstance(item, dict): + continue + key = (item.get("review_code"), item.get("severity")) + if key in queue_keys: + queue_keys[key]["count"] += 1 + else: + row = {"review_code": key[0], "severity": key[1] or "SOFT_WARNING", + "count": 1} + queue_keys[key] = row + review_queue.append(row) + review_queue.sort(key=lambda row: (row["review_code"], row["severity"])) + status = "READY_WITH_REVIEW" if (review_queue or any( + record.get("review_required") for record in records)) else "READY" + + final_doc = { + "schema_version": "stage1_legal_effect_structures.v1", + "status": status, + "registry_version": bundle.get("registry_version"), + "registry_index_sha256": sha_text(index_raw), + "activation_manifest_sha256": sha_text(read_raw(ACTIVATION_MANIFEST)), + "signal_manifest_transaction_id": bundle.get("signal_manifest_transaction_id"), + "expected_runnable_domain_ids": expected_runnable, + "theta": bundle.get("theta") or [], + "structure_records": records, + "structure_index": {"by_domain_id": by_domain_id, + "by_module": by_module, + "by_bo_id": by_bo_id}, + "quality_gate": { + "declaration_conservation": { + "structure_records": len(records), + "declared_total_from_config": declared_total, + "conservation_pass": declaration_pass, + }, + "route_conservation": { + "routes_attached": len(attached_signal_ids), + "routes_unattached": routes_unattached, + "sg13_route_total_from_source": sg13_total, + "conservation_pass": route_pass, + }, + "bo_conservation": { + "bo_attached": len(attached_bo), + "bo_unattached": bo_unattached, + "bo_total_from_source": bo_total, + "conservation_pass": bo_pass, + }, + "review_queue": review_queue, + }, + "created_by": TASK_NAME, + } + + # 닫힌 스키마 검증 -> 기록 -> 재읽기. + schema_errors = schema_subset_validator.validate(final_doc, index_schema) + if schema_errors: + raise RuntimeError(json.dumps({ + "reason_code": "PART3_FINAL_SCHEMA_VALIDATION_FAILED", + "stage": "L2", "errors": schema_errors[:10]}, ensure_ascii=False)) + text = canonical(final_doc) + write_doc(TARGET_PATH, text) + reread = read_raw(TARGET_PATH) + if sha_text(reread) != sha_text(text): + raise RuntimeError("PART3_WRITE_REREAD_MISMATCH") + + # handoff FINALIZED 갱신(공동 기록자). 항목을 줄이지 않는다. + handoff["status"] = "FINALIZED" + handoff["finalized_by"] = TASK_NAME + write_doc(HANDOFF_PATH, canonical({"stage1_part3_review_handoff": handoff})) + + return {"status": status, "modules": staged, + "structure_record_count": len(records), + "theta_count": len(bundle.get("theta") or []), + "index_bucket_counts": {"by_domain_id": len(by_domain_id), + "by_module": len(by_module), + "by_bo_id": len(by_bo_id)}, + "quality_gate_pass": {"declaration": declaration_pass, + "route": route_pass, "bo": bo_pass}, + "review_queue_count": len(review_queue)} + + + _sink = io.StringIO() + with contextlib.redirect_stdout(_sink): + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + task_procedure: + # L0 → L1(glossary → planner → recommender_* → capture_* → apply) → L2. L0 가 seed bundle 과 handoff 를 내고서야 L1 이 선다. + IN: + nexts: ["Task_C_LE_L0_structure_seed_reducer"] + wait_until: [] + + Task_C_LE_L0_structure_seed_reducer: + nexts: ["Task_C_LE_L1_glossary", "Task_C_LE_L1_candidate_planner"] + wait_until: ["IN"] + + # L1 = 후보 유형 추천기(JEV) — 2026-11-05 개정전략서_part_3_v2_with_part_1_2.md §2.1. + # planner 는 fan-out 부모이고 raise 하지 않는다. planner→apply 직접 간선은 wildcard 확장 전에 + # all capture_* 가 공집합으로 풀려 apply 가 planner 보다 먼저 서는 일을 막는다(Part 1 B1 quality gate 선례, 프로브 P-3). + # 빈 fan-out 이면 all 장벽이 바로 풀리고 apply 는 요청 파일을 보고 통과만 한다. + # glossary(11-05 오후) — L0 번들을 읽어 정의표 초안을 낸다. planner 는 L0 와 glossary 를 함께 기다려 + # prev 에 두 결과를 받는다. glossary 가 실패해도 planner 는 돈다(정의 없이 식별자만). + Task_C_LE_L1_glossary: + nexts: ["Task_C_LE_L1_candidate_planner"] + wait_until: ["Task_C_LE_L0_structure_seed_reducer"] + + Task_C_LE_L1_candidate_planner: + nexts: ["Task_C_LE_L1_recommender_*", "Task_C_LE_L1_apply"] + wait_until: ["Task_C_LE_L0_structure_seed_reducer", "Task_C_LE_L1_glossary"] + + Task_C_LE_L1_recommender_*: + nexts: ["Task_C_LE_L1_capture_{same_ordinal}"] + wait_until: ["Task_C_LE_L1_candidate_planner"] + + # jev 인스턴스가 실패해도 이벤트는 set 되어 capture 가 FAILED 표식을 쓰고 이어진다(프로브 P-2). + Task_C_LE_L1_capture_*: + nexts: ["Task_C_LE_L1_apply"] + wait_until: ["Task_C_LE_L1_recommender_{same_ordinal}"] + + Task_C_LE_L1_apply: + nexts: ["Task_C_LE_L2_final_structure_index_writer"] + wait_until: ["Task_C_LE_L1_candidate_planner", "all Task_C_LE_L1_capture_*"] + + Task_C_LE_L2_final_structure_index_writer: + nexts: ["OUT"] + wait_until: ["Task_C_LE_L1_apply"] + + OUT: + nexts: [] + wait_until: ["Task_C_LE_L2_final_structure_index_writer"] + + prevs: [] + nexts: [] diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8.yml index 5dc42c69..c6507249 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8.yml +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8.yml @@ -5,8 +5,9 @@ # 전략 : stage_1_part_4_개정전략서.md (§2 설계 결정 · §4 소작업 · §6 자산 · §7 검증) · 개정전략서_part_4_v.3.md # 상위 계약 : stage_1_part_1_v.8.yml · stage_1_part_2_v.8.yml · stage_1_part_3_v.8.yml 실산출 # 진입 계약 : signals/signal_manifest.json (downstream_read_sets.part4_F0 = -# SG-04 · SG-06 · SG-07 · SG-10 · SG-11) + SG-01 + BO.json +# SG-04 · SG-07 · SG-11) + SG-01 + BO.json # + legal_effect_structures.json + 도메인 봉투 + P2 review handoff +# + P3 review handoff · part3_receipt.json · value_facts_party_links.json (11-05) # # 구성 — task 3종 (완전 직렬 · fan-out 없음) # [신설] Task_C_FL_F0_fact_ledger_reducer 행 생성 · 조인 · 게이트 · 예외 pack @@ -29,6 +30,23 @@ # F0 판정 파일을 PENDING 으로 덮어써 지난 회차 판정을 지운다 # F1 SELECT_AMOUNT 는 후보 value_id 만 고른다. patch_field 없음. blocked_review_items 는 늘 [] # F2 adjudication_outcome — 판정 이상은 UNRESOLVED 표시와 CALCULATION_BASIS_CONFLICT_REVIEW 로 내린다. 멈추지 않는다 +# +# 2026-11-05 일치성 해결법 적용 (작업간일치성보고서_해결법_part_4_on_part_1_to_3.md) +# P4-06 Part 2 투영 메모의 source_review_code 를 null 로, 칸 이름은 source_field 로(Part 2 YAML) +# P4-07 F0 이 BO.json sha256·행 수를 part3_receipt.json bo_input 과 대조한다. 어긋나면 멈춘다 +# P4-08 투영 행 0 인 게이트 발화는 GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW 로, domain_id·blocks_final_drafting 을 싣는다(compiler) +# S2_20 은 차단 게이트를 blocks_final_drafting 으로도 세어 HARD 는 1등급 그대로다. 비차단(SOFT) 무행 경보는 +# GATE_FIRED_REVIEW 의 3등급 대신 Stage 1 SOFT 기본 4등급이 된다 — 사실 행 없는 비차단 경보라 수용한다 +# 입력 결손 receipt bo_input·P3 handoff 부재, BOUND 인데 연결표가 다른 판이면 handoff SOFT 검토(detail=경로) +# 자산 fact_ledger_policy — parties·calculation_request_key 계약 문구 +# P4-02 PART3_BO_ATTACHED_BY_RECOMMENDER 는 P3 handoff 의 (domain_id, attached_type_id, bo_id) 레코드·행에만 옮긴다(compiler + F0) +# LES 레코드 스키마가 닫혀 있어 Part 3 에 새 키를 두지 않고, L2 가 같은 회차에 확정한 P3 handoff 를 읽는다 +# P4-03 계산 요청의 유일 키는 request_id 다. 행 목록은 관련성 표시다. writer report 에 고유 기준 수치를 둔다 +# P4-04 SG-06·SG-10 은 읽지 않는다. S2_00 이 신호 전부를 직접 읽는다(signal_compiler part4_F0 동시 개정) +# P4-01 parties 는 BO value_refs 의 금액 연결 당사자(value_facts_party_links RESOLVED, client_goal 정규명)다 +# 연결표의 value_facts_sha256 이 P2 handoff value_facts_binding 과 같을 때만 쓴다 +# 빈 배열 = 금액 연결 당사자 없음. Performer·Subject 는 Part 2 가 채우지 않는 칸이라 쓰지 않는다 +# 자산 fact_ledger_compiler·signal_compiler (.py·.txt)·fact_ledger_policy → runtime_manifest 재봉인 # 복구 안내를 Part 2·3 문구로 맞춘다(삭제 동기화 금지) # base 스키마와 writer report blocked_review_items 빈 배열은 S2_00 고정값이라 바꾸지 않는다 # @@ -218,9 +236,7 @@ Agent: # 사건 산출물 — Part 1·2·3 이 낸 것만 읽는다. 구 signal 3종 뿌리 이름은 읽지 않는다. SIGNAL_MANIFEST = "signals/signal_manifest.json" SG04_PATH = "signals/governing_law_version_signals.json" - SG06_PATH = "signals/timeline_notice_condition_signals.json" SG07_PATH = "signals/asset_right_state_signals.json" - SG10_PATH = "signals/evidence_proof_conflict_signals.json" SG11_PATH = "signals/calculation_requirements.json" DOMAIN_SIGNAL_DIR = "signals/domain_signals" ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" @@ -228,6 +244,11 @@ Agent: LES_PATH = "legal_effect_structures.json" P2_HANDOFF_PATH = "quality_gates/stage1_part2_review_handoff.json" EVIDENCE_PATH = "evidence_indexed.json" + P3_HANDOFF_PATH = "quality_gates/stage1_part3_review_handoff.json" + P3_RECEIPT_PATH = "validation_assets/routing/part3_receipt.json" + PARTY_LINKS_PATH = "value_facts_party_links.json" + # 구조 레코드에 달리지만 실제로는 특정 BO 를 가리키는 Part 3 코드(P4-02). + BO_SCOPED_P3_CODES = ("PART3_BO_ATTACHED_BY_RECOMMENDER",) # 산출 BUNDLE_PATH = "stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json" @@ -517,9 +538,7 @@ Agent: signal_documents = { "SG-04": read_json(SG04_PATH), - "SG-06": read_json(SG06_PATH), "SG-07": read_json(SG07_PATH), - "SG-10": read_json(SG10_PATH), "SG-11": read_json(SG11_PATH), } @@ -541,13 +560,63 @@ Agent: warn("P2_HANDOFF_ABSENT", P2_HANDOFF_PATH) p2_handoff = {} - bo_doc = read_json(BO_PATH) + bo_raw = read_raw(BO_PATH) + try: + bo_doc = json.loads(bo_raw.strip()) + except json.JSONDecodeError: + bo_doc, _ = json.JSONDecoder().raw_decode(bo_raw.strip()) + input_gap_reviews = [] bo_records = bo_doc if isinstance(bo_doc, list) else [] + # P4-07 — BO 회차 봉인. Part 3 이 읽은 BO 와 같은 원문이어야 by_bo_id 조인이 맞다. + try: + bo_input = read_json(P3_RECEIPT_PATH).get("bo_input") or {} + except Exception: + bo_input = {} + if not bo_input: + warn("PART4_BO_SEAL_UNCHECKED_REVIEW", P3_RECEIPT_PATH) + input_gap_reviews.append(("PART4_BO_SEAL_UNCHECKED_REVIEW", P3_RECEIPT_PATH)) + if bo_input and (bo_input.get("sha256") != sha_text(bo_raw) + or bo_input.get("record_count") != len(bo_records)): + raise RuntimeError(json.dumps({ + "reason_code": "PART4_BO_SEAL_MISMATCH", + "expected": {"sha256": bo_input.get("sha256"), + "record_count": bo_input.get("record_count")}, + "actual": {"sha256": sha_text(bo_raw), "record_count": len(bo_records)}, + }, ensure_ascii=False)) + bo_seal = "MATCHED" if bo_input else "UNCHECKED_REVIEW" try: evidence_doc = read_json(EVIDENCE_PATH) except Exception: warn("EVIDENCE_INDEXED_ABSENT", EVIDENCE_PATH) evidence_doc = {} + # P4-02 — BO 단위 Part 3 코드. 부재면 None(구조 단위 그대로). + try: + p3_handoff = read_json(P3_HANDOFF_PATH) + p3_items = (p3_handoff.get("stage1_part3_review_handoff", p3_handoff) + .get("review_items") or []) + bo_scoped_codes = {code: {(i.get("domain_id"), i.get("attached_type_id"), i.get("bo_id")) + for i in p3_items + if isinstance(i, dict) and i.get("review_code") == code} + for code in BO_SCOPED_P3_CODES} + except Exception: + warn("P3_HANDOFF_ABSENT_REVIEW", P3_HANDOFF_PATH) + input_gap_reviews.append(("P3_HANDOFF_ABSENT_REVIEW", P3_HANDOFF_PATH)) + bo_scoped_codes = None + # P4-01 — 금액 연결 당사자. Part 2 가 BO value_refs 에 묶은 value_facts 와 같은 판일 때만 쓴다. + # 부재·불일치면 parties 는 빈 배열. + binding = (p2_handoff.get("stage1_part2_review_handoff", p2_handoff) + .get("value_facts_binding") or {}) + try: + party_links = read_json(PARTY_LINKS_PATH) + except Exception: + party_links = {} + if not (binding.get("status") == "BOUND" + and party_links.get("value_facts_sha256") == binding.get("value_facts_sha256")): + if binding.get("status") == "BOUND": + # 금액이 묶였는데 연결표가 다른 판이면 parties 가 조용히 비지 않게 검토로 남긴다. + warn("VALUE_FACTS_PARTY_LINKS_STALE_REVIEW", PARTY_LINKS_PATH) + input_gap_reviews.append(("VALUE_FACTS_PARTY_LINKS_STALE_REVIEW", PARTY_LINKS_PATH)) + party_links = {} # 6) 모듈 호출 — 판정 규칙을 이 파일에 쓰지 않는다. try: @@ -555,7 +624,9 @@ Agent: bo_records, les_root, signal_documents, domain_envelopes, p2_handoff, evidence_doc, registry_index, domain_configs, gate_sidecars, structure_type_sidecars, activation_doc, - alias_declarations, policy) + alias_declarations, policy, + party_links_document=party_links, + bo_scoped_review_codes=bo_scoped_codes) except TypeError as exc: raise RuntimeError(json.dumps({ "reason_code": "PART4_COMPILER_STALE", "detail": "signature_mismatch", @@ -565,7 +636,9 @@ Agent: bundle = result["fact_ledger_candidate_bundle"] pack = result["fact_exception_pack"] - review_items = result["review_items"] + review_items = result["review_items"] + [ + {"review_code": code, "severity": "SOFT_WARNING", "detail": path} + for code, path in input_gap_reviews] audit = result["audit"] # 진입 봉인의 거래 식별자를 bundle 에 부착한다 — F2 는 signal_manifest 를 # 다시 읽지 않고 이 값을 승계한다. @@ -621,6 +694,7 @@ Agent: "registry_index_sha256": registry_index_sha, "config_sha256_chain_checked": len(domain_configs), "les_transaction_seal": les_seal, + "bo_input_seal": bo_seal, }, "gate_execution": { "declared": counts.get("gates_declared"), @@ -1178,10 +1252,16 @@ Agent: for domain_id in (row.get("domain_effects") or {}): effect_coverage[domain_id] = effect_coverage.get(domain_id, 0) + 1 readiness = {} + unique_requests = {} for row in rows: for req in (row.get("calculation_requests") or []): state = str(req.get("operand_state")) readiness[state] = readiness.get(state, 0) + 1 + unique_requests.setdefault(req.get("request_id"), state) + # P4-03 — 행 목록은 관련성 표시라 같은 요청이 여러 행에 있다. 계산·합산은 request_id 고유 기준이다. + readiness_unique = {} + for state in unique_requests.values(): + readiness_unique[state] = readiness_unique.get(state, 0) + 1 # S2_00 은 blocked_review_items 항목 하나로 회차를 멈춘다. 값 갈림은 멈춤이 아니라 표시이므로 # 그 키를 비워 두고 review 로 남긴다. F2 재실행에도 건수가 늘지 않게 먼저 걷어 낸다. handoff["review_items"] = [ @@ -1203,6 +1283,9 @@ Agent: "gate_firings": gate_report.get("fired_by_domain") or {}, "domain_effect_coverage": effect_coverage, "calculation_readiness": readiness, + "calculation_request_key": "request_id", + "calculation_request_unique_count": len(unique_requests), + "calculation_readiness_unique": readiness_unique, "amount_basis_selected": selected, "unresolved_amount_exceptions": unresolved, "blocked_review_items": [], diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8_11_05_5_22pm.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8_11_05_5_22pm.yml new file mode 100644 index 00000000..5dc42c69 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8_11_05_5_22pm.yml @@ -0,0 +1,1265 @@ +# ============================================================================= +# Liti-agent Stage 1 Part 4 v.8 — 사실원장(Fact Ledger) · 통합 실행본 +# +# 정본 근거 +# 전략 : stage_1_part_4_개정전략서.md (§2 설계 결정 · §4 소작업 · §6 자산 · §7 검증) · 개정전략서_part_4_v.3.md +# 상위 계약 : stage_1_part_1_v.8.yml · stage_1_part_2_v.8.yml · stage_1_part_3_v.8.yml 실산출 +# 진입 계약 : signals/signal_manifest.json (downstream_read_sets.part4_F0 = +# SG-04 · SG-06 · SG-07 · SG-10 · SG-11) + SG-01 + BO.json +# + legal_effect_structures.json + 도메인 봉투 + P2 review handoff +# +# 구성 — task 3종 (완전 직렬 · fan-out 없음) +# [신설] Task_C_FL_F0_fact_ledger_reducer 행 생성 · 조인 · 게이트 · 예외 pack +# [개정] Task_C_FL_F1_fact_exception_adjudicator LLM 판정 (유일 생존 부류 1종, 금액 불변) +# [신설] Task_C_FL_F2_final_fact_ledger_gate_and_writer 판정 표시 · 보존 등식 5 · 최종 기록 +# +# 확정 계약 +# 행 BO 1건 = 1행 · fact_id = F-{idx:03d} 1-기반 연속(경성 단언) +# 행 스키마 구 27키(이름·순서 불변) + domain_effects · calculation_requests = 29키 +# 게이트 사이드카 25 배포본을 17축 정규화 리더로 읽는다 — 판정식 창작 0 +# 구현 25(dict 3부류) · 가시화 96(str 90 + boundary 6) · 고아 6 검토 +# operand_state Part 2 산출을 승계한다 — 재산정 금지(D-P4-6) +# 최종 산출 Fact_Ledger_base.json (래핑 없는 배열) +# 로직 거처 stage1_runtime/fact_ledger_compiler.py · 규칙은 fact_ledger_policy.v1.json +# +# 2026-11-01 Part 4 금액 표시 개정 (개정전략서_part_4_v.3.md M2~M5, 상류 M1 은 Part 2) +# 금액 본체는 언제나 BO 값이다. 값 갈림과 관련 값은 amount 문자열의 표시로 S2_10 까지 간다. +# 자산 fact_ledger_compiler — amount 에 conflict·related_values, 값 갈림 행 예외, 미부착 SG-11·게이트 발화 review +# fact_ledger_policy — 표시 문구, patch·coverage·판정 파일 부재 경성 실패 제거. runtime_manifest 3행 재봉인 +# F0 판정 파일을 PENDING 으로 덮어써 지난 회차 판정을 지운다 +# F1 SELECT_AMOUNT 는 후보 value_id 만 고른다. patch_field 없음. blocked_review_items 는 늘 [] +# F2 adjudication_outcome — 판정 이상은 UNRESOLVED 표시와 CALCULATION_BASIS_CONFLICT_REVIEW 로 내린다. 멈추지 않는다 +# 복구 안내를 Part 2·3 문구로 맞춘다(삭제 동기화 금지) +# base 스키마와 writer report blocked_review_items 빈 배열은 S2_00 고정값이라 바꾸지 않는다 +# +# 제약 1 — 구 Part 4 명세의 어떤 파일도 읽지 않는다. 구 signal 3종 뿌리 이름을 읽지 않는다. +# 137종 — 사건 이름·도메인 목록·유형 열거를 코드에 두지 않는다. +# 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. +# ============================================================================= +--- +Agent: + name: Liti-agent_Civil_Suit_Plaintiff_Stage_1_Part_4 + description: 민사소송 원고 송무 초지능 AI변호사 - Stage 1 Part 4 + version: v.2 + Stages: + - name: stage1_사실원장_생성 + description: 사실원장 생성, 게이트 실행, 최종 기록 + llm_provider: openai + llm_model: gpt-4o-2024-08-06 + tools: + mcpServers: + localdocs: + type: streamable-http + url: http://mcp-localdocs:8012/mcp + description: Get the content of local documents + code-executor: + type: streamable-http + url: https://code-executor.mcp.eroomai.com/mcp + description: Run scripts of programming languages + headers: + Authorization: Bearer rR8OXqWrVZA1gFEo8oWfBkw2XgpWoGrrspw5ObsxTCM= + tasks: + - task_name: Task_C_FL_F0_fact_ledger_reducer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 300 + code: |- + #!/usr/bin/env python3 + # Task_C_FL_F0_fact_ledger_reducer (v1) + # 0) 배포 게이트 -> 1) 모듈 5종 반입 -> 2) 정책 반입 -> 3) 의미 검사 둘 -> + # 4) 진입 봉인 셋 -> 5) 입력 적재 -> 6) compile_fact_ledger_candidates -> + # 7) bundle · exception pack · review handoff(OPEN) · receipt 기록 + import contextlib + import hashlib + import io + import itertools + import json + import pathlib + import re + import sys + + import httpx + + # ------------------------------------------------------------------ + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) — Part 3 L0 검증 완료본 복사. + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # ------------------------------------------------------------------ + TASK_NAME = "Task_C_FL_F0_fact_ledger_reducer" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 재직렬화 없이 원문 그대로. 봉인·미러 해시 대조의 전제다. + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def try_read_json(name): + try: + return read_json(name) + except Exception: + return None + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + # ------------------------------------------------------------------ + # 실행 뿌리 — /tmp/s1 공유(Part 3 규율. 새 뿌리를 만들지 않는다). + # ------------------------------------------------------------------ + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + RT = pathlib.Path(EXECUTION_ROOT) / "_rt" + + MODULE_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "registry_loader": "Default_Agent/stage1_runtime/registry_loader.txt", + "structure_index_compiler": "Default_Agent/stage1_runtime/structure_index_compiler.txt", + "fact_ledger_compiler": "Default_Agent/stage1_runtime/fact_ledger_compiler.txt", + } + MODULES = ["runtime_common", "schema_subset_validator", "registry_loader", + "structure_index_compiler", "fact_ledger_compiler"] + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + RUNTIME_MANIFEST_SCHEMA = "stage1_runtime_manifest.v1" + + # 정적 자산 + REGISTRY_INDEX = "Default_Agent/domains/_registry_index.json" + POLICY = "Default_Agent/stage1_runtime/fact_ledger_policy.v1.json" + POLICY_SCHEMA_VERSION = "stage1_fact_ledger_policy.v1" + ALIAS_DECLARATIONS = "Default_Agent/routing/extension_payload_key_declarations.v1.json" + BUNDLE_SCHEMA = "Default_Agent/platform/schemas/fact_ledger_candidate_bundle.schema.json" + BASE_SCHEMA = "Default_Agent/platform/schemas/fact_ledger_base.schema.json" + PACK_SCHEMA = "Default_Agent/platform/schemas/fact_exception_pack.schema.json" + LES_SCHEMA = "Default_Agent/platform/schemas/legal_effect_structures.schema.json" + + # 사건 산출물 — Part 1·2·3 이 낸 것만 읽는다. 구 signal 3종 뿌리 이름은 읽지 않는다. + SIGNAL_MANIFEST = "signals/signal_manifest.json" + SG04_PATH = "signals/governing_law_version_signals.json" + SG06_PATH = "signals/timeline_notice_condition_signals.json" + SG07_PATH = "signals/asset_right_state_signals.json" + SG10_PATH = "signals/evidence_proof_conflict_signals.json" + SG11_PATH = "signals/calculation_requirements.json" + DOMAIN_SIGNAL_DIR = "signals/domain_signals" + ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" + BO_PATH = "BO.json" + LES_PATH = "legal_effect_structures.json" + P2_HANDOFF_PATH = "quality_gates/stage1_part2_review_handoff.json" + EVIDENCE_PATH = "evidence_indexed.json" + + # 산출 + BUNDLE_PATH = "stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json" + PACK_PATH = "stage1_tmp/fact_ledger/fact_exception_pack.json" + ADJUDICATION_PATH = "stage1_tmp/fact_ledger/fact_adjudication.json" + HANDOFF_PATH = "quality_gates/stage1_part4_review_handoff.json" + RECEIPT_PATH = "validation_assets/routing/part4_receipt.json" + + # 배포 게이트가 한 벌로 검사하는 필수 자산 13 리터럴 (전략서 §4.1⓪). + # 사이드카 25 · SG 스키마 · 봉투 스키마는 여기 넣지 않는다 — expected_runnable + # 것만 읽는 시점에 _verify_asset 이 지킨다(Part 3 규율). + PART4_REQUIRED_ASSETS = ( + BUNDLE_SCHEMA, + BASE_SCHEMA, + PACK_SCHEMA, + LES_SCHEMA, + POLICY, + ALIAS_DECLARATIONS, + "Default_Agent/signals/signal_registry.v2.json", + "Default_Agent/contracts/signals/s5_execution_contract.v2.json", + "Default_Agent/stage1_runtime/runtime_common.txt", + "Default_Agent/stage1_runtime/schema_subset_validator.txt", + "Default_Agent/stage1_runtime/registry_loader.txt", + "Default_Agent/stage1_runtime/structure_index_compiler.txt", + "Default_Agent/stage1_runtime/fact_ledger_compiler.txt", + ) + PART4_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + + TRANSACTION_ID_RE = re.compile(r"^S5TX-[a-f0-9]{20}$") + + ERRORS = [] + WARNINGS = [] + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + # ------------------------------------------------------------------ + # 0) 배포 게이트 — 등재·sha256·가독을 한 벌로. 첫 실패에서 멈추지 않고 모은다. + # ------------------------------------------------------------------ + def assert_deployment(): + manifest = json.loads(read_raw(RUNTIME_MANIFEST)) + if manifest.get("schema_version") != RUNTIME_MANIFEST_SCHEMA: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_RUNTIME_MANIFEST_INVALID", "detail": "schema_version", + "expected": RUNTIME_MANIFEST_SCHEMA, "actual": manifest.get("schema_version"), + }, ensure_ascii=False)) + expected = {row["path"]: row["sha256"] + for row in (manifest.get("entries") or []) if isinstance(row, dict)} + unregistered, mismatch, unreadable = [], [], [] + for logical in sorted(set(list(MODULE_MIRRORS.values()) + list(PART4_REQUIRED_ASSETS))): + rel = logical[len(ASSET_ROOT):] + want = expected.get(rel) + if want is None: + unregistered.append(rel) + try: + body = read_raw(logical) + except Exception: + unreadable.append(rel) + continue + if want is not None and want != sha_text(body): + mismatch.append({"path": rel, "expected": want, "actual": sha_text(body)}) + if unregistered or mismatch or unreadable: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_ASSET_DEPLOYMENT_INCOMPLETE", + "message": "배포 원본에 Part 4 자산이 한 벌로 반영되지 않았다.", + "unregistered": unregistered, "hash_mismatch": mismatch, + "unreadable": unreadable, "remedy": PART4_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + return manifest + + + _MANIFEST_MAP = None + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART4_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART4_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical): + """원문을 돌려준다. 등재·해시 대조를 통과해야만 소비된다.""" + body = read_raw(logical) + want = _manifest_map().get(logical[len(ASSET_ROOT):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != sha_text(body): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + # ------------------------------------------------------------------ + # 1) 모듈 반입 — R-1~R-5. 해시가 어긋나면 실행하지 않는다. + # ------------------------------------------------------------------ + def materialize_modules(): + RT.mkdir(parents=True, exist_ok=True) + expected = _manifest_map() + staged = [] + for name in MODULES: + logical = MODULE_MIRRORS[name] + raw = read_raw(logical).encode("utf-8") + want = expected.get(logical[len(ASSET_ROOT):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (RT / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(RT) not in sys.path: + sys.path.insert(0, str(RT)) + return staged + + + # ------------------------------------------------------------------ + # 3) 의미 검사 둘 — 장부 검사만으로는 닫히지 않는다(Part 2 교훈). + # ------------------------------------------------------------------ + def assert_bundle_schema_capability(bundle_schema): + row_props = (((((bundle_schema.get("properties") or {}) + .get("fact_ledger_candidate_bundle") or {}) + .get("properties") or {}) + .get("rows") or {}).get("items") or {}).get("properties") or {} + missing = [key for key in ("domain_effects", "calculation_requests") + if key not in row_props] + if missing: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LEDGER_SCHEMA_STALE", + "message": "후보 bundle 스키마가 Part 4 계약 필드를 모른다. 배포 원본의 스키마가 개정 전 판본이다.", + "missing": missing, "remedy": PART4_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + def assert_compiler_capability(result): + bundle = (result or {}).get("fact_ledger_candidate_bundle") or {} + rows = bundle.get("rows") + bad = (not isinstance(rows, list) + or "gate_report" not in bundle + or any("domain_effects" not in row for row in rows + if isinstance(row, dict))) + if bad: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_COMPILER_STALE", + "message": "컴파일러 산출에 domain_effects·gate_report 가 실려 나오지 않는다. " + "배포 원본의 fact_ledger_compiler 가 개정 전 판본이다.", + "remedy": PART4_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + # ------------------------------------------------------------------ + # 4) 진입 봉인 셋 (전략서 §4.1④) + # ------------------------------------------------------------------ + def verify_signal_seal(): + doc = read_json(SIGNAL_MANIFEST) + root = doc.get("signal_manifest", doc) if isinstance(doc, dict) else {} + transaction_id = root.get("transaction_id") + if not isinstance(transaction_id, str) or not TRANSACTION_ID_RE.match(transaction_id): + raise RuntimeError(json.dumps({ + "reason_code": "PART4_SIGNAL_SEAL_FAILED", "detail": "transaction_id", + "actual": transaction_id}, ensure_ascii=False)) + checked = 0 + for row in root.get("files") or []: + if not isinstance(row, dict): + continue + # files[].path 에는 signals/ 접두사가 없다. 붙여서 대조한다. + rel = str(row.get("path") or "") + actual = sha_text(read_raw("signals/" + rel)) + if actual != row.get("file_sha256"): + raise RuntimeError(json.dumps({ + "reason_code": "PART4_SIGNAL_SEAL_FAILED", "detail": "file_sha256", + "path": rel, "expected": row.get("file_sha256"), "actual": actual, + }, ensure_ascii=False)) + checked += 1 + return {"transaction_id": transaction_id, "files_checked": checked} + + + def verify_registry_index_seal(activation_root, index_raw): + declared = activation_root.get("registry_index_sha256") + actual = sha_text(index_raw) + if declared != actual: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_REGISTRY_INDEX_SEAL_FAILED", + "declared": declared, "actual": actual}, ensure_ascii=False)) + return actual + + + def verify_les_transaction(les_root, transaction_id): + """두 갈래 — 키가 있고 값이 다르면 경성 실패, 키가 없으면 검토(fail-open).""" + if "signal_manifest_transaction_id" not in les_root: + warn("PART4_LES_TRANSACTION_UNSEALED_REVIEW", + "LES 가 거래 식별자 키 없이 왔다 — 계약상 적법. 검토로 남긴다.") + return "UNSEALED_REVIEW" + value = les_root.get("signal_manifest_transaction_id") + if value != transaction_id: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LES_TRANSACTION_MISMATCH", + "expected": transaction_id, "actual": value}, ensure_ascii=False)) + return "MATCHED" + + + def main(): + gate_manifest = assert_deployment() + staged = materialize_modules() + import fact_ledger_compiler + import schema_subset_validator + + # 2) 정책 반입 — 판본 불일치는 PART4_POLICY_INVALID. + policy = json.loads(_verify_asset(POLICY)) + if policy.get("schema_version") != POLICY_SCHEMA_VERSION: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_POLICY_INVALID", + "expected": POLICY_SCHEMA_VERSION, + "actual": policy.get("schema_version")}, ensure_ascii=False)) + + # 3) 의미 검사 (입력 쪽) + bundle_schema = json.loads(_verify_asset(BUNDLE_SCHEMA)) + assert_bundle_schema_capability(bundle_schema) + + # 4) 진입 봉인 셋 + seal = verify_signal_seal() + activation_doc = read_json(ACTIVATION_MANIFEST) + activation_root = activation_doc.get("domain_activation_manifest", activation_doc) + index_raw = read_raw(REGISTRY_INDEX) + registry_index_sha = verify_registry_index_seal(activation_root, index_raw) + registry_index = json.loads(index_raw) + index_root = registry_index.get("domain_registry_index", registry_index) + les_doc = read_json(LES_PATH) + les_root = les_doc if isinstance(les_doc, dict) else {} + les_seal = verify_les_transaction(les_root, seal["transaction_id"]) + + expected_runnable = [d for d in (activation_root.get("expected_runnable_domain_ids") or []) + if isinstance(d, str)] + + # 5) 입력 적재 + # domain_config 무결성은 SG-01 봉인 -> _registry_index -> config_sha256 사슬. + config_sha = {row.get("domain_id"): row.get("config_sha256") + for row in (index_root.get("entries") or []) if isinstance(row, dict)} + domain_configs = {} + gate_sidecars = {} + structure_type_sidecars = {} + sidecar_gaps = [] + for domain_id in expected_runnable: + raw = read_raw("Default_Agent/domains/%s/domain_config.json" % domain_id) + if config_sha.get(domain_id) and sha_text(raw) != config_sha[domain_id]: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_REGISTRY_INDEX_SEAL_FAILED", + "detail": "config_sha256", "domain_id": domain_id}, ensure_ascii=False)) + domain_configs[domain_id] = json.loads(raw) + try: + gate_sidecars[domain_id] = json.loads(_verify_asset( + "Default_Agent/domains/%s/gates.json" % domain_id)) + except Exception as exc: + # 사이드카 부재·미등재는 컴파일러가 게이트별 + # GATE_SPEC_NOT_DEPLOYED_REVIEW 로 가시화한다. 여기서는 계수만 한다. + sidecar_gaps.append({"domain_id": domain_id, "kind": "gates", + "error": str(exc)[:160]}) + try: + structure_type_sidecars[domain_id] = json.loads(_verify_asset( + "Default_Agent/domains/%s/structure_types.json" % domain_id)) + except Exception as exc: + sidecar_gaps.append({"domain_id": domain_id, "kind": "structure_types", + "error": str(exc)[:160]}) + + alias_declarations = json.loads(_verify_asset(ALIAS_DECLARATIONS)) + + signal_documents = { + "SG-04": read_json(SG04_PATH), + "SG-06": read_json(SG06_PATH), + "SG-07": read_json(SG07_PATH), + "SG-10": read_json(SG10_PATH), + "SG-11": read_json(SG11_PATH), + } + + domain_envelopes = {} + envelope_absent = [] + for domain_id in expected_runnable: + doc = try_read_json("%s/%s.json" % (DOMAIN_SIGNAL_DIR, domain_id)) + if doc is not None: + domain_envelopes[domain_id] = doc + else: + envelope_absent.append(domain_id) + + # P2 handoff · evidence 는 상수 경로를 read_json 에 직접 넘긴다 — + # 선언표 검사기(U4)가 읽기를 코드에서 확인할 수 있는 형태다(Part 3 규율). + # 간접 호출로 감싸면 소비 선언이 실측 불가가 된다. 부재는 try 로 감싸 계수한다. + try: + p2_handoff = read_json(P2_HANDOFF_PATH) + except Exception: + warn("P2_HANDOFF_ABSENT", P2_HANDOFF_PATH) + p2_handoff = {} + + bo_doc = read_json(BO_PATH) + bo_records = bo_doc if isinstance(bo_doc, list) else [] + try: + evidence_doc = read_json(EVIDENCE_PATH) + except Exception: + warn("EVIDENCE_INDEXED_ABSENT", EVIDENCE_PATH) + evidence_doc = {} + + # 6) 모듈 호출 — 판정 규칙을 이 파일에 쓰지 않는다. + try: + result = fact_ledger_compiler.compile_fact_ledger_candidates( + bo_records, les_root, signal_documents, domain_envelopes, + p2_handoff, evidence_doc, registry_index, domain_configs, + gate_sidecars, structure_type_sidecars, activation_doc, + alias_declarations, policy) + except TypeError as exc: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_COMPILER_STALE", "detail": "signature_mismatch", + "signature_error": str(exc)[:200], + "remedy": PART4_DEPLOYMENT_REMEDY}, ensure_ascii=False)) + assert_compiler_capability(result) + + bundle = result["fact_ledger_candidate_bundle"] + pack = result["fact_exception_pack"] + review_items = result["review_items"] + audit = result["audit"] + # 진입 봉인의 거래 식별자를 bundle 에 부착한다 — F2 는 signal_manifest 를 + # 다시 읽지 않고 이 값을 승계한다. + bundle["signal_manifest_transaction_id"] = seal["transaction_id"] + bundle["les_transaction_seal"] = les_seal + bundle["created_by"] = TASK_NAME + + # 자기 산출을 닫힌 스키마로 검증한 뒤에만 기록한다. + schema_errors = schema_subset_validator.validate( + {"fact_ledger_candidate_bundle": bundle}, bundle_schema) + if schema_errors: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LEDGER_SCHEMA_INVALID", + "stage": "F0", "errors": schema_errors[:10]}, ensure_ascii=False)) + pack_schema = json.loads(_verify_asset(PACK_SCHEMA)) + pack_errors = schema_subset_validator.validate( + {"fact_exception_pack": pack}, pack_schema) + if pack_errors: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LEDGER_SCHEMA_INVALID", + "stage": "F0.pack", "errors": pack_errors[:10]}, ensure_ascii=False)) + + # 7) 기록 — bundle · pack · handoff(OPEN) · receipt(실측값. 상수 PASS 금지). + write_doc(BUNDLE_PATH, canonical({"fact_ledger_candidate_bundle": bundle})) + write_doc(PACK_PATH, canonical({"fact_exception_pack": pack})) + # 지난 회차 판정이 남아 쓰이지 않게 비운다. F1 이 못 쓰면 F2 가 UNRESOLVED 로 둔다. + write_doc(ADJUDICATION_PATH, canonical({"fact_exception_adjudication": {"status": "PENDING"}})) + write_doc(HANDOFF_PATH, canonical({"stage1_part4_review_handoff": { + "schema_version": "stage1_part4_review_handoff.v1", + "status": "OPEN", + "review_items": review_items, + "counts": {"review_items": len(review_items)}, + "created_by": TASK_NAME, + }})) + counts = bundle.get("counts") or {} + write_doc(RECEIPT_PATH, canonical({ + "schema_version": "stage1_part4_receipt.v1", + "stage": "P4-F0", + "deployment_gate": { + "checked_count": len(set(list(MODULE_MIRRORS.values()) + + list(PART4_REQUIRED_ASSETS))), + "runtime_manifest_sha256": sha_text(read_raw(RUNTIME_MANIFEST)), + "runtime_artifact_count": gate_manifest.get("runtime_artifact_count"), + "schema_capability_checked": ["rows[].domain_effects", + "rows[].calculation_requests"], + "compiler_output_checked": ["rows[].domain_effects", "gate_report"], + "policy_schema_version": policy.get("schema_version"), + "note": "무엇을 봤는지 적는다. 상수 PASS 는 증거가 아니다.", + }, + "entry_seals": { + "signal_manifest_transaction_id": seal["transaction_id"], + "signal_files_checked": seal["files_checked"], + "registry_index_sha256": registry_index_sha, + "config_sha256_chain_checked": len(domain_configs), + "les_transaction_seal": les_seal, + }, + "gate_execution": { + "declared": counts.get("gates_declared"), + "implemented": counts.get("gates_implemented"), + "visualized_str": counts.get("gates_visualized_str"), + "visualized_unsupported": counts.get("gates_visualized_unsupported"), + "fired": counts.get("gates_fired"), + "orphan_rules": counts.get("orphan_rules"), + "sidecar_dialects": audit.get("sidecar_dialects"), + "input_counts": audit.get("gate_input_counts"), + "note": "선언 존재와 실측 비공백을 따로 적는다(§7.5-4).", + }, + "conservation": counts.get("conservation"), + "envelope_absent_domains": envelope_absent, + "sidecar_gaps": sidecar_gaps, + "evidence_truncation_slack_min": audit.get("evidence_truncation_slack_min"), + "warnings": WARNINGS, + "created_by": TASK_NAME, + })) + + return {"status": bundle.get("status"), + "modules": staged, + "expected_runnable_domain_ids": expected_runnable, + "row_count": len(bundle.get("rows") or []), + "gates": {"declared": counts.get("gates_declared"), + "implemented": counts.get("gates_implemented"), + "fired": counts.get("gates_fired")}, + "exception_count": pack.get("exception_count"), + "review_item_count": len(review_items), + "errors": ERRORS, "warnings": WARNINGS} + + + _sink = io.StringIO() + with contextlib.redirect_stdout(_sink): + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_C_FL_F1_fact_exception_adjudicator + llm_provider: google + llm_model: 'gemini-3.5-flash-lite' + llm_reasoning: low + llm_verbosity: low + max_iterations: 1 + use_tools: + - localdocs + cache_control: + mode: auto + ttl: 20m + preflight: true + preflight_files: + - stage1_tmp/fact_ledger/fact_exception_pack.json + prompts: + - role: user + content: |- + + + - You are executing one LLM sub-task inside Stage 1 of a Korean civil-litigation complaint-generation pipeline. + - The current task's static block, role overlay, assigned inputs, output schema, and writer boundary control. + - This common prefix cannot expand the current task's input set, output set, legal domain, validation authority, writer authority, or reasoning depth. + - If any common rule appears broader than the current task, apply only the narrower current-task version. + - Stage 1 prepares verified structured artifacts. Do not draft complaint prose or final counsel-level conclusions unless the current task explicitly authorizes a validation or gate conclusion. + + + + - Use only assigned files, provided context inputs, prior outputs, and allowed tools. + - Do not import facts, law, procedural history, parties, dates, amounts, IDs, document contents, or source meanings from memory, outside knowledge, or unassigned files. + - Treat prior outputs as authority only to the extent the current task names them or provides them as context. + - If a value is unsupported, missing, conflicting, stale, or out of scope, use only the current schema's allowed null, empty, unknown, warning, blocked, or needs_review path. + + + + - Preserve exact source identifiers required by the current schema. + - Maintain separation among raw fact, inferred fact, legal signal, evidence support, fact support, validation issue, and final gate decision when the current schema distinguishes them. + - Do not upgrade meeting-only or indirect material into direct proof. + - Do not silently resolve material conflicts. If the current schema has a conflict or uncertainty field, use it; otherwise stay within the task's allowed warning or review path. + + + + - Follow required JSON shape, key names, enum values, ordering, file names, and status strings exactly. + - Do not add arbitrary keys, prose, markdown fences, alternative files, unauthorized repair, or explanatory material outside allowed fields. + - Create, mutate, normalize, merge, or finalize IDs only when the current task explicitly authorizes it. + - Write final files only when the current task is the authorized writer. Validators and guards report issues in their own authorized schema and do not silently repair unless instructed. + + + + - Prefer the current prompt and schema, assigned structured upstream artifacts, compact indexes, ledgers, manifests, bundles, and gates. + - Read raw evidence or meeting text only when the current task requires direct provenance, ambiguity resolution, or a schema-required value missing from structured artifacts. + - For map or projection tasks, process only the assigned item, domain, or batch. Reducers aggregate only the inputs assigned to them. + - Do not restate, summarize, cite, or copy this common prefix in any output. + + + + - Return only the requested structured artifact, concise allowed rationale fields, validation notes, or status object. + - Keep chain-of-thought private. + - Stop when the current schema is complete and safe. + + + + + + TASK_NAME: Task_C_FL_F1_fact_exception_adjudicator + STAGE: Part 4 조건부 예외 판정자 (Part 2 R1 패턴 승계) + MISSION: 결정적 reducer(F0)가 pack 에 실은 예외만 판정한다. 유일 생존 부류는 + legal_calculation_required(계산 근거 다중성)다. 병합·최종 파일 작성·사실 창작은 하지 않는다. + + + + - 유일한 입력은 preflight 로 제공된 `stage1_tmp/fact_ledger/fact_exception_pack.json` 이다. + - BO.json, 후보 bundle, 최종 원장, review handoff, signal 파일을 읽거나 쓰지 않는다. + - pack 에 없는 exception_id·fact_id·source_bo_id 를 창작하지 않는다. + - 금액을 계산하지 않는다. 제공된 후보 하나를 고르거나 `BLOCK_REVIEW` 로 남길 뿐이다. + - 출력 파일은 `stage1_tmp/fact_ledger/fact_adjudication.json` 하나뿐이다. + - 도구 호출은 write_file 하나만 허용된다(출력 기록 용도). 다른 read 는 금지된다. + + + + 1. preflight 로 제공된 exception pack 의 `has_exceptions` 를 확인한다. + 2. `has_exceptions == false` 이면: `write_file(overwrite=true)` 로 아래 no-exception 객체를 + `stage1_tmp/fact_ledger/fact_adjudication.json` 에 저장하고 `"NO_EXCEPTIONS"` 만 출력한 뒤 + 즉시 종료한다(terminate). 다른 어떤 파일도 읽지 않는다. + {"fact_exception_adjudication": {"schema_version": "stage1_fact_exception_adjudication.v1", "status": "READY_NO_EXCEPTIONS", "decisions": [], "blocked_review_items": [], "adjudication_gate": {"input_exception_count": 0, "decision_count": 0, "blocked_count": 0}}} + 3. `has_exceptions == true` 이면: 각 exception 을 `compact_payload` 만으로 판정한다. 추가 read 는 금지된다. + 4. 판정 규칙 (부류: legal_calculation_required — 계산 근거 다중성): + - `compact_payload.amount_candidates` 는 값이 갈린 금액 정본 레코드 전부다. BO 금액이 있으면 그 레코드도 들어 있고 + `current_value_id` 가 그것을 가리킨다. BO 금액이 없으면 `current_value_id` 는 null 이다. `legal_calculation_object` 도 null 일 수 있다. + 값이 다른 레코드는 별개 사실일 수 있다. 행 금액은 바뀌지 않는다. 이 BO 의 계산 근거가 무엇인지만 판단한다. + - `action`·`legal_calculation_object`·`object_spec`·`calculation_request_ids` 와 각 후보의 + `item_label`·`value_kind`·`dates`·`value_basis`·`object_label_text` 로 근거가 분명하면 + decision `SELECT_AMOUNT`, `selected_value` 에 그 후보의 `value_id` 를 적는다. 숫자·문구를 쓰지 않는다. + - 우열을 가릴 수 없거나 별개 사실이면 decision `BLOCK_REVIEW`, `selected_value` 는 null 이다(확신 없는 확정 금지). + - exception 마다 decision 을 정확히 하나 쓴다. `blocked_review_items` 는 언제나 `[]` 다. + 5. `write_file(overwrite=true)` 로 결과를 저장한다. root 는 `fact_exception_adjudication` 이며 + schema_version 은 `stage1_fact_exception_adjudication.v1`, status 는 `READY` 다. + decision 객체는 `decisions` 배열에 담는다: {"exception_id", "fact_id", "decision", "selected_value", "rationale"(1문장)}. + adjudication_gate: {"input_exception_count", "decision_count", "blocked_count"}. `blocked_count` 는 `BLOCK_REVIEW` 건수다. + 6. `"F1 예외 판정 완료 (decisions=<건수>)"` 만 출력하고 작업을 끝낸다(terminate). + + + + - exception pack 부재·파싱 불가: 즉시 중단하고 채팅으로만 보고한다. adjudication 파일은 쓰지 않는다. + - tool 오류: 1회만 재시도. 재실패 시 `FAILED: ` 만 보고하고 종료한다. + + + + - task_name: Task_C_FL_F2_final_fact_ledger_gate_and_writer + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 240 + code: |- + #!/usr/bin/env python3 + # Task_C_FL_F2_final_fact_ledger_gate_and_writer (v1) + # 1) 게이트·정책·의미 검사 -> 2) bundle·pack·판정·원본 적재 -> + # 3) 판정을 amount 의 conflict 표시로 반영(금액 불변) -> 4) 보존 등식 다섯(바깥 수 직접 계수) -> + # 5) domain_effects ⊆ 활성 · fact_id 연속 · BO 보존 -> 6) 닫힌 스키마 -> + # 7) 기록·재읽기 -> 8) writer report · handoff FINALIZED + import contextlib + import hashlib + import io + import itertools + import json + import pathlib + import sys + + import httpx + + TASK_NAME = "Task_C_FL_F2_final_fact_ledger_gate_and_writer" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + ASSET_ROOT = "Default_Agent/" + EXECUTION_ROOT = "/tmp/s1" + RT = pathlib.Path(EXECUTION_ROOT) / "_rt" + + MODULE_MIRRORS = { + "runtime_common": "Default_Agent/stage1_runtime/runtime_common.txt", + "schema_subset_validator": "Default_Agent/stage1_runtime/schema_subset_validator.txt", + } + MODULES = ["runtime_common", "schema_subset_validator"] + RUNTIME_MANIFEST = "Default_Agent/runtime_manifest.json" + + POLICY = "Default_Agent/stage1_runtime/fact_ledger_policy.v1.json" + POLICY_SCHEMA_VERSION = "stage1_fact_ledger_policy.v1" + BASE_SCHEMA = "Default_Agent/platform/schemas/fact_ledger_base.schema.json" + + BUNDLE_PATH = "stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json" + PACK_PATH = "stage1_tmp/fact_ledger/fact_exception_pack.json" + ADJUDICATION_PATH = "stage1_tmp/fact_ledger/fact_adjudication.json" + HANDOFF_PATH = "quality_gates/stage1_part4_review_handoff.json" + CONFLICT_REVIEW_CODE = "CALCULATION_BASIS_CONFLICT_REVIEW" + ACTIVATION_MANIFEST = "routing/domain_activation_manifest.json" + BO_PATH = "BO.json" + LES_PATH = "legal_effect_structures.json" + SG11_PATH = "signals/calculation_requirements.json" + TARGET_PATH = "Fact_Ledger_base.json" + REPORT_PATH = "stage1_tmp/fact_ledger/fact_ledger_writer_report.json" + + PART4_DEPLOYMENT_REMEDY = ( + "배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 " + "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.") + + _MANIFEST_MAP = None + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":")) + "\n" + + + def _manifest_map(): + global _MANIFEST_MAP + if _MANIFEST_MAP is None: + _MANIFEST_MAP = {row["path"]: row["sha256"] + for row in (json.loads(read_raw(RUNTIME_MANIFEST)).get("entries") or []) + if isinstance(row, dict)} + return _MANIFEST_MAP + + + def _deployment_error(logical, detail, extra=None): + payload = {"reason_code": "PART4_ASSET_DEPLOYMENT_INCOMPLETE", "path": logical, + "detail": detail, "remedy": PART4_DEPLOYMENT_REMEDY} + if extra: + payload.update(extra) + return RuntimeError(json.dumps(payload, ensure_ascii=False)) + + + def _verify_asset(logical): + body = read_raw(logical) + want = _manifest_map().get(logical[len(ASSET_ROOT):]) + if want is None: + raise _deployment_error(logical, "unregistered") + if want != sha_text(body): + raise _deployment_error(logical, "hash_mismatch", {"expected": want}) + return body + + + def materialize_modules(): + RT.mkdir(parents=True, exist_ok=True) + expected = _manifest_map() + staged = [] + for name in MODULES: + logical = MODULE_MIRRORS[name] + raw = read_raw(logical).encode("utf-8") + want = expected.get(logical[len(ASSET_ROOT):]) + if want is None: + raise RuntimeError("MODULE_MIRROR_UNREGISTERED:%s" % logical) + if want != hashlib.sha256(raw).hexdigest(): + raise RuntimeError("MODULE_MIRROR_HASH_MISMATCH:%s" % logical) + (RT / (name + ".py")).write_bytes(raw) + staged.append(name) + if str(RT) not in sys.path: + sys.path.insert(0, str(RT)) + return staged + + + def assert_base_schema_capability(base_schema): + row_props = ((base_schema.get("items") or {}).get("properties") or {}) + missing = [key for key in ("domain_effects", "calculation_requests") + if key not in row_props] + if missing: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LEDGER_SCHEMA_STALE", + "message": "최종 스키마가 신규 2키를 모른다. 배포 원본의 스키마가 개정 전 판본이다.", + "missing": missing, "remedy": PART4_DEPLOYMENT_REMEDY, + }, ensure_ascii=False)) + + + def adjudication_outcome(item, decisions): + """예외 하나의 (사유, value_id). 금액은 BO 값이 이미 있으므로 LLM 출력 이상으로 멈추지 않는다.""" + if decisions is None: + return "adjudication_unusable", None + same = [d for d in decisions if d.get("exception_id") == item.get("exception_id")] + if not same: + return "no_decision", None + if len(same) > 1: + return "invalid_decision", None + one = same[0] + if one.get("decision") == "BLOCK_REVIEW": + return "block_review", None + value = one.get("selected_value") + values = {c.get("value_id") for c in item["compact_payload"]["amount_candidates"]} + if (one.get("decision") == "SELECT_AMOUNT" and one.get("fact_id") == item.get("fact_id") + and isinstance(value, str) and value in values): + return "selected", value + return "invalid_decision", None + + + def main(): + staged = materialize_modules() + import schema_subset_validator + + policy = json.loads(_verify_asset(POLICY)) + if policy.get("schema_version") != POLICY_SCHEMA_VERSION: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_POLICY_INVALID", + "expected": POLICY_SCHEMA_VERSION, + "actual": policy.get("schema_version")}, ensure_ascii=False)) + base_schema = json.loads(_verify_asset(BASE_SCHEMA)) + assert_base_schema_capability(base_schema) + + # 입력은 전부 파일 계약. 메모리 전달 없음. + bundle_doc = read_json(BUNDLE_PATH) + bundle = bundle_doc.get("fact_ledger_candidate_bundle", bundle_doc) + rows = [row for row in (bundle.get("rows") or []) if isinstance(row, dict)] + pack_doc = read_json(PACK_PATH) + pack = pack_doc.get("fact_exception_pack", pack_doc) + exceptions = [e for e in (pack.get("exceptions") or []) if isinstance(e, dict)] + handoff_doc = read_json(HANDOFF_PATH) + handoff = handoff_doc.get("stage1_part4_review_handoff", handoff_doc) + activation_doc = read_json(ACTIVATION_MANIFEST) + activation_root = activation_doc.get("domain_activation_manifest", activation_doc) + expected_runnable = set(d for d in (activation_root.get("expected_runnable_domain_ids") or []) + if isinstance(d, str)) + + # ------------------------------------------------------------------ + # 판정 표시 — 금액 본체는 BO 값 그대로다. amount JSON 의 conflict 만 갱신한다. + # 판정 파일이 없거나 어긋나도 멈추지 않고 UNRESOLVED 로 둔다. + # ------------------------------------------------------------------ + # 상수 경로를 read_json 에 직접 넘긴다(U4 가시성 — Part 3 규율). 부재는 UNRESOLVED 로 내린다. + try: + adjudication_doc = read_json(ADJUDICATION_PATH) + except Exception: + adjudication_doc = {} + adjudication = (adjudication_doc.get("fact_exception_adjudication", adjudication_doc) + if isinstance(adjudication_doc, dict) else None) + accepted = tuple((policy.get("adjudication") or {}).get("accepted_status") + or ()) + decisions = None + if isinstance(adjudication, dict) and adjudication.get("status") in accepted: + raw = adjudication.get("decisions") + decisions = [d for d in raw if isinstance(d, dict)] if isinstance(raw, list) else [] + rows_by_fact = {row.get("fact_id"): row for row in rows} + selected = [] + unresolved = [] + for item in exceptions: + reason, value_id = adjudication_outcome(item, decisions) + if value_id: + target = rows_by_fact[item["fact_id"]] + amount = json.loads(target["amount"]) + amount["conflict"].update(status="SELECTED", selected_value_id=value_id) + target["amount"] = json.dumps(amount, ensure_ascii=False, sort_keys=True) + selected.append({"fact_id": item["fact_id"], "value_id": value_id}) + else: + unresolved.append({"exception_id": item["exception_id"], + "fact_id": item["fact_id"], "reason": reason}) + + # ------------------------------------------------------------------ + # domain_effects ⊆ SG-01 활성 — 위반 시 즉시 실패 (등식보다 앞 — G-g 기대). + # ------------------------------------------------------------------ + for row in rows: + bad = sorted(set(row.get("domain_effects") or {}) - expected_runnable) + if bad: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_DOMAIN_EFFECT_NOT_ACTIVE", + "fact_id": row.get("fact_id"), "domains": bad}, + ensure_ascii=False)) + + # ------------------------------------------------------------------ + # 보존 등식 다섯 — 바깥 수를 원본에서 직접 계수한다(bundle counts 를 믿지 않는다). + # ------------------------------------------------------------------ + bo_doc = read_json(BO_PATH) + bo_records = bo_doc if isinstance(bo_doc, list) else [] + les_doc = read_json(LES_PATH) + les_root = les_doc if isinstance(les_doc, dict) else {} + structure_records = [r for r in (les_root.get("structure_records") or []) + if isinstance(r, dict)] + record_by_id = {r.get("structure_id"): r for r in structure_records + if isinstance(r.get("structure_id"), str)} + by_bo_id = {k: [s for s in v if isinstance(s, str)] + for k, v in ((les_root.get("structure_index") or {}) + .get("by_bo_id") or {}).items()} + sg11_doc = read_json(SG11_PATH) + sg11_records = [r for r in (sg11_doc.get("records") or []) + if isinstance(r, dict)] + sg11_ids = {r.get("signal_id") for r in sg11_records + if isinstance(r.get("signal_id"), str)} + + failures = [] + # ① 행 + if len(rows) != len(bo_records): + failures.append({"reason_code": "PART4_ROW_CONSERVATION_BROKEN", + "rows": len(rows), "bo_total": len(bo_records)}) + # ② LES 부착 커버리지 + attached_bo = 0 + unattached_bo = 0 + for row in rows: + if (row.get("linked_structures") or {}).get("structure_ids"): + attached_bo += 1 + else: + unattached_bo += 1 + if attached_bo + unattached_bo != len(bo_records): + failures.append({"reason_code": "PART4_BO_ATTACHMENT_COVERAGE_BROKEN", + "attached": attached_bo, "unattached": unattached_bo, + "bo_total": len(bo_records)}) + # ③ 효과 (도메인 차원) + effect_left = sum(len(row.get("domain_effects") or {}) for row in rows) + effect_right = 0 + calc_right = 0 + used_sg11 = set() + for bo in bo_records: + bo_id = str(bo.get("BO_ID") or "") + attached = [record_by_id[s] for s in by_bo_id.get(bo_id, []) + if s in record_by_id] + effect_right += len({r.get("domain_id") for r in attached + if isinstance(r.get("domain_id"), str)}) + refs = {ref for r in attached + for ref in (r.get("calculation_request_refs") or []) + if isinstance(ref, str)} + calc_right += len(refs) + used_sg11.update(ref for ref in refs if ref in sg11_ids) + if effect_left != effect_right: + failures.append({"reason_code": "PART4_EFFECT_CONSERVATION_BROKEN", + "left": effect_left, "right": effect_right}) + # ④ 계산 (행 차원) + calc_left = sum(len(row.get("calculation_requests") or []) for row in rows) + if calc_left != calc_right: + failures.append({"reason_code": "PART4_CALC_CONSERVATION_BROKEN", + "left": calc_left, "right": calc_right}) + # ⑤ 계산 (원천 차원) + sg11_unused = len(sg11_ids) - len(used_sg11) + if len(used_sg11) + sg11_unused != len(sg11_ids): + failures.append({"reason_code": "PART4_CALC_SOURCE_CONSERVATION_BROKEN", + "attached": len(used_sg11), "unattached": sg11_unused, + "total": len(sg11_ids)}) + if failures: + raise RuntimeError(json.dumps({"conservation_failures": failures}, + ensure_ascii=False)) + + # BO 보존 — 후보 ↔ 최종 BO 집합 동일성 + fact_id 연속·유일 (구본 자구). + candidate_bo = sorted(str(b.get("BO_ID") or "") for b in bo_records) + final_bo = sorted(str(row.get("source_bo_id") or "") for row in rows) + if candidate_bo != final_bo: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_BO_CONSERVATION_BROKEN"}, ensure_ascii=False)) + fact_ids = [row.get("fact_id") for row in rows] + if fact_ids != ["F-%03d" % i for i in range(1, len(rows) + 1)]: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_FACT_ID_SEQUENCE_BROKEN"}, ensure_ascii=False)) + + # ------------------------------------------------------------------ + # 닫힌 스키마 -> 기록 -> 재읽기. + # ------------------------------------------------------------------ + schema_errors = schema_subset_validator.validate(rows, base_schema) + if schema_errors: + raise RuntimeError(json.dumps({ + "reason_code": "PART4_LEDGER_SCHEMA_INVALID", + "stage": "F2", "errors": schema_errors[:10]}, ensure_ascii=False)) + text = canonical(rows) + write_doc(TARGET_PATH, text) + reread = read_raw(TARGET_PATH) + if sha_text(reread) != sha_text(text): + raise RuntimeError("PART4_WRITE_REREAD_MISMATCH") + + # ------------------------------------------------------------------ + # writer report — 게이트별 발화 목록 · 도메인 효과 커버리지 · 계산 준비도 · 금액 판정. + # F2 는 receipt 를 쓰지 않는다(F0 단독 기록). + # ------------------------------------------------------------------ + gate_report = bundle.get("gate_report") or {} + effect_coverage = {} + for row in rows: + for domain_id in (row.get("domain_effects") or {}): + effect_coverage[domain_id] = effect_coverage.get(domain_id, 0) + 1 + readiness = {} + for row in rows: + for req in (row.get("calculation_requests") or []): + state = str(req.get("operand_state")) + readiness[state] = readiness.get(state, 0) + 1 + # S2_00 은 blocked_review_items 항목 하나로 회차를 멈춘다. 값 갈림은 멈춤이 아니라 표시이므로 + # 그 키를 비워 두고 review 로 남긴다. F2 재실행에도 건수가 늘지 않게 먼저 걷어 낸다. + handoff["review_items"] = [ + i for i in (handoff.get("review_items") or []) + if not (isinstance(i, dict) and i.get("review_code") == CONFLICT_REVIEW_CODE) + ] + [{"review_code": CONFLICT_REVIEW_CODE, "severity": "HARD_WARNING", + "fact_id": i["fact_id"], "detail": "%s %s" % (i["exception_id"], i["reason"])} + for i in unresolved] + handoff["counts"] = {"review_items": len(handoff["review_items"])} + row_review = any(row.get("skeleton_validation_codes") for row in rows) + status = ("READY_WITH_REVIEW" + if (handoff["review_items"] or row_review + or bundle.get("status") == "READY_WITH_REVIEW") + else "READY") + write_doc(REPORT_PATH, canonical({ + "schema_version": "stage1_fact_ledger_writer_report.v1", + "final_writer_status": status, + "row_count": len(rows), + "gate_firings": gate_report.get("fired_by_domain") or {}, + "domain_effect_coverage": effect_coverage, + "calculation_readiness": readiness, + "amount_basis_selected": selected, + "unresolved_amount_exceptions": unresolved, + "blocked_review_items": [], + "conservation": { + "row": {"rows": len(rows), "bo_total": len(bo_records)}, + "attachment": {"attached": attached_bo, "unattached": unattached_bo}, + "effect": {"left": effect_left, "right": effect_right}, + "calc_row": {"left": calc_left, "right": calc_right}, + "calc_source": {"attached": len(used_sg11), + "unattached": sg11_unused, + "total": len(sg11_ids)}, + }, + "final_sha256": sha_text(text), + "created_by": TASK_NAME, + })) + + # handoff FINALIZED 갱신(F0 과 공동 기록자). + handoff["status"] = "FINALIZED" + handoff["finalized_by"] = TASK_NAME + write_doc(HANDOFF_PATH, canonical({"stage1_part4_review_handoff": handoff})) + + return {"status": status, "modules": staged, + "row_count": len(rows), + "selected_count": len(selected), + "unresolved_count": len(unresolved), + "conservation_pass": True, + "final_sha256": sha_text(text)} + + + _sink = io.StringIO() + with contextlib.redirect_stdout(_sink): + _init() + RESULT = main() + print(json.dumps(RESULT, ensure_ascii=False)) + + task_procedure: + # F0 가 bundle 과 pack 을 내고서야 F1 이 서고, F1 이 끝나야 F2 가 선다. 판정이 없으면 F2 가 UNRESOLVED 로 둔다. 완전 직렬이다. + IN: + nexts: ["Task_C_FL_F0_fact_ledger_reducer"] + wait_until: [] + + Task_C_FL_F0_fact_ledger_reducer: + nexts: ["Task_C_FL_F1_fact_exception_adjudicator"] + wait_until: ["IN"] + + # F1 은 예외 0 이어도 READY_NO_EXCEPTIONS 를 쓰고 종료한다 — 그래프상 무조건 노드. + Task_C_FL_F1_fact_exception_adjudicator: + nexts: ["Task_C_FL_F2_final_fact_ledger_gate_and_writer"] + wait_until: ["Task_C_FL_F0_fact_ledger_reducer"] + + Task_C_FL_F2_final_fact_ledger_gate_and_writer: + nexts: ["OUT"] + wait_until: ["Task_C_FL_F1_fact_exception_adjudicator"] + + OUT: + nexts: [] + wait_until: ["Task_C_FL_F2_final_fact_ledger_gate_and_writer"] + + prevs: [] + nexts: [] diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md new file mode 100644 index 00000000..5e5aa6a6 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md @@ -0,0 +1,254 @@ +# 작업 간 일치성 보고서 — Stage 1 Part 1·2·3 → Part 4 + +- **점검 대상:** `stage_1_part_4_v.8.yml`(1,265행, sha256 `ce6e76280f21…`). task 셋: + - F0: 결정적 reducer. + - F1: LLM 예외 판정. + - F2: 최종 기록. +- **상류:** + - `stage_1_part_1_v.8.yml`(`4cf8c5b70be4…`) + - `stage_1_part_2_v.8.yml`(`3a66272ca511…`) + - `stage_1_part_3_v.8.yml`(`5b6336bd76e6…`, 11-05 3:30pm 판) +- **함께 본 코드·자산:** `v.7/extension_research/Default_Agent/` 아래의 다음 파일들. + - `fact_ledger_compiler.py`(945행), `fact_ledger_policy.v1.json`, `bo_surface_projection_policy.v1.json` + - `signal_registry.v2.json`, `signals/compiler/projections.py` + - `runtime_manifest.json`(`a828e962d1f6…`, 465건) +- **실측 자료:** workspace `11월_1일_구성`의 4차 실행(Part 3 세션 `6ed2a14b`) localdocs 산출물을 읽기 전용으로 회수했다. + - BO 78건, LES, 신호 31파일, 활성 manifest. + - Part 2·3 handoff, `evidence_indexed.json`, `part3_receipt.json`. + - BO sha `654529b4…`는 Part 3 receipt의 `bo_input.sha256`과 같다. 같은 회차의 BO다. +- **작성일:** 2026-11-05. 읽기 전용 점검이다. YAML과 모듈은 수정하지 않았다. +- **절차:** 초안 작성 → 별도 검증자 1회 독립 검증 → 개정본(이 문서). + - 검증자가 한 일: 하네스 재실행, 수치 재계산, 줄 번호 대조, F1 `SELECT_AMOUNT` 경로 추가 재생. + - 반영한 지적: 오류 7건 정정, 심각도 조정 3건, 누락 4건 추가. + +## 0. 결론 + +**Part 4는 4차 실행의 실제 상류 산출물 위에서 끝까지 돈다.** 이것은 F1(LLM)을 모의한 오프라인 재생 결과다. 실행을 멈추는 결함은 F1의 두 판정 경로(`BLOCK_REVIEW`·`SELECT_AMOUNT`) 모두에서 없었다. **그러나 "일치성 100%"는 아니다.** 정상 실행에서도 다음 세 가지 문제가 생긴다. +- 행의 일부 칸이 늘 빈다. +- 실제와 다른 검토 표지가 붙는다. +- 같은 계산 요청이 여러 행에 반복된다. + +| 구분 | 건수 | 대표 | +|---|---:|---| +| MAJOR | 0 | — | +| MINOR | 7 | `parties`가 78행 전부 비었다(P4-01) · 추천기 표지가 원래 붙어 있던 BO 7건에도 붙는다(P4-02) · 계산 요청이 46종에서 400건으로 불어난다(P4-03) · 사실 행 없는 HARD 게이트 발화(P4-08) | +| INFO | 14 | 구조 연결 공백인 `object_spec`(I-1) · Part 3 handoff 미독, S2_00이 직접 읽음(I-2) · 보존 등식 둘은 항등식(I-9) · 평문 토큰(I-14) | + +1. **경로·봉인·스키마 연결은 맞다.** + - 봉인 셋이 모두 통과했다: 신호 31파일 sha, registry index, LES 거래 id `MATCHED`. + - `config_sha256` 사슬 15/15와 닫힌 스키마 셋도 통과했다. + - F2 보존 등식 다섯도 통과했다: + + | 등식 | 결과 | + |---|---| + | 행 | 78=78 | + | 부착 | 68+10=78 | + | 효과 | 68=68 | + | 계산 | 400=400 | + | SG-11 원천 | 46+1=47 | + + - 다만 필드 의미 수준에서는 어긋남이 있다(P4-06의 코드 칸에 코드가 아닌 값). +2. **빠진 연결이 있다.** + - Part 2는 당사자 칸을 BO에 채우지 않는다고 선언했는데, Part 4는 그 칸에서 `parties`를 만든다(P4-01). + - Part 3이 BO 단위로 남긴 추천기 부착 정보를 Part 4는 구조 단위 표지로만 받는다(P4-02). + - Part 2가 Part 4용으로 지정한 신호 다섯 가운데 SG-06·SG-10을 읽기만 하고 쓰지 않는다(P4-04). +3. **온라인 미실행.** 서버에 `Fact_Ledger_base.json`이 없다. Part 4는 이 산출물 위에서 온라인으로 돈 적이 없다(§1·§6). + +## 1. 점검 방법 + +| 단계 | 내용 | +|---|---| +| 정적 대조 | F0·F2가 읽는 경로·필드와 compiler가 쓰는 키를 상류 writer 코드·정책과 대조했다. 대상은 Part 1 B1, Part 2 F0·S0와 신호 모듈, Part 3 L1 apply·L2다 | +| 실데이터 재생 | F0·F2 코드를 YAML에서 바이트 그대로 꺼내 실행했다. 바꾼 것은 둘뿐이다: httpx를 가짜 localdocs로, 실행 뿌리 `/tmp/s1`을 sandbox 경로로. F1은 두 번 모의했다: 예외 7건 모두 `BLOCK_REVIEW`(작성자), 모두 `SELECT_AMOUNT`(검증자) | +| 자산 대조 | 필수 자산 13개의 등재·sha는 **로컬 배포 원본**으로 확인했다. 서버와 직접 바이트 대조한 것은 `runtime_manifest.json`과 `_registry_index.json` 둘이다. 둘 다 같았다 | +| 하류 대조 | `Stage_2_S2_00.yml`의 입력 계약(16경로)을 보고, Part 4가 상류 정보를 대신 전달해야 하는지 판단했다. 실제 ingress workflow 파일은 보지 않았다 | + +**재생 결과(실측):** + +| 경로 | 결과 | +|---|---| +| F0 | `READY_WITH_REVIEW`. 78행. 게이트 선언 82·구현 10·발화 5. 예외 7. 검토 200 | +| F2, BLOCK 경로 | 선택 0·미해결 7. 보존 등식 통과. `final_sha256 a4a88c99…`. handoff `FINALIZED`, 검토 207 | +| F2, SELECT 경로 | 선택 7·미해결 0. 보존 등식 통과. 검토 200 | + +## 2. Part 4가 읽는 것과 상류 산출 대응 + +F0이 읽는 사건 산출은 12종이다. 도메인 신호 폴더를 하나로 센다. + +| Part 4 입력 | 생산자 | 일치 | 비고 | +|---|---|---|---| +| `BO.json` | Part 2 F0 | △ | 읽는 키는 아래 다섯 줄이다. `amount` 4키와 대안 레코드(9~10키)는 F1 프롬프트 어휘와 맞다. `dates`·`object_label_text`는 선택 키다. **`core_field_base.Performer·Subject`는 Part 2가 채우지 않는다고 선언한 칸이다(P4-01)** | +| (위 BO의 읽기 키) | | | `BO_ID`·`BOType`·`Action` | +| | | | `core_field_base` | +| | | | `amount` | +| | | | `provenance.amount_alternatives·amount_related_values·source_domain` | +| | | | `source_evidence_indexes` | +| `legal_effect_structures.json` | Part 3 L2 | ✓ | `structure_records[]`의 `structure_id`·`domain_id`·`module`·`role_projection`·`type_id`·`review_codes`·`review_required`·`calculation_request_refs`, 그리고 `structure_index.by_bo_id`·`signal_manifest_transaction_id`를 읽는다. 거래 id 키가 있어 `MATCHED`다. `quality_gate.review_queue`는 읽지 않는다 | +| `signals/signal_manifest.json` | Part 2 S0 | ✓ | `files[].path`에 `signals/` 접두사를 붙여 대조하는 처리가 맞다. 31/31 | +| SG-04·06·07·10·11 | Part 2 S0 | ✓(형식) | `downstream_read_sets.part4_F0`와 같다. **compiler가 쓰는 것은 SG-04·SG-11뿐이다(P4-04).** 4차 실행에서는 SG-04·06·07·10이 모두 레코드 0이다 | +| `signals/domain_signals/.json` | Part 2 S0 | ✓ | `review_items[].review_code`와 `evidence_slot_status[]`를 읽는다. 15/15 있다. 리뷰 코드 213, 슬롯 303 | +| `routing/domain_activation_manifest.json` | Part 1 D0 → Part 2 갱신 | ✓ | 봉인된 사본 `signals/domain_activation_manifest.json`과 내용은 같고 바이트만 다르다(I-4) | +| `quality_gates/stage1_part2_review_handoff.json` | Part 2 F0 | △ | 451건 가운데 50건은 `source_review_code` 칸에 필드 경로가, 94건은 null이 들어 있다(P4-06) | +| `evidence_indexed.json` | Part 1 B1 | ✓ | `items[].evidence_index·title·key_facts`를 읽는다. BO의 증거 참조가 모두 30건 안에 있다(`EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE` 0) | +| `Default_Agent/` 자산 13 + 사이드카 30 | 배포 | ✓ | 로컬 원본 기준으로 등재·sha가 맞다. 사이드카 결손 0 | + +**F1·F2의 연결:** +- F1 지시문이 쓰라고 한 후보 필드(`item_label`·`value_kind`·`dates`·`value_basis`·`object_label_text`)는 F0 pack에 모두 있다. 뒤의 둘은 선택 키다. +- pack은 9.6k자라 preflight에 문제없다. +- F0은 판정 파일을 `PENDING`으로 덮어써(YAML 595행) 지난 회차 판정을 지운다. +- F2는 판정 이상이나 부재를 `UNRESOLVED`로 내린다(985-1003·1037-1061행). +- 대안이 있으면 `amount_text`가 반드시 `conflict` 키를 내므로(compiler 108-113행) F2의 갱신이 안전하다. + +**Part 4가 읽지 않는 상류 산출과 판단:** + +| 산출 | 판단 | +|---|---| +| `client_goal.json`, `routing/party_aliases.json`, `value_facts_party_links.json`, evidence `key_parties` | 당사자 정보의 실재 출처다. `parties`가 비는 원인과 직결된다(P4-01) | +| `quality_gates/stage1_part3_review_handoff.json`, `validation_assets/routing/part3_recommender_receipt.json` | S2_00이 handoff를 직접 읽으므로 전달 의무는 없다(I-2). 다만 BO 단위 추천기 부착 정보는 여기에만 있다(P4-02) | +| `value_facts.json`, `evidence_event_candidates.json`, Part 1 soft gate handoff | Part 2가 BO로 매개하고, S2_00이 직접 읽는다. 문제없다 | +| SG-02·03·05·08·09·12·13, compatibility view 3종 | Part 4 read set 밖이다. S2_00은 `ALL`을 읽는다. compatibility view 셋은 모두 `EMPTY`다 | + +## 3. 지적사항 + +### MINOR + +**P4-01 · `parties`가 구조적으로 항상 빈다(78/78 실측).** +- **원인:** + - compiler는 `core_field_base.Performer`·`Subject`에서 당사자를 만든다(`fact_ledger_compiler.py:493-500`). + - 그런데 Part 2 정책 `bo_surface_projection_policy.v1.json`의 `not_projected`는 이 두 칸을 채우지 않는다고 명시한다. 사유는 이렇다: "registry가 party_roles의 role을 BO 칸에 대응시키는 선언을 두지 않았으므로 배정하면 창작이 된다. 이 정보는 signal 번들(party_roles 투영)로 간다". +- **대체 경로도 비었다.** + - 그 투영처인 `compatibility_views/case_liability_signals.json`은 4차 실행에서 `EMPTY`다. + - 신호 31파일 어디에도 `party_roles` 키가 없다. +- **영향:** + - 구 27키 계약의 `parties`가 쓰이지 않는 칸이 됐다. + - S2_00은 `client_goal.json`에서 사건 단위 당사자를 얻을 수 있다. + - 그러나 사실(행) 단위 당사자 연결은 Stage 1 어디에도 남지 않는다. +- **MAJOR로 올리지 않은 이유:** 하류에 사건 단위 대체 경로가 있다. + +**P4-02 · 추천기 부착 표지가 원래 부착된 BO에도 붙는다.** +- **원인:** + - Part 3 L1 apply는 `PART3_BO_ATTACHED_BY_RECOMMENDER`를 구조 레코드의 `review_codes`에 달고 `review_required=True`로 바꾼다(part 3 YAML 1912-1914행 부근). + - Part 4는 그것을 행의 `domain_effects[d].review_codes`로 옮길 뿐이다(`fact_ledger_compiler.py:536-537`). +- **실측:** + - `LES-E-02-money_claim`에 붙은 12행 모두가 이 코드를 갖는다. + - 추천기가 실제로 붙인 것은 bh3·bh7·bh31·bh40·bh42 5건이다. + - L0이 원래 붙인 bh2·bh5·bh14·bh22·bh26·bh29·bh34 7건이 실제와 다른 표지를 받는다. +- **BO 단위 정보의 위치:** Part 3 handoff 항목의 `bo_id`와 `part3_recommender_receipt.json`의 `attached_bo`에만 있다(part 3 YAML 1632·2117행). Part 4는 둘 다 읽지 않는다. +- **MINOR인 이유:** 정상 실행에서 틀린 값이 생기므로 MAJOR 경계에 있다. 그러나 틀리는 것은 SOFT 검토 표지이고, 법률·금액 값은 아니다. + +**P4-03 · 계산 요청이 도메인 단위로 복제된다(46종 → 400건).** +- **원인:** + - 계산 조인은 구조 레코드의 `calculation_request_refs`를 행마다 싣는다(`fact_ledger_compiler.py:549-588`). + - 중복 제거는 한 행 안에서만 한다(548행). 이 복제는 설계된 동작이고, 결함은 하류의 합산 규칙이 없다는 데 있다. +- **실측:** + - 고유 SG-11 46종이 행 전체에서 400건이 됐다. + - ref별 반복 횟수는 다음과 같다: + + | 반복 횟수 | 12 | 13 | 9 | 7 | 4 | 2 | 3 | 1 | + |---|---:|---:|---:|---:|---:|---:|---:|---:| + | ref 수 | 16 | 7 | 5 | 5 | 6 | 4 | 1 | 2 | + + - money_claim 구조의 ref 16개는 12행에 각각 실린다(192건). 추천기가 붙인 5행만으로 80건이 늘었다. + - E-10 ref 7개는 E-10의 구조 셋에 걸쳐 13행에 실린다. +- **영향:** + - 보존 등식 ④는 양변에서 같이 세므로 통과한다. + - 하류가 행별 계산 요청을 더하면 같은 계산을 최대 13번 센다. + - 4차 보고서 §5-1이 예고한 확인 사항이 실측으로 확정됐다. + +**P4-04 · SG-06·SG-10을 읽지만 쓰지 않는다.** +- F0은 다섯 신호를 모두 읽어 compiler에 넘긴다(YAML 518-524행). 그러나 compiler의 `signal_records()` 호출은 SG-11과 SG-04뿐이다(`fact_ledger_compiler.py:404-411`). +- Part 2 manifest의 `part4_F0` 읽기 집합은 형식상 충족된다. +- 시한·통지 조건(SG-06)과 증거 충돌(SG-10)은 행·게이트·검토 어디에도 반영되지 않는다. +- SG-07은 Part 3 receipt의 `empty_read_set_signals`가 생산자 0(닫힌 스키마에 어휘 없음)으로 기록한 설계상 빈 신호다. 그래서 잠재 영향은 SG-06·SG-10에 한정된다. +- 4차 실행은 이 신호들이 비어 있어 영향이 드러나지 않았다. + +**P4-06 · Part 2 handoff의 `source_review_code`에 코드가 아닌 값이 들어 있다.** +- **계약과 실제:** + - Part 2 정책은 이 키를 "원본 review_code를 잃지 않기 위한" 추가 키로 정의한다. + - 그런데 Part 2 F0은 노트 항목에서 `"source_review_code": note_item.get("field")`로 필드 이름을 넣는다(part 2 YAML 3596행). +- **실측(451건):** + - 필드 경로: 50건 `core_field_base.BehaviorTime`, 5건 `ActionType`. + - null: 94건. + - 정상 코드: 302건. 게이트 입력으로 쓰였다. +- **Part 4 쪽 영향:** 필드 경로 55건마다 `P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW`(SOFT)를 만든다(`fact_ledger_compiler.py:430-437`). 최종 검토 207건 가운데 55건이 이 잡음이다. +- **결함 위치:** Part 4가 아니라 Part 2 생산자다. + +**P4-07 · BO.json이 같은 회차의 것인지 확인하지 않는다.** +- 신호·LES·registry는 봉인 대조를 한다. BO는 하지 않는다. F0도 F2도 Part 3 receipt를 읽지 않는다. +- Part 3 receipt의 `bo_input.sha256`(`654529b4…`)이 이미 있지만 대조에 쓰이지 않는다. +- BO가 다른 회차 것이면 `by_bo_id` 조인이 조용히 어긋난다. 행·BO 보존은 같은 BO로 세므로 통과한다. +- Part 3 보고서 P3-01과 같은 비대칭이다. 비정상 경로에서만 나타난다. + +**P4-08 · 활성 도메인 E-15에 사실 행이 없는데도 HARD 게이트가 발화한다.** +- **실측:** + - E-15를 가진 행은 0이다. E-15 LES 레코드 둘은 `source_bo_ids`가 비어 있다. + - 그런데도 E-15 게이트 셋이 발화했다. 그 가운데 E15-G01·G03은 `blocks_final_drafting` HARD이고, `projected_rows`는 `[]`다. + - 미부착 SG-11 1건도 `E-15:001:1`이다. +- **영향:** 최종 기안을 막는 게이트 결과가 사실 행 근거 없이 handoff와 writer report에만 남는다. +- **원인 위치:** Part 3 L0·L1에서 E-15에 BO가 붙지 않은 것(Part 3 보고서의 목표 무관 판정 bh44)과 연결된다. + +### INFO + +| ID | 내용 | +|---|---| +| I-1 | **`object_spec` 78/78 공백**(초안 MINOR에서 낮춤). Part 4는 `core.Object`를 계약대로 읽는다(compiler 594행). 원인은 Part 2가 `object_refs`를 한 건도 내지 않은 데 있다. `CALCULATION_BASIS_INCOMPLETE_REVIEW` 26건 가운데 22건이 이 공백 때문이다. 나머지 4건은 BO 금액도 없어서 생긴다 | +| I-2 | Part 3 handoff를 읽지 않는다. S2_00이 handoff 넷을 모두 직접 읽으므로 전달 누락은 아니다. 같은 미부착 BO 10건(Part 3 집합과 완전히 같음)을 Part 3은 HARD `PART3_BO_UNATTACHED`로, Part 4는 SOFT `FACT_ROW_UNATTACHED_REVIEW`로 적어 심각도가 갈린다 | +| I-3 | `claim_chain_ref.claim_group_ids`·`liability_group_ids`가 78/78 `[]`다. 출처 후보인 case_liability view가 `EMPTY`다. `signal_count`는 실제로는 계산 ref 수다(compiler 627-628행) | +| I-4 | 봉인된 `signals/domain_activation_manifest.json` 대신 `routing/` 사본을 읽는다. 4차 실행에서 둘은 내용이 같고 바이트가 다르다 | +| I-5 | 정책 `les_inherited_review_codes`에 `PART3_*` L1 코드가 없다. 그래도 `review_required`로 상태가 `READY_WITH_REVIEW`가 되므로 결과는 같다 | +| I-6 | 증거 권위표의 `priority`·`authentication` 키가 `evidence_indexed.v3`에 없어 30건 모두 null이다. 300자 절단 여유의 최소값은 −41이지만, 문서 표지 판정이 바뀐 행은 0이다 | +| I-7 | 정책 `domain_payload_keep_keys` 6종이 BO `domain_payload`의 실제 키(`action_summary`·`action_type`·`payload`)와 하나도 겹치지 않는다. 압축 결과가 행에 쓰이지 않으므로 영향은 없다 | +| I-8 | 게이트 82개 가운데 구현 조건은 10개다. 서술형 72개는 가시화만 된다. 발화 5건: HARD 셋(E15-G01·E15-G03·X1-G01), SOFT 둘(E15-G02·X1-G02) | +| I-9 | F2 보존 등식 ②(부착)와 ⑤(SG-11 원천)는 정의상 항상 참이다(YAML 1108·1138행). 실질 대조는 ①·③·④ 셋이다. ③·④는 BO와 LES에서 같은 조인을 다시 세므로 compiler 대조로서는 유효하다. 다만 조인 설계와는 독립적이지 않다 | +| I-10 | 반입만 하고 import하지 않는 모듈이 있다. F0: `runtime_common`·`registry_loader`·`structure_index_compiler`. F2: `runtime_common`. 실제로 import되는 것은 `fact_ledger_compiler`·`schema_subset_validator` 둘이다 | +| I-11 | `LEGACY_ALIAS_*` 검토 3건은 자산 내부 별칭표 불일치에서 나온다(B2에 E-09 누락, B5에 X1·X3 누락·E-10 초과). 상류 산출과는 무관하다 | +| I-12 | F1 pack의 `calculation_request_ids`에 중복이 있다(예: FX-001의 `CE-04` 4회). 400건의 계산 요청이 `calculation_id` 8종으로 모인다. F1 입력의 잡음이다 | +| I-13 | F2 주석(YAML 1185행 부근)은 "S2_00은 `blocked_review_items` 항목 하나로 회차를 멈춘다"고 쓴다. S2_00 계약은 `blocked_review_item_limits_affected_ready_scope_only: true`다. 동작에는 영향이 없다 | +| I-14 | YAML 머리에 code-executor Bearer 토큰이 평문으로 있다. Part 1~3과 같은 값이다. 교체와 환경 주입이 필요하다 | + +## 4. 일치를 확인한 항목 + +- **경로:** F0이 읽는 사건 산출 12종이 모두 상류 writer의 실제 경로와 같다. 구 Part 4 경로와 구 signal 3종 경로는 읽지 않는다. +- **읽기 집합:** F0의 신호 읽기가 Part 2 manifest `downstream_read_sets.part4_F0`(SG-04·06·07·10·11)와 정확히 같다. +- **봉인:** 모두 맞다. + - 신호 31/31 sha. + - registry index sha `9f177ebf…`. 활성 manifest의 선언값과 같고, 서버본과 바이트도 같다. + - `config_sha256` 15/15. + - LES 거래 id `S5TX-89d93dca8f879c30090d` `MATCHED`. +- **금액:** Part 2 M1의 `amount`(4키)·`amount_alternatives`(9~10키)·`amount_related_values`가 compiler의 `amount_text`와 F1 판정 어휘에 대응한다. 대안을 가진 BO 7건이 예외 7건이 됐다. F1의 두 판정 경로 모두 F2가 정상 처리했다. +- **LES 조인:** + - `by_bo_id`로 68행이 부착됐다. Part 3 L2의 BO 보존(68+10=78)과 같다. + - 추천기가 붙인 5건도 행에 반영됐다. + - `STRUCTURE_UNATTACHED_REVIEW` 28건은 LES 선언 50 가운데 BO가 붙은 22를 뺀 수와 같다. +- **SG-11:** 47건 가운데 46건이 행에 닿고, 1건은 검토로 남는다. `operand_state`를 재산정하지 않고 승계한다(partial 323·blocked 67·deferred 10). +- **증거:** BO의 증거 참조가 모두 Part 1 `evidence_indexed` 30건 안에 있다. +- **스키마:** + - bundle·pack·base 세 스키마 모두 자기 산출이 통과했다. + - base 29키에 S2_00 필수 2키(`domain_effects`·`calculation_requests`)가 있다. + - `amount`는 JSON 문자열(49행) 또는 null(29행)이다. BO 금액 없이 관련 값 표시만 가진 행 7개는 v.3 전략서의 의도대로다. + +## 5. 권고(제안이며 적용하지 않았다) + +1. **P4-02:** + - 권장: Part 3 L1 apply가 구조 레코드에 BO 단위 부착 출처(예: 추천기가 붙인 `source_bo_ids` 부분집합)를 남긴다. 경로를 늘리지 않는다. + - 대안: Part 4가 `part3_recommender_receipt.json`의 `attached_bo`를 읽어 해당 행에만 표지를 단다. +2. **P4-01:** `parties`의 출처를 정한다. + - 후보: Part 1 `value_facts_party_links.json`(BO `value_refs`로 연결 가능), 또는 party_roles 투영을 실제로 생산하는 것. + - 출처를 정하지 못하면 이 칸을 "항상 비어 있음"으로 계약에 명시한다. +3. **P4-03:** 행에는 계산 요청 ref만 두고 계산 본문은 구조 단위로 한 번만 싣는 방식을 검토한다. 하류 합산 규칙도 함께 정한다. +4. **P4-04:** SG-06·SG-10을 compiler에서 쓰거나, Part 2 read set에서 빼서 계약과 실제를 맞춘다. +5. **P4-06:** Part 2 F0 3596행의 `note_item.get("field")`를 코드 출처로 바꾸거나 다른 키로 옮긴다. +6. **P4-07:** F0에서 BO sha를 Part 3 receipt의 `bo_input.sha256`과 대조한다(한 줄). +7. **P4-08:** 사실 행이 없는 도메인의 HARD 게이트 발화를 별도 검토 코드로 구분할지 정한다. +8. 다음 온라인 실행에서 Part 4를 4차 산출물 위에 돌려 이 재생 결과를 확인한다. + +## 6. 점검의 한계 + +- **F1:** 실제 Gemini 출력은 검증하지 않았다. F1 경로의 preflight와 LLM의 `write_file`도 지나가지 않았다. 두 판정 경로는 모의로만 확인했다. +- **법령 버전 조인:** 4차 실행은 SG-04·06·10이 비어 있다. 그래서 법령 버전 조인과 P4-04의 실제 영향을 데이터로 확인하지 못했다. +- **자산:** 필수 자산 13개 본문은 서버와 직접 대조하지 않았다. manifest·registry index만 대조했다. +- **하네스와 실제 백엔드의 차이:** + - 문서 부재 응답의 모양이 다르다. + - 자산을 로컬 원본에서 읽는다. +- **S2_00:** 입력 계약 파일만 봤다. 실제 ingress workflow는 보지 않았다. 따라서 "S2_00은 handoff를 직접 읽는다"는 계약 근거다. +- **법률적 타당성:** 부착·게이트·증거력 판정이 법률적으로 맞는지는 판단하지 않았다. 형식·흐름·계약 일치만 봤다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md new file mode 100644 index 00000000..9f05bd02 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md @@ -0,0 +1,190 @@ +# 작업 간 일치성 보고서 해결법 — Part 4 on Part 1~3 (§3 지적사항 질의응답) + +- **대상:** `작업간일치성보고서_part_4_on_part_1_to_3.md` §3의 MINOR 7건(P4-01·02·03·04·06·07·08)에 대한 질문 17개. +- **작성일:** 2026-11-05. 읽기 전용 점검이다. YAML·모듈·자산은 수정하지 않았다. +- **근거:** 아래 파일을 직접 읽어 확인했다. 줄 번호는 작성 시점 기준이다. + - Part 1·2 YAML: `stage_1_part_1_v.8.yml`, `stage_1_part_2_v.8.yml` + - Part 4 compiler: `v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py` + - signal registry: `signal_registry.v2.json` + - S2_00 계약본: `2. Stage_2/Stage_2_S2_00.yml` + - S2_00 배포 코드본: `2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml`(4,893행) + - S2_20: `2. Stage_2/Stage_2_S2_20.yml` + - 4차 실행 재생 산출물: Fact_Ledger, Part 4 handoff, gate_report, Part 3 receipt. +- **표기:** 실측하지 못한 부분은 "미실측"으로 표시했다. + +## 요약 + +| 항목 | 핵심 답 | 가장 간단한 해결 | +|---|---|---| +| P4-01 | `client_goal`만으로는 해결되지 않는다. S2_00은 행 단위 당사자를 이름 공출현으로 추정할 뿐이다 | F0이 `value_facts_party_links.json`을 읽고, BO `value_refs`로 `parties`를 채운다 | +| P4-02 | — | Part 3 apply가 구조 레코드에 `recommender_attached_bo_ids`를 남기고, Part 4는 그 BO 행에만 표지를 단다 | +| P4-03 | LLM이 400건을 계산하지 않는다. 지금은 잠재 위험이다 | `request_id`를 고유 키로 선언하고 writer report에 고유 기준 수치를 추가한다 | +| P4-04 | 정보는 Stage 2로 직접 간다. 문제는 계약과 실제의 어긋남이다 | Part 4 읽기 집합에서 SG-06·SG-10을 뺀다 | +| P4-06 | 검토 목록의 27%(55/207)가 형식 잡음이다 | Part 2 3596행에서 필드명을 `source_field`로 옮기고 코드 칸은 null로 둔다 | +| P4-07 | — | F0이 Part 3 receipt의 `bo_input.sha256`과 BO sha를 대조한다 | +| P4-08 | 근거 행 없는 HARD 경보가 Stage 2에 도메인 정보 없이 전달된다 | 행이 0인 발화는 별도 코드로 내고 `domain_id`를 싣는다 | + +## 1. P4-01 · `parties`가 구조적으로 항상 빈다 + +**[질문 1-1] `client_goal.json`으로 완전히 해결되는가?** + +완전히 해결되지 않는다. `client_goal.json`에서 얻는 것은 사건 단위 당사자 명부다. 사건에 누가 있고 원고·피고 등 어떤 역할인지를 알 수 있다. 그러나 각 사실에서 누가 행위하고 누가 상대방인지는 알 수 없다. S2_00 계약은 사실과 당사자의 연결 사슬 `FACT_TO_BO_PARTY_OBJECT`를 요구하면서(계약본 546행) 유사 이름 병합을 금지한다(538행). 그래서 배포된 S2_00은 행 단위 당사자를 직접 재구성한다(배포 코드본 3211-3237행). 재료는 셋을 합친 것이다. +- BO의 원천 사건 후보 `participants`. 다만 원천 사건 id를 가진 BO는 78건 중 10건뿐이다. +- 인용 증거 `key_parties` 전체. 문서 단위 목록이다. +- `Action` 문장에 나타난 등록 이름. + +이렇게 얻은 집합에는 두 가지 한계가 있다. 행위자와 상대방이 구분되지 않는다. 그리고 계약서 하나를 인용한 사실에 그 문서의 모든 당사자가 붙을 만큼 과포함된다. 이 이름 공출현 방식은 10-11에 확인된 피고 과식별(RC-07·08)의 원인이었다. 따라서 S2_00이 부족분을 부분적으로 메우기는 하지만, 사실 단위의 역할 정보와 정밀도는 여전히 없다. + +**[질문 1-2] `parties`를 채우면 S2_00의 사건 단위 당사자 추출과 충돌하는가?** + +현재 구조에서는 충돌하지 않는다. 배포된 S2_00은 Fact_Ledger 행의 `parties`를 읽지 않는다. S2_10으로 넘기는 키 목록 `COMPACT_KEYS`(배포 코드본 2804-2809행)에 없다. FACT 당사자 태그도 BO 태그와 본문 이름 대조로만 만든다(3234-3237행). 따라서 채워 넣는 것은 순수한 추가다. 충돌 위험은 두 경우뿐이다. +- **표기 체계가 다를 때:** 이름이 `client_goal` 정규명과 다른 체계에서 오면, 유사 병합 금지(538행) 때문에 같은 사람이 다른 당사자로 갈라진다. 출처를 Part 1 `value_facts_party_links.json`의 `party_ref`로 하면 이 위험은 사라진다. 이 값은 `client_goal` 당사자에서 만든 `party_aliases.canonical_parties`의 정규명이다(Part 1 YAML 9978-9985·11179-11181행). 그래서 S2_00 명부와 글자 단위로 같다. +- **S2_00이 나중에 이 칸을 쓰기 시작할 때:** Part 4 집합과 S2_00 추정 집합이 다를 수 있다. 이때는 "Part 4의 RESOLVED 연결이 먼저이고 추정은 보충"이라는 우선순위만 정하면 된다. + +**[질문 1-3] 가장 간단하고 효율적인 해결 방법** + +F0이 Part 1 산출 `value_facts_party_links.json`을 하나 더 읽고, compiler가 BO의 `value_refs`를 그 연결표에 조인해 `parties`를 채운다. 조인 대상은 `status=RESOLVED`인 `party_ref`다. 각 항목은 `{"role": null, "value": <정규명>, "source": "value_facts_party_links:/"}` 형태로 둔다. `parties[]`·`stances[]` 경로는 `source`에 남는다. +- **이 방법이 쉬운 이유:** + - Part 2가 같은 파일을 이미 같은 경로로 읽는다(Part 2 YAML 398·652행). 생산과 읽기가 검증된 경로다. + - 이름이 `client_goal` 정규명이라 S2_00과 맞다. + - Part 2 정책이 금지한 Performer·Subject 배정(창작)을 하지 않는다. +- **수정 범위:** + - F0 입력 1개와 sha 기록. + - compiler 약 10행(493-500행의 Performer·Subject 분기를 대체). + - 스키마 변경 없음(`parties` 배열은 이미 있다). +- **적용 범위:** `value_refs`가 있는 BO는 49/78건이라 최대 49행이 채워진다. RESOLVED 비율은 미실측이다. 나머지 행은 "금액 연결 당사자 없음"을 뜻하는 빈 배열이라고 계약에 적는다. + +## 2. P4-02 · 추천기 부착 표지가 원래 부착된 BO에도 붙는다 + +**[질문 2-1] 가장 간단하고 효과적인 해결 방법** + +Part 3 L1 apply가 `PART3_BO_ATTACHED_BY_RECOMMENDER`를 구조 레코드에 다는 바로 그 자리(Part 3 YAML 1912-1914행 부근)에서, 실제로 붙인 BO 목록 `recommender_attached_bo_ids`(4차 실행: bh3·bh7·bh31·bh40·bh42)를 함께 기록한다. 그러면 Part 4 compiler가 구조 레코드의 `review_codes`를 행으로 옮길 때(`fact_ledger_compiler.py:536-537`) 그 행의 `bo_id`가 목록 안에 있을 때만 이 코드를 남길 수 있다. +- **장점:** 새 파일 읽기와 새 봉인이 필요 없다. 이미 읽는 `legal_effect_structures.json` 안에서 해결된다. +- **수정 범위:** Part 3 한 줄, Part 4 두세 줄이다. +- **주의:** + - Part 3 코드는 `src/`를 고친 뒤 `splice.py`로 다시 조립한다. + - LES 레코드 스키마가 닫혀 있다면 새 키를 스키마에 등록해야 한다(미확인). +- **대안:** Part 4가 `part3_recommender_receipt.json`의 `attached_bo`를 직접 읽는 방법도 있다. 다만 입력 경로와 봉인 대조가 하나 늘어 더 무겁다. + +**[질문 2-2] 해결했을 때의 장점** + +검토 표지가 사실과 일치하게 된다. +- **사람 검토가 줄어든다:** 대상이 `money_claim` 12행에서 실제 추천기 부착 5행으로 준다. 오경보 7건(58%)이 사라져, "기계가 붙였으니 확인하라"는 SOFT 표지가 다시 의미를 갖는다. 표지가 늘 붙는 것이 아니라 필요한 곳에만 붙으면 검토자가 경보에 무뎌지지 않는다. +- **부착 근거를 구분할 수 있다:** 하류(S2_00·S2_10)가 같은 청구 구조 안에서 L0의 결정적 부착과 JEV 추천에 의한 확률적 부착을 가를 수 있다. 청구원인 사실을 고를 때 약한 근거의 사실을 따로 다룰 수 있다. +- **감사와 보정이 쉬워진다:** + - Part 3 handoff의 SOFT 5건과 Part 4 표지 5건이 일치한다. + - JEV 임계값을 보정할 때 BO 단위로 결과를 대조할 수 있다. + +## 3. P4-03 · 계산 요청이 도메인 단위로 복제된다(46종 → 400건) + +**[질문 3-1] 심각성과 작동상 문제점** + +지금 당장 틀린 결과를 내지는 않는다. 하류 계산이 이 목록을 더하기 시작하는 순간 금액이 부풀 수 있는 잠재 위험이다. 현재 소비처는 세 곳이다. +- **S2_00:** 행 목록의 `operand_state` 빈도를 writer report와 대조하기만 한다(배포 코드본 2041-2056행). 양쪽 모두 중복을 포함해 세므로 통과한다. +- **S2_10:** LLM이 이 키를 받지 않는다(`COMPACT_KEYS`에 없음). +- **S2_20:** 계산은 원자 청구 × 계산기 단위의 코드 계산이다. Stage 1 요청은 아직 바인딩하지 않는다(operand 출처가 `UNRESOLVED_STAGE1_CALCULATION_REQUEST`, S2_20 1145-1155행). + +그래도 생기는 문제는 셋이다. +1. **보고 수치가 부푼다:** 준비 상태 집계(partial 323 · blocked 67 · deferred 10, 합계 400)가 고유 46건의 실제보다 크다. 검토자가 미비 피연산자 규모를 과대평가한다. +2. **장래 이중 계산 위험:** S2_20이 Stage 1 요청을 피연산자로 바인딩할 때 고유 키 규칙이 없으면, 같은 이자·원금 계산이 최대 13번 잡혀 청구금액이 부풀 수 있다. 가장 큰 위험이다. +3. **F1 입력 잡음:** F1 pack에 같은 id가 반복된다(I-12, FX-001의 `CE-04` 4회). 토큰을 쓰고 판정을 흐릴 수 있다. + +**[질문 3-2] 현재 사건에서 LLM이 400건을 계산하는가?** + +아니다. 계산 요청은 계산 결과가 아니다. "이 계산이 필요하고 피연산자 상태는 이렇다"는 기록이다. 키는 `calculation_id`·`operand_state`·`missing_operands`·`request_id` 등이다. 400건 가운데 LLM이 계산하는 것은 0건이다. +- **Stage 1:** 계산하지 않는다. LLM인 F1은 금액 예외 7건을 판정할 뿐이고, 계산 요청 id는 참고로만 본다(pack 9.6k자). +- **S2_10 LLM:** 이 목록을 받지 않는다. +- **S2_20:** 실제 계산은 Decimal 코드로 결정적으로 한다(S2_20 1074·1241행). 단위는 원자 청구 × 계산기이고, Stage 1 행 단위가 아니다. +- **고유 계산 종류:** `calculation_id` 기준 8종이다. + +**[질문 3-3] 가장 간단하고 효과적인 해결 방법** + +행 구조는 그대로 둔다. S2_00은 각 행에 dict 목록이 있기를 요구한다(배포 코드본 1708·1806·2043행). 대신 이미 고유한 `request_id`(= SG-11 `signal_id`)를 "합산·계산의 유일 키"로 선언한다. 할 일은 셋이다. +1. F2 writer report에 고유 기준 수치를 추가한다: `calculation_request_unique_count`(46)와 `calculation_readiness_unique`. +2. Fact_Ledger 계약에 한 줄을 넣는다: "행의 `calculation_requests`는 관련성 표시이고, 계산·합산은 `request_id` 고유 기준으로 한다". +3. F0이 F1 pack의 `calculation_request_ids`를 집합으로 줄인다(I-12 동시 해소). + +수정은 약 5행이다. S2_00의 기존 대조(중복 포함 빈도)는 그대로 통과한다. 다른 방법으로, 행에는 ref만 두고 본문은 최상위에 한 번만 싣는 구조 개편이 있다. 그러나 S2_00 2043행 대조를 깨므로 더 무겁다. + +## 4. P4-04 · SG-06·SG-10을 읽지만 쓰지 않는다 + +**[질문 4-1] 심각성** + +낮다. 정보가 사라지지 않기 때문이다. registry는 SG-06·SG-10의 하류 소비자에 Stage 2를 명시한다(`signal_registry.v2.json`). S2_00은 신호 전부를 직접 읽는다(계약본 `signal_downstream_read_set_exact: ALL`, 426행). 4차 실행에서는 두 신호가 모두 비어 있어 실제 영향도 없었다. 문제는 계약과 실제가 어긋나 생기는 거짓 안심이다. manifest가 "Part 4가 읽는다"고 적고 있으니, 독자는 사실 행에 시한·통지 조건과 증거 충돌이 반영됐다고 믿기 쉽다. 그런데 신호가 채워진 사건에서 실제로는 다음이 일어난다. +- **SG-06:** 시한에 걸린 사실에 `must_consider`가 서지 않는다. 예: 사해행위취소의 제척기간은 취소원인을 안 날부터 1년, 법률행위가 있은 날부터 5년이다(민법 제406조 제2항). +- **SG-10:** 두 증거가 충돌하는 사실의 `proof_strength`·`credibility`가 문서 표지만으로 계산돼 증명력이 과대 표시될 수 있다. + +**[질문 4-2] 가장 간단하고 효과적인 해결 방법** + +계약을 실제에 맞춘다. 두 곳에서 SG-06·SG-10을 뺀다. +- F0의 신호 읽기(Part 4 YAML 518-524행). +- Part 2 manifest의 `downstream_read_sets.part4_F0`. + +그리고 "Stage 2(S2_00)가 직접 읽는다"고 적는다. 로직 변경 없이 두세 줄이다. +- **주의:** manifest를 고치면 sha가 바뀐다. 재봉인과 서버 업로드가 필요하다. +- **나중에 사실 행에도 반영하고 싶을 때:** SG-04와 같은 도메인 조인 방식을 쓴다(compiler 406-410행). 행 `domain_effects`에 신호 id를 ref로 싣고, SG-10이 있으면 행별 SOFT 검토를 내면 된다. 약 10행이다. 신호가 실제로 채워진 회차를 먼저 관찰한 뒤 하는 것을 권한다. + +## 5. P4-06 · Part 2 handoff의 `source_review_code`에 코드가 아닌 값이 들어 있다 + +**[질문 5-1] 유발하는 문제점(직관적 설명)** + +Part 2 handoff는 Part 4에게 넘기는 "확인할 일 목록"이다. 각 항목의 `source_review_code` 칸에는 "무엇이 문제인지"를 가리키는 코드가 와야 한다. 그런데 55건은 이 칸에 `core_field_base.BehaviorTime`·`ActionType` 같은 칸 이름이 들어 있다. 제목란에 "날짜 누락"이 아니라 "날짜 칸"이라고만 적힌 업무 티켓과 같다. 원인은 이 55건이 원래 코드가 없는 "투영 기본값 메모"인데, 생산 코드가 칸 이름을 코드 자리에 넣은 데 있다(Part 2 YAML 3596행). 결과는 이렇다. +- Part 4는 무슨 문제인지 알 수 없어, 항목마다 "코드가 아님"이라는 검토(`P2_HANDOFF_CODE_NOT_A_REVIEW_CODE_REVIEW`)를 새로 만든다(compiler 430-437행). +- 최종 검토 207건 가운데 55건(27%)이 형식에 관한 잡음이 되어, 실제 법률·증거 문제를 가린다. +- Part 2 정책이 "원본 review_code를 잃지 않기 위한" 칸이라고 정의한 계약도 어긋난다. + +**[질문 5-2] 가장 간단하고 효과적인 해결 방법** + +Part 2 YAML 3596행 한 줄을 고친다. `"source_review_code": note_item.get("field")`를 `"source_review_code": None`으로 바꾸고, 칸 이름은 새 키 `"source_field": note_item.get("field")`로 옮긴다. +- **결과:** + - 투영 메모는 원래 게이트 입력용 코드가 없는 항목이다. compiler는 null 코드를 조용히 건너뛰므로(431-433행, 기존 null 94건과 같은 처리) 잡음 55건이 사라진다. + - 칸 이름은 `source_field`와 `template_note`에 그대로 남아 정보가 줄지 않는다. + - Part 4는 바꾸지 않아도 된다. +- **필요하면:** handoff 스키마나 정책에 `source_field` 키를 등록한다. + +## 6. P4-07 · BO.json이 같은 회차의 것인지 확인하지 않는다 + +**[질문 6-1] 가장 간단하고 효과적인 해결 방법** + +F0이 `validation_assets/routing/part3_receipt.json`을 하나 더 읽어 두 값을 대조한다. +- BO.json 원문의 sha256과 receipt의 `bo_input.sha256`. 4차 실행 값은 `654529b42d0c…`이고, 재생에서 BO 원문 sha와 일치함을 확인했다. +- BO 행 수와 `bo_input.record_count`(78). + +결과는 다음처럼 처리한다. +- **불일치:** status를 BLOCKED로 하고 HARD 검토 `BO_INPUT_SEAL_MISMATCH`를 낸다. +- **receipt 없음:** SOFT 검토로 남긴다. + +추가는 약 8행이다. Part 3이 BO를 읽은 것과 같은 localdocs 원문을 해시하므로 표현 차이로 오탐이 나지 않는다. 이렇게 하면 신호·LES·registry와 같은 수준의 봉인 사슬이 BO까지 닫힌다. 그러면 `by_bo_id` 조인이 다른 회차 BO 위에서 조용히 어긋나는 경로가 막힌다. + +## 7. P4-08 · 활성 도메인 E-15에 사실 행이 없는데도 HARD 게이트가 발화한다 + +**[질문 7-1] 유발할 문제점(직관적·상세 설명)** + +E-15(상속)는 Part 1이 활성 도메인으로 골랐지만, Part 3에서 E-15에 붙은 BO가 하나도 없다. 유일한 후보 bh44는 "목표 무관"으로 판정됐다. 그래서 E-15 사실 행은 0이다. 그런데 Part 2 도메인 신호는 E-15의 요건 칸이 비었거나 충돌한다고 보고하고, 이를 입력으로 두 게이트가 HARD(`blocks_final_drafting`)로 발화했다. +- E15-G01: 요건사실 결여, 상속인 범위 충돌, 상속재산 범위 결여. +- E15-G03: 법령 버전, 피연산자 결여, 트랙 경계. + +이 경보는 "기안을 막아야 할 만큼 중대한 문제"라고 말하지만, 가리킬 사실 행이 없다(`projected_rows: []`). 그래서 행의 `skeleton_validation_codes` 어디에도 나타나지 않고, Part 4 handoff에 한 줄씩만 남는다. 그 줄의 `review_code`는 범용 코드 `GATE_FIRED_REVIEW`이고, 구체 코드는 `detail` 문자열 안에 있다. S2_00은 HARD 코드를 `review_code` 기준으로 센다(배포 코드본 3678행). 그 결과 S2_10의 모든 RC에 가는 공통 맥락 `stage1_hard_review_codes`에는 "`GATE_FIRED_REVIEW` 3건"만 적힌다. X1-G01 1건을 포함한 수이고, 어느 도메인인지, 왜인지는 빠진다. 이로 인해 두 방향의 실패가 생길 수 있다. +1. **과잉 차단:** 사실이 없는 도메인 때문에 사건 전체가 중대 문제를 안은 것처럼 보인다. 검토자는 추적할 근거 행이 없는 경보에 시간을 쓴다. +2. **과소 주의:** 반대로 E-15 쟁점이 실제로 중요할 수 있다. 예를 들어 채무자의 상속 관련 행위가 사해행위 판단에 걸리는 경우다. 이때 경보는 실재하는 증거 공백을 알리는 것이다. 그런데 근거 없이 떠 있어 잡음으로 무시되기 쉽다. + +S2_00은 이 항목에 `blocking` 키가 없어 전역 차단으로 쓰지는 않는다. 다만 경보의 범위를 E-15로 한정해 줄 정보가 전달되지 않는다. + +**[질문 7-2] 가장 간단하고 효과적인 해결 방법** + +compiler가 게이트 발화 검토를 만드는 곳(`fact_ledger_compiler.py` 756-762행 부근)에서 두 가지를 한다. +1. 검토 항목에 `domain_id`와 `projected_row_count`를 싣는다. +2. 투영 행이 0이면 `review_code`를 `GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW`로 바꿔 낸다. 심각도는 HARD를 유지해 문제를 숨기지 않는다. + +약 4행이다. +- **결과:** + - S2_00의 HARD 코드 집계가 "근거 행 있는 차단"과 "사실 없는 도메인 경보"를 자동으로 구분한다. + - `domain_id`가 있어 S2_00 계약의 `blocked_review_item_limits_affected_ready_scope_only: true` 원칙대로 영향 범위를 E-15에 묶을 수 있다. + - 검토자는 "E-15에 붙을 사실이 없다. 증거를 보강할지, 도메인을 비활성할지 정하라"는 구체적 판단만 하면 된다. +- **원인 쪽 조치:** bh44의 목표 무관 판정이 맞는지는 Part 3 사람 검토 항목(4차 보고서 §5-3)에서 함께 본다. + +## 적용 순서 제안 + +- 수정량이 작고 효과가 바로 보이는 것: P4-06(Part 2 한 줄) → P4-07(F0 약 8행) → P4-08(compiler 약 4행) → P4-02(Part 3 + Part 4 몇 줄). +- 계약 문구가 함께 필요한 것: P4-03, P4-04, P4-01. +- 모든 변경은 미적용이다. 커밋·배포·온라인 실행은 승인이 필요하다. diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/작업_히스토리_11_04_밤.txt b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/작업_히스토리_11_04_밤.txt index 7ce7de50..70fb6cbe 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/작업_히스토리_11_04_밤.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/작업_히스토리_11_04_밤.txt @@ -1089,7 +1089,6 @@ Commit and push to git repo. │ Part 4 -- Consistency Check │ │ │ └───────────────────────────────────────┘ -[Claude Desktop -- Sonnet 5 high] Stage 1 - Part 4 작업명세서 `/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_4_v.8.yml`를 읽고, 그것이 현행 Stage 1 -- Part 1/Part 2/Part 3 작업명세서들 `/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8.yml`~`/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_3_v.8.yml`을 upstream으로 하는 downstream 작업으로서의 consistency를 100% 확보하고 있는지 점검하라. 즉, 현행 Part 4 yaml이 Part 1~Part 3의 작업 결과물들을 정상적으로 사용하고 있는지, Part 1~Part 3 작업 결과물들 중 사용해야 할 것들을 사용하지 않는 경우는 없는지, PArt 1~Part 3 결과물들의 형식을 정확하게 반영하고 있는지, Part 4 작업에서 Part 1~Part 3 작업과 연계되지 않는 항목은 없는지 등을 중점적으로 파악하여 보고서를 작성한다. @@ -1097,6 +1096,445 @@ Stage 1 - Part 4 작업명세서 `/Case_02_Comparison_Research/YAML_Prompts/1. S 개정한 보고서를 `/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md`로 생성·저장하라. 작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입하라. +---·---·---·---·---·---· +⬇⬇⬇ + +Part 4는 Part 1~3과 경로·봉인·스키마는 맞지만, 일치성 100%는 아닙니다. 실행을 멈추는 결함(MAJOR)은 없고, 정상 실행에서도 생기는 연결 공백(MINOR)이 7건, 참고 사항(INFO)이 14건 있습니다. + +**점검 방법:** 4차 실행의 실제 산출물을 서버에서 읽기 전용으로 가져왔습니다. BO 78건, `legal_effect_structures.json`, 신호 31파일, handoff 등입니다. 그 위에서 Part 4 F0·F2 코드를 YAML 그대로 재생했습니다. 재생에서 Part 4는 끝까지 돌았고 보존 등식 다섯이 모두 통과했습니다. 다만 F1(Gemini 판정)은 모의였고, 온라인 실행은 아직 하지 않았습니다. + +**MINOR 7건 (먼저 볼 순서대로):** +1. **추천기 표지 오부착(P4-02):** Part 3 추천기가 실제로 붙인 BO는 5건입니다. 그런데 "추천기가 붙임" 표지는 같은 구조에 붙은 12행 모두에 달립니다. 원래 붙어 있던 BO 7건이 실제와 다른 표지를 받습니다. 원인은 Part 3이 이 표지를 BO가 아니라 구조 레코드에 단 데 있습니다. +2. **당사자 칸이 늘 빔(P4-01):** Part 4는 BO의 Performer·Subject에서 `parties`를 만드는데, Part 2 정책은 이 두 칸을 채우지 않는다고 선언했습니다. 그래서 78행 전부 비었습니다. 대체 출처인 party_roles 신호도 4차 실행에서 비어 있었습니다. +3. **계산 요청 복제(P4-03):** 고유 계산 요청 46종이 행마다 복제돼 400건이 됩니다. 같은 요청이 최대 13행에 반복됩니다. 하류가 이것을 더하면 같은 계산을 여러 번 셉니다. 4차 보고서에서 예고했던 확인 사항이 실측으로 확정됐습니다. +4. **읽기만 하는 신호(P4-04):** Part 4가 읽도록 지정된 신호 가운데 SG-06(시한·통지)과 SG-10(증거 충돌)은 읽기만 하고 쓰지 않습니다. +5. **Part 2 handoff의 잘못된 값(P4-06):** 코드가 들어가야 할 칸에 필드 이름이 들어가, Part 4 검토 항목에 잡음 55건이 생깁니다. 결함 위치는 Part 2 YAML 3596행입니다. +6. **BO 회차 대조 없음(P4-07):** 비교할 값(Part 3 receipt의 BO sha)이 이미 있는데도 Part 4는 BO가 같은 회차 것인지 대조하지 않습니다. +7. **근거 행 없는 HARD 게이트(P4-08):** 도메인 E-15에는 사실 행이 하나도 없는데, 기안을 막는 HARD 게이트 둘이 발화합니다. + +**검증과 개정:** 별도 검증자가 재생을 다시 돌리고 수치를 재계산했습니다. 그 지적을 반영해 다음을 고쳤습니다. +- 게이트 HARD·SOFT 구분을 바로잡았습니다. +- 계산 요청 최대 반복 횟수를 12에서 13으로 정정했습니다. +- `object_spec` 공백은 원인이 Part 2에 있어 MINOR에서 INFO로 낮췄습니다. +- E-15 게이트 발화 등 누락 4건을 추가했습니다. + +**저장 위치:** +- 보고서: `1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md` +- `2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" 바로 아래에 작업 내역을 요약해 넣었습니다. +- YAML과 모듈은 수정하지 않았습니다. + +**결정해 주실 일:** 수정 순서로는 P4-02(Part 3이 BO 단위 부착 출처를 남기게 함), P4-01(`parties`의 출처 결정), P4-03(하류 합산 규칙)을 권합니다. 어느 수정을 적용할지 정해 주시면 진행하겠습니다. + +**보안:** Part 4 YAML 머리에도 Part 1~3과 같은 code-executor 토큰이 평문으로 있어, 교체가 여전히 필요합니다. + + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +┌───────────────────────────────────────┐ +│ │ +│ Revision Strategy for Part 4 YAML │ +│ │ +└───────────────────────────────────────┘ +┌────────────────────────────────────────────────────┐ +│ │ +│ Follow-Up Checks on │ +│ `작업간일치성보고서_part_4_on_part_1_to_3.md` │ +│ │ +└────────────────────────────────────────────────────┘ +`작업간일치성보고서_part_4_on_part_1_to_3.md`의 `§3. 지적사항`의 각 항목에 대해 질문 및 요청 사항을 아래에 제시한다. + +[1] **P4-01 · `parties`가 구조적으로 항상 빈다(78/78 실측).** + +[질문 1-1] +사실(행) 단위 당사자 연결이 Stage 1 어디에도 남지 않는 문제를 S2_00이 `client_gola.json`에서 사건 단위 당사자를 얻음으로써 완전히 해결되는가? 한 문단 이내로 답하라. + +[질문 1-2] +`parties`가 구조적으로 비는 문제를 해결하게 되면 Stage 2의 `S2_00`에서 사건 단위 당사자를 추출하는 과정과 충돌이 발생하는가? 한 문단 이내로 답하라. + +[질문 1-3] **P4-01 · `parties`가 구조적으로 항상 빈다(78/78 실측).** 문제를 해결할 가장 간단하고 효율적인 방법을 한 문단 이내로 제시하라. + +[2] **P4-02 · 추천기 부착 표지가 원래 부착된 BO에도 붙는다.** + +[질문 2-1] {{**BO 단위 정보의 위치:** Part 3 handoff 항목의 `bo_id`와 `part3_recommender_receipt.json`의 `attached_bo`에만 있다(part 3 YAML 1632·2117행). Part 4는 둘 다 읽지 않는다.}} 문제를 해결할 가장 간단하고 효과적인 방법을 제시하라. + +[질문 2-2] {{**BO 단위 정보의 위치:** Part 3 handoff 항목의 `bo_id`와 `part3_recommender_receipt.json`의 `attached_bo`에만 있다(part 3 YAML 1632·2117행). Part 4는 둘 다 읽지 않는다.}} 문제를 해결할 경우의 장점을 한 문단 이내로 서술하라. + +[3] **P4-03 · 계산 요청이 도메인 단위로 복제된다(46종 → 400건).** + +[질문 3-1] "P4-03 · 계산 요청이 도메인 단위로 복제"되는 문제의 심각성은 무엇인가? 에이전트 작동 과정에서 어떤 문제점이 발생하는가? 한 문단 이내로 설명하라. + +[질문 3-2] 계산 요청이 도메인 단위로 복제되면 현재 다루는 사건에서는 400건에 대한 계산을 LLM이 수행하게 되는가? 한 문단 이내로 답하라. + +[질문 3-3] "**P4-03 · 계산 요청이 도메인 단위로 복제된다(46종 → 400건).**" 문제를 해결할 가장 간단하고 효과적인 방법을 한 문단 이내로 제시하라. + +[4] **P4-04 · SG-06·SG-10을 읽지만 쓰지 않는다.** + +[질문 4-1] "**P4-04 · SG-06·SG-10을 읽지만 쓰지 않는다.**" 문제점의 심각성은 무엇인가? 한 문단 이내로 설명하라. + +[질문 4-2] "**P4-04 · SG-06·SG-10을 읽지만 쓰지 않는다.**" 문제점을 해결할 가장 간단하고 효과적인 방법을 한 문단 이내로 제시하라. + +[5] **P4-06 · Part 2 handoff의 `source_review_code`에 코드가 아닌 값이 들어 있다.** + +[질문 5-1] "**P4-06 · Part 2 handoff의 `source_review_code`에 코드가 아닌 값이 들어 있다.**"가 유발하는 문제점을 한 문단 이내로 직관적이고 이해하기 쉽게 설명하라. + +[질문 5-2] "**P4-06 · Part 2 handoff의 `source_review_code`에 코드가 아닌 값이 들어 있다.**" 문제를 해결할 가장 간단하고 효과적인 방법을 한 문단 이내로 제시하라. + +[6] **P4-07 · BO.json이 같은 회차의 것인지 확인하지 않는다.** + +[질문 6-1] "**P4-07 · BO.json이 같은 회차의 것인지 확인하지 않는다.**" 문제를 해결할 가장 간단하고 효과적인 방법을 한 문단 이내로 제시하라. + +[7] **P4-08 · 활성 도메인 E-15에 사실 행이 없는데도 HARD 게이트가 발화한다.** + +[질문 7-1] "**P4-08 · 활성 도메인 E-15에 사실 행이 없는데도 HARD 게이트가 발화한다.**"가 유발할 문제점을 한 문단 이내로 직관적이고 상세하게 설명하라. + +[질문 7-2] "**P4-08 · 활성 도메인 E-15에 사실 행이 없는데도 HARD 게이트가 발화한다.**"를 해결할 가장 간단하고 효과적인 방법을 한 문단 이내로 제시하라. + + +에 제시된 질문 혹은 요구 사항 해결책을 작성하여 '/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md'으로 생성·저장하라. + +작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입하라. + +---·---·---·---·---·---· +⬇⬇⬇ +[요약답변] + +질문 17개에 대한 해결법 문서를 만들어 저장했고, `2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" 바로 아래에 작업 요약을 넣었습니다. 모든 답은 Stage 1·2 YAML과 compiler 코드, 그리고 4차 실행 산출물을 직접 읽고 확인했습니다. YAML과 모듈은 수정하지 않았습니다. + +**질문별 답:** +- **P4-01 (당사자 칸):** + - `client_goal`만으로는 해결되지 않습니다. 실제 서버에 올라간 S2_00은 사실마다 당사자를 이름이 함께 나오는지로 추정합니다. 그래서 누가 행위자이고 누가 상대방인지 구분하지 못하고, 관계없는 사람까지 붙습니다. 10월 11일에 확인한 피고 과식별의 원인과 같은 방식입니다. + - 칸을 채워도 충돌은 없습니다. 지금 S2_00은 이 칸을 읽지 않습니다. + - 가장 간단한 해결은 Part 4가 Part 1의 당사자 연결표(`value_facts_party_links.json`)를 읽어 BO의 금액 참조로 연결하는 것입니다. 이 표의 이름은 `client_goal` 정규명이라 S2_00 명부와 그대로 맞습니다. 최대 49/78행이 채워지고, 실제로 연결되는 비율은 측정하지 않았습니다. +- **P4-02 (추천기 표지):** Part 3이 표지를 다는 바로 그 자리에, 실제로 붙인 BO 목록을 함께 남기면 됩니다. 그러면 Part 4는 그 BO 행에만 표지를 답니다. 오경보 7건이 사라지고, 기계가 붙인 사실과 규칙으로 붙인 사실을 하류에서 구분할 수 있습니다. +- **P4-03 (계산 요청 복제):** + - LLM이 400건을 계산하지는 않습니다. 계산 요청은 "이 계산이 필요하다"는 기록일 뿐입니다. S2_10에는 전달되지 않고, 실제 계산은 S2_20이 코드로 합니다. + - 지금의 피해는 보고 수치가 부풀어 보이는 정도입니다. 진짜 위험은 나중에 S2_20이 이 목록을 그대로 쓰면 같은 계산이 최대 13번 들어가 청구금액이 부풀 수 있다는 점입니다. + - 해결은 이미 고유한 `request_id`를 합산 기준으로 선언하고, writer report에 고유 기준 수치(46건)를 추가하는 것입니다. 약 5행입니다. +- **P4-04 (SG-06·SG-10):** 심각도는 낮습니다. S2_00이 모든 신호를 직접 읽으므로 정보가 사라지지 않습니다. 문제는 사실 행에 시한이나 증거 충돌이 반영된 것처럼 보이는 거짓 안심입니다. Part 4 읽기 목록에서 두 신호를 빼는 것을 권합니다. 이 경우 manifest를 다시 봉인해야 합니다. +- **P4-06 (Part 2 코드 칸):** 최종 검토 207건 가운데 55건(27%)이 형식 잡음입니다. Part 2 YAML 3596행 한 줄만 고치면 됩니다. 필드 이름은 `source_field`라는 새 칸으로 옮기고, 코드 칸은 비워 둡니다. +- **P4-07 (BO 회차 확인):** Part 4의 첫 task가 Part 3 receipt에 기록된 BO의 sha256과 실제 BO를 대조하면 됩니다. 약 8행입니다. +- **P4-08 (E-15 게이트):** + - 근거 사실이 없는 "기안 차단" 경보가 S2_10의 모든 청구 묶음에 "`GATE_FIRED_REVIEW` 3건"으로만 전달됩니다. 어느 도메인인지가 빠져 있습니다. + - 그래서 사건 전체가 막힌 것처럼 보이는 과잉 차단이 생기거나, 반대로 실재하는 증거 공백이 잡음으로 무시될 수 있습니다. + - 해결은 사실 행이 0인 발화를 별도 코드로 내고 도메인 id를 함께 싣는 것입니다. 약 4행입니다. + +적용 순서는 수정량이 작은 P4-06, P4-07, P4-08, P4-02를 먼저 하길 권합니다. 어느 항목을 적용할지 정해 주시면 진행하겠습니다. 커밋, 배포, 온라인 실행에는 승인이 필요합니다. + +파일: +- [작업간일치성보고서_해결법_part_4_on_part_1_to_3.md](../1.%20Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md) +- [MEMORY.md](MEMORY.md) + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +┌───────────────────────────────────────┐ +│ │ +│ Revision of Part 4 YAML │ +│ │ +└───────────────────────────────────────┘ + +아래 작업을 수행하라. + +[0] 현행 `stage_1_part_4_v.8.yml`을 `stage_1_part_4_v.8_11_05_5_22pm.yml`으로 복제·저장하라. + +[1] `작업간일치성보고서_해결법_part_4_on_part_1_to_3.md`가 제시하는 수정 방안을 "적용 순서 제안"대로 "P4-06(Part 2 한 줄) → P4-07(F0 약 8행) → P4-08(compiler 약 4행) → P4-02(Part 3 + Part 4 몇 줄)." 순서로 먼저 개정한다. 이후, "계약 문구가 함께 필요한 것: P4-03, P4-04, P4-01." 순서대로 개정한다. + +[2] 개정된 `stage_1_part_4_v.8.yml`이 `작업간일치성보고서_해결법_part_4_on_part_1_to_3.md`가 제시하는 수정 방안을 정확히 반영했는지, '단순 해법 우선' 및 '최소 개정' 원칙을 잘 준수했는지를 sub-agent를 통해 독립 검증하고, 검증 과정에서 도출된 개선사항을 반영하여 `stage_1_part_4_v.8.yml`을 재개정한다. `독립검증->재개정` 작업은 2회 반복 후 종료한다. + +[3] [2]에서 최종 개정된 `stage_1_part_4_v.8.yml`을 overwrite하여 저장하고, prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입하라. + + + +- yaml 작성 시 Liti-agent의 yaml 작성 가이드라인(`Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/SKILL.md`)을 준수한다. +- Python code 작성 시 Liti-agent의 python code 작성 가이드라인(`Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/test_code_executor.ipynb`)을 준수한다. + + +---·---·---·---·---·---· +⬇⬇⬇ +[요약답변] + +해결법 문서의 7건을 모두 개정해 덮어쓰기 저장했고, 독립 검증과 재개정을 2회 마쳤습니다. 4차 실행 데이터로 오프라인 재생을 돌린 결과, 각 수정이 의도대로 동작했습니다. 다만 Gemini 판정 단계(F1)는 모의로 대신했고, 커밋·서버 배포·온라인 실행은 하지 않았습니다. + +**항목별 결과 (4차 데이터 재생, 개정 전 → 개정 후)** + +| 항목 | 개정 전 | 개정 후 | +|---|---|---| +| P4-01 당사자 칸 | 0행 | 42행 (`client_goal` 정규명) | +| P4-02 추천기 표지 | 12행 | 실제 추천기가 붙인 5행 | +| P4-03 계산 요청 | 400건 집계만 | writer report에 고유 46건 기준 수치 추가, F1 입력의 중복 id 제거 | +| P4-04 SG-06·SG-10 | 읽고 쓰지 않음 | 읽지 않음 | +| P4-06 형식 잡음 | 55건 | 0건 (모사 시험, 아래 참고) | +| P4-07 BO 회차 대조 | 없음 | 대조 일치. BO를 한 글자만 바꿔도 작업이 멈춤 | +| P4-08 E-15 게이트 | 범용 코드 | 새 코드 `GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW`와 도메인 id를 실음 | + +- **P4-06은 아직 실데이터로 확인되지 않았습니다.** 4차 데이터의 Part 2 handoff는 개정 전 판이라, 고친 형태의 handoff를 모사해 시험했습니다. 실제 효과는 Part 2를 다시 실행해야 나타납니다. +- **예외 경로도 시험했습니다.** Part 3 영수증 부재, Part 3 handoff 부재, 다른 회차의 당사자 연결표, BO 변조를 넣어 보았습니다. 앞의 셋은 해당 기능을 개정 전 동작으로 되돌리거나 당사자 칸을 비우고 SOFT 검토를 남깁니다. BO 변조는 작업을 멈춥니다. + +**계획과 다르게 한 두 가지** +- **P4-02는 Part 3을 고치지 않았습니다.** 계획의 기본안은 Part 3이 구조 레코드에 새 키를 다는 것이었습니다. 그런데 그 레코드 스키마는 새 키를 허용하지 않아, Part 3 코드와 스키마를 고치고 다시 봉인해야 했습니다. 대신 Part 4가 Part 3 review handoff를 읽습니다. 이 파일은 같은 회차에 확정되고 BO 단위 정보를 이미 담고 있습니다. 검증자 둘 다 더 단순하고 타당하다고 판단했습니다. +- **P4-07은 불일치 시 작업을 멈춥니다.** 계획은 "BLOCKED 상태와 HARD 검토"였지만, F0의 다른 봉인 실패와 같은 방식으로 맞췄습니다. + +**검증 과정에서 고친 것** +- **1차 검증이 하류 의존을 찾았습니다.** S2_20은 코드 이름이 `GATE_FIRED_REVIEW`인지로 등급을 매깁니다. 새 코드만 쓰면 E-15의 HARD 경보가 낮아질 뻔했습니다. 검토 항목에 차단 표지(`blocks_final_drafting`)를 함께 실어 HARD는 1등급을 유지하게 했습니다. +- 그 밖에 반영한 것: + - 당사자 연결표가 같은 회차인지 확인 + - BO 파싱 대비책 복원(SKILL.md §5) + - 입력이 없을 때 SOFT 검토 항목 생성 + - 정책 파일의 낡은 `parties` 규칙과 계산 요청 키 계약 문구 수정 +- **받아들인 차이 하나:** 사실 행이 없는 비차단(SOFT) 게이트 경보는 S2_20에서 3등급 대신 4등급이 됩니다. 고치려면 Stage 2 파일을 수정해야 해서, 이번에는 받아들이고 YAML 머리말에 적었습니다. + +**바뀐 파일** +- `stage_1_part_4_v.8.yml`: 덮어썼습니다. 개정 전 판은 `stage_1_part_4_v.8_11_05_5_22pm.yml`로 복제해 두었습니다. +- `stage_1_part_2_v.8.yml`: P4-06 두 줄, 머리말 메모, manifest 기대값을 고쳤습니다. +- 자산 다섯 개: `fact_ledger_compiler`와 `signal_compiler`(각각 .py·.txt), `fact_ledger_policy`. `runtime_manifest.json` sha는 `a828e962…`에서 `9d2df172…`로 바뀌었습니다. +- Part 3 YAML은 바꾸지 않았습니다. +- 백업 파일은 모두 `v.8` 폴더에 있습니다. +- `2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" 바로 아래에 작업 요약을 넣었습니다. + +**결정해 주실 일** +- 다음 실행 전에 `Default_Agent` 폴더 전체와 manifest를 서버에 다시 올려야 합니다. Part 2가 새 manifest sha를 기대하므로, 옛 묶음이 서버에 남아 있으면 배포 게이트에서 멈춥니다. +- 커밋, 서버 배포, 온라인 실행(Part 2부터 다시)은 승인해 주셔야 진행합니다. + +**보안:** Part 1~4 YAML 머리에 있는 code-executor 토큰 평문 노출은 이번 개정과 무관하게 그대로 남아 있습니다. 토큰 교체가 여전히 필요합니다. + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +┌─────────────────────────┐ +│ Follow-Up Checks │ +└─────────────────────────┘ +이번 개정 과정에서 수정한 정적 자산 항목들을 리스트로 작성하고, 그것들의 백엔드 배포 위치 및 현재 로컬 저장 위치를 제시하라. +---·---·---·---·---·---· +⬇⬇⬇ + +이번 개정에서 수정한 정적 자산은 6개입니다. 백엔드에서는 모두 워크스페이스의 `Default_Agent/` 폴더 아래에 있습니다. 서버 확인은 읽기 전용으로만 했습니다. + +**수정한 정적 자산** + +| # | 자산 | 수정 내용 | 백엔드 논리 경로 (YAML이 읽는 경로) | +|---|---|---|---| +| 1 | `fact_ledger_compiler.py` | P4-01·02·03·08 | `Default_Agent/stage1_runtime/fact_ledger_compiler.py` | +| 2 | `fact_ledger_compiler.txt` | 1과 같은 내용의 사본. Part 4가 실제로 실행하는 파일 | `Default_Agent/stage1_runtime/fact_ledger_compiler.txt` | +| 3 | `fact_ledger_policy.v1.json` | `parties` 규칙과 `calculation_request_key` 계약 문구 | `Default_Agent/stage1_runtime/fact_ledger_policy.v1.json` | +| 4 | `signal_compiler.py` | P4-04: Part 4 읽기 집합을 SG-04·SG-07·SG-11로 줄임 | `Default_Agent/signals/compiler/signal_compiler.py` | +| 5 | `signal_compiler.txt` | 4와 같은 내용의 사본. Part 2가 실행하는 파일 | `Default_Agent/signals/compiler/signal_compiler.txt` | +| 6 | `runtime_manifest.json` | 1~5의 sha256을 다시 기록함. 파일 sha가 `a828e962…`에서 `9d2df172…`로 바뀜 | `Default_Agent/runtime_manifest.json` | + +**백엔드 물리 위치** +- 실제 파일은 `mcp-localdocs` 컨테이너 안에 워크스페이스별로 있습니다. + - 경로 형식: `/mcp-localdocs/users/{사용자 해시}/{워크스페이스 해시}/Default_Agent/<논리 경로>` + - 4차 실행에 쓴 `11월_1일_구성` 워크스페이스: `/mcp-localdocs/users/31d5b916…/3d5eb245…/Default_Agent/` + - 이 폴더에 `stage1_runtime/fact_ledger_compiler.py`·`.txt`와 `fact_ledger_policy.v1.json`이 있는 것을 확인했습니다. 지금 서버에 있는 것은 개정 전 판입니다. + - 다른 워크스페이스에도 각자 `Default_Agent/` 사본이 있습니다. +- `agent-backend`의 `/app/pre_loads/Default_Agent/`에는 이 자산들이 없습니다. 그래서 새 워크스페이스를 만들어도 자동으로 들어가지 않으니, 실행할 워크스페이스에 직접 올려야 합니다. + +**현재 로컬 저장 위치** +- 기준 폴더: `Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/` + - [stage1_runtime/fact_ledger_compiler.py](../1.%20Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py)와 같은 폴더의 `.txt` + - [stage1_runtime/fact_ledger_policy.v1.json](../1.%20Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json) + - [signals/compiler/signal_compiler.py](../1.%20Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py)와 같은 폴더의 `.txt` + - [runtime_manifest.json](../1.%20Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json) +- 개정 전 백업은 [v.8](../1.%20Stage_1/v.8/) 폴더에 있습니다. + - `fact_ledger_compiler_11_05_5_22pm.py.bak` + - `fact_ledger_policy_11_05_5_22pm.json.bak` + - `signal_compiler_11_05_5_22pm.py.bak` + - `runtime_manifest_11_05_5_22pm.json.bak` + +**배포할 때 주의할 점** +- **여섯 파일은 한 벌로 올려야 합니다.** Part 2는 manifest 파일 sha가 `9d2df172…`인지 확인하고, Part 2·4는 각 자산의 sha를 manifest와 대조합니다. 일부만 올리면 배포 게이트에서 멈춥니다. +- YAML 두 개(`stage_1_part_2_v.8.yml`, `stage_1_part_4_v.8.yml`)는 정적 자산이 아니라 실행 스크립트입니다. 위 목록과 별도로 반영해야 합니다. + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +┌─────────────────────────────────────┐ +│ Test Run w/ Stage 1 -- Part 4 │ +└─────────────────────────────────────┘ +런타임: 14.4 secs + + +백엔드 workspace '11월_1일_구성'에서 조금 전 개정된 `stage_1_part_4_v.8.yml`를 업로드하고 실행하였다. +백엔드 로그 기록을 분석하여 작업의 실패 혹은 성공 여부를 판정하라. 작업이 실패했다면 실패 지점, 실패 원인, 해결 방안을 문서로 작성하고, 성공했다면 성공 내역을 분석하여 '/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md'로 생성·저장하라. 작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입한다. +---·---·---·---·---·---· +⬇⬇⬇ + +Part 4 실행은 **성공**입니다. 세 작업이 모두 오류 없이 끝났고, 실행 시간은 14.6초입니다(세션 `13825502`). 결과보고서와 MEMORY.md 항목을 작성했습니다. + +**판정 근거 (백엔드 로그, 읽기 전용)** +- 세 작업 모두 `task_complete`로 끝났습니다. 오류·재시도·Traceback은 0건이고, `execution_complete`가 정상으로 찍혔습니다. + - **F0 (코드):** `READY_WITH_REVIEW`입니다. 사실 원장 행 78개, 게이트 발화 5개, 금액 예외 7건, 검토 항목 200건입니다. `errors`와 `warnings`는 비어 있습니다. + - **F1 (Gemini):** 금액 예외 7건을 모두 판정했습니다. + - **F2 (코드):** 7건 모두 금액을 선택했고 미해결은 0건입니다. 보존 등식을 통과했고, 최종 sha는 `0780f4f0…`입니다. +- 로그에 남은 실행 코드에서 개정 표지를 확인했습니다. 업로드된 YAML은 개정판(`c53a0120…`)입니다. + +**서버 산출과 로컬 재생이 같다는 확인** +- localdocs는 파일을 암호화해서 저장합니다. 그래서 sha로 직접 비교할 수 없습니다. +- 백엔드 API로 평문을 받는 방법은 관리자 토큰이 필요합니다. 권한 분류기가 막아서 우회하지 않았습니다. +- 대신 세 가지를 대조했습니다. + - 서버 F0 결과가 같은 YAML·자산·입력으로 돌린 로컬 재생 결과와 필드 단위로 같습니다. + - F1 입력 파일이 로컬 재생본과 바이트 단위로 같습니다. + - 로컬에서 F1이 각 예외의 첫 후보를 고른다고 가정하고 F2를 돌렸더니, 최종 sha가 서버 값과 정확히 같았습니다. 서버 최종 원장은 로컬 재생본과 같은 파일입니다. + +**수정 효과 (서버 산출 기준)** +- **당사자 (P4-01):** 당사자 정보가 있는 행이 0개에서 42개가 됐습니다. +- **추천기 표지 (P4-02):** 12개 행에 퍼져 있던 표지가 실제로 붙은 BO 5건에만 남았습니다. +- **계산 요청 (P4-03):** 중복을 제거한 고유 요청 46건이 보고서에 실립니다. +- **BO 봉인 (P4-07):** `MATCHED`입니다. +- **행 없는 게이트 (P4-08):** E-15 게이트 3건이 새 코드로 나왔습니다. HARD 경보에는 `blocks_final_drafting: true`가 실려 있어, S2_20에서 경보 등급이 낮아지지 않습니다. +- **Part 2 비코드 항목 (P4-06):** 55건이 그대로 남았습니다. Part 2를 다시 실행하지 않았기 때문이고, 예상된 결과입니다. +✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎ +**확인이 필요한 두 가지** +1. **F1이 7건 모두 첫 번째 후보를 골랐습니다.** 위치 편향일 수 있습니다. + - 특히 FX-004는 신림동 상가와 포천 임야 두 목적물에 걸친 평가인데, 신림동 값 하나를 골랐습니다. + - F2는 원래 금액과 후보를 그대로 두고 선택 표시만 하므로 손실은 없습니다. + - 다만 계산이 필요한 예외는 후보를 고르지 않고 검토로 넘기는 규칙을 F1 프롬프트에 둘지 판단해 주십시오. +✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎✖︎ +2. **P4-06 효과는 Part 2를 다시 실행해야 확인됩니다.** 서버 manifest는 이미 새 판이라 Part 2 배포 검사는 통과할 것으로 봅니다. 개정 파일들은 아직 커밋하지 않았습니다. + +**작성한 파일** +- 보고서: [실행결과보고서_1_part_4.md](../1.%20Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md) +- [MEMORY.md](MEMORY.md)의 "How to Write MEMORY.md" 바로 아래에 이번 실행 항목을 추가했습니다. + + + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +┌─────────────────────────────────────┐ +│ Test Run w/ Stage 1 -- Part 4 │ +└─────────────────────────────────────┘ +실제 런타임: 4 min 14.1 secs +(카프카 효과를 크게 누릴 수 있는 지점 -> 3 min 미만으로 줄어들 가능성 높음) + + +백엔드 workspace '11월_1일_구성'에서 조금 전 개정된 `stage_1_part_2_v.8.yml`를 업로드하고 실행하였다. +백엔드 로그 기록을 분석하여 작업의 실패 혹은 성공 여부를 판정하라. 작업이 실패했다면 실패 지점, 실패 원인, 해결 방안을 문서로 작성하고, 성공했다면 성공 내역을 분석하고, 로그에 기록된 토큰 사용 기록을 통해 LLM API 사용 비용도 추정·기록하여 '/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md'로 생성·저장하라. 작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입한다. +---·---·---·---·---·---· +⬇⬇⬇ +Part 2 실행은 **성공**입니다(세션 `1fb26ede`, 4분 14초). 결과보고서와 MEMORY.md 항목을 작성했습니다. + +**판정 근거 (백엔드 로그, 읽기 전용)** +- task 37개가 모두 끝났습니다. task 오류·재시도는 0건이고, 실행 완료 이벤트가 정상으로 찍혔습니다. +- **배포 검사(A0):** 통과했습니다(`READY`). 개정판에 넣은 manifest 고정값 `9d2df172…`가 서버 manifest와 맞았습니다. 로그에 남은 실행 코드에서도 P4-06 수정(`source_review_code: None`, `source_field`)을 확인했습니다. +- **BO 작성(F0):** `PASS`, BO 88건입니다. 게이트 7개가 모두 통과했고, 금액이 결속된 BO는 46건, 사람 판정은 0건입니다. +- **signal 작성(S0):** `READY_WITH_REVIEW`입니다. signal gate를 통과했고 오류는 0건입니다. Part 4가 읽는 신호 집합이 SG-04·SG-07·SG-11로 바뀐 것도 나타나, 개정한 `signal_compiler`가 서버에서 쓰였습니다. +- **로그의 오류 기록:** 사전 읽기 직후의 부수 `read_docs` 호출 12건이 `SSE stream ended without a response`로 재시도 3회 끝에 실패했습니다. 실행에는 영향이 없습니다. 15개 worker 모두 그 전에 입력 파일 6개를 받아 정상 응답했습니다. + +**LLM API 비용: $1.99** (로그 `[USAGE]` 17건 합계 $1.988904) + +| 호출 | 모델 | 비용 | +|---|---|---:| +| prewarm 1회 (캐시 기록) | GPT-6.1 Sol | $0.29 | +| worker 15회 | GPT-6.1 Sol | $1.68 (그중 출력 토큰 $1.12) | +| R1 1회 | Gemini 3.5 Flash-Lite | $0.03 | + +- worker마다 공유 입력 114,055토큰이 캐시에서 읽혔습니다. 캐시가 없었다면 worker 비용은 약 $4.93였을 것입니다. +- 로그 비용에서 단가를 역산했습니다(100만 토큰당). 15개 worker 모두에서 오차 없이 맞습니다. + - GPT-6.1 Sol: 입력 $2, 캐시 적중 $0.10, 출력 $10. + - Gemini Flash-Lite: 입력 $0.30, 출력 $2.50. + +**다음에 하실 일** +1. **Part 3을 실행한 뒤 Part 4를 실행해 주십시오.** + - worker를 다시 실행하면서 BO가 78건에서 88건으로 바뀌었고, signal 거래 id도 새로 바뀌었습니다. 지금 서버의 Part 3·4 산출은 예전 BO 78건 기준입니다. + - Part 4는 BO가 Part 3 영수증과 같은지 대조합니다. 그래서 Part 3를 건너뛰고 Part 4만 돌리면 그 대조에서 멈춥니다. +2. **P4-06 효과는 그 Part 4 실행에서 확인됩니다.** Part 4 검토 항목 중 Part 2 비코드 항목 55건이 0건이 되어야 합니다. +3. **아직 커밋하지 않았습니다.** Part 2·4 YAML과 정적 자산 6종이 로컬 작업 트리에만 있습니다. + +**작성한 파일** +- 보고서: [실행결과보고서_1_part_2.md](Case_02_Comparison_Research/YAML_Prompts/1.%20Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md) +- [MEMORY.md](Case_02_Comparison_Research/YAML_Prompts/2.%20Stage_2/MEMORY.md)의 "How to Write MEMORY.md" 바로 아래에 이번 실행 항목을 추가했습니다. + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +Part 3 런타임: 48.5 secs + + +백엔드 workspace '11월_1일_구성'에서 `stage_1_part_3_v.8.yml`를 재실행하였다. +백엔드 로그 기록을 분석하여 작업의 실패 혹은 성공 여부를 판정하라. 작업이 실패했다면 실패 지점, 실패 원인, 해결 방안을 문서로 작성하고, 성공했다면 성공 내역을 분석하고, 로그에 기록된 토큰 사용 기록을 통해 LLM API 사용 비용도 추정·기록(LLM 사용 없으면 무시)하여 '/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md'로 생성·저장하라. 작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입한다. +---·---·---·---·---·---· +⬇⬇⬇ +* L0: BO 88 중 82 부착(이전 63/78). L1: 후보 6·쌍 15 전부 UNDECIDED, 부착 0. planner 쌍에 glossary_source llm_unverified 표시 — glossary 검증 상태 확인. +* JEV 16회 확률 분포 확보. part_of 최고 0.75 — 수용 임계값 0.80 미달로 6건 모두 UNDECIDED 설명됨. 비용 집계 후 보고서 작성. + +[요약답변] +Part 3 재실행은 **성공**입니다(세션 `88ee7816`, 48.5초). 최종 결과는 `READY_WITH_REVIEW`이고, LLM 비용은 약 $0.023입니다. 보고서와 MEMORY.md 항목을 작성했습니다. + +**판정 근거 (백엔드 로그, 읽기 전용)** +- task 37개가 모두 완료됐습니다. 오류·재시도·Traceback은 0건이고, 실행 완료 이벤트가 정상으로 찍혔습니다. 이번에는 YAML을 다시 올리지 않고 4차와 같은 판으로 실행됐습니다. +- **L0 (규칙 부착):** 새 Part 2 산출(BO 88건) 중 82건이 규칙만으로 법률효과 구조에 붙었습니다. 4차는 BO 78건 중 63건이었습니다. 미부착은 6건, SG-11 47개는 모두 연결됐습니다. +- **glossary:** 정상입니다(Gemini 3.8 Flash, 정의 40개 수용). +- **추천기:** 후보 유형 6개, 비교 쌍 16개를 만들었고 JEV 16회가 모두 응답했습니다. +- **apply:** 6건 모두 판정 보류(UNDECIDED)라 추천기로 새로 붙은 BO는 0건입니다. +- **L2:** 품질 게이트 세 개를 통과했습니다. BO 색인 82개는 부착 수와 같습니다. + +**추천기가 하나도 붙이지 않은 이유** +- capture 코드에 남은 확률 분포를 로그에서 복원했습니다. +- "선언 유형의 일부(part_of)"를 고른 쌍은 4개이고, 확률은 0.75·0.66·0.44·0.43입니다. 모두 수용 임계값 0.80에 못 미칩니다. 나머지 12쌍은 "관련 없음(unrelated)"을 골랐습니다. +- 가장 높은 0.75는 경매개시결정이 피담보채권의 일부라는 판정입니다. 법률적으로 방향은 맞지만 임계값 미달이라 사람 검토로 남았습니다. +- E-12 명의신탁 소유 주장은 선언 유형 5개 모두와 "관련 없음"이었습니다. 이 영역에 맞는 선언 유형이 registry에 없을 수 있습니다. + +**LLM API 비용 (로그 기록)** +- glossary: Gemini 3.8 Flash 1회, $0.0229. +- JEV: 16회, $0.0005. +- 합계: 약 $0.0234. + +**다음에 하실 일** +1. **Part 4를 다시 실행해 주십시오.** Part 3 산출과 영수증이 새 BO 88건 기준으로 바뀌어, Part 4의 BO 봉인 대조를 통과할 조건이 갖춰졌습니다. 그 실행에서 확인할 것은 다음과 같습니다. + - Part 2 비코드 검토 항목(이전 55건)이 0건이 되는지. + - 추천기 표지가 0행인지. 이번에 추천기가 붙인 BO가 없으므로 0행이 나와야 합니다. +2. **수용 임계값 0.80을 유지할지 정해 주십시오.** + - 유지하면 0.75처럼 방향이 맞는 판정도 사람 검토로 넘어갑니다. + - 4차에서 수용된 4건은 모두 0.99였으므로, 지금 값은 보수적인 설정입니다. +3. **아직 커밋하지 않았습니다.** Part 2·4 YAML과 정적 자산 6종이 로컬 작업 트리에만 있습니다. + +**작성한 파일** +- 보고서: [실행결과보고서_5_part_3.md](Case_02_Comparison_Research/YAML_Prompts/1.%20Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md) +- [MEMORY.md](Case_02_Comparison_Research/YAML_Prompts/2.%20Stage_2/MEMORY.md)의 "How to Write MEMORY.md" 바로 아래에 이번 실행 항목을 추가했습니다. + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +Part 4 런타임: 14.8 secs + + +백엔드 workspace '11월_1일_구성'에서 `stage_1_part_4_v.8.yml`를 재실행하였다. +백엔드 로그 기록을 분석하여 작업의 실패 혹은 성공 여부를 판정하라. 작업이 실패했다면 실패 지점, 실패 원인, 해결 방안을 문서로 작성하고, 성공했다면 성공 내역을 분석하고, 로그에 기록된 토큰 사용 기록을 통해 LLM API 사용 비용도 추정·기록(LLM 사용 없으면 무시)하여 '/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md'로 생성·저장하라. 작업 완료 후, `prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/MEMORY.md`의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입한다. +---·---·---·---·---·---· +⬇⬇⬇ + +Part 4 재실행은 **성공**입니다(세션 `b4fc2158`, 14.8초). 결과는 `READY_WITH_REVIEW`이고 LLM 비용은 $0.0114입니다. 이로써 11-05의 Part 2 → Part 3 → Part 4 재실행이 모두 성공했습니다. 세 Part 합계는 약 $2.02, 약 5분 17초입니다. + +**판정 근거 (백엔드 로그, 읽기 전용)** +- task 3개가 모두 완료됐습니다. 오류·재시도·Traceback은 0건입니다. +- **F0 (코드):** 사실 원장 행 88개로, 새 BO 88건과 같습니다. 게이트 발화 5개, 금액 예외 7건, 검토 항목 133건입니다. 오류와 경고는 없습니다. +- **BO 봉인 검사:** 통과했습니다. BO가 Part 3 영수증과 어긋나면 F0가 멈추고, 영수증이 비어 있으면 경고를 남깁니다. 둘 다 일어나지 않았으므로 새 BO가 Part 3 5차 영수증과 일치한 것입니다. +- **F1 (Gemini Flash-Lite):** 금액 예외 7건을 판정했습니다. F2는 3건을 채택하고 4건을 미해결로 남겼습니다. 보존 등식을 통과했고, 최종 sha는 `701a65e1…`입니다. + +**1차 실행과 달라진 점** +- **검토 항목:** 200건에서 133건으로 줄었습니다. P4-06 수정으로 빠져야 할 Part 2 비코드 항목 55건과 방향은 맞습니다. 다만 입력 데이터도 함께 바뀌어 항목별로 나눠 확인하지는 못했습니다. +- **F1 판정:** 1차에서 우려했던 "7건 모두 첫 번째 후보 선택"은 이번에 반복되지 않았습니다. 두 목적물에 걸친 기간별 평가 같은 항목은 미해결로 남는 편이 맞습니다. + +**이번에 확인하지 못한 것** +- 1차 때는 같은 입력으로 로컬 재생을 돌려 최종 sha가 서버와 같은지 대조했습니다. 이번에는 Part 2·3 입력이 새로 바뀌었고, 서버 파일이 암호화돼 있어 그 대조를 할 수 없었습니다. +- 그래서 다음 항목은 확인하지 못했습니다. + - 당사자 정보가 있는 행 수. + - 추천기 표지가 0행인지. + - 게이트 review 코드 구성. + - F1이 어느 3건을 골랐는지(판정 원문이 로그에서 잘렸습니다). +- 확인하려면 둘 중 하나가 필요합니다. 관리자 토큰으로 백엔드 파일 API를 쓰도록 허용해 주시거나, 해당 파일을 내려받아 로컬에 두시면 됩니다. + +**LLM API 비용** +- F1: Gemini 3.5 Flash-Lite 호출 2회, 로그 기록 $0.011424. +- 같은 단가로 계산해도 같은 값입니다(100만 토큰당 입력 $0.30, 캐시 적중 $0.03, 출력 $2.50). +- 이번에 로그에서 1차 Part 4 비용도 확인했습니다. $0.0115이고, 이 값은 2차 보고서에 함께 적었습니다. + +**남은 결정** +1. **커밋:** Part 2·4 YAML과 정적 자산 6종은 서버에는 올라가 있지만 아직 커밋하지 않았습니다. +2. **Stage 2 연결:** 새 사실 원장(행 88)을 S2_00 입력으로 다시 연결할지 정해 주십시오. + +**작성한 파일** +- 보고서: [실행결과보고서_2_part_4.md](Case_02_Comparison_Research/YAML_Prompts/1.%20Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md) +- [MEMORY.md](Case_02_Comparison_Research/YAML_Prompts/2.%20Stage_2/MEMORY.md)의 "How to Write MEMORY.md" 바로 아래에 이번 실행 항목을 추가했습니다. + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ + + + + @@ -1124,9 +1562,9 @@ Part 3 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Part 4 - -> consistency 체크(Part 1~Part 3 모두를 참고한다) - -> 개정 필요 항목 도출 -> 개정 전략서 작성 -> 개정 - -> 실행 -> 성공할 때까지 개정 반복 + -> consistency 체크(Part 1~Part 3 모두를 참고한다) ✅ + -> 개정 필요 항목 도출 -> 개정 전략서 작성 -> 개정 ✅ + -> 실행 -> 성공할 때까지 개정 반복 ✅ ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ @@ -1225,3 +1663,4 @@ Net profit = +3천억 per year after R&D(2천억 per year) + \ No newline at end of file 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 7827842c..84c9a643 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 @@ -4,6 +4,147 @@ ## How to Write MEMORY.md +### 2026-11-05 — Part 4 재실행 성공 (세션 b4fc2158, 2차) — Stage 1 Part 2~4 재실행 완료 + + +한 줄 요약: Part 2·3 새 산출(BO 88) 위에서 Part 4가 14.8초 만에 `READY_WITH_REVIEW`로 성공했다. 비용은 $0.0114다. 보고서는 `1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_2_part_4.md`다. +- **결과:** + - 행 88, 게이트 82/10/5, 예외 7, review 133(1차 200). + - F1(Flash-Lite): 선택 3, 미해결 4. `final_sha256` `701a65e1…`. + - BO 봉인 통과(`warnings` 비어 있음). +- **P4-06:** review가 67건 줄었다. 비코드 항목 55건이 빠진 것과 방향은 맞지만, 입력도 바뀌어 항목별 분해는 하지 못했다. +- **F1 위치 편향:** 1차의 "7건 모두 첫 후보"는 반복되지 않았다. 어느 3건을 골랐는지는 로그에서 잘려 알 수 없다. +- **확인 한계:** 입력이 바뀌어 로컬 재생으로 대조할 수 없었다. 당사자 행·추천기 표지·게이트 코드는 미확인이다. 확인하려면 암호화 파일을 백엔드 API(관리자 토큰)로 받거나, 사용자가 파일을 내려받아야 한다. +- **11-05 Stage 1 재실행 합계:** + - Part 2 $1.989(4분 14초), Part 3 $0.023(48.5초), Part 4 $0.011(14.8초). + - 전체 약 $2.02, 약 5분 17초. +- **남은 일:** Part 2·4 YAML과 자산 6종 커밋. S2_00 재바인딩 여부 결정. + +### 2026-11-05 — Part 3 재실행 성공 (세션 88ee7816, 5차) + + +한 줄 요약: Part 2 새 산출(BO 88) 위에서 Part 3를 다시 실행했다(YAML 재업로드 없음). 48.5초 만에 `READY_WITH_REVIEW`로 성공했고 비용은 약 $0.023이다. 보고서는 `1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_5_part_3.md`다. +- **결과:** + - task 37개 완료, 오류 0. + - L0: BO 88 중 82개가 규칙만으로 붙었다(4차는 78 중 63). 미부착 6, route 83/8, SG-11 47/47. + - glossary OK(수용 40). 추천기 후보 6·쌍 16. JEV 16회 응답. + - apply: UNDECIDED 6, 부착 0. L2 게이트 셋 통과, by_bo_id 82. +- **JEV:** part_of를 고른 쌍은 4개다(0.75 경매개시결정 → 피담보채권, 0.66, 0.44, 0.43). 모두 수용 임계값 0.80 미만이다. 나머지 12쌍은 unrelated였다. E-12 명의신탁은 선언 유형 5개 모두와 unrelated다. +- **비용:** glossary(Gemini 3.8 Flash) $0.0229. JEV 16회 합계 $0.0005. +- **로그 판독법:** JEV 확률 분포는 capture 코드 본문에 `probabilities` 문자열로 남는다. 그래서 암호화된 답 파일을 읽지 않아도 쌍별 확률을 복원할 수 있다. +- **남은 일:** Part 4를 다시 실행한다(P4-06 잡음 0건 확인, 추천기 표지 0행 예상). 임계값 0.80 유지 여부를 판단한다. 커밋. + +### 2026-11-05 — Part 2 개정판(`a212b744`) 온라인 실행 성공 (세션 1fb26ede) + + +한 줄 요약: P4-06과 manifest 고정값(`9d2df172`)을 반영한 Part 2가 4분 14초 만에 성공했다. BO `PASS` 88건, signal `READY_WITH_REVIEW`, 비용 $1.99다. 보고서는 `1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_2.md`다. +- **결과:** + - task 37개 모두 완료. A0 `READY`(새 manifest 통과), capture 15개 `CAPTURED`. + - R0: 후보 88, 예외 13(모두 field_conflict), review 382. + - F0: 게이트 7개 PASS, 금액 결속 46, 사람 판정 0. + - S0: 거래 `S5TX-92952e6df623cb1f439f`, 32파일. `part4_F0` 읽기 집합이 SG-04·07·11로 바뀐 것도 확인했다. +- **비용:** `[USAGE]` 17건 합계 $1.988904. + - prewarm $0.29, worker 15개 $1.68(그중 출력 $1.12), R1 $0.03. + - worker마다 캐시 114,055토큰이 적중했다. 캐시가 없었다면 worker 비용은 약 $4.93였다. + - 로그에서 역산한 Sol 단가(100만 토큰당): 입력 $2, 캐시 적중 $0.10, 캐시 기록 $2.50, 출력 $10. Flash-Lite: 입력 $0.30, 캐시 적중 $0.03, 출력 $2.50. +- **로그 잡음:** worker 사전 읽기 직후 부수 `read_docs` 12건이 `SSE stream ended without a response`로 3회 재시도 끝에 실패했다. 입력 6파일은 모두 주입돼 영향은 없다. +- **남은 일:** + - BO(78 → 88)와 signal 거래가 바뀌었다. Part 3 → Part 4 순서로 다시 실행해야 한다. Part 4만 돌리면 BO 봉인 대조에서 멈춘다. + - P4-06 효과(Part 4의 비코드 review 55건 → 0건)는 그 실행에서 확인한다. + - 커밋. +- **교훈:** + - 비용 분해는 `usage: prompt=… completion=… cached=…` 줄과 `[USAGE] … cost=` 줄을 짝지어 계산한다. + - docker 로그는 16KB마다 줄을 나눠 타임스탬프를 끼워 넣는다. 로그에 남은 파일 원문을 복원하려면 `\n ` 조각부터 지운다. + +### 2026-11-05 — Part 4 개정판 첫 온라인 실행 성공 (세션 13825502) + + +한 줄 요약: `c53a0120…` 판과 자산 6종을 `11월_1일_구성`에 올려 실행했다. 14.6초 만에 F0·F1·F2가 모두 `READY_WITH_REVIEW`로 끝났다. 보고서는 `1. Stage_1/v.8/Testrun/Nov_05/실행결과보고서_1_part_4.md`다. +- **결과:** + - 행 78, 게이트 82/10/5, 예외 7, review 200(HARD 3). + - F1(gemini-3.5-flash-lite)이 7건 모두 `SELECT_AMOUNT`로 판정했다. 미해결 0. `final_sha256` `0780f4f0…`. +- **수정 효과 확인:** + - parties 42행, 추천기 표지 5행, 고유 계산 요청 46건. + - BO 봉인 MATCHED. + - E-15 게이트 3건이 `GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW`로 나오고, HARD 2건은 `blocks_final_drafting: true`다. + - P4-06 잡음 55건은 남았다. Part 2를 다시 실행해야 사라진다. +- **검증법:** + - localdocs는 파일을 암호화해 저장한다(평문 + 28바이트). 그래서 sha로 대조할 수 없다. + - 대신 세 가지를 맞췄다: 로그에 남은 F0 결과 JSON, F1 사전 읽기 원문의 sha, 그리고 F1을 "첫 후보 선택"으로 둔 로컬 재생의 F2 `final_sha256`. F2 sha가 서버와 같았다. 나머지 파일은 크기−28이 로컬과 6/6 일치했다. + - 백엔드 API로 평문을 받는 방법은 권한 분류기가 막았다(관리자 토큰 사용). +- **남은 일:** + - F1이 7건 모두 첫 후보를 골랐다. 위치 편향일 수 있다. 특히 FX-004는 두 목적물에 걸친 평가인데 값 하나를 골랐다. `rationale`을 확인하거나 계산이 필요한 예외는 BLOCK으로 두는 규칙을 검토한다. + - Part 2 재실행으로 P4-06 효과를 확인한다. + - 커밋. +- **교훈:** 서버 산출 평문을 못 읽어도 된다. LLM 판정 하나만 가정해 결정적 code task를 로컬에서 재생하고, 최종 sha가 서버와 같으면 그 가정과 전체 산출이 함께 확정된다. + +### 2026-11-05 5:22pm — Part 4 일치성 해결법 7건 적용 (독립 검증 2회) + + +한 줄 요약: 해결법 문서의 7건을 P4-06 → 07 → 08 → 02 → 03 → 04 → 01 순서로 적용했다. 독립 검증과 재개정을 2회 했다. 오프라인 재생과 예외 6경로 시험을 통과했다. 커밋·배포·온라인 실행은 하지 않았다. +- **결과 판:** + - Part 4 `c53a0120…`(1,348행), 보존본 `_11_05_5_22pm` + - Part 2 `a212b744…` + - compiler `533dcee7…` + - runtime_manifest `a828e962…` → `9d2df172…`. 다섯 항목을 재봉인했다(fact_ledger_compiler·signal_compiler의 .py·.txt, fact_ledger_policy). Part 2 `EXPECTED_RUNTIME_MANIFEST_SHA256`도 갱신했다. + - Part 3은 바꾸지 않았다. + - 백업(.bak)은 v.8에 있다. +- **재생 결과(4차 데이터):** + - parties: 0행 → 42행 + - 추천기 표지: 12행 → 5행 + - 고유 계산 요청 46건이 writer report에 실린다. + - BO 봉인: MATCHED. 변조하면 멈춘다. + - E-15 게이트 3건이 새 코드로 나온다. + - P4-06: Part 2 입력을 모사한 시험에서 잡음 55건 → 0건(검토 207 → 152). 실제 효과는 Part 2를 다시 실행해야 나타난다. +- **계획과 다르게 한 것:** + - P4-02: LES 레코드 스키마가 닫혀 있어 Part 3에 새 키를 두지 않았다. 대신 L2가 확정한 P3 handoff에서 `(domain_id, attached_type_id, bo_id)`를 읽는다. + - P4-07: 어긋나면 BLOCKED 상태가 아니라 RuntimeError로 멈춘다(다른 봉인 실패와 같은 방식). + - P4-01: 스키마가 role을 문자열로 요구해 `role: value_party`로 썼다. 연결표는 P2 handoff `value_facts_binding` sha와 같을 때만 쓴다. + - P4-08: 검토 항목에 `blocks_final_drafting`도 싣는다. 그래야 S2_20이 HARD 게이트를 1등급으로 유지한다. 비차단 무행 경보만 3등급에서 4등급이 되며, 이를 수용했다. +- **미적용:** `signal_registry`의 SG-06·SG-10 소비자 문구. 읽는 코드가 없다. +- **교훈:** 하류 코드가 review_code 문자열과 같은지로 분기하는지 확인한 뒤 새 코드를 만든다. S2_20은 `GATE_FIRED_REVIEW`와 같은지로 등급을 매긴다. 1차 검증에서 이 의존이 드러났다. + +### 2026-11-05 — Part 4 일치성 지적 MINOR 7건 해결법 (질의 17개) + + +한 줄 요약: 일치성 보고서 §3의 질문 17개에 답하는 해결법 문서 `1. Stage_1/v.8/작업간일치성보고서_해결법_part_4_on_part_1_to_3.md`를 썼다. 읽기 전용 작업이며 YAML은 수정하지 않았다. +- **새로 확인한 사실:** + - 배포된 S2_00(`Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml`)은 Fact_Ledger의 `parties`와 `calculation_requests` 본문을 S2_10으로 넘기지 않는다. 둘 다 `COMPACT_KEYS`에 없다. + - S2_00은 행 단위 당사자를 따로 재구성한다. 재료는 원천 사건의 participants(BO 10/78건에만 있음), 증거 `key_parties`, 본문 이름 대조다(3211-3237행). 역할 구분이 없고 과포함된다. + - S2_20은 Stage 1 계산 요청을 아직 바인딩하지 않는다. 따라서 400건을 LLM이 계산하는 일은 없다. + - S2_00은 HARD 코드를 `review_code` 기준으로 센다(3678행). 그래서 E-15 게이트는 공통 맥락에 `GATE_FIRED_REVIEW`로만 보이고 도메인 정보가 빠진다. +- **권고한 최소 해결:** + - P4-01: F0이 `value_facts_party_links.json`을 읽고 BO `value_refs`로 조인한다. 값은 `client_goal` 정규명이다. 최대 49행이 채워진다. + - P4-02: Part 3 apply가 구조 레코드에 `recommender_attached_bo_ids`를 남긴다. + - P4-03: `request_id`를 고유 키로 선언하고 writer report에 고유 수치를 추가한다. + - P4-04: Part 4 읽기 집합에서 SG-06·SG-10을 뺀다. manifest 재봉인이 필요하다. + - P4-06: Part 2 3596행에서 필드명을 `source_field`로 옮기고 코드 칸은 None으로 둔다. + - P4-07: F0이 `part3_receipt.json`의 `bo_input.sha256`과 BO sha를 대조한다. + - P4-08: 투영 행이 0인 게이트 발화는 `GATE_FIRED_WITHOUT_FACT_ROWS_REVIEW` 코드로 내고 `domain_id`를 싣는다. +- **교훈:** 하류 영향은 S2_00 계약본(954행)이 아니라 배포 코드본(4,893행)으로 판단한다. 계약본에는 실제 키 사용이 보이지 않는다. + +### 2026-11-05 — Part 4 ↔ Part 1~3 일치성 점검 (MAJOR 0 · MINOR 7 · INFO 14) + + +한 줄 요약: `stage_1_part_4_v.8.yml`(`ce6e7628`)이 Part 1~3(`4cf8c5b7`·`3a66272c`·`5b6336bd`) 산출을 맞게 쓰는지 점검했다. 보고서는 `1. Stage_1/v.8/작업간일치성보고서_part_4_on_part_1_to_3.md`다. 초안 → 독립 검증 1회 → 개정 순서로 썼다. YAML은 수정하지 않았다. +- **방법:** 4차 실행 localdocs(BO 78, LES, 신호 31, handoff)를 서버에서 읽기 전용으로 회수했다. F0·F2 코드를 YAML에서 그대로 꺼내 가짜 localdocs 위에서 재생했다. F1은 BLOCK·SELECT 두 경로를 모의했다. 하네스는 session scratchpad `p4c/harness.py`에 있다. +- **통과한 것:** 봉인 31/31, registry, LES 거래 id `MATCHED`. 보존 등식 다섯: 78, 68+10, 68, 400, 46+1. 온라인 실행은 아직 하지 않았다. +- **MINOR:** + - **P4-01:** `parties`가 78/78 빈다. Part 2 정책 `not_projected`가 Performer·Subject를 비운다. + - **P4-02:** 추천기 표지가 구조 단위로 달려, 원래 붙어 있던 BO 7건에도 붙는다. + - **P4-03:** 계산 요청이 46종에서 400건으로, 최대 13배 복제된다. + - **P4-04:** SG-06·SG-10을 읽기만 하고 쓰지 않는다. + - **P4-06:** Part 2 handoff `source_review_code`에 필드 경로가 들어 있다(P2 YAML 3596행). 그 결과 잡음 55건이 생긴다. + - **P4-07:** BO 봉인 대조가 없다. Part 3 receipt `bo_input.sha256`이 있지만 쓰지 않는다. + - **P4-08:** E-15는 행이 없는데 HARD 게이트가 발화한다. + +**Why:** Part 4가 처음으로 실데이터 위에서 재생됐다. 그 결과 형식 연결은 맞지만 칸의 의미 연결에서 공백이 드러났다. + +**How to apply:** +- 수정 우선순위는 P4-02(Part 3 apply가 BO 단위 출처를 남기게 함) → P4-01(parties 출처 결정) → P4-03(하류 합산 규칙)이다. +- 이 수정에는 사용자 승인이 필요하다. +- 다음 온라인 실행에서 Part 4를 4차 산출물 위에 돌려 재생 결과를 확인한다. + ### 2026-11-05 — Part 3 그림자 실행 해제 후 첫 실행 (성공, BO 5건 부착)