diff --git a/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/HITL/화면연구/revised_files/1. Stage_1/v.8/Agent_Block_1.yml b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/HITL/화면연구/revised_files/1. Stage_1/v.8/Agent_Block_1.yml new file mode 100644 index 00000000..7e0d6399 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/HITL/화면연구/revised_files/1. Stage_1/v.8/Agent_Block_1.yml @@ -0,0 +1,23851 @@ +# Agent_Block_1.yml — Stage 1 Part 1~5 를 한 번에 순차 실행한다. +# Stage 5개: stage1_사건개요파악_기초작업 -> stage1_BO_시그널_생성 -> stage1_법률효과구조_생성 -> stage1_사실원장_생성 -> stage1_결과화면_모델_생성 +# Stage 사이는 prevs/nexts 로 잇고 모두 skip_confirm: true(앞 Stage 가 끝나면 확인 없이 다음 Stage). +# 각 Stage 의 tools · task_procedure · tasks 는 원본 Part YAML 과 같다(들여쓰기와 공백만 있는 줄만 맞춤. 파싱 값 동일을 병합 때 검사). +# 원본(sha256 앞 12자): stage_1_part_1_v.8.yml d6e5c444f958 · stage_1_part_2_v.8.yml b20ca8a07cd2 · stage_1_part_3_v.8.yml 5b6336bd76e6 · stage_1_part_4_v.8.yml daf452603346 · stage_1_part_5_v.8.yml 23c1225ff69c +# Part 6(변호사 결정 반영)은 화면 결정 뒤 따로 실행하므로 넣지 않는다. +# 원본 Part YAML 을 고치면 이 파일을 다시 병합한다(merge_block1.py). + +Agent: + name: Liti-agent_Civil_Suit_Plaintiff_Stage_1_Block_1 + description: 민사소송 원고 송무 초지능 AI변호사 - Stage 1 Block 1 (Part 1~5 순차 실행) + version: v.1 + Stages: + + # ====================================================================== + # Part 1 — 원본 stage_1_part_1_v.8.yml + # ====================================================================== + # ============================================================================= + # Liti-agent Stage 1 Part 1 v.8 — 증거 기반 · 목표 · 도메인 확정 (통합 실행본) + # + # 정본 근거 + # 전체 DAG : stage_1_update_strategy.md §1 Part 1 블록 + # 개정 명세 : P1-T2_to_T9_update_strategy.md §1~§4 + # 조립 명세 : stage_1_part_1_완성용_작업명세서.md §3 (16 슬라이스) + # 설계 판정 : P1-T2_to_T9_선결작업수행결과/01_설계판정/P0_설계판정_결정문서.md + # 계측 재정의 : 같은 폴더 02_계측재정의/P2_계측통로_재정의.md + # + # 구성 — task 29종 (v3 대비 +20 신설 · 9 개정 · 0 무변경). 2026-10-30 V 사슬 5종 신설, 기존 13종 코드 무변경. + # 2026-11-02 A0·B1·B2 를 V1 구조(도구 없는 1회 호출 + 코드 저장)로 전환, capture 3종 신설. 게이트 코드 무변경. + # 2026-11-03 캐시 경계 개정·Task_A·B12 1회 호출 전환·복구 경로 추가(복구 6종, capture 2종 신설, 게이트·T9 수정). + # [신설] Task_A0_domain_screener_01 / 02 / 03 ver_8 후보본 + 2026-11-03 4pm 실패 조건·표식·연동 검사 + # [신설] Task_A0c_domain_screener_capture 2026-11-02 V1c 패턴 + # [개정] Task_A_client_goal Task_A_client_goal_v4.yml + 2026-11-03 구조 전환 + 4pm FAILURE_POLICY + # [신설] Task_Ac_client_goal_capture 2026-11-03 A0c 복제 + # [개정] Task_Evidence_shard_planner v3 622-945 + 2026-11-03 오후 part 표식 + 4pm handoff 표식 + # [개정] Task_B1_map_doc_* T3_Task_B1_map_doc_v4.yml + # [신설] Task_B1c_map_doc_capture_* 2026-11-02 V1c 패턴 + # [개정] Task_B2_map_events_* v3 1540-2204 + 2026-11-02 구조 전환 + # [신설] Task_B2c_map_events_capture_* 2026-11-02 V1c 패턴 + # [신설] Task_B1r_repair_planner / Task_B1r_map_doc_* / Task_B1rc_map_doc_capture_* 2026-11-03 복구 + # [신설] Task_B2r_repair_planner / Task_B2r_map_events_* / Task_B2rc_map_events_capture_* 2026-11-03 복구 + # [개정] Task_B1_quality_gate_evidence_indexed v3 2205-2802 + 2026-11-03 B1_failure.json + # [개정] Task_B2_quality_gate_event_candidates v3 2803-3519 + v.8 R5(CHECK 3 정본 id 부여) + 2026-11-03 B2_failure.json + # [개정] Task_B12_gate_llm_adjudicator v3 3520-3679 + 2026-11-03 구조 전환 + # [신설] Task_B12c_gate_adjudication_capture 2026-11-03 A0c 복제 + # [개정] Task_B12_gate_audit_finalizer v3 3680-4041 + 2026-11-03 no_suspects 표시 + # [신설] Task_D0_domain_activation_gate ver_8 후보본 (정정본) + 2026-11-03 4pm manifest 표식 + # [개정] Task_B2_SHA256_soft_gate_handoff_writer T9_..._v4.yml (2026-10-30: nexts 에 V3 추가, 2026-11-03: 게이트 미통과 시 BLOCKED, 4pm: A0·D0 산출물 게이트) + # [신설] Task_V0_value_facts_input_planner 가액금액_포함_작업구조도개정_계획서.md §2 + # [신설] Task_V1_value_facts_* 가액금액_정보추출_프롬프트.md [SYSTEM] (full 모드) + # [신설] Task_V1c_value_facts_capture_* S2_10 capture 패턴 + # [신설] Task_V2_value_facts_gate_merger assets_for_stage_1/value_facts/v4 gate_check.run_gate + # [신설] Task_V3_value_facts_party_linker T9 norm_name 복사 + # + # 개정 요지 + # 2026-11-03 7:25pm 추론 수준·verbosity 조정 (LLM_추론수준_개정된_stage_1.md, 보존본 _11_03_7_25pm.yml) + # (reasoning, verbosity): Task_A (high, 기본) -> (medium, low), B1·B2 (high, medium) -> (medium, low), + # B1r·B2r (high, medium) -> (high, low), V1 (medium, 없음) -> (medium, low). A0_01 (medium, low)·B12 (low, low) 그대로. + # Gemini 브리지는 llm_verbosity 를 쓰지 않는다(_apply_verbosity 는 openai 전용). Gemini task 에서는 표시값이다. + # 2026-11-03 4pm 지난 실행 파일 차단 (Testrun/Nov_03/추가개정전략_for_part_1.md M1~M6) + # A0_01: 사전 머리말·26개 검사를 지우고 '내용 없음'만 FAILED 로 둔다. 배포 사전에는 머리말이 없어 + # 헛 FAILED 가 났고 A0_01 은 재시도가 없다. 구조 검사는 A0_02 코드가 한다. + # 표식: planner 가 handoff 에 HANDOFF_PENDING, A0_02·A0_03·D0 가 시작할 때 자기 산출물에 *_PENDING 을 쓴다. + # 실패·취소·미실행이면 표식이 남아 지난 실행 파일이 하류로 흐르지 않는다. 표식 쓰기는 try 밖이라 실패하면 raise 한다. + # A0_03: {{prev}} 로 A0_02 의 written 을 보고, 쓴 sha 와 읽은 sha 가 다르면 경고한다(쓰기·읽기 동일성 미실측). + # Task_A FAILURE_POLICY: screening 규칙에 SCREENING_PENDING 조건을 더하고, vocabulary 규칙은 존재·표식 검사로 줄였다. + # 절 수는 A0_02(중복 후보 실패)·A0_03(if ERRORS) 코드가 보장한다. + # T9: screening·vocabulary·manifest 를 게이트로 본다. vocabulary 머리말의 screening_sha256 이 다르면 VOCABULARY_STALE. + # 남은 것: when 으로 Task_A 를 건너뛰는 안은 probe 전까지 보류(Task_A 는 S1~S3 에서도 1회 호출된다). + # 2026-11-03 오후 실행 실패 수정 (Testrun/Nov_03/실패분석서_part_1.md §5 의 1~3) + # Task_A: llm_verbosity 삭제. 브리지가 chat.completions 에도 text 인자를 넣어 SDK 가 거부했다. + # chat.completions 의 verbosity 기본값이 medium 이라 출력 설정은 같다. + # capture 7종 extract: prev 표기가 치환되지 않았거나 비었으면 UPSTREAM_NO_OUTPUT 으로 표시한다. + # 표식 동작(비JSON 쓰기)은 그대로다. + # Task_A cache_control ttl 20m -> 30m(백엔드가 보내던 값과 같다). planner write_doc 이 쓰기 실패를 raise 한다. + # shard planner: READY 이면 계획한 B1·B2 part 경로에 PART_PENDING 표식을 먼저 쓴다. + # 취소된 실행이 남긴 지난 part 를 정상으로 읽지 않게 한다. + # 2026-11-03 캐시·복구 개정 (Stage 1 - Part 1 캐시 최적화 개정 및 코드 오류 수정 방안.md) + # 캐시 경계: Gemini 브리지는 줄 시작 를 먼저 찾고, 없으면 앞에서 자른다. + # B1·B2 는 닫는 태그를 앞줄 끝에 붙이고, 고정 지시를 TAIL 앞으로, 값은 TAIL 의 RUNTIME_PARAMETERS 로 모았다. + # 지시 내용은 그대로이고 `{{item.*}}` 표기만 고정 문구로 바꿨다. TAIL 앞에 변수를 다시 넣으면 인스턴스마다 캐시가 갈린다. + # V1 은 TAIL 이 없어 고정부를 이중 전송했으므로 TAIL 만 더했다. + # Task_A·B12: 도구 없는 호출 + capture. Task_A 만 max_iterations 2 + terminate(빈 응답 1회 재호출, 온라인 확인 필요). + # Task_A 의 preflight: false 는 옛 96,000 바이트 상한 때문이었고 그 상한은 2026-08-20 삭제됐다. + # A0_01 은 prev 가 없어 백엔드가 max_iterations 를 적용하지 않고 8회까지 돈다. override 에 terminate 를 넣었다. + # B12 는 B2 게이트의 exception_count > 0 전이로만 돈다. cache_control 은 지우면 프롬프트 앞부분이 사라진다. + # 복구: 빈 응답은 예외가 아니라 백엔드 재시도를 받지 못한다. B1r·B2r planner 가 고장 part 만 1회 다시 만든다. + # 실패 표시: 게이트가 stage1_tmp/quality_gate/B{1,2}_failure.json 을 RUNNING 으로 시작해 CLEARED 로 끝낸다. + # 백엔드는 실패한 부모 뒤 자식을 실행하므로 B2 게이트와 T9 가 이 파일로 멈춘다(T9 는 BLOCKED handoff 기록). + # T9 는 client_goal.json 이 깨져도 BLOCKED 로 기록한다. B2r 는 방안의 'B1 복구 뒤'보다 늦은 B1 게이트 뒤에서 기다린다. + # 남은 위험: repair planner 의 run_code 자체가 실패하면 aggregate 가 풀리지 않아 run 이 멈춘다(백엔드 수정 필요). + # A0_03 이 FAILED 면 Task_A 도 prev 가 없어 max_iterations 가 적용되지 않고 8회까지 돈다(terminate 로 멈춤). + # 게이트 _init() 이 실패하면 지난 CLEARED 가 남는다(확률 낮음, 미처리). Task_A ttl 은 30m 이다(2026-11-03 오후, 20m 은 백엔드가 30m 으로 바꿔 보냈다). + # 2026-11-02 구조 전환 (Testrun/Nov_02/실패분석서_part_1.md) + # A0_01·B1·B2: expose_tools false, max_iterations 1, llm_result_envelope true. LLM 은 JSON 을 응답으로만 내고 + # capture 가 기존 경로에 쓴다. 파일 경로·스키마 불변이라 게이트와 A0_02 는 그대로 읽는다. + # 프롬프트 본문은 바이트 불변이고 끝에 만 덧붙였다(입출력 방식 지시). + # capture 실패 표식은 비JSON 이라 게이트의 parse_failures 또는 A0_02 의 DRAFT_UNREADABLE 로 나타난다. + # planner 의 fanout_meta·streaming_edges·barriers 는 소비처 없는 기록용이라 그대로 뒀다. + # 전환으로 달라진 동작: 전에는 빈 응답이면 다음 회차로 넘어갔으나, 이제 표식이 되고 LLM 은 다시 부르지 않는다 + # (백엔드 재시도는 예외가 난 호출만 받는다). A0 는 2026-11-03 부터 terminate 가 없으면 다시 호출된다. + # 실주행 확인 필요: LLM 인스턴스 FAILED 뒤 capture 기동 여부, 빈 응답 빈도, run_code 코드 크기 상한(B2c). + # T0 3종 스크리너 사슬 신설. 02 가 01 의 초안을 봉인하고 03 이 후보 어휘를 압축한다. + # T1 domain_profiles 를 도메인ID 키 개방형으로. 스키마는 정적 자산으로 분리. + # T3 증거 구성요소 어휘를 registry 합집합 참조로. v3 구조 어휘와 병존(P0 판정 A)하며 + # part 파일에 registry_component_ids 슬롯 1개를 additive 로 더한다(P0 판정 B). + # schema_contract_version 은 evidence_indexed_part.v4 유지 — 순수 additive 다. + # D0 판정 로직을 YAML 에 쓰지 않는다. stage1_runtime/activation_gate.py 를 반입해 호출하고 + # signals/adapters/sg01_activation_adapter.py 로 자기검증한다. 결정 필드는 + # execution_eligible 하나뿐이다(D-3 넓은 정의). + # T9 봉인 사전에 세 해시 추가(screening / activation_manifest / registry_index). + # 원문 sha256 이므로 read_raw 를 쓴다. unwrap_text 재직렬화 금지. + # schema_version 은 stage1_part1_soft_gate_handoff.v1 유지 — 역시 additive 다. + # T9(v.8 alias) client_goal.parties 를 canonical 로 삼아 증거·사건의 당사자 표기 변형을 집계한 + # routing/party_aliases.json 을 handoff 직전에 1회 쓴다(aliases / alias_candidates / + # succession_candidates). digest 7 키·handoff 바이트·client_goal.json 은 불변. T1 -> T9 변 추가. + # 보조 산출물이므로 집계 실패는 error 필드로 남기고 handoff 기록을 막지 않는다. + # T4/T6(v.8 OBLIGEE) 사건 후보에 additive 필드 obligation_direction{obligee_candidates, obligor_candidates} 추가. + # 문서가 채권 자체의 채권자·채무자를 직접 특정할 때만 채운다(stage_1_OBLIGEE_개정방안.md §2~§3). + # T6 CHECK 6 는 비차단(R-SELFWARN 재사용). schema_contract_version·DAG·B12 지침·digest 키 불변. + # T4 r2(2026-10-07) 방향 규칙을 event_kind 매핑 양성 조건으로 교체(채권발생·채권관리·amount 있는 통지만 채움), 빈 상수·예시 4개를 + # 출력 템플릿 옆으로 이동, self-validation invariant 7(누락 시 빈 상수 삽입 보정) 추가, T3·T4 llm_model gemini-3.5-flash-lite. + # T6 R5(2026-10-10) CHECK 3 에서 형식·ordinal 이탈 candidate_id_proposed 를 part 내 순번으로 EVT-{o}-{seq:02d} 정본 부여(제자리 치환, + # precheck·audit checks[candidate_id_collision].id_normalizations 기록, severity HARD_WARNING; 치환 후 중복만 hard). + # 실패분석_stage_1_part_2_v.8.md §4 F-1. mapper 프롬프트·CANDIDATE_ID_RE·최종 파일 스키마·보존 불변식 불변. + # + # 2026-11-22 인간변호사방식 개정 2(P1-1). V1 프롬프트에 R20(CLIENT_STATEMENT 문서의 변제·상환·공탁 금액을 PAYMENT_MADE·PAID, + # 날짜 역할 PAYMENT 로 기록)과 제출 전 점검 7번을 더했다. 모델·추론 수준·어휘 자산은 그대로다. + # 2026-11-22 인간변호사방식 개정(F-5·O-1). V0 가 상담기록을 예약 번호 E-000(provenance CLIENT_STATEMENT, 증거 목록 미포함)으로 + # 한 건 더 계획한다(금액 값 기록 전용, 값 번호 E-000-VF-NNN). V0 render_input·V2 run_gate 가 항목 provenance 를 읽는다. + # Part 2 카탈로그는 CLIENT_STATEMENT 값 기록을 거른다. B1 통지서 규칙 두 곳에 본문 기재 선행 최고 한 줄. + # V(2026-10-30) 금액의 출처를 하나로 모은다. 정본은 gate 를 통과한 value_facts.json 이다(원문에 있다는 것까지만 보증). + # 산출: value_facts_inputs/ · value_facts_input_plan.json · value_facts_parts/ · value_facts.json · + # quality_gates/value_facts_gate.json(출처 지문) · value_facts_party_links.json. 기존 B1·B2 금액 칸은 대조용으로 남긴다. + # T9 봉인 7 키·handoff 바이트 불변(value_facts 실패가 사건 handoff 를 막지 않는다). 하류 대조는 + # gate.source_fingerprint.evidence_indexed_sha256 == handoff digest_guard.evidence_indexed_sha256 으로 한다. + # V 자산은 Default_Agent/value_facts/v4/MANIFEST.json 의 sha256 으로 대조한다(runtime_manifest 아님). + # party_ref 는 client_goal 성명이다(당사자 id 없음). 어휘 party_refs 설명("당사자 정본 ID") 문구 수정은 다음 자산 개정으로 미룬다. + # Stage 2 수용 조건: gate.status ∈ {READY, READY_WITH_REVIEW} · gate.run_id == value_facts.run_id · + # gate.value_facts_sha256 == sha256(value_facts.json) · 위 evidence_indexed_sha256 일치. 하나라도 어긋나면 쓰지 않는다. + # OUT 은 T9 와 V3 를 함께 기다린다. V 사슬이 멈춰 run 이 끝나지 않아도 T9 가 쓴 handoff 는 유효하다. + # 실주행 확인 필요(probe): (1) V1 인스턴스 1건 실패·시간 초과 시 all V1c_* 대기와 OUT 도달 여부 — 멈추면 OUT.wait 에서 V3 를 뺀다, + # (2) B1/B2 와 V1/V1c 두 fan-out 이 동시에 돌 때 {same_ordinal} 짝과 all V1c_* 집계, (3) T9 실패 시 V3 미기동 후 종료 상태, + # (4) V1 MODEL_INCOMPLETE 빈도(나오면 llm_reasoning 을 medium 으로). + # + # 모듈 반입 규약 (localdocs 가 .py 를 서빙하지 않아 도입한 우회책) + # 모든 .py 에는 같은 디렉터리에 바이트 동일한 .txt 형제 미러가 배포된다. + # 빌더 규칙이며 예외는 build_default_agent_stage1.py 하나다. 미러는 정본 옆에 놓이므로 + # sg01_activation_adapter 의 미러는 signals/adapters/ 에 있다(stage1_runtime/ 이 아니다). + # 반입 시 sha256 을 Default_Agent/runtime_manifest.json 과 대조하고, 불일치면 실행하지 않는다. + # + # 정적 자산 선행 조건 (P1-T2_to_T9_update_strategy.md §0.2 — 전부 충족) + # Default_Agent/stage1_runtime/activation_gate.py + # Default_Agent/platform/schemas/client_goal_domain_profiles.schema.json + # Default_Agent/routing/activation_cue_digest.md + # Default_Agent/routing/evidence_component_union.md + # Default_Agent/platform/contracts/determinism_scope_contract.json + # Default_Agent/value_facts/v4/{MANIFEST.json, value_facts_vocab_block.v4.full.txt, + # value_facts_gate_rules.v4.json, value_normalize_lexicon.json, gate_check.txt} (V 사슬, 2026-10-30 신규 배포) + # + # 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. + # 조각 후보본들이 각자 갖고 있던 Agent/Stages 머리와 자기 task_procedure 는 전부 걷어냈다. + # mcpServers 합집합은 {localdocs, code-executor} 이며 v3 머리가 이미 둘 다 선언한다. + # ============================================================================= + - 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_A0_domain_screener_01 + # 도구 없는 호출. 응답 봉투는 Task_A0c 가 저장한다. 이 task 는 prev 가 없어 백엔드가 아래 값을 적용하지 않고 + # 기본 8회로 돈다(prev 가 있을 때만 설정으로 재생성한다). 그래서 응답 끝 terminate 로 멈춘다. + max_iterations: 1 + llm_provider: google + llm_model: 'gemini-3.8-flash' + llm_reasoning: low + llm_verbosity: low + cache_control: + mode: auto + ttl: 1h + use_tools: + - localdocs + # preflight: true + preflight_files 화이트리스트. + # 화이트리스트를 명시하면 프롬프트 본문 regex 스캔이 꺼지고 이 두 경로만 + # 미리 읽힌다. 입출력 통제는 유지되면서, 정적 경로인 단어 사전이 캐시 + # 공유 영역에 inline 되어 매 실행 35KB 를 다시 태우지 않는다. + # 도구는 preflight 읽기에만 쓴다. LLM 에는 노출하지 않는다. + expose_tools: false + preflight: true + llm_result_envelope: true + preflight_files: + - Default_Agent/routing/activation_cue_digest.md + - client_meeting.md + prompts: + - role: user + content: |- + + "출력은 JSON 하나, 첫 글자는 `{`, 사고 과정·설명 금지" + + - 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. + + + + + - Fill only slots that the current extraction, mapping, support, or projection schema asks for. + - Treat legal labels, party assertions, meeting narrative, and upstream candidates as routing signals only, not proof by themselves. + - Preserve the strongest source IDs and locators required by the current schema; do not quote long passages unless asked. + - Separate raw fact, inferred fact, support signal, and review note when the schema distinguishes them. + - If a source conflict is visible, preserve it only through the current schema's allowed uncertainty, warning, or review field. Do not classify full contradiction severity here. + - Do not perform norm search, final legal-effect classification, merits judgment, cross-domain merge, or final writer repair unless the current task explicitly requires it. + - Stop after the assigned item, evidence shard, domain, batch, support file, or fact-support projection is complete. + + + + + Task_A0_domain_screener_01 + + You are an MCP-enabled LLM agent assisting plaintiff-side Korean civil/commercial litigation counsel. + + + `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md` 두 개만 읽고 `routing/domain_screening_draft.json`을 생성한다. + 이 task가 답해야 할 질문은 "이 사건이 137종 사건유형 중 무엇인가"가 아니라 "사전 `## DOMAINS`에 실린 법리 렌즈 중 어느 것이 켜지는가"이다. + 산출물은 확정이 아니라 가설이다. 확정은 하류의 `Task_D0_domain_activation_gate`가 registry 모듈을 호출하여 결정론적으로 수행한다. + 본 task는 판단 4종(`status`, `candidates`, `unmatched_issue_refs`, `review_items`)과 그 판단을 검증 가능하게 만드는 최소 부속 정보만 생성한다. + 닫힌 스키마 `stage1_domain_screening.v1`의 비판단 6종(`schema_version`, `registry_version`, `registry_index_sha256`, `source_document_refs`, `screening_policy`, `contract_guards`)은 본 task가 만들지 않는다. 후속 task `Task_A0_domain_screener_02`가 registry에서 직접 읽어 붙이고 스키마 검증까지 수행한다. + 본 task의 산출물은 개방형 초안이므로 닫힌 스키마의 필드 집합에 구속되지 않는다. 다만 `candidates` 배열의 각 원소는 닫힌 스키마의 후보 객체와 키 구성이 정확히 같아야 한다. 후속 task가 변형 없이 그대로 복사하기 때문이다. + + + + + - In this task, `provisional_status` and `confidence` are meeting-grounded routing hypotheses, not legal conclusions. + - The EXTRACTION overlay's prohibition on final legal-effect classification does not prohibit the schema-authorized `provisional_status`, `confidence`, or `requested_calculation_domains` fields. + - The overlay's prohibition on norm search remains absolute here. 법령·판례·조문 검색과 인용은 어떤 형태로도 금지한다. + - 본 task는 final writer가 아니다. `FINAL_WRITER_REDUCER` 오버레이는 본 task에 적용되지 않으며, 어떤 최종 산출물도 확정하지 않는다. + + + + + - `client_meeting.md` — 유일한 사실 원천 + - `Default_Agent/routing/activation_cue_digest.md` — 단어 사전(라우팅 어휘). 사실 원천이 아니다. + + + - `routing/domain_screening_draft.json` + + + - `list_docs` : 입력 2종의 존재 확인과 출력 1종의 생성 확인에만 쓴다. + - `write_file` : `routing/domain_screening_draft.json` 한 경로에만 1회 쓴다. + - `read_docs` : 원칙적으로 쓰지 않는다. 두 입력은 preflight로 이미 제공되어 있다. preflight 내용이 제공되지 않은 경우에 한하여 위 두 경로에만 1회 쓴다. + + + - 위 화이트리스트 밖의 어떤 파일도 읽지 않는다. 특히 `Default_Agent/domains/*/domain_config.json` 원본 26개를 직접 읽지 않는다. + - `Default_Agent/validation_assets/routing/case_kind_domain_matrix.v2.json`을 읽지 않는다. 사건유형 이름을 담은 오프라인 회귀 전용 자산이며 런타임 입력이 금지되어 있다. + - `routing/domain_screening.json`을 만들거나 건드리지 않는다. 그 파일은 후속 task의 산출물이다. + - 중간 파일 생성, 산출물 재읽기, `write_file` 2회 이상 호출. + - 사건유형 명칭, 당사자 이름, 사건번호를 라우팅 판단의 근거로 삼기. + - 최종 법률효과 판단, 단일 도메인 확정, 승패 예측, 청구금액 산정, 법령·판례 검색. + - 닫힌 스키마에 없는 필드명 사용: `track_hypothesis`, `domain_hypotheses`, `relief_mode_hints`, `computation_hints`, `matched_cues`, `notes_kr`. + - 비판단 6종(`schema_version`, `registry_version`, `registry_index_sha256`, `source_document_refs`, `screening_policy`, `contract_guards`)을 초안에 넣기. + - 단어 사전에만 있고 상담록에 없는 표현을 사실처럼 근거로 삼기. + + + + + 1. `list_docs`로 `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md`의 존재만 확인한다. + 2. preflight로 제공된 두 파일의 내용을 쓴다. 제공되지 않은 경우에 한하여 `read_docs`를 1회 호출한다. + 3. ``에 따라 상담록을 source unit으로 나누고 각 unit에 `MTG.*` 식별자를 부여한다. + 4. ``로 사전을 해석한다. + 5. `` → `` → `` → `` → `` 순서로 판단 4종을 만든다. + 6. ``를 적용하고 ``를 자기점검한다. + 7. 메모리에서 초안 객체를 만들고 `write_file(overwrite=true)`로 `routing/domain_screening_draft.json`에 저장한다. + 8. `list_docs`로 `routing/domain_screening_draft.json` 존재만 확인한다. 절대 읽지 않는다. + 9. 정확히 `"도메인 스크리닝 초안 생성 완료"`만 출력하고 종료한다. + + + + - 필수 입력 누락, 빈 파일, 파싱 불가: 즉시 중단하고 채팅으로만 보고한다. 파일은 쓰지 않는다. + - 단어 사전(`Default_Agent/routing/activation_cue_digest.md`)의 내용이 대화에 없거나 비어 있으면 중단하고 `FAILED: activation_cue_digest`만 보고한다. 사전의 형식과 도메인 수는 후속 코드가 검사하므로 판단하지 않는다. + - tool 오류: 원인 확인 후 1회만 재시도한다. 재실패 시 `FAILED: `만 보고하고 종료한다. + - 판단이 어려운 사안을 억지로 확정하지 않는다. 판단 불가는 실패가 아니라 `review` 상태와 검토 항목으로 표현한다. + + + + - 사실 원천은 `client_meeting.md` 하나뿐이다. + - `Default_Agent/routing/activation_cue_digest.md`는 사실 원천이 아니다. 무엇을 찾을지 알려주는 라우팅 어휘 목록이다. 사전의 `match_value` 문구를 상담록의 대응 서술 없이 근거로 인용하면 그것은 환각이다. + - 상담록의 문장들을 조합해 새로운 사실을 만들지 않는다. 상대방 주장은 주장으로만, 희망사항은 희망으로만 취급한다. + - 상담록에만 있는 내용은 증거가 아니다. 증거 승격은 하류 단계의 권한이며 본 task는 그 판단을 하지 않는다. + - 사건유형 이름을 사실 권위로 쓰지 않는다. 라우팅은 구조화된 단서와 서술로만 한다. + + + + - 사전은 `## LEGEND`, `## GLOBAL_DEFAULTS`, `## USAGE`, `## DOMAINS` 네 부분이다. 판단에 쓰는 것은 `GLOBAL_DEFAULTS`와 `DOMAINS`이다. + - 도메인 절 머리 형식: `### | | kind= | ao=<0|1> | dep= | calc=` + - 단서 줄 형식: + `P|||||||` + `N|||||||` + `C|||` + `OVR|=|...` + - `` 코드는 두 개뿐이다. `DR`=confidence_downrank_only, `MR`=monitor_review. + - `` 코드 `SP`/`SU`는 하류 단계의 조회 위치 표시다. 본 task는 상담록만 보므로 `src` 값을 이유로 단서를 배제하지 않는다. + - `OVR` 줄이 있으면 그 도메인에 한하여 `GLOBAL_DEFAULTS`를 덮어쓴다. 값 `absent`는 원본에 그 키가 없다는 뜻이므로 그 임계값 판정을 적용하지 않는다. + - 모든 충돌 단서의 효과는 `hard_review`이며 그래서 `C` 줄에서 생략되어 있다. + - 사전에 없는 도메인 ID, 단서 ID, 검토 코드, 계산 ID는 만들지 않는다. + + + + - 상담록을 문단 단위 source unit으로 나누고 각 unit에 다음 형식의 식별자를 부여한다. + `MTG.
.<사건군 2자리>.<항 2자리>` + - `
`은 세 값만 쓴다. 【상담내용】=`FACT`, 【사건관계인의 주장】=`OPP`, 【의뢰인의 희망사항】=`WISH`. + - `<사건군 2자리>`는 그 섹션 안의 `1.`~`9.` 번호를 두 자리로 채운 값이다. 사건군에 속하지 않는 문단은 `00`. + - `<항 2자리>`는 `가.`=`01`, `나.`=`02`, `다.`=`03`, `라.`=`04`, `마.`=`05`, `바.`=`06`, `사.`=`07`, `아.`=`08` 순서다. 항 구분이 없는 문단은 `00`. + - 상담일지 머리표(사무소·연락처·접수번호·상담일자·의뢰인 표)는 문단마다 자르지 않고 `MTG.META.01` 한 단위로 접는다. 상담일자와 의뢰인 값은 그 안에 보존된 것으로 본다. + - 예시: 【상담내용】 `2.` 사건군의 `라.` 문단 → `MTG.FACT.02.04`. 【사건관계인의 주장】 `5.`의 항 구분 없는 문단 → `MTG.OPP.05.00`. 【의뢰인의 희망사항】 `3.` → `MTG.WISH.03.00`. 【상담내용】의 사건군 앞 머리 문단 → `MTG.FACT.00.00`. + - 식별자는 반드시 `^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$`를 만족해야 한다. 한글, 공백, 대괄호, `#`을 쓰지 않는다. + - 어떤 문단도 버리지 않는다. 위 규칙에 맞지 않는 문단은 `MTG.RAW.<3자리 일련번호>`로 부여하고 `review_items`에 `SCREENING_SOURCE_UNIT_FALLBACK`를 남긴다. + - 부여한 전체 목록을 `source_unit_index`에 문서 등장 순서대로 기록한다. 이 목록이 본 task가 살펴본 원천의 전부이며, 후속 task가 같은 규칙으로 독립 재산출하여 대조한다. + - 후속 task가 `source_document_refs`를 만든다. 본 task는 그 필드를 만들지 않는다. + + + + - 각 source unit을 읽고 사전의 긍정 단서 `match_value`에 대응하는 서술이 그 unit에 있는지 판단한다. + - 대응이 인정되면 그 도메인 후보의 `positive_refs`에 해당 unit 식별자를 넣는다. 단서 ID(`E13-P01` 같은 값)는 `positive_refs`에 넣지 않는다. 그 배열은 원천 식별자만 담는다. + - 어떤 단서가 근거였는지는 `reasoning_summary`에 단서 ID로 적는다. + - 단서 하나에만 걸린 상태로 후보를 세우지 않는다(`single_keyword_activation_forbidden`). 서로 다른 단서 두 개 이상 또는 서로 다른 source unit 두 개 이상이 필요하다. + - `cue_type`이 `evidence_component`인 단서는 그 자료의 존재가 상담록에 직접 언급된 경우에만 인정한다. 있을 법하다는 추론으로 인정하지 않는다. + - 한 unit이 여러 도메인에 동시에 걸릴 수 있다. 배타적으로 하나만 고르지 않는다. + - 사건유형 명칭, 당사자 이름, 사건번호는 어떤 경우에도 매칭 근거가 되지 않는다. + + + + - 도메인별로 걸린 긍정 단서의 `weight`를 합산한다. 같은 단서가 여러 unit에서 걸려도 1회만 계산한다. + - 합이 `leaf_activation_threshold` 이상이면 `candidate`, `monitor_threshold` 이상이면 `monitor`로 본다. 기본값은 각각 1.0과 0.5이며 `OVR` 줄이 있으면 그 값을 쓴다. + - 임계값은 registry가 정한 참고값이며 판정 권한이 없다. 임계값에 못 미쳐도 강한 서술이 있으면 `monitor` 또는 `review`로 보존한다. 임계값을 넘었다는 사실만으로 `candidate`를 확정하지도 않는다. + - 네 상태의 뜻은 다음과 같다. + `candidate` — 이 도메인이 독자 쟁점으로 켜질 만한 서술이 있다. + `supporting` — 독자 쟁점은 아니나 다른 도메인의 요건을 뒷받침한다. 다른 도메인의 `dep=`에 등장하는 선행 도메인이 주로 여기에 온다. + `monitor` — 가능성은 있으나 서술이 얇다. 삭제하지 않고 감시한다. + `review` — 판단이 갈리거나 충돌 단서가 걸렸다. + - `confidence`는 `high|medium|low` 세 값이다. 강한 단서 두 개 이상이면 `high`, 강한 단서 하나이거나 보조 단서 위주이면 `medium`, 부정 단서로 낮춰졌거나 서술이 얇으면 `low`로 본다. + - `ao=1`인 도메인(E-00, X1, X2, X3)은 상시 활성 대상이다. 단서가 걸리지 않아도 후보 목록에서 누락시키지 않으며, 대응 서술이 없으면 `monitor`와 `low`로 남긴다. + - `reasoning_summary`는 1자 이상 1200자 이하다. 어떤 단서 ID가 어느 unit에서 걸렸는지와 상태를 그렇게 정한 이유만 적는다. 법률 결론, 승패 전망, 조문 인용을 적지 않는다. + - `final_determination_forbidden`은 모든 후보에서 `true`이다. + + + + - 부정 단서가 걸리면 해당 unit 식별자를 `negative_refs`에 넣는다. + - `DR`은 `confidence`만 한 단계 낮춘다. `high`→`medium`, `medium`→`low`, `low`는 그대로 둔다. + - `MR`은 `provisional_status`를 `monitor`로 옮긴다. + - 어느 경우에도 후보를 목록에서 삭제하지 않고, `provisional_status`를 `candidate`에서 두 단계 넘게 내리지 않는다(`candidate_downgrade_forbidden`). + - 충돌 단서가 걸리면 해당 unit 식별자를 `conflict_refs`에 넣고, 그 `C` 줄의 `review_code`를 그대로 써서 `review_items`에 항목을 추가한다. 검토 코드를 새로 만들지 않는다. + - 충돌 단서가 걸린 후보의 `provisional_status`는 `review`로 하고 `confidence`는 `low`를 넘지 않는다. + - 충돌을 조용히 해소하지 않는다. 어느 쪽이 맞는지 고르지 않고 양쪽 근거를 모두 남긴다. + + + + - `source_unit_index`의 unit 중 어떤 후보의 `positive_refs`·`negative_refs`·`conflict_refs`에도 들어가지 않은 것을 모두 `unmatched_issue_refs`에 넣는다. 하나도 버리지 않는다. + - `unmatched_issue_refs`가 비어 있지 않으면 `review_items`에 `UNROUTED_ISSUE_REVIEW` 항목을 하나 만들고 그 unit들을 `source_refs`에 담는다. `severity`는 `review`, `domain_ids`는 `["E-00"]`로 한다. + - `review_items` 각 항목의 필수 키는 `review_code`, `severity`, `reason`, `source_refs` 넷이다. 선택 키는 `domain_ids`, `unresolved_type`, `blocks_final_drafting` 셋이다. 다른 키를 만들지 않는다. + - `review_code`는 `^[A-Z][A-Z0-9_]{2,127}$`를 만족해야 하고, 사전의 `C` 줄에 적힌 코드이거나 `UNROUTED_ISSUE_REVIEW` 또는 `SCREENING_SOURCE_UNIT_FALLBACK` 중 하나여야 한다. + - `severity`는 `info|review|hard_warning|block` 네 값이다. 본 task는 `block`을 쓰지 않는다. 실행을 막는 판정은 하류 게이트의 권한이다. + - `status`는 다음 순서로 정한다. + 입력 자체가 판정 불가이면 `BLOCKED`. + 하드 실패가 있으면 `FAILED`. + `review_items`가 하나라도 있으면 `READY_WITH_REVIEW`. + 그 외에는 `READY`. + - 본 task는 `status`를 제안할 뿐이다. 후속 task는 이 값을 올릴 수 있어도 내릴 수 없다. + + + + - 금액 계산이 필요해 보이는 서술이 있으면 그 후보의 `requested_calculation_domains`에 계산 ID를 넣는다. + - 넣을 수 있는 값은 사전의 그 도메인 머리에 적힌 `calc=` 목록 안에 있는 것뿐이다. 목록 밖 값은 넣지 않는다. + - 계산 ID 형식은 `^CE-[A-Z0-9][A-Z0-9-]{0,15}$`이다. + - 본 task는 어떤 금액도 계산하지 않고 이율·기산일·기간·원금을 정하지 않는다. 계산이 필요하다는 표시만 남긴다. + - 필요 없으면 빈 배열로 둔다. + + + + - 인코딩은 UTF-8, 줄바꿈은 LF, 문자열은 NFC로 정규화한다. + - 모든 참조 배열은 중복 없이 문자열 오름차순으로 정렬한다. + - `candidates`는 `domain_id` 문자열 오름차순으로 정렬한다. + - `source_unit_index`는 문서 등장 순서를 유지한다. + - 숫자를 문자열로 감싸지 않고 불리언은 `true`/`false`로 쓴다. + - 값이 없으면 빈 배열을 쓰고 `null`이나 빈 문자열을 쓰지 않는다. + - 출력은 순수 JSON 하나다. 마크다운 코드펜스, 머리말, 꼬리 설명을 붙이지 않는다. + + + + 최상위 키는 `domain_screening_draft` 하나다. 아래 키 구성을 정확히 지킨다. + + { + "domain_screening_draft": { + "draft_schema_version": "stage1_domain_screening_draft.v1", + "produced_by": "Task_A0_domain_screener_01", + "source_document_code": "MTG", + "source_document_name": "client_meeting.md", + "unit_numbering_rule": "MTG.
..", + "source_unit_index": [ + { "unit_id": "MTG.FACT.01.01", "gist": "60자 이내 요지. 판단이 아니라 그 문단이 무엇을 다루는지만 적는다." } + ], + "status": "READY | READY_WITH_REVIEW | BLOCKED | FAILED 중 하나", + "candidates": [ + { + "domain_id": "E-13", + "provisional_status": "candidate | supporting | monitor | review 중 하나", + "positive_refs": ["MTG.FACT.03.01"], + "negative_refs": [], + "conflict_refs": [], + "confidence": "high | medium | low 중 하나", + "reasoning_summary": "E13-P01은 MTG.FACT.03.01에서, E13-P02는 MTG.FACT.03.03에서 대응 서술을 확인함. 합 2.0으로 활성 임계값을 넘어 candidate로 둠.", + "final_determination_forbidden": true, + "requested_calculation_domains": ["CE-03"] + } + ], + "unmatched_issue_refs": ["MTG.WISH.05.00"], + "review_items": [ + { + "review_code": "UNROUTED_ISSUE_REVIEW", + "severity": "review", + "reason": "어느 도메인 단서에도 걸리지 않은 상담록 단위를 잔여로 보존함.", + "source_refs": ["MTG.WISH.05.00"], + "domain_ids": ["E-00"], + "unresolved_type": "unrouted_meeting_unit", + "blocks_final_drafting": true + } + ] + } + } + + 고정값 규칙: + - `draft_schema_version`, `produced_by`, `source_document_code`, `source_document_name`, `unit_numbering_rule` 다섯 값은 위에 적힌 문자열을 글자 그대로 쓴다. + - `candidates`의 각 원소는 위 아홉 개 키만 쓴다. `requested_calculation_domains`가 빈 배열이어도 키는 남긴다. + - `review_items`가 없으면 빈 배열로 둔다. + + + + - `source_unit_index`의 모든 `unit_id`가 `^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$`를 만족하고 중복이 없는지 점검한다. + - 상담록의 모든 문단이 `source_unit_index`에 하나씩 대응하는지, 빠뜨린 문단이 없는지 점검한다. + - 모든 `positive_refs`·`negative_refs`·`conflict_refs`·`review_items[].source_refs`·`unmatched_issue_refs`의 원소가 전부 `source_unit_index`의 `unit_id` 집합 안에 있는지 점검한다. 목록 밖 식별자가 하나라도 있으면 고친다. + - `source_unit_index`의 개수가 (어느 후보엔가 인용된 unit 수) + (`unmatched_issue_refs` 수)와 같은지 점검한다. 어긋나면 인용 관계를 다시 본다. + - 모든 `domain_id`가 사전 `## DOMAINS`에 실제로 있는 값이고 `^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$`를 만족하는지 점검한다. + - 같은 `domain_id`가 `candidates`에 두 번 등장하지 않는지 점검한다. + - 모든 후보에 `final_determination_forbidden: true`가 있는지 점검한다. + - 부정 단서가 걸린 후보가 목록에서 사라지지 않았는지, `candidate`에서 두 단계 넘게 내려가지 않았는지 점검한다. + - 충돌 단서가 걸린 후보의 `provisional_status`가 `review`이고 `confidence`가 `low`인지 점검한다. + - 모든 `review_code`가 사전의 `C` 줄에 있는 값이거나 `UNROUTED_ISSUE_REVIEW` 또는 `SCREENING_SOURCE_UNIT_FALLBACK`인지 점검한다. + - 각 후보의 `requested_calculation_domains`가 그 도메인 머리의 `calc=` 목록의 부분집합인지 점검한다. + - `ao=1`인 E-00, X1, X2, X3 네 도메인이 `candidates`에 모두 있는지 점검한다. + - 금지 필드명 여섯 개와 비판단 6종이 초안에 하나도 없는지 점검한다. + - `reasoning_summary`에 사건유형 명칭, 당사자 이름, 사건번호가 판단 근거로 쓰이지 않았는지 점검한다. + - `reasoning_summary`가 1200자를 넘지 않는지 점검한다. + - 출력 파일 경로와 성공 메시지가 정확한지 점검한다. + + + + + + [ ] 1) `list_docs`로 `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md` 존재 확인(내용은 preflight로 이미 제공됨) + [ ] 2) source unit 채번 → 단서 매칭 → 판단 4종 생성 + [ ] 3) `` 자기점검 + [ ] 4) `write_file` 사용해서 `routing/domain_screening_draft.json` 생성 + [ ] 5) `list_docs` 사용해서 `routing/domain_screening_draft.json` 존재만 확인(절대 읽기 금지) + [ ] 6) `"도메인 스크리닝 초안 생성 완료"` 출력하고 작업을 끝낸다(terminate) + + + + + - `client_meeting.md` + - `Default_Agent/routing/activation_cue_digest.md` + + + - `routing/domain_screening_draft.json` + + + + + - 이 산출물은 가설이다. 어떤 도메인도 확정하지 않는다. + - `routing/domain_screening.json`은 후속 task의 산출물이다. 만들지 않는다. + - 비판단 6종은 초안에 넣지 않는다. + - 초안을 재읽지 않는다. + - 성공 시 마지막 채팅 출력은 정확히 `"도메인 스크리닝 초안 생성 완료"` 한 줄만 쓴다. + + + + + 이 블록은 이 실행의 입출력 방식만 정하며, 위의 입출력·도구·완료 문구 지시보다 우선한다. 판단·추출·스키마 규칙은 위 지시를 그대로 따른다. + - 이 실행에는 도구가 없다. `list_docs`, `read_docs`, `write_file` 등 어떤 도구도 호출하지 않는다. `list_docs`·`read_docs` 호출과 파일 존재 확인은 건너뛴다. `write_file` 전에 하도록 된 자기 점검과 내부 보정은 응답을 내기 전에 그대로 수행한다. + - 입력 파일은 이 대화에 미리 읽혀 제공된다. 그 내용을 도구로 읽은 내용과 같은 것으로 취급하며, 금지된 '자동 로드 데이터'가 아니다. 내용이 대화에 없는 입력은 입력 누락으로 보고 `FAILED`를 출력한다. + - 위 지시에서 `write_file`로 저장하게 되어 있는 ``의 최상위 객체(`domain_screening_draft` 키 하나)를 응답 본문으로 출력한다. 저장은 다음 단계의 코드가 `routing/domain_screening_draft.json`에 한다. + - 응답은 그 JSON 객체 하나 뒤에 줄을 바꿔 `terminate` 한 단어만 쓴다. 마크다운 코드 펜스, 설명, 완료 문구를 붙이지 않는다. + - 위 지시가 중단·실패를 보고하게 하거나 파일을 쓰지 말라고 한 경우에는 JSON 없이 `FAILED: <사유>` 한 줄을 쓰고 줄을 바꿔 `terminate` 한 단어를 쓴다. + + + - task_name: Task_A0c_domain_screener_capture + description: A0_01 응답 봉투의 JSON 을 routing/domain_screening_draft.json 에 저장 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: | + #!/usr/bin/env python3 + # Task_A0c_domain_screener_capture + # Task_A0_domain_screener_01 의 응답 봉투(llm_result_envelope)에서 JSON 객체를 꺼내 + # LLM 이 직접 쓰던 경로에 그대로 쓴다. 내용 검사는 하류 작업이 한다(V1c 와 같은 역할 분리). + # 응답이 불완전하거나 JSON 객체가 아니면 비JSON 표식을 쓴다. 지난 실행의 파일이 남아 + # 하류를 통과하지 못하게 하고, 하류가 그 파일을 읽기 실패로 보고하게 한다. + # LLM 응답 문제로는 raise 하지 않는다. 쓰기 실패만 raise 해서 백엔드 재시도를 받는다. + TASK_NAME = "Task_A0c_domain_screener_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])) + + + REQUIRED_KEY = "domain_screening_draft" + + + 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 earlier_answer(env): + # 여러 회차를 도는 task 는 마지막 회차 본문만 content 가 된다. 앞 회차 JSON 뒤에 terminate 를 빠뜨리면 + # 다음 회차가 정상 답을 덮는다. 이때만 json_output 을 쓰되, 잘린 조각을 막으려고 최상위 키를 확인한다. + obj = env.get("json_output") + finish = str(env.get("finish_reason") or "").lower() + if (env.get("iterations") or 0) < 2 or str(env.get("status")).lower() != "completed": + return None + # 마지막 회차가 실패를 선언했으면 앞 회차 답을 살리지 않는다. + if str(env.get("content") or "").lstrip().startswith("FAILED"): + return None + if finish in {"length", "max_tokens", "max_output_tokens"}: + return None + return obj if isinstance(obj, dict) and REQUIRED_KEY in obj else None + + + # 백엔드가 치환하지 않도록 prev 표기를 나눠 쓴다. + PREV_PLACEHOLDER = "{" * 2 + "prev" + "}" * 2 + + + def extract(prev_text, llm_task): + # 의존 task 가 실패하면 백엔드는 prev 를 채우지 않아 표기가 그대로 남는다. 이를 파싱 오류와 구분한다. + if prev_text.strip() in ("", PREV_PLACEHOLDER): + raise CaptureError("UPSTREAM_NO_OUTPUT", 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) + try: + obj = parse_model(env) + except CaptureError: + obj = earlier_answer(env) + if obj is None: + raise + if REQUIRED_KEY not in obj: + # 마지막 회차가 다른 dict 를 내면 앞 회차 정답을 덮는다. + obj = earlier_answer(env) + if obj is None: + raise CaptureError("MISSING_REQUIRED_KEY", REQUIRED_KEY) + return obj, env.get("status") + + LLM_TASK = "Task_A0_domain_screener_01" + OUTPUT_PATH = "routing/domain_screening_draft.json" + 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) + 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_A0_domain_screener_02 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 180 + code: | + #!/usr/bin/env python3 + # Task_A0_domain_screener_02 + # domain_screening_draft.json (LLM 판단 4종) 를 받아 + # 비판단 6종을 registry 에서 직접 읽어 붙이고, + # 멤버십과 보존 등식을 검증하여 routing/domain_screening.json 을 기록한다. + # 판단은 하지 않는다. 상태를 올릴 수는 있어도 내리지 않는다. + import hashlib + import itertools + import json + import re + import unicodedata + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # 빠지면 localdocs 가 루트 경로를 보므로 사용자 파일을 찾지 못한다. + # -------------------------------------------------------------------------- + TASK_NAME = "Task_A0_domain_screener_02" + 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_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 %s failed" % name) + return p + + + def read_raw(name): + # 파일 내용을 재직렬화 없이 원문 그대로 돌려준다. + # registry_index_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): + # 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])) + + + # -------------------------------------------------------------------------- + # 경로와 상수 + # -------------------------------------------------------------------------- + DRAFT_PATH = "routing/domain_screening_draft.json" + MEETING_PATH = "client_meeting.md" + REGISTRY_INDEX_PATH = "Default_Agent/domains/_registry_index.json" + DIGEST_PATH = "Default_Agent/routing/activation_cue_digest.md" + OUTPUT_PATH = "routing/domain_screening.json" + + SCHEMA_VERSION = "stage1_domain_screening.v1" + + # platform/schemas/domain_screening.schema.json 이 const 로 못박은 값이다. + # 하나라도 다르면 스키마 검증에서 떨어지므로 판단 대상이 아니다. + SCREENING_POLICY = { + "case_name_lookup_forbidden": True, + "single_keyword_activation_forbidden": True, + "negative_cue_downrank_only": True, + "evidence_refinement_required": True, + "unknown_review_code": "UNROUTED_ISSUE_REVIEW", + } + CONTRACT_GUARDS = { + "final_conclusion_forbidden": True, + "unknown_values_require_review": True, + "source_membership_required": True, + "strict_json_output": True, + "meeting_only_evidence_promotion_forbidden": True, + } + + STATUS_RANK = {"READY": 0, "READY_WITH_REVIEW": 1, "BLOCKED": 2, "FAILED": 3} + PROVISIONAL_STATUS = ("candidate", "supporting", "monitor", "review") + CONFIDENCE = ("high", "medium", "low") + SEVERITY = ("info", "review", "hard_warning", "block") + + REF_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$") + DOMAIN_RE = re.compile(r"^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$") + CALC_RE = re.compile(r"^CE-[A-Z0-9][A-Z0-9-]{0,15}$") + CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") + REG_VER_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{2,127}$") + SHA_RE = re.compile(r"^[a-f0-9]{64}$") + + CANDIDATE_REQUIRED = ("domain_id", "provisional_status", "positive_refs", + "negative_refs", "conflict_refs", "confidence", + "reasoning_summary", "final_determination_forbidden") + CANDIDATE_ALLOWED = CANDIDATE_REQUIRED + ("requested_calculation_domains",) + REVIEW_REQUIRED = ("review_code", "severity", "reason", "source_refs") + REVIEW_ALLOWED = REVIEW_REQUIRED + ("domain_ids", "unresolved_type", + "blocks_final_drafting") + SCREENING_REQUIRED = ("schema_version", "status", "registry_version", + "registry_index_sha256", "source_document_refs", + "candidates", "unmatched_issue_refs", "review_items", + "screening_policy", "contract_guards") + + # 01 이 쓰면 안 되는 필드. 하나라도 있으면 초안이 계약을 벗어난 것이다. + FORBIDDEN_DRAFT_FIELDS = ("track_hypothesis", "domain_hypotheses", + "relief_mode_hints", "computation_hints", + "matched_cues", "notes_kr") + NONJUDGMENT_FIELDS = ("schema_version", "registry_version", + "registry_index_sha256", "source_document_refs", + "screening_policy", "contract_guards") + + GANADA = "가나다라마바사아자차카타파하" + SECTION_MARKERS = (("상담내용", "FACT"), + ("사건관계인의주장", "OPP"), + ("의뢰인의희망사항", "WISH")) + + ERRORS = [] + WARNINGS = [] + ADDED_REVIEWS = [] + + + def fail(code, message): + ERRORS.append({"code": code, "message": message}) + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + # -------------------------------------------------------------------------- + # 1) source unit 독립 재산출 + # Task_A0_domain_screener_01 의 와 같은 규칙을 + # 코드로 다시 구현한다. LLM 의 채번을 신뢰하지 않고 대조하기 위한 것이다. + # -------------------------------------------------------------------------- + def mint_source_units(meeting_text): + lines = unicodedata.normalize("NFC", meeting_text).split("\n") + section = None + cluster = 0 + units = [] + meta_seen = False + raw_seq = 0 + for line in lines: + t = line.strip() + if not t: + continue + squashed = re.sub(r"\s+", "", t) + if "【" in t and "】" in t: + hit = None + for needle, code in SECTION_MARKERS: + if needle in squashed: + hit = code + break + if hit: + section = hit + cluster = 0 + continue + if section is None: + # 상담일지 머리표는 문단마다 자르지 않고 MTG.META.01 한 단위로 접는다. + if set(t) <= set("| -"): + continue + if not meta_seen: + units.append("MTG.META.01") + meta_seen = True + continue + m = re.match(r"^(\d{1,2})\.\s", t) + if m: + cluster = int(m.group(1)) + continue + m2 = re.match(r"^([" + GANADA + r"])\.\s", t) + if m2: + item = GANADA.index(m2.group(1)) + 1 + else: + item = 0 + unit_id = "MTG.%s.%02d.%02d" % (section, cluster, item) + if unit_id in units: + raw_seq += 1 + unit_id = "MTG.RAW.%03d" % raw_seq + units.append(unit_id) + return units, raw_seq + + + # -------------------------------------------------------------------------- + # 2) 단어 사전 파싱 + # 도메인 화이트리스트, 도메인별 계산 허용목록, 충돌 검토코드, 상시활성 목록, + # 그리고 사전이 어느 registry 스냅숏에서 나왔는지를 뽑는다. + # -------------------------------------------------------------------------- + def parse_digest(md): + text = unicodedata.normalize("NFC", md) + info = {"registry_version": None, "registry_index_sha256": None, + "domains": {}, "always_on": [], "review_codes": set()} + m = re.search(r"^registry_version:\s*`([^`]+)`", text, re.M) + if m: + info["registry_version"] = m.group(1).strip() + m = re.search(r"^registry_index:.*sha256=`([a-f0-9]{64})`", text, re.M) + if m: + info["registry_index_sha256"] = m.group(1) + current = None + for line in text.split("\n"): + t = line.rstrip() + if t.startswith("### "): + parts = [x.strip() for x in t[4:].split("|")] + if len(parts) < 6: + continue + did = parts[0] + kv = {} + for seg in parts[2:]: + if "=" in seg: + k, v = seg.split("=", 1) + kv[k.strip()] = v.strip() + calc = [] if kv.get("calc", "-") == "-" else kv["calc"].split(",") + dep = [] if kv.get("dep", "-") == "-" else kv["dep"].split(",") + info["domains"][did] = {"calc": calc, "dep": dep, + "kind": kv.get("kind"), + "ao": kv.get("ao") == "1"} + if kv.get("ao") == "1": + info["always_on"].append(did) + current = did + elif t.startswith("C|") and current: + fields = t.split("|") + if len(fields) >= 4: + info["review_codes"].add(fields[3].strip()) + return info + + + # -------------------------------------------------------------------------- + # 3) 최종 산출물 자기검증 — 닫힌 스키마의 형태를 코드로 다시 확인한다. + # -------------------------------------------------------------------------- + def self_check(doc): + problems = [] + if list(doc.keys()) != ["domain_screening"]: + problems.append("root key must be exactly domain_screening") + return problems + ds = doc["domain_screening"] + missing = [k for k in SCREENING_REQUIRED if k not in ds] + extra = [k for k in ds if k not in SCREENING_REQUIRED] + if missing: + problems.append("missing required: %s" % ",".join(missing)) + if extra: + problems.append("additionalProperties: %s" % ",".join(extra)) + if ds.get("schema_version") != SCHEMA_VERSION: + problems.append("schema_version const mismatch") + if ds.get("status") not in STATUS_RANK: + problems.append("status enum invalid") + if not REG_VER_RE.match(str(ds.get("registry_version", ""))): + problems.append("registry_version pattern invalid") + if not SHA_RE.match(str(ds.get("registry_index_sha256", ""))): + problems.append("registry_index_sha256 pattern invalid") + for key in ("source_document_refs", "unmatched_issue_refs"): + arr = ds.get(key, []) + if len(set(arr)) != len(arr): + problems.append("%s not unique" % key) + for v in arr: + if not REF_RE.match(v): + problems.append("%s ref pattern invalid: %s" % (key, v)) + for c in ds.get("candidates", []): + for k in CANDIDATE_REQUIRED: + if k not in c: + problems.append("candidate missing %s" % k) + for k in c: + if k not in CANDIDATE_ALLOWED: + problems.append("candidate extra key %s" % k) + if c.get("final_determination_forbidden") is not True: + problems.append("final_determination_forbidden must be true") + for r in ds.get("review_items", []): + for k in REVIEW_REQUIRED: + if k not in r: + problems.append("review_item missing %s" % k) + for k in r: + if k not in REVIEW_ALLOWED: + problems.append("review_item extra key %s" % k) + if r.get("severity") not in SEVERITY: + problems.append("review_item severity invalid") + if not CODE_RE.match(str(r.get("review_code", ""))): + problems.append("review_code pattern invalid") + reason = r.get("reason", "") + if not (1 <= len(reason) <= 1000): + problems.append("review_item reason length invalid") + if ds.get("screening_policy") != SCREENING_POLICY: + problems.append("screening_policy const mismatch") + if ds.get("contract_guards") != CONTRACT_GUARDS: + problems.append("contract_guards const mismatch") + return problems + + + # -------------------------------------------------------------------------- + # main + # -------------------------------------------------------------------------- + def main(): + # ---- 입력 4종 ---- + try: + draft_doc = read_json(DRAFT_PATH) + except Exception as exc: + fail("DRAFT_UNREADABLE", "%s: %s" % (DRAFT_PATH, exc)) + return None + try: + meeting_raw = read_raw(MEETING_PATH) + except Exception as exc: + fail("MEETING_UNREADABLE", "%s: %s" % (MEETING_PATH, exc)) + return None + try: + registry_raw = read_raw(REGISTRY_INDEX_PATH) + except Exception as exc: + fail("REGISTRY_INDEX_UNREADABLE", "%s: %s" % (REGISTRY_INDEX_PATH, exc)) + return None + try: + digest_raw = read_raw(DIGEST_PATH) + except Exception as exc: + fail("DIGEST_UNREADABLE", "%s: %s" % (DIGEST_PATH, exc)) + return None + + if not isinstance(draft_doc, dict) or "domain_screening_draft" not in draft_doc: + fail("DRAFT_ROOT_KEY_INVALID", "root key domain_screening_draft not found") + return None + draft = draft_doc["domain_screening_draft"] + + for k in FORBIDDEN_DRAFT_FIELDS: + if k in draft: + fail("FORBIDDEN_FIELD_PRESENT", "draft contains forbidden field %s" % k) + for k in NONJUDGMENT_FIELDS: + if k in draft: + fail("NONJUDGMENT_FIELD_IN_DRAFT", + "draft must not carry non-judgment field %s" % k) + + # ---- registry 원문 해시. 재직렬화하지 않은 원문 바이트로 계산한다. ---- + registry_index_sha256 = hashlib.sha256(registry_raw.encode("utf-8")).hexdigest() + try: + registry_doc = json.loads(registry_raw) + registry = registry_doc["domain_registry_index"] + except Exception as exc: + fail("REGISTRY_INDEX_UNREADABLE", "parse failed: %s" % exc) + return None + registry_version = registry.get("registry_version") + registry_domain_ids = sorted(e["domain_id"] for e in registry.get("entries", [])) + + # ---- 단어 사전 ---- + digest = parse_digest(digest_raw) + if len(digest["domains"]) != len(registry_domain_ids): + fail("DIGEST_MALFORMED", + "digest domains=%d registry entries=%d" + % (len(digest["domains"]), len(registry_domain_ids))) + return None + unknown_in_digest = sorted(set(digest["domains"]) - set(registry_domain_ids)) + if unknown_in_digest: + fail("DIGEST_DOMAIN_SET_MISMATCH", + "digest has domains absent from registry: %s" % ",".join(unknown_in_digest)) + return None + # 사전 머리말은 있으면 낡음 감지에 쓰고, 없으면 경고만 남긴다. + # registry_version 과 registry_index_sha256 의 정본은 _registry_index.json 이지 + # 사전이 아니다. 사전 머리말이 편집되어 사라져도 산출물은 정확해야 한다. + if digest["registry_index_sha256"] is None: + warn("DIGEST_HEADER_ABSENT", + "activation_cue_digest.md has no registry_index sha256 header; " + "staleness cross-check skipped") + elif digest["registry_index_sha256"] != registry_index_sha256: + # 사전이 만들어진 뒤 registry 가 바뀌었거나, 읽는 과정에서 원문이 변형된 것이다. + # 사전이 낡은 단서로 판단한 초안을 봉인하면 안 되므로 여기서 멈춘다. + fail("REGISTRY_INDEX_SHA_MISMATCH", + "digest=%s computed=%s" % (digest["registry_index_sha256"], + registry_index_sha256)) + return None + if digest["registry_version"] is None: + warn("DIGEST_HEADER_ABSENT", + "activation_cue_digest.md has no registry_version header") + elif digest["registry_version"] != registry_version: + fail("REGISTRY_VERSION_MISMATCH", + "digest=%s registry=%s" % (digest["registry_version"], registry_version)) + return None + + # ---- source unit 독립 재산출 ---- + universe, raw_fallback = mint_source_units(meeting_raw) + if raw_fallback: + warn("SCREENING_SOURCE_UNIT_FALLBACK", + "%d unit(s) fell back to MTG.RAW.* numbering" % raw_fallback) + if not universe: + fail("SOURCE_UNIT_SET_EMPTY", "no source unit minted from %s" % MEETING_PATH) + return None + universe_set = set(universe) + if len(universe_set) != len(universe): + fail("SOURCE_UNIT_DUPLICATE", "duplicate unit id after minting") + return None + for u in universe: + if not REF_RE.match(u): + fail("REF_PATTERN_INVALID", "minted unit id invalid: %s" % u) + source_document_refs = sorted(universe_set) + + # 초안이 스스로 적어둔 목록과 대조한다. 어긋나면 재산출본을 정본으로 삼고 검토를 남긴다. + draft_units = [] + for row in draft.get("source_unit_index", []) or []: + if isinstance(row, dict) and row.get("unit_id"): + draft_units.append(row["unit_id"]) + if draft_units and set(draft_units) != universe_set: + only_draft = sorted(set(draft_units) - universe_set) + only_mint = sorted(universe_set - set(draft_units)) + ADDED_REVIEWS.append({ + "review_code": "E00_MEMBERSHIP_CONFLICT_REVIEW", + "severity": "review", + "reason": ("초안의 source_unit_index 와 재산출한 원천 단위 집합이 다르다. " + "재산출본을 정본으로 삼았다. 초안에만 있음=%s, 재산출본에만 있음=%s" + % (",".join(only_draft) or "-", ",".join(only_mint) or "-"))[:1000], + "source_refs": sorted(set(only_mint))[:64], + "domain_ids": ["E-00"], + "unresolved_type": "source_unit_index_divergence", + "blocks_final_drafting": False, + }) + + # ---- 후보 검증 ---- + candidates = draft.get("candidates") + if not isinstance(candidates, list): + fail("DRAFT_FIELD_MISSING", "candidates must be a list") + return None + seen_domains = set() + cited = set() + clean_candidates = [] + for c in candidates: + if not isinstance(c, dict): + fail("CANDIDATE_KEY_INVALID", "candidate is not an object") + continue + did = c.get("domain_id") + for k in CANDIDATE_REQUIRED: + if k not in c: + fail("CANDIDATE_KEY_INVALID", "%s missing %s" % (did, k)) + for k in c: + if k not in CANDIDATE_ALLOWED: + fail("CANDIDATE_KEY_INVALID", "%s extra key %s" % (did, k)) + if not DOMAIN_RE.match(str(did)) or did not in digest["domains"]: + fail("DOMAIN_ID_UNKNOWN", "unknown domain_id: %r" % did) + continue + if did in seen_domains: + fail("DOMAIN_ID_DUPLICATE", "duplicate domain_id: %s" % did) + continue + seen_domains.add(did) + if c.get("provisional_status") not in PROVISIONAL_STATUS: + fail("ENUM_INVALID", "%s provisional_status=%r" % (did, c.get("provisional_status"))) + if c.get("confidence") not in CONFIDENCE: + fail("ENUM_INVALID", "%s confidence=%r" % (did, c.get("confidence"))) + summary = c.get("reasoning_summary", "") + if not isinstance(summary, str) or not (1 <= len(summary) <= 1200): + fail("REASONING_SUMMARY_LENGTH", "%s length=%d" % (did, len(str(summary)))) + if c.get("final_determination_forbidden") is not True: + fail("FINAL_DETERMINATION_FLAG_INVALID", "%s" % did) + for key in ("positive_refs", "negative_refs", "conflict_refs"): + arr = c.get(key) or [] + if not isinstance(arr, list): + fail("CANDIDATE_KEY_INVALID", "%s %s must be a list" % (did, key)) + continue + for ref in arr: + if not REF_RE.match(str(ref)): + fail("REF_PATTERN_INVALID", "%s %s %r" % (did, key, ref)) + elif ref not in universe_set: + # source_membership_required 위반. 조용히 지우지 않고 실패로 처리한다. + fail("REF_NOT_IN_SOURCE_UNIVERSE", "%s %s %s" % (did, key, ref)) + else: + cited.add(ref) + allowed_calc = set(digest["domains"][did]["calc"]) + calc = c.get("requested_calculation_domains") or [] + if not isinstance(calc, list): + fail("CANDIDATE_KEY_INVALID", "%s requested_calculation_domains must be a list" % did) + calc = [] + for cid in calc: + if not CALC_RE.match(str(cid)): + fail("CALC_PATTERN_INVALID", "%s %r" % (did, cid)) + elif cid not in allowed_calc: + fail("CALC_NOT_IN_BINDINGS", "%s requested %s but calc=%s" + % (did, cid, ",".join(sorted(allowed_calc)) or "-")) + out = {} + for k in CANDIDATE_REQUIRED: + out[k] = c.get(k) + for key in ("positive_refs", "negative_refs", "conflict_refs"): + out[key] = sorted(set(out.get(key) or [])) + if "requested_calculation_domains" in c: + out["requested_calculation_domains"] = sorted(set(calc)) + clean_candidates.append(out) + clean_candidates.sort(key=lambda x: str(x.get("domain_id"))) + + # 상시 활성 4종은 D0 게이트의 보장 대상이다. 여기서 후보를 만들어내지 않고 경고만 남긴다. + missing_ao = [d for d in sorted(digest["always_on"]) if d not in seen_domains] + if missing_ao: + warn("ALWAYS_ON_NOT_IN_DRAFT", + "always_on domains absent from draft candidates: %s" % ",".join(missing_ao)) + + # ---- 검토 항목 검증 ---- + allowed_codes = set(digest["review_codes"]) | { + "UNROUTED_ISSUE_REVIEW", "SCREENING_SOURCE_UNIT_FALLBACK", + "E00_MEMBERSHIP_CONFLICT_REVIEW", "E00_FALSE_UNROUTED_REVIEW", + "E00_CONSERVATION_FAILURE"} + clean_reviews = [] + for r in draft.get("review_items") or []: + if not isinstance(r, dict): + fail("REVIEW_ITEM_KEY_INVALID", "review_item is not an object") + continue + for k in REVIEW_REQUIRED: + if k not in r: + fail("REVIEW_ITEM_KEY_INVALID", "missing %s" % k) + for k in r: + if k not in REVIEW_ALLOWED: + fail("REVIEW_ITEM_KEY_INVALID", "extra key %s" % k) + code = str(r.get("review_code", "")) + if not CODE_RE.match(code): + fail("REVIEW_CODE_PATTERN_INVALID", code) + elif code not in allowed_codes: + fail("REVIEW_CODE_UNKNOWN", code) + if r.get("severity") not in SEVERITY: + fail("ENUM_INVALID", "review severity=%r" % r.get("severity")) + for ref in r.get("source_refs") or []: + if ref not in universe_set: + fail("REF_NOT_IN_SOURCE_UNIVERSE", "review_items %s" % ref) + for did in r.get("domain_ids") or []: + if not DOMAIN_RE.match(str(did)): + fail("DOMAIN_ID_UNKNOWN", "review_items %r" % did) + item = {} + for k in REVIEW_ALLOWED: + if k in r: + item[k] = r[k] + item["source_refs"] = sorted(set(item.get("source_refs") or [])) + clean_reviews.append(item) + + # ---- 보존 등식. 초안의 미분류를 신뢰하지 않고 다시 계산한다. ---- + computed_unmatched = sorted(universe_set - cited) + draft_unmatched = sorted(set(draft.get("unmatched_issue_refs") or [])) + if draft_unmatched != computed_unmatched: + only_draft = sorted(set(draft_unmatched) - set(computed_unmatched)) + only_calc = sorted(set(computed_unmatched) - set(draft_unmatched)) + ADDED_REVIEWS.append({ + "review_code": "E00_FALSE_UNROUTED_REVIEW", + "severity": "review", + "reason": ("초안의 unmatched_issue_refs 가 재계산 결과와 다르다. 재계산본으로 대체했다. " + "초안에만 있음=%s, 재계산본에만 있음=%s" + % (",".join(only_draft) or "-", ",".join(only_calc) or "-"))[:1000], + "source_refs": (only_draft + only_calc)[:64], + "domain_ids": ["E-00"], + "unresolved_type": "unmatched_set_divergence", + "blocks_final_drafting": False, + }) + unmatched = computed_unmatched + if computed_unmatched and not any( + r.get("review_code") == "UNROUTED_ISSUE_REVIEW" for r in clean_reviews): + ADDED_REVIEWS.append({ + "review_code": "UNROUTED_ISSUE_REVIEW", + "severity": "review", + "reason": "어느 도메인 단서에도 걸리지 않은 상담록 단위를 잔여로 보존한다.", + "source_refs": computed_unmatched[:64], + "domain_ids": ["E-00"], + "unresolved_type": "unrouted_meeting_unit", + "blocks_final_drafting": True, + }) + clean_reviews.extend(ADDED_REVIEWS) + + if len(universe_set) != len(cited) + len(unmatched): + fail("CONSERVATION_FAILED", + "universe=%d cited=%d unmatched=%d" + % (len(universe_set), len(cited), len(unmatched))) + + # ---- 상태. 올릴 수는 있어도 내리지 않는다. ---- + draft_status = draft.get("status") + if draft_status not in STATUS_RANK: + fail("ENUM_INVALID", "draft status=%r" % draft_status) + draft_status = "READY_WITH_REVIEW" + status = draft_status + if clean_reviews and STATUS_RANK[status] < STATUS_RANK["READY_WITH_REVIEW"]: + status = "READY_WITH_REVIEW" + + if ERRORS: + return None + + # ---- 비판단 6종을 붙여 조립한다. 키 순서는 스키마의 required 순서를 따른다. ---- + screening = { + "schema_version": SCHEMA_VERSION, + "status": status, + "registry_version": registry_version, + "registry_index_sha256": registry_index_sha256, + "source_document_refs": source_document_refs, + "candidates": clean_candidates, + "unmatched_issue_refs": unmatched, + "review_items": clean_reviews, + "screening_policy": dict(SCREENING_POLICY), + "contract_guards": dict(CONTRACT_GUARDS), + } + doc = {"domain_screening": screening} + + problems = self_check(doc) + if problems: + for p in problems: + fail("OUTPUT_SCHEMA_SELF_CHECK_FAILED", p) + return None + + body = json.dumps(doc, ensure_ascii=False, indent=2) + "\n" + write_doc(OUTPUT_PATH, body) + try: + _call("list_docs", {"path": "routing", "pattern": "domain_screening.json"}, + next_msg_id()) + except Exception as exc: + warn("OUTPUT_LIST_CHECK_SKIPPED", str(exc)) + + return { + "screening_sha256": hashlib.sha256(body.encode("utf-8")).hexdigest(), + "status": status, + "source_unit_count": len(universe_set), + "cited_unit_count": len(cited), + "unmatched_unit_count": len(unmatched), + "candidate_count": len(clean_candidates), + "review_item_count": len(clean_reviews), + "review_items_added_by_02": [r["review_code"] for r in ADDED_REVIEWS], + "registry_version": registry_version, + "registry_index_sha256": registry_index_sha256, + } + + + # 지난 실행의 screening 이 하류로 흐르지 않게 먼저 무효화한다. 성공하면 main() 이 정본으로 덮는다. + # try 밖에 두어 세션 열기·표식 쓰기의 실패는 raise 되고 백엔드 재시도를 받는다. + _init() + write_doc(OUTPUT_PATH, "SCREENING_PENDING %s\n" % datetime.now(timezone.utc).isoformat()) + + try: + RESULT = main() + except Exception as exc: + fail("UNHANDLED_EXCEPTION", "%s: %s" % (type(exc).__name__, exc)) + RESULT = None + + if RESULT is None: + print(json.dumps({"status": "FAILED", "written": False, + "output_path": OUTPUT_PATH, + "errors": ERRORS, "warnings": WARNINGS}, + ensure_ascii=False)) + else: + payload = {"status": RESULT["status"], "written": True, + "output_path": OUTPUT_PATH, "errors": [], "warnings": WARNINGS} + payload.update(RESULT) + print(json.dumps(payload, ensure_ascii=False)) + - task_name: Task_A0_domain_screener_03 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + # 후보 15개면 도구 호출이 4(고정 읽기)+15(후보 config)+1(쓰기)+1(확인)=21회다. + # 후보가 26개까지 늘어도 여유가 남도록 240초로 둔다. + timeout: 240 + code: | + #!/usr/bin/env python3 + # Task_A0_domain_screener_03 + # routing/domain_screening.json 의 후보 도메인 목록으로 + # Default_Agent/domains/<후보>/domain_config.json 에서 7개 항목만 발췌하여 + # routing/candidate_profile_vocabulary.md 를 기록한다. + # Task_A_client_goal 이 domain_profiles 를 채울 때 쓸 낱말 목록이며, + # 판단은 하지 않는다. registry 원문이 정본이고 이 파일은 파생본이다. + import hashlib + import itertools + import json + import re + import unicodedata + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # 빠지면 localdocs 가 루트 경로를 보므로 사용자 파일을 찾지 못한다. + # -------------------------------------------------------------------------- + TASK_NAME = "Task_A0_domain_screener_03" + 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_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 %s failed" % name) + return p + + + def read_raw(name): + # 원문을 재직렬화 없이 그대로 돌려준다. + # domain_config 의 sha256 을 registry 색인과 대조하므로 바이트 보존이 필수다. + 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): + # 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])) + + + # -------------------------------------------------------------------------- + # 경로와 상수 + # -------------------------------------------------------------------------- + SCREENING_PATH = "routing/domain_screening.json" + REGISTRY_INDEX_PATH = "Default_Agent/domains/_registry_index.json" + DOMAIN_CATALOG_PATH = "Default_Agent/platform/reference_catalogs/domain_ids.json" + CALC_CATALOG_PATH = "Default_Agent/platform/reference_catalogs/calculation_ids.json" + CONFIG_PATH_FMT = "Default_Agent/domains/%s/domain_config.json" + OUTPUT_PATH = "routing/candidate_profile_vocabulary.md" + + # A0_02 의 이번 실행 결과. 스크립트가 실패(raise)하면 백엔드가 prev 를 채우지 않아 표기가 그대로 남는다. + # FAILED 를 정상 출력한 경우는 prev 가 채워지고 written=false 로 본다. + # 백엔드가 치환하지 않도록 비교용 prev 표기는 나눠 쓴다. + PREV_PLACEHOLDER = "{" * 2 + "prev" + "}" * 2 + A0_02_TASK = "Task_A0_domain_screener_02" + A0_02_PREV_TEXT = r"""{{prev}}""" + + DIGEST_SCHEMA = "candidate_profile_vocabulary.v1" + + # Task_A 프롬프트의 잔여 예산. §2.2 로 고정 4-profile 블록(약 9,000 B)이 + # 삭제되는 것을 반영한 값이다. 초과하면 라벨을 단계적으로 줄인다. + MAX_OUTPUT_BYTES = 28000 + # 라벨 길이 사다리. 앞에서부터 시도하고 예산에 맞는 첫 단계를 쓴다. + LABEL_TIERS = [("full", None), ("60", 60), ("40", 40), ("24", 24), ("none", 0)] + + DOMAIN_RE = re.compile(r"^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$") + CALC_RE = re.compile(r"^CE-[A-Z0-9][A-Z0-9-]{0,15}$") + REF_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$") + + ERRORS = [] + WARNINGS = [] + + + def fail(code, message): + ERRORS.append({"code": code, "message": message}) + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + def cut(text, limit): + # 라벨 축약. 파이프는 구분자이므로 슬래시로 치환한다. + if text is None: + return "-" + t = unicodedata.normalize("NFC", str(text)).replace("\n", " ").replace("|", "/").strip() + if not t: + return "-" + if limit is None: + return t + if limit == 0: + return "" + return t if len(t) <= limit else t[:limit] + + + def render(rows, refs, meta, limit): + # rows: [(domain_id, cfg)] 순서 고정. limit 은 라벨 길이 상한. + L = [] + a = L.append + a("# CANDIDATE_PROFILE_VOCABULARY") + a("") + a("digest_schema: `%s`" % DIGEST_SCHEMA) + a("purpose: `client_goal_domain_profiles.schema.json` 을 채울 때 쓰는 낱말 목록이다. " + "사실 원천이 아니며 registry 원문의 파생본이다.") + a("source: `Default_Agent/domains//domain_config.json` 에서 7개 항목만 발췌 " + "(label_ko·kind, element_slots, opposing_fact_slots, evidence_components, " + "defense_map, calculation_bindings, review_codes)") + a("registry_version: `%s`" % meta["registry_version"]) + a("registry_index_sha256: `%s`" % meta["registry_index_sha256"]) + a("screening_sha256: `%s`" % meta["screening_sha256"]) + a("candidate_count: %d" % len(rows)) + a("label_tier: `%s`" % meta["label_tier"]) + a("") + a("## LEGEND") + a("") + a("도메인 머리: `### ||kind=|calc=`") + a("- `E||||